code stringlengths 2 1.05M |
|---|
var http = require('http');
var ecstatic = require('ecstatic')(__dirname);
var server = http.createServer(function (req, res) {
if (/^\/[^\/.]+$/.test(req.url)) {
req.url = '/';
}
ecstatic(req, res);
});
server.listen(5001);
console.log('http://localhost:5001');
|
'use strict';
// MODULES //
var mustache = require( 'mustache' );
var validate = require( './validate.js' );
// TEMPLATES //
var URL = 'https://github.com/{{owner}}/{{repo}}/issues';
var IMAGE = 'https://img.shields.io/github/issues{{#raw}}-raw{{/raw}}/{{owner}}/{{repo}}.{{format}}?style={{style}}';
mustache.parse( URL );
mustache.parse( IMAGE );
// URLS //
/**
* FUNCTION: urls( options )
* Creates Shields.io badge URLs.
*
* @param {Object} options - function options
* @param {String} options.owner - repository owner
* @param {String} options.repo - repository name
* @param {Boolean} [options.raw=false] - boolean indicating whether to return "raw" or decorated badge links
* @param {String} [options.style="flat"] - badge style
* @param {String} [options.format="svg"] - badge format
* @returns {Object}
*/
function urls( options ) {
var opts;
var out;
var err;
opts = {};
err = validate( opts, options );
if ( err ) {
throw err;
}
opts.raw = opts.raw || false;
opts.style = opts.style || 'flat';
opts.format = opts.format || 'svg';
out = {};
out.image = mustache.render( IMAGE, opts );
out.url = mustache.render( URL, opts );
return out;
} // end FUNCTION urls()
// EXPORTS //
module.exports = urls;
|
module.exports = {
init: function () {
//Add here your scaling options
},
preload: function () {
//Load just the essential files for the loading screen,
//they will be used in the Load State
game.load.image('loading', 'assets/loading.png');
game.load.image('load_progress_bar', 'assets/progress_bar_bg.png');
game.load.image('load_progress_bar_dark', 'assets/progress_bar_fg.png');
game.load.bitmapFont('bits-1', 'assets/fonts/bits1.png', 'assets/fonts/bits1.fnt');
},
create: function () {
game.stage.backgroundColor = '#cccccc';
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.state.start('intro');
}
};
|
function AppRun(AppConstants, $rootScope) {
'ngInject';
$rootScope.$on('$stateChangeSuccess', (event, toState) => {
$rootScope.setPageTitle(toState.title);
});
$rootScope.setPageTitle = (title) => {
$rootScope.pageTitle = '';
if (title) {
$rootScope.pageTitle += title;
$rootScope.pageTitle += ' | ';
}
$rootScope.pageTitle += AppConstants.appName;
};
}
export default AppRun;
|
require('./tweet.less');
var appFunc = require('../utils/appFunc'),
commentModule = require('../comment/comment'),
template = require('./tweet.tpl.html');
var id;
var tweetModule = {
init: function(query){
id = query.id;
appFunc.hideToolbar();
this.bindEvents();
// render tweet card
this.getTweet();
// init comment module
commentModule.init(query);
},
getTweet: function(){
var $this = $$('#homeView .home-timeline .card[data-id="'+ id +'"]');
var item = {
id: $this.data('id'),
nickname: $this.find('.ks-facebook-name').html(),
avatar: $this.find('.ks-facebook-avatar').data('avatar-id'),
time: appFunc.timeFormat($this.find('.ks-facebook-date').data('time')),
text: $this.find('.card-content-inner>p').html()
};
if($this.find('.item-image>img')[0])
item.image = $this.find('.item-image img').attr('src');
var output = appFunc.renderTpl(template, item);
$$('#itemContent').html(output);
},
bindEvents: function(){
var bindings = [{
element: '#commentContent',
selector: '.comment-item',
event: 'click',
handler: commentModule.createActionSheet
},{
element: '#homeView .item-comment-btn',
event: 'click',
handler: commentModule.commentPopup
}];
appFunc.bindEvents(bindings);
}
};
module.exports = tweetModule; |
console.log("Manipulating DOM");
var addButton = function() {
var story_id = $(this).attr("id");
var story_link = story_id + "_link";
$("<div class=\"factbuddy\" style=\"margin: 10px 0 -12px 0; padding: 9px 0; border-top: 1px solid #e5e5e5;\">" +
"<span>" +
'<a class="factbuddy-open" id="' + story_link + '" href="#" style="color: #7f7f7f; font-size: 12px; font-weight: bold;"><img src="' + self.options.buttonLogoUrl + '" style="float: left; margin-top: -2px; margin-right: 7px;">Frag Fact Buddy!' +
"</a>" +
"</span>" +
"</div>").appendTo($(this).find(".userContentWrapper div:first-child").first());
$("#" + story_link).click(function() {
var postText = $("#" + story_id + " .userContent").text();
postText += " " + $("#" + story_id + " .userContent + div" ).text();
var dataObj = {
text : postText,
id : story_id
};
self.port.emit("requestNews", dataObj);
});
};
$("div[id^='hyperfeed_story_id']").each(addButton);
$("div[id^='topnews_main_stream']").observe("childlist subtree", "div[id^='hyperfeed_story_id']", function(record) {
$("div[id^='hyperfeed_story_id']").each(function() {
if($(this).find('.factbuddy').length === 0) {
$(this).each(addButton);
}
});
});
self.port.on("responseNews",function(payload) {
if (payload.success) {
var blockToAppend = '<div class="factbuddy-container" id="factbuddy-container-' + payload.id + '">' +
'<div class="factbuddy-borderimage"><img src="' + self.options.borderUrl + '" height="7px" width="15px"></div>' +
'<div class="factbuddy-header"><img height="44px" width="44px" src="' + self.options.logoUrl + '">' +
'<div class="factbuddy-headline">Fact Buddy</div><a href="#" class="factbuddy-close" id="factbuddy-close-' + payload.id + '">schließen</a></div>' +
'<div class="factbuddy-content">';
$.each(payload.content.news, function( index, value ) {
var imageUrl = self.options.noImageUrl;
if (value.imageUrl) {
imageUrl = value.imageUrl
}
blockToAppend += '<div class="factbuddy-entry">' +
'<div class="factbuddy-entry-image"><img width="80px" src="' + imageUrl + '" alt="' + value.headline + '"></div>' +
'<h1>' + value.headline + '</h1>' +
'<div class="factbuddy-entry-text">' + value.shortText + '</div>' +
'<div class="factbuddy-entry-source">Quelle: ' + value.source + '</div>' +
'<div class="factbuddy-entry-buttons"><a href="'+ value.url +'" target="_blank">Artikel lesen</a> <a href="#">In Kommentar einfügen</a></div>' +
'</div>';
});
blockToAppend += "</div></div>";
$(blockToAppend).insertAfter($("#" + payload.id + " .factbuddy"));
$('#factbuddy-container-' + payload.id).show();
$('#factbuddy-close-' + payload.id).click(function() {
$('#factbuddy-container-' + payload.id).remove();
});
} else {
console.log("Ne: " + payload.content);
var blockToAppend = '<div class="factbuddy-container" id="factbuddy-container-' + payload.id + '">' +
'<div class="factbuddy-borderimage"><img src="' + self.options.borderUrl + '" height="7px" width="15px"></div>' +
'<div class="factbuddy-header"><img height="44px" width="44px" src="' + self.options.logoUrl + '">' +
'<div class="factbuddy-headline">Fact Buddy</div><a href="#" class="factbuddy-close" id="factbuddy-close-' + payload.id + '">schließen</a></div>' +
'<div class="factbuddy-content">Keine passenden Beiträge gefunden!</div></div>';
$(blockToAppend).insertAfter($("#" + payload.id + " .factbuddy"));
$('#factbuddy-container-' + payload.id).show();
$('#factbuddy-close-' + payload.id).click(function() {
$('#factbuddy-container-' + payload.id).remove();
});
}
});
console.log("Done");
$('head').append('<style>' +
'.factbuddy-container {' +
' position: absolute;' +
' margin-left: -5px;' +
' margin-top: 10px;' +
' height:300px;' +
' width:400px;' +
' background-color: #f5f5f5;' +
' display:block;' +
' z-index:1002;' +
' border-radius: 5px;' +
' -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.5);' +
' -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.5);' +
' box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.5);' +
'}' +
'.factbuddy-header {' +
' border-bottom: 1px solid #ccc;' +
' display: block;' +
' height: 48px;' +
' padding: 2px;' +
'}' +
'.factbuddy-header img {' +
' float: left;' +
' margin: 0 10px 0 2px;' +
'}' +
'.factbuddy-borderimage {' +
' position:absolute;' +
' left: 7px;' +
' top:-11px;' +
'}' +
'.factbuddy-headline {' +
' font-size: 18px;' +
' font-family: sans-serif;' +
' line-height: 52px;' +
' color: #222;' +
' font-weight: bold;' +
'}' +
'.factbuddy-close {' +
' position: absolute;' +
' top: 21px;' +
' right: 10px;' +
' font-size: 8pt;' +
' text-decoration: none;' +
' font-family: sans-serif;' +
'}' +
'.factbuddy-content {' +
' margin: 0 6px 0 6px;' +
' display: block;' +
' overflow-y: scroll;' +
' height: 245px;' +
' padding-top: 2px' +
'}' +
'.factbuddy-entry {' +
' clear: both;' +
' display: inline-block;' +
' margin: 4px 0 4px 0;' +
' width: 100%;' +
'}' +
'.factbuddy-entry-image {' +
' float: left;' +
' margin: 0 10px 10px 0;' +
' height: 75px;' +
' width: 80px;' +
'}' +
'.factbuddy-entry h1 {' +
' font-size: 16px;' +
' font-weight: normal;' +
' margin: 0;' +
' padding: 2px 0 4px 0;' +
'}' +
'.factbuddy-entry-text {' +
' font-size: 12px;' +
' float: right;' +
' width: 298px;' +
'}' +
'.factbuddy-entry-buttons {' +
' clear: both;' +
' padding: 7px 0 5px 0;' +
' border-top: 1px solid #ccc;' +
' border-bottom: 1px solid #ccc;' +
' text-align: right;' +
' font-size: 12px;' +
' line-height: 12px;' +
'}' +
'.factbuddy-entry-buttons a {' +
' color: #999;' +
' text-decoration: none;' +
' margin: 0 0 40px 0;' +
'}' +
'.factbuddy-entry-buttons a:hover {' +
' color: #999;' +
' text-decoration: underline;' +
'}' +
'.factbuddy-entry-source {' +
' font-size: 10px;' +
' color: #999;' +
' text-transform: uppercase;' +
' float: right;' +
' width: 298px;' +
' margin: 8px 0 8px 0;' +
'}' +
'.factbuddy-open {' +
' display: block;' +
'}' +
'</style>');
|
const hooks = require('hooks');
hooks.after('Resource > Update Resource', (transaction, done) => {
const body = JSON.parse(transaction.test.request.body);
delete body.token;
transaction.test.request.body = JSON.stringify(body);
done();
});
|
export { default as QuestionnaireNewEdit } from './containers/questionnaire-new-edit-form';
export { default as Questionnaire } from './model/questionnaire';
|
var React = require('react');
var ReactNative = require('react-native');
var {
AppRegistry,
StyleSheet,
View,
TouchableOpacity,
Text
} = ReactNative;
var Spinner = require('react-native-spinkit');
var Example = React.createClass({
getInitialState() {
return {
index: 0,
types: ['CircleFlip', 'Bounce', 'Wave', 'WanderingCubes', 'Pulse', 'ChasingDots', 'ThreeBounce', 'Circle', '9CubeGrid', 'WordPress', 'FadingCircle', 'FadingCircleAlt', 'Arc', 'ArcAlt'],
size: 100,
color: "#FFFFFF",
isVisible: true
}
},
next() {
if (this.state.index++ >= this.state.types.length)
this.setState({index: 0})
else
this.setState({index: this.state.index++})
},
increaseSize() {
this.setState({size: this.state.size + 10});
},
changeColor() {
this.setState({color: '#'+Math.floor(Math.random()*16777215).toString(16)});
},
changeVisibility() {
this.setState({isVisible: !this.state.isVisible});
},
render() {
var type = this.state.types[this.state.index];
return (
<View style={styles.container}>
<Spinner style={styles.spinner} isVisible={this.state.isVisible} size={this.state.size} type={type} color={this.state.color}/>
<Text style={styles.text}>Type: {type}</Text>
<TouchableOpacity style={styles.btn} onPress={this.next}>
<Text style={styles.text}>Next</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.btn} onPress={this.increaseSize}>
<Text style={styles.text}>Increase size</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.btn} onPress={this.changeColor}>
<Text style={styles.text}>Change color</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.btn} onPress={this.changeVisibility}>
<Text style={styles.text}>Change visibility</Text>
</TouchableOpacity>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#d35400',
},
spinner: {
marginBottom: 50
},
btn: {
marginTop: 20
},
text: {
color: "white"
}
});
AppRegistry.registerComponent('Example', () => Example);
|
import Ember from 'ember';
import layout from './template';
import BasePickerMixin from 'ember-datetime-controls/mixins/base-picker-mixin';
const {
Component,
get,
set
} = Ember;
export default Component.extend(BasePickerMixin, {
layout,
classNames: ['dt-period'],
//functions
onDateFromChange(newDate) {
this.send('onChange', newDate, get(this, 'dateTo'));
},
onDateToChange(newDate) {
this.send('onChange', get(this, 'dateFrom'), newDate);
},
//passed in
dateFrom: null,
minDateFrom: null,
maxDateFrom: null,
disabledDatesFrom: null,
dateTo: null,
minDateTo: null,
maxDateTo: null,
disabledDatesTo: null,
actions: {
onChange(dateFrom, dateTo) {
if ( this.attrs.onchange && this.attrs.onchange instanceof Function ) {
return this.attrs.onchange(dateFrom, dateTo);
}
set(this, 'dateFrom', dateFrom);
set(this, 'dateTo', dateTo);
}
}
});
|
/**
* This task builds and launches the node.js server.
* This node.js server serves the application.
* Even if the server rendering is disabled, the server serves the
* static website.
* Then it launches browser-sync to proxy requests to the node.js server.
* Browser-sync allows live reloading ONLY if a public ressource has changed.
* For all other changes (like react components, component css, etc...),
* the webpackHotMiddleware reload the changing part of the app.
*/
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import BrowserSync from 'browser-sync';
import webpackConfig from '../webpack.config';
const bundler = webpack(webpackConfig[0]); // client configuration
const browserSync = BrowserSync.create();
export function serve() {
const proxyOptions = {
target: 'localhost:5000',
middleware: [
webpackDevMiddleware(bundler, {
publicPath: webpackConfig[0].output.publicPath,
stats: webpackConfig[0].stats,
}),
webpackHotMiddleware(bundler),
],
};
browserSync.init({
proxy: proxyOptions,
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: [
'build/public/**/*.css',
'build/public/**/*.html',
// './build/server.js',
],
});
}
|
let Logic = class {
constructor() {
this.previousCells = 0;
this.currentCells = 0;
}
/**
* Make game step with matrix calculation
* @param {String} currentColor
* @param {Array} matrix
*/
newStep(currentColor, matrix) {
if (matrix.length) {
let statusMatrix = this.generateStatusMatrix(matrix),
previousColor = matrix[0][0];
matrix = this.tableCalculation(matrix, statusMatrix, previousColor, currentColor);
}
return matrix;
}
/**
* Additional checks for set current color of cells by using cross method
* @param {Array} matrix
* @param {Array} statusMatrix
* @param {String} previousColor
* @param {String} color
* @param {Number} row
* @param {Number} col
*/
tableCalculation(matrix, statusMatrix, previousColor, color, row = 0, col = 0) {
if (statusMatrix[row][col] !== 1 && matrix[row][col] === previousColor) {
/**
* Set flag that this cell was checked
*/
statusMatrix[row][col] = 1;
matrix[row][col] = color;
/**
* The same column, but row higher on one
*/
if ((row - 1) >= 0) {
matrix = this.tableCalculation(matrix, statusMatrix, previousColor, color, row - 1, col);
}
/**
* The same row, but next column
*/
if ((col + 1) < matrix[0].length) {
matrix = this.tableCalculation(matrix, statusMatrix, previousColor, color, row, col + 1);
}
/**
* The same column, but row below on one
*/
if ((row + 1) < matrix.length) {
matrix = this.tableCalculation(matrix, statusMatrix, previousColor, color, row + 1, col);
}
/**
* The same row, but previous column
*/
if ((col - 1) >= 0) {
matrix = this.tableCalculation(matrix, statusMatrix, previousColor, color, row, col - 1);
}
}
return matrix;
}
/**
* Calculate the number of cells with provided color by using cross method
*/
calculateIdenticalCells(matrix, statusMatrix, color, row = 0, col = 0) {
let numberOfCells = 0;
if (matrix.length) {
if (statusMatrix[row][col] !== 1 && matrix[row][col] === color) {
numberOfCells++;
statusMatrix[row][col] = 1;
/**
* The same column, but row higher on one
*/
if ((row - 1) >= 0) {
numberOfCells += this.calculateIdenticalCells(matrix, statusMatrix, color, row - 1, col);
}
/**
* The same row, but next column
*/
if ((col + 1) < matrix[0].length) {
numberOfCells += this.calculateIdenticalCells(matrix, statusMatrix, color, row, col + 1);
}
/**
* The same column, but row below on one
*/
if ((row + 1) < matrix.length) {
numberOfCells += this.calculateIdenticalCells(matrix, statusMatrix, color, row + 1, col);
}
/**
* The same row, but previous column
*/
if ((col - 1) >= 0) {
numberOfCells += this.calculateIdenticalCells(matrix, statusMatrix, color, row, col - 1);
}
}
}
return numberOfCells;
}
/**
* Wrapper for calculating cells number
*/
calcScore(matrix, color) {
if (matrix.length) {
/**
* Create empty array with matrix structure to set which cell was handled
*/
let statusMatrix = this.generateStatusMatrix(matrix),
row = 0,
col = 0;
return this.calculateIdenticalCells(matrix, statusMatrix, color, row, col);
}
return 0;
}
/**
* Calculate score
*/
getScore(score) {
let newCells = this.currentCells - this.previousCells;
return score + Math.ceil(newCells * Math.pow(1.1, newCells));
}
/**
* Generate status matrix for correct handling
* @param {Array} matrix
*/
generateStatusMatrix(matrix) {
return [...Array(matrix.length)].map(
() => {
return [...Array(matrix[0].length)].map(() => {
return 0;
})
}
);
}
/**
* Check that game is finished after each step
* @param {Array} matrix
*/
isGameFinished(matrix) {
const currentColor = matrix[0][0];
let finished = matrix.every((rowData, rowIndex) => {
return rowData.every((colData, colIndex) => {
return colData === currentColor;
});
});
console.log(finished)
return finished;
}
}
export default Logic |
'use strict';
const jQuery = require('jquery');
import * as customFunctions from '../shared/methods/common-functions.js';
const FutureEventsCtrl = (app) => {
app.controller('FutureEventsCtrl', ['$scope', '$http', 'futureEventsRESTResource', `$rootScope`, ($scope, $http, resource, $rootScope) => {
$scope.errors = [];
$scope.futureEvents = [];
$scope.slides = [];
const testArr = [];
//set the watch array for new events
$rootScope.latestDbChangeMadeTime = [];
let FutureEvents = resource();
$scope.getUpcomingEvents = () => {
let imageCount = 0;
FutureEvents.getFutureEvents( (err, data) => {
if (err) {
return $scope.errors.push({msg: 'could not retrieve future events'});
};
$scope.futureEvents = [];
$scope.slides = [];
for (let i = 0, len = data.length; i < len; i++) {
let testObj = {city: data[i].city, dates: data[i].eventDates};
if (data[i].eventHomepageImage) {
let tmpObj = {};
tmpObj.eventHomepageImage = '/uploads/' + data[i].eventHomepageImage;
tmpObj.eventUrl = data[i].eventUrl;
imageCount++;
$scope.slides.push(tmpObj);
}
if (data[i].showOnHeader) {
$scope.futureEvents.push(data[i]);
testArr.push(testObj);
}
}
$scope.imageCount = imageCount;
// $scope.futureEvents = data;
})
};
$rootScope.$watch(`latestDbChangeMadeTime`, () => {
console.log(`$watch reached :::::::::::::: `);
$scope.getUpcomingEvents();
});
/*for (let i = 0, len = $scope.futureEvents.length; i < len; i++) {
if ($scope.futureEvents[i].eventHomepageImage) {
let tmpObj = {};
tmpObj.eventHomepageImage = $scope.futureEvents[i].eventHomepageImage;
$scope.slides.push($scope.futureEvents[i].eventHomepageImage)
}
}*/
//make block slide up effect for upcoming event blocks
$scope.riseText = (e) => {
let $this = angular.element(e.currentTarget);
$this.find('div').stop(true, true).animate({'bottom': '0'}, 200);
$this.find('h1').animate({opacity: 0}, 0);
$this.find('h3').animate({opacity: 0}, 0);
$this.find('p').show();
$this.find('p').animate({opacity: 1}, 200);
};
$scope.lowerText = (e) => {
let $this = angular.element(e.currentTarget);
$this.find('div').stop(true, true).animate({'bottom': '-100%'}, 200);
$this.find('h1').animate({opacity: 1}, 0);
$this.find('h3').animate({opacity: 1}, 0);
$this.find('p').hide();
$this.find('p').animate({opacity: 0}, 0);
};
//add border to show focus
$scope.showBorder = (e) => {
let $this = angular.element(e.currentTarget);
$this.parent().css('border', '3px solid #50B1FE');
};
$scope.removeBorder = (e) => {
let $this = angular.element(e.currentTarget);
$this.parent().css('border', '');
};
}])
}
module.exports = FutureEventsCtrl; |
/**
* @license Angular v4.4.7
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/common/testing'), require('@angular/core'), require('@angular/router')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/common', '@angular/common/testing', '@angular/core', '@angular/router'], factory) :
(factory((global.ng = global.ng || {}, global.ng.router = global.ng.router || {}, global.ng.router.testing = global.ng.router.testing || {}),global.ng.common,global.ng.common.testing,global.ng.core,global.ng.router));
}(this, (function (exports,_angular_common,_angular_common_testing,_angular_core,_angular_router) { 'use strict';
/**
* @license Angular v4.4.7
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @whatItDoes Allows to simulate the loading of ng modules in tests.
*
* @howToUse
*
* ```
* const loader = TestBed.get(NgModuleFactoryLoader);
*
* @Component({template: 'lazy-loaded'})
* class LazyLoadedComponent {}
* @NgModule({
* declarations: [LazyLoadedComponent],
* imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])]
* })
*
* class LoadedModule {}
*
* // sets up stubbedModules
* loader.stubbedModules = {lazyModule: LoadedModule};
*
* router.resetConfig([
* {path: 'lazy', loadChildren: 'lazyModule'},
* ]);
*
* router.navigateByUrl('/lazy/loaded');
* ```
*
* @stable
*/
var SpyNgModuleFactoryLoader = (function () {
function SpyNgModuleFactoryLoader(compiler) {
this.compiler = compiler;
/**
* @docsNotRequired
*/
this._stubbedModules = {};
}
Object.defineProperty(SpyNgModuleFactoryLoader.prototype, "stubbedModules", {
/**
* @docsNotRequired
*/
get: function () { return this._stubbedModules; },
/**
* @docsNotRequired
*/
set: function (modules) {
var res = {};
for (var _i = 0, _a = Object.keys(modules); _i < _a.length; _i++) {
var t = _a[_i];
res[t] = this.compiler.compileModuleAsync(modules[t]);
}
this._stubbedModules = res;
},
enumerable: true,
configurable: true
});
SpyNgModuleFactoryLoader.prototype.load = function (path) {
if (this._stubbedModules[path]) {
return this._stubbedModules[path];
}
else {
return Promise.reject(new Error("Cannot find module " + path));
}
};
return SpyNgModuleFactoryLoader;
}());
SpyNgModuleFactoryLoader.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
SpyNgModuleFactoryLoader.ctorParameters = function () { return [
{ type: _angular_core.Compiler, },
]; };
/**
* Router setup factory function used for testing.
*
* @stable
*/
function setupTestingRouter(urlSerializer, contexts, location, loader, compiler, injector, routes, urlHandlingStrategy) {
var router = new _angular_router.Router(null, urlSerializer, contexts, location, injector, loader, compiler, _angular_router.ɵflatten(routes));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
return router;
}
/**
* @whatItDoes Sets up the router to be used for testing.
*
* @howToUse
*
* ```
* beforeEach(() => {
* TestBed.configureTestModule({
* imports: [
* RouterTestingModule.withRoutes(
* [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}])]
* )
* ]
* });
* });
* ```
*
* @description
*
* The modules sets up the router to be used for testing.
* It provides spy implementations of {@link Location}, {@link LocationStrategy}, and {@link
* NgModuleFactoryLoader}.
*
* @stable
*/
var RouterTestingModule = (function () {
function RouterTestingModule() {
}
RouterTestingModule.withRoutes = function (routes) {
return { ngModule: RouterTestingModule, providers: [_angular_router.provideRoutes(routes)] };
};
return RouterTestingModule;
}());
RouterTestingModule.decorators = [
{ type: _angular_core.NgModule, args: [{
exports: [_angular_router.RouterModule],
providers: [
_angular_router.ɵROUTER_PROVIDERS, { provide: _angular_common.Location, useClass: _angular_common_testing.SpyLocation },
{ provide: _angular_common.LocationStrategy, useClass: _angular_common_testing.MockLocationStrategy },
{ provide: _angular_core.NgModuleFactoryLoader, useClass: SpyNgModuleFactoryLoader }, {
provide: _angular_router.Router,
useFactory: setupTestingRouter,
deps: [
_angular_router.UrlSerializer, _angular_router.ChildrenOutletContexts, _angular_common.Location, _angular_core.NgModuleFactoryLoader, _angular_core.Compiler, _angular_core.Injector,
_angular_router.ROUTES, [_angular_router.UrlHandlingStrategy, new _angular_core.Optional()]
]
},
{ provide: _angular_router.PreloadingStrategy, useExisting: _angular_router.NoPreloading }, _angular_router.provideRoutes([])
]
},] },
];
/** @nocollapse */
RouterTestingModule.ctorParameters = function () { return []; };
exports.SpyNgModuleFactoryLoader = SpyNgModuleFactoryLoader;
exports.setupTestingRouter = setupTestingRouter;
exports.RouterTestingModule = RouterTestingModule;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=router-testing.umd.js.map
|
import Ember from 'ember';
import EmberValidations from 'ember-validations';
import { buildContainer } from '../helpers/container';
import Base from 'ember-validations/validators/base';
var user, User;
var get = Ember.get;
var set = Ember.set;
module('Validate test', {
setup: function() {
User = Ember.Object.extend(EmberValidations.Mixin, {
container: buildContainer(),
validations: {
firstName: {
presence: true,
length: 5
},
lastName: {
format: { with: /\w+/ }
}
}
});
Ember.run(function() {
user = User.create();
});
}
});
asyncTest('returns a promise', function() {
Ember.run(function(){
user.validate().then(function(){
ok(false, 'expected validation failed');
}, function() {
equal(get(user, 'isValid'), false);
start();
});
});
});
test('isInvalid tracks isValid', function() {
equal(get(user, 'isInvalid'), true);
Ember.run(function() {
user.setProperties({firstName: 'Brian', lastName: 'Cardarella'});
});
equal(get(user, 'isInvalid'), false);
});
asyncTest('runs all validations', function() {
Ember.run(function(){
user.validate().then(null, function(errors){
deepEqual(get(errors, 'firstName'), ["can't be blank", 'is the wrong length (should be 5 characters)']);
deepEqual(get(errors, 'lastName'), ["is invalid"]);
equal(get(user, 'isValid'), false);
set(user, 'firstName', 'Bob');
user.validate('firstName').then(null, function(errors){
deepEqual(get(errors, 'firstName'), ['is the wrong length (should be 5 characters)']);
equal(get(user, 'isValid'), false);
set(user, 'firstName', 'Brian');
set(user, 'lastName', 'Cardarella');
user.validate().then(function(errors){
ok(Ember.isEmpty(get(errors, 'firstName')));
ok(Ember.isEmpty(get(errors, 'lastName')));
equal(get(user, 'isValid'), true);
start();
});
});
});
});
});
test('can be mixed into an object controller', function() {
var Controller, controller, user;
Controller = Ember.ObjectController.extend(EmberValidations.Mixin, {
container: buildContainer(),
validations: {
name: {
presence: true
}
}
});
Ember.run(function() {
controller = Controller.create();
});
equal(get(controller, 'isValid'), false);
user = Ember.Object.create();
Ember.run(function() {
set(controller, 'content', user);
});
equal(get(controller, 'isValid'), false);
Ember.run(function() {
set(user, 'name', 'Brian');
});
equal(get(controller, 'isValid'), true);
});
module('Array controller');
test('can be mixed into an array controller', function() {
var Controller, controller, user, UserController;
var container = buildContainer();
UserController = Ember.ObjectController.extend(EmberValidations.Mixin, {
container: buildContainer(),
validations: {
name: {
presence: true
}
}
});
container.register('controller:User', UserController);
Controller = Ember.ArrayController.extend(EmberValidations.Mixin, {
itemController: 'User',
container: container,
validations: {
'[]': true
}
});
Ember.run(function() {
controller = Controller.create();
});
equal(get(controller, 'isValid'), true);
user = Ember.Object.create();
Ember.run(function() {
controller.pushObject(user);
});
equal(get(controller, 'isValid'), false);
Ember.run(function() {
set(user, 'name', 'Brian');
});
equal(get(controller, 'isValid'), true);
Ember.run(function() {
set(user, 'name', undefined);
});
equal(get(controller, 'isValid'), false);
Ember.run(function() {
get(controller, 'content').removeObject(user);
});
equal(get(controller, 'isValid'), true);
});
var Profile, profile;
module('Relationship validators', {
setup: function() {
Profile = Ember.Object.extend(EmberValidations.Mixin, {
container: buildContainer(),
validations: {
title: {
presence: true
}
}
});
Ember.run(function() {
profile = Profile.create({hey: 'yo'});
});
User = Ember.Object.extend(EmberValidations.Mixin, {
container: buildContainer()
});
}
});
test('validates other validatable property', function() {
Ember.run(function() {
user = User.create({
validations: {
profile: true
}
});
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
set(user, 'profile', profile);
});
equal(get(user, 'isValid'), false);
Ember.run(function() {
set(profile, 'title', 'Developer');
});
equal(get(user, 'isValid'), true);
});
// test('validates custom validator', function() {
// Ember.run(function() {
// user = User.create({
// profile: profile,
// validations: [AgeValidator]
// });
// });
// equal(get(user, 'isValid'), false);
// Ember.run(function() {
// set(user, 'age', 22);
// });
// equal(get(user, 'isValid'), true);
// });
test('validates array of validable objects', function() {
var friend1, friend2;
Ember.run(function() {
user = User.create({
validations: {
friends: true
}
});
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
set(user, 'friends', Ember.A());
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
friend1 = User.create({
validations: {
name: {
presence: true
}
}
});
});
Ember.run(function() {
user.friends.pushObject(friend1);
});
equal(get(user, 'isValid'), false);
Ember.run(function() {
set(friend1, 'name', 'Stephanie');
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
friend2 = User.create({
validations: {
name: {
presence: true
}
}
});
user.friends.pushObject(friend2);
});
equal(get(user, 'isValid'), false);
Ember.run(function() {
user.friends.removeObject(friend2);
});
equal(get(user, 'isValid'), true);
});
test('revalidates arrays when they are replaced', function() {
var friend1, friend2;
Ember.run(function() {
user = User.create({
validations: {
friends: true
}
});
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
set(user, 'friends', Ember.A());
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
friend1 = User.create({
validations: {
name: {
presence: true
}
}
});
});
Ember.run(function() {
set(user, 'friends', Ember.A([friend1]));
});
equal(get(user, 'isValid'), false);
Ember.run(function() {
set(friend1, 'name', 'Stephanie');
});
equal(get(user, 'isValid'), true);
Ember.run(function() {
friend2 = User.create({
validations: {
name: {
presence: true
}
}
});
set(user, 'friends', Ember.A([friend1, friend2]));
});
equal(get(user, 'isValid'), false);
Ember.run(function() {
user.friends.removeObject(friend2);
});
equal(get(user, 'isValid'), true);
});
/*globals define, registry, requirejs*/
requirejs.rollback = function() {
for(var entry in this.backupEntries) {
this.entries[entry] = this.backupEntries[entry];
}
};
requirejs.backup = function() {
this.backupEntries = {};
for(var entry in this.entries) {
this.backupEntries[entry] = this.entries[entry];
}
};
module('validator class lookup order', {
setup: function() {
requirejs.backup();
requirejs.clear();
requirejs.rollback();
User = Ember.Object.extend(EmberValidations.Mixin, {
container: buildContainer()
});
},
teardown: function() {
requirejs.clear();
requirejs.rollback();
}
});
test('should lookup in project namespace first', function() {
var dummyValidatorCalled = false;
var nativeValidatorCalled = false;
define('ember-validations/validators/local/presence', [], function() {
nativeValidatorCalled = true;
return Base.extend({
call: Ember.K
});
});
define('dummy/validators/local/presence', [], function() {
dummyValidatorCalled = true;
return Base.extend({
call: Ember.K
});
});
Ember.run(function() {
user = User.create({
validations: {
name: {
presence: true
}
}
});
});
ok(!nativeValidatorCalled, 'should not have preferred ember-validation\'s presence validator');
ok(dummyValidatorCalled, 'should have preferred my applications presence validator');
});
test('will lookup both local and remote validators of similar name', function() {
var localValidatorCalled = false;
var remoteValidatorCalled = false;
define('ember-validations/validators/local/uniqueness', [], function() {
localValidatorCalled = true;
return Base.extend({
call: Ember.K
});
});
define('ember-validations/validators/remote/uniqueness', [], function() {
remoteValidatorCalled = true;
return Base.extend({
call: Ember.K
});
});
Ember.run(function() {
user = User.create({
validations: {
name: {
uniqueness: true
}
}
});
});
ok(localValidatorCalled, 'should call local uniqueness validator');
ok(remoteValidatorCalled, 'should call remote uniqueness validator');
});
test('should prefer lookup in just "validators" before "native"', function() {
var dummyValidatorCalled = false;
var nativeValidatorCalled = false;
define('ember-validations/validators/local/presence', [], function() {
nativeValidatorCalled = true;
return Base.extend({
call: Ember.K
});
});
define('dummy/validators/presence', [], function() {
dummyValidatorCalled = true;
return Base.extend({
call: Ember.K
});
});
Ember.run(function() {
user = User.create({
validations: {
name: {
presence: true
}
}
});
});
ok(!nativeValidatorCalled, 'should not have preferred ember-validation\'s presence validator');
ok(dummyValidatorCalled, 'should have preferred my applications presence validator');
});
module('inline validations', {
setup: function() {
User = Ember.Object.extend(EmberValidations.Mixin, {
container: buildContainer()
});
}
});
test("mixed validation syntax", function() {
Ember.run(function() {
user = User.create({
validations: {
name: {
inline: EmberValidations.validator(function() {
return 'it failed';
})
}
}
});
});
deepEqual(['it failed'], get(user, 'errors.name'));
});
test("concise validation syntax", function() {
Ember.run(function() {
user = User.create({
validations: {
name: EmberValidations.validator(function() {
return 'it failed';
})
}
});
});
deepEqual(['it failed'], get(user, 'errors.name'));
});
|
'use strict';
const fs = require( 'fs' );
const path = require( 'path' );
const bo = require( 'business-objects' );
const DaoBase = bo.dataAccess.DaoBase;
const Argument = bo.system.Argument;
const daoBuilder = function ( dataSource, modelPath, modelName ) {
try {
if (typeof dataSource !== 'string' || dataSource.trim().length === 0)
throw new Error( 'The dataSource argument of daoBuilder function must be a non-empty string.' );
if (typeof modelPath !== 'string' || modelPath.trim().length === 0)
throw new Error( 'The modelPath argument of daoBuilder function must be a non-empty string.' );
if (typeof modelName !== 'string' || modelName.trim().length === 0)
throw new Error( 'The modelName argument of daoBuilder function must be a non-empty string.' );
const modelStats = fs.statSync( modelPath );
if (!modelStats.isFile())
throw new Error( 'The modelPath argument of daoBuilder function is not a valid file path: ' + modelPath );
const fileName = path.basename( modelPath );
const relativePath = modelPath.slice( __dirname.length, -fileName.length );
const daoPath = path.join( __dirname, relativePath, dataSource, fileName );
const daoStats = fs.statSync( daoPath );
if (!daoStats.isFile())
throw new Error( 'The required data access file does not exist: ' + daoPath );
const daoCtor = require( daoPath );
if (typeof daoCtor !== 'function')
throw new Error( 'The data access file must return a constructor: ' + daoPath );
return Argument.check( new daoCtor() ).forMandatory()
.asType( DaoBase, daoPath + ' must inherit DaoBase type.' );
}
catch( e ) {
console.log( e.message );
throw e;
}
};
module.exports = daoBuilder;
|
import styled from 'styled-components';
export default styled.div`
height: ${props => 2 * props.size}px;
width: ${props => 2 * props.size}px;
`;
|
var searchData=
[
['cache',['Cache',['../class_engine_1_1_core_1_1_animation_cache.html#a2d677b71c3a959135f28bd15709d8c01',1,'Engine::Core::AnimationCache']]]
];
|
import React, {Component} from 'react'
const firebase = window.firebase
class HelloWorld extends Component {
componentWillMount() {
const fbref = this.props.data.getRef({fbref:'', parentRef:this.props.fbref})
this.cancelListener = this.props.data.setListener({ref:fbref, callback:(data) => this.setState({data})})
this.setState({fbref})
}
componentWillUnmount() { if (this.cancelListener) this.cancelListener() }
render() {
return (
<div>
<p>Here is some data in a subcomponent:</p>
<p>
{
JSON.stringify(this.state.data, '/n')
}
</p>
</div>
)
}
}
export default HelloWorld |
/*!
* jQuery Raty - A Star Rating Plugin - http://wbotelhos.com/raty
* -------------------------------------------------------------------
*
* jQuery Raty is a plugin that generates a customizable star rating.
*
* Licensed under The MIT License
*
* @version 2.4.5
* @since 2010.06.11
* @author Washington Botelho
* @documentation wbotelhos.com/raty
* @twitter twitter.com/wbotelhos
*
* Usage:
* -------------------------------------------------------------------
* $('#star').raty();
*
* <div id="star"></div>
*
*/
;(function($) {
var methods = {
init: function(settings) {
return this.each(function() {
var self = this,
$this = $(self).empty();
self.opt = $.extend(true, {}, $.fn.raty.defaults, settings);
$this.data('settings', self.opt);
if (typeof self.opt.number == 'function') {
self.opt.number = self.opt.number.call(self);
} else {
self.opt.number = methods.between(self.opt.number, 0, 20)
}
if (self.opt.path.substring(self.opt.path.length - 1, self.opt.path.length) != '/') {
self.opt.path += '/';
}
if (typeof self.opt.score == 'function') {
self.opt.score = self.opt.score.call(self);
}
if (self.opt.score) {
self.opt.score = methods.between(self.opt.score, 0, self.opt.number);
}
for (var i = 1; i <= self.opt.number; i++) {
$('<img />', {
src : self.opt.path + ((!self.opt.score || self.opt.score < i) ? self.opt.starOff : self.opt.starOn),
alt : i,
title : (i <= self.opt.hints.length && self.opt.hints[i - 1] !== null) ? self.opt.hints[i - 1] : i
}).appendTo(self);
if (self.opt.space) {
$this.append((i < self.opt.number) ? ' ' : '');
}
}
self.stars = $this.children('img:not(".raty-cancel")');
self.score = $('<input />', { type: 'hidden', name: self.opt.scoreName }).appendTo(self);
if (self.opt.score && self.opt.score > 0) {
self.score.val(self.opt.score);
methods.roundStar.call(self, self.opt.score);
}
if (self.opt.iconRange) {
methods.fill.call(self, self.opt.score);
}
methods.setTarget.call(self, self.opt.score, self.opt.targetKeep);
var space = self.opt.space ? 4 : 0,
width = self.opt.width || (self.opt.number * self.opt.size + self.opt.number * space);
if (self.opt.cancel) {
self.cancel = $('<img />', { src: self.opt.path + self.opt.cancelOff, alt: 'x', title: self.opt.cancelHint, 'class': 'raty-cancel' });
if (self.opt.cancelPlace == 'left') {
$this.prepend(' ').prepend(self.cancel);
} else {
$this.append(' ').append(self.cancel);
}
width += (self.opt.size + space);
}
if (self.opt.readOnly) {
methods.fixHint.call(self);
if (self.cancel) {
self.cancel.hide();
}
} else {
$this.css('cursor', 'pointer');
methods.bindAction.call(self);
}
$this.css('width', width);
});
}, between: function(value, min, max) {
return Math.min(Math.max(parseFloat(value), min), max);
}, bindAction: function() {
var self = this,
$this = $(self);
$this.mouseleave(function() {
var score = self.score.val() || undefined;
methods.initialize.call(self, score);
methods.setTarget.call(self, score, self.opt.targetKeep);
if (self.opt.mouseover) {
self.opt.mouseover.call(self, score);
}
});
var action = self.opt.half ? 'mousemove' : 'mouseover';
if (self.opt.cancel) {
self.cancel.mouseenter(function() {
$(this).attr('src', self.opt.path + self.opt.cancelOn);
self.stars.attr('src', self.opt.path + self.opt.starOff);
methods.setTarget.call(self, null, true);
if (self.opt.mouseover) {
self.opt.mouseover.call(self, null);
}
}).mouseleave(function() {
$(this).attr('src', self.opt.path + self.opt.cancelOff);
if (self.opt.mouseover) {
self.opt.mouseover.call(self, self.score.val() || null);
}
}).click(function(evt) {
self.score.removeAttr('value');
if (self.opt.click) {
self.opt.click.call(self, null, evt);
}
});
}
self.stars.bind(action, function(evt) {
var value = parseInt(this.alt, 10);
if (self.opt.half) {
var position = parseFloat((evt.pageX - $(this).offset().left) / self.opt.size),
diff = (position > .5) ? 1 : .5;
value = parseFloat(this.alt) - 1 + diff;
methods.fill.call(self, value);
if (self.opt.precision) {
value = value - diff + position;
}
methods.showHalf.call(self, value);
} else {
methods.fill.call(self, value);
}
$this.data('score', value);
methods.setTarget.call(self, value, true);
if (self.opt.mouseover) {
self.opt.mouseover.call(self, value, evt);
}
}).click(function(evt) {
self.score.val((self.opt.half || self.opt.precision) ? $this.data('score') : this.alt);
if (self.opt.click) {
self.opt.click.call(self, self.score.val(), evt);
}
});
}, cancel: function(isClick) {
return $(this).each(function() {
var self = this,
$this = $(self);
if ($this.data('readonly') === true) {
return this;
}
if (isClick) {
methods.click.call(self, null);
} else {
methods.score.call(self, null);
}
self.score.removeAttr('value');
});
}, click: function(score) {
return $(this).each(function() {
if ($(this).data('readonly') === true) {
return this;
}
methods.initialize.call(this, score);
if (this.opt.click) {
this.opt.click.call(this, score);
} else {
methods.error.call(this, 'you must add the "click: function(score, evt) { }" callback.');
}
methods.setTarget.call(this, score, true);
});
}, error: function(message) {
$(this).html(message);
$.error(message);
}, fill: function(score) {
var self = this,
number = self.stars.length,
count = 0,
$star ,
star ,
icon ;
for (var i = 1; i <= number; i++) {
$star = self.stars.eq(i - 1);
if (self.opt.iconRange && self.opt.iconRange.length > count) {
star = self.opt.iconRange[count];
if (self.opt.single) {
icon = (i == score) ? (star.on || self.opt.starOn) : (star.off || self.opt.starOff);
} else {
icon = (i <= score) ? (star.on || self.opt.starOn) : (star.off || self.opt.starOff);
}
if (i <= star.range) {
$star.attr('src', self.opt.path + icon);
}
if (i == star.range) {
count++;
}
} else {
if (self.opt.single) {
icon = (i == score) ? self.opt.starOn : self.opt.starOff;
} else {
icon = (i <= score) ? self.opt.starOn : self.opt.starOff;
}
$star.attr('src', self.opt.path + icon);
}
}
}, fixHint: function() {
var $this = $(this),
score = parseInt(this.score.val(), 10),
hint = this.opt.noRatedMsg;
if (!isNaN(score) && score > 0) {
hint = (score <= this.opt.hints.length && this.opt.hints[score - 1] !== null) ? this.opt.hints[score - 1] : score;
}
$this.data('readonly', true).css('cursor', 'default').attr('title', hint);
this.score.attr('readonly', 'readonly');
this.stars.attr('title', hint);
}, getScore: function() {
var score = [],
value ;
$(this).each(function() {
value = this.score.val();
score.push(value ? parseFloat(value) : undefined);
});
return (score.length > 1) ? score : score[0];
}, readOnly: function(isReadOnly) {
return this.each(function() {
var $this = $(this);
if ($this.data('readonly') === isReadOnly) {
return this;
}
if (this.cancel) {
if (isReadOnly) {
this.cancel.hide();
} else {
this.cancel.show();
}
}
if (isReadOnly) {
$this.unbind();
$this.children('img').unbind();
methods.fixHint.call(this);
} else {
methods.bindAction.call(this);
methods.unfixHint.call(this);
}
$this.data('readonly', isReadOnly);
});
}, reload: function() {
return methods.set.call(this, {});
}, roundStar: function(score) {
var diff = (score - Math.floor(score)).toFixed(2);
if (diff > this.opt.round.down) {
var icon = this.opt.starOn; // Full up: [x.76 .. x.99]
if (diff < this.opt.round.up && this.opt.halfShow) { // Half: [x.26 .. x.75]
icon = this.opt.starHalf;
} else if (diff < this.opt.round.full) { // Full down: [x.00 .. x.5]
icon = this.opt.starOff;
}
this.stars.eq(Math.ceil(score) - 1).attr('src', this.opt.path + icon);
} // Full down: [x.00 .. x.25]
}, score: function() {
return arguments.length ? methods.setScore.apply(this, arguments) : methods.getScore.call(this);
}, set: function(settings) {
this.each(function() {
var $this = $(this),
actual = $this.data('settings'),
clone = $this.clone().removeAttr('style').insertBefore($this);
$this.remove();
clone.raty($.extend(actual, settings));
});
return $(this.selector);
}, setScore: function(score) {
return $(this).each(function() {
if ($(this).data('readonly') === true) {
return this;
}
methods.initialize.call(this, score);
methods.setTarget.call(this, score, true);
});
}, setTarget: function(value, isKeep) {
if (this.opt.target) {
var $target = $(this.opt.target);
if ($target.length == 0) {
methods.error.call(this, 'target selector invalid or missing!');
}
var score = value;
if (!isKeep || score === undefined) {
score = this.opt.targetText;
} else {
if (this.opt.targetType == 'hint') {
score = (score === null && this.opt.cancel)
? this.opt.cancelHint
: this.opt.hints[Math.ceil(score - 1)];
} else {
score = this.opt.precision
? parseFloat(score).toFixed(1)
: score;
}
}
if (this.opt.targetFormat.indexOf('{score}') < 0) {
methods.error.call(this, 'template "{score}" missing!');
}
if (value !== null) {
score = this.opt.targetFormat.toString().replace('{score}', score);
}
if ($target.is(':input')) {
$target.val(score);
} else {
$target.html(score);
}
}
}, showHalf: function(score) {
var diff = (score - Math.floor(score)).toFixed(1);
if (diff > 0 && diff < .6) {
this.stars.eq(Math.ceil(score) - 1).attr('src', this.opt.path + this.opt.starHalf);
}
}, initialize: function(score) {
score = !score ? 0 : methods.between(score, 0, this.opt.number);
methods.fill.call(this, score);
if (score > 0) {
if (this.opt.halfShow) {
methods.roundStar.call(this, score);
}
this.score.val(score);
}
}, unfixHint: function() {
for (var i = 0; i < this.opt.number; i++) {
this.stars.eq(i).attr('title', (i < this.opt.hints.length && this.opt.hints[i] !== null) ? this.opt.hints[i] : i);
}
$(this).data('readonly', false).css('cursor', 'pointer').removeAttr('title');
this.score.attr('readonly', 'readonly');
}
};
$.fn.raty = 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!');
}
};
$.fn.raty.defaults = {
cancel : false,
cancelHint : 'cancel this rating!',
cancelOff : 'cancel-off.png',
cancelOn : 'cancel-on.png',
cancelPlace : 'left',
click : undefined,
half : false,
halfShow : true,
hints : ['bad', 'poor', 'regular', 'good', 'gorgeous'],
iconRange : undefined,
mouseover : undefined,
noRatedMsg : 'not rated yet',
number : 5,
path : 'img/',
precision : false,
round : { down: .25, full: .6, up: .76 },
readOnly : false,
score : undefined,
scoreName : 'score',
single : false,
size : 16,
space : true,
starHalf : 'star-half.png',
starOff : 'star-off.png',
starOn : 'star-on.png',
target : undefined,
targetFormat : '{score}',
targetKeep : false,
targetText : '',
targetType : 'hint',
width : undefined
};
})(jQuery);
|
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var aurelia_binding_1 = require("aurelia-binding");
var aurelia_templating_1 = require("aurelia-templating");
var aurelia_dependency_injection_1 = require("aurelia-dependency-injection");
var ko = require("knockout");
var KnockoutBindable = /** @class */ (function () {
function KnockoutBindable(observerLocator) {
this.subscriptions = []; // Knockout subscriptions
this.observerLocator = observerLocator;
}
/**
* Applys all values from a data object (usually the activation data) to the corresponding instance fields
* in the current view model if they are marked as @bindable. By default all matching values from the data object
* are applied. To only apply observable values set the last parameter to `true`. Subscriptions are created
* for all Knockout observables in the data object to update the view-model values respectively.
*
* @param data - the data object
* @param target - the target view model
* @param applyOnlyObservables - `true` if only observable values should be applied, false by default.
*/
KnockoutBindable.prototype.applyBindableValues = function (data, target, applyOnlyObservables) {
var _this = this;
data = data || {};
target = target || {};
applyOnlyObservables = applyOnlyObservables === undefined ? true : applyOnlyObservables;
Object.keys(data).forEach(function (key) {
var outerValue = data[key];
var isObservable = ko.isObservable(outerValue);
if (isObservable || !applyOnlyObservables) {
var observer_1 = _this.getObserver(target, key);
if (observer_1 && observer_1 instanceof aurelia_templating_1.BehaviorPropertyObserver) { // check if inner property is @bindable
observer_1.setValue(isObservable ? ko.unwrap(outerValue) : outerValue);
}
if (isObservable) {
_this.subscriptions.push(outerValue.subscribe(function (newValue) {
observer_1.setValue(newValue);
}));
}
}
});
var originalUnbind = target.unbind;
target.unbind = function () {
_this.subscriptions.forEach(function (subscription) { return subscription.dispose(); });
_this.subscriptions = [];
if (originalUnbind) {
originalUnbind.call(target);
}
};
};
/** internal: do not use */
KnockoutBindable.prototype.getObserver = function (target, key) {
return this.observerLocator.getObserver(target, key);
};
KnockoutBindable = __decorate([
aurelia_dependency_injection_1.inject(aurelia_binding_1.ObserverLocator)
], KnockoutBindable);
return KnockoutBindable;
}());
exports.KnockoutBindable = KnockoutBindable;
|
import Component from '@ember/component';
import layout from '../templates/components/b-card-list';
export default Component.extend({
tagName: 'div',
layout,
classNames: ['b-card-list']
});
|
"use strict";
/**
* Created by anzer on 2016/11/8.
*/
let nunjucks = require('nunjucks');
class ViewEngine {
view(viewName, data) {
return nunjucks.render(viewName, data);
}
}
module.exports = function (app) {
return {
install(app){
nunjucks.configure(app.VIEW_PATH);
app.viewEngine('nunjucks', ViewEngine);
}
}
}
|
/*!
* jquery.event.drag - v 2.2
* Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
* Open Source MIT License - http://threedubmedia.com/code/license
*/
// Created: 2008-06-04
// Updated: 2012-05-21
// REQUIRES: jquery 1.7.x
;(function( $ ){
// add the jquery instance method
$.fn.drag = function( str, arg, opts ){
// figure out the event type
var type = typeof str == "string" ? str : "",
// figure out the event handler...
fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
// fix the event type
if ( type.indexOf("drag") !== 0 )
type = "drag"+ type;
// were options passed
opts = ( str == fn ? arg : opts ) || {};
// trigger or bind event handler
return fn ? this.bind( type, opts, fn ) : this.trigger( type );
};
// local refs (increase compression)
var $event = $.event,
$special = $event.special,
// configure the drag special event
drag = $special.drag = {
// these are the default settings
defaults: {
which: 1, // mouse button pressed to start drag sequence
distance: 0, // distance dragged before dragstart
not: ':input', // selector to suppress dragging on target elements
handle: null, // selector to match handle target elements
relative: false, // true to use "position", false to use "offset"
drop: true, // false to suppress drop events, true or selector to allow
click: false // false to suppress click events after dragend (no proxy)
},
// the key name for stored drag data
datakey: "dragdata",
// prevent bubbling for better performance
noBubble: true,
// count bound related events
add: function( obj ){
// read the interaction data
var data = $.data( this, drag.datakey ),
// read any passed options
opts = obj.data || {};
// count another realted event
data.related += 1;
// extend data options bound with this event
// don't iterate "opts" in case it is a node
$.each( drag.defaults, function( key, def ){
if ( opts[ key ] !== undefined )
data[ key ] = opts[ key ];
});
},
// forget unbound related events
remove: function(){
$.data( this, drag.datakey ).related -= 1;
},
// configure interaction, capture settings
setup: function(){
// check for related events
if ( $.data( this, drag.datakey ) )
return;
// initialize the drag data with copied defaults
var data = $.extend({ related:0 }, drag.defaults );
// store the interaction data
$.data( this, drag.datakey, data );
// bind the mousedown event, which starts drag interactions
$event.add( this, "touchstart mousedown", drag.init, data );
// prevent image dragging in IE...
if ( this.attachEvent )
this.attachEvent("ondragstart", drag.dontstart );
},
// destroy configured interaction
teardown: function(){
var data = $.data( this, drag.datakey ) || {};
// check for related events
if ( data.related )
return;
// remove the stored data
$.removeData( this, drag.datakey );
// remove the mousedown event
$event.remove( this, "touchstart mousedown", drag.init );
// enable text selection
drag.textselect( true );
// un-prevent image dragging in IE...
if ( this.detachEvent )
this.detachEvent("ondragstart", drag.dontstart );
},
// initialize the interaction
init: function( event ){
// sorry, only one touch at a time
if ( drag.touched )
return;
// the drag/drop interaction data
var dd = event.data, results;
// check the which directive
if ( event.which != 0 && dd.which > 0 && event.which != dd.which )
return;
// check for suppressed selector
if ( $( event.target ).is( dd.not ) )
return;
// check for handle selector
if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length )
return;
drag.touched = event.type == 'touchstart' ? this : null;
dd.propagates = 1;
dd.mousedown = this;
dd.interactions = [ drag.interaction( this, dd ) ];
dd.target = event.target;
dd.pageX = event.pageX;
dd.pageY = event.pageY;
dd.dragging = null;
// handle draginit event...
results = drag.hijack( event, "draginit", dd );
// early cancel
if ( !dd.propagates )
return;
// flatten the result set
results = drag.flatten( results );
// insert new interaction elements
if ( results && results.length ){
dd.interactions = [];
$.each( results, function(){
dd.interactions.push( drag.interaction( this, dd ) );
});
}
// remember how many interactions are propagating
dd.propagates = dd.interactions.length;
// locate and init the drop targets
if ( dd.drop !== false && $special.drop )
$special.drop.handler( event, dd );
// disable text selection
drag.textselect( false );
// bind additional events...
if ( drag.touched )
$event.add( drag.touched, "touchmove touchend", drag.handler, dd );
else
$event.add( document, "mousemove mouseup", drag.handler, dd );
// helps prevent text selection or scrolling
if ( !drag.touched || dd.live )
return false;
},
// returns an interaction object
interaction: function( elem, dd ){
var offset = $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 };
return {
drag: elem,
callback: new drag.callback(),
droppable: [],
offset: offset
};
},
// handle drag-releatd DOM events
handler: function( event ){
// read the data before hijacking anything
var dd = event.data;
// handle various events
switch ( event.type ){
// mousemove, check distance, start dragging
case !dd.dragging && 'touchmove':
event.preventDefault();
case !dd.dragging && 'mousemove':
// drag tolerance, x� + y� = distance�
if ( Math.pow( event.pageX-dd.pageX, 2 ) + Math.pow( event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) )
break; // distance tolerance not reached
event.target = dd.target; // force target from "mousedown" event (fix distance issue)
drag.hijack( event, "dragstart", dd ); // trigger "dragstart"
if ( dd.propagates ) // "dragstart" not rejected
dd.dragging = true; // activate interaction
// mousemove, dragging
case 'touchmove':
event.preventDefault();
case 'mousemove':
if ( dd.dragging ){
// trigger "drag"
drag.hijack( event, "drag", dd );
if ( dd.propagates ){
// manage drop events
if ( dd.drop !== false && $special.drop )
$special.drop.handler( event, dd ); // "dropstart", "dropend"
break; // "drag" not rejected, stop
}
event.type = "mouseup"; // helps "drop" handler behave
}
// mouseup, stop dragging
case 'touchend':
case 'mouseup':
default:
if ( drag.touched )
$event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events
else
$event.remove( document, "mousemove mouseup", drag.handler ); // remove page events
if ( dd.dragging ){
if ( dd.drop !== false && $special.drop )
$special.drop.handler( event, dd ); // "drop"
drag.hijack( event, "dragend", dd ); // trigger "dragend"
}
drag.textselect( true ); // enable text selection
// if suppressing click events...
if ( dd.click === false && dd.dragging )
$.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 );
dd.dragging = drag.touched = false; // deactivate element
break;
}
},
// re-use event object for custom events
hijack: function( event, type, dd, x, elem ){
// not configured
if ( !dd )
return;
// remember the original event and type
var orig = { event:event.originalEvent, type:event.type },
// is the event drag related or drog related?
mode = type.indexOf("drop") ? "drag" : "drop",
// iteration vars
result, i = x || 0, ia, $elems, callback,
len = !isNaN( x ) ? x : dd.interactions.length;
// modify the event type
event.type = type;
// remove the original event
event.originalEvent = null;
// initialize the results
dd.results = [];
// handle each interacted element
do if ( ia = dd.interactions[ i ] ){
// validate the interaction
if ( type !== "dragend" && ia.cancelled )
continue;
// set the dragdrop properties on the event object
callback = drag.properties( event, dd, ia );
// prepare for more results
ia.results = [];
// handle each element
$( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){
// identify drag or drop targets individually
callback.target = subject;
// force propagtion of the custom event
event.isPropagationStopped = function(){ return false; };
// handle the event
result = subject ? $event.dispatch.call( subject, event, callback ) : null;
// stop the drag interaction for this element
if ( result === false ){
if ( mode == "drag" ){
ia.cancelled = true;
dd.propagates -= 1;
}
if ( type == "drop" ){
ia[ mode ][p] = null;
}
}
// assign any dropinit elements
else if ( type == "dropinit" )
ia.droppable.push( drag.element( result ) || subject );
// accept a returned proxy element
if ( type == "dragstart" )
ia.proxy = $( drag.element( result ) || ia.drag )[0];
// remember this result
ia.results.push( result );
// forget the event result, for recycling
delete event.result;
// break on cancelled handler
if ( type !== "dropinit" )
return result;
});
// flatten the results
dd.results[ i ] = drag.flatten( ia.results );
// accept a set of valid drop targets
if ( type == "dropinit" )
ia.droppable = drag.flatten( ia.droppable );
// locate drop targets
if ( type == "dragstart" && !ia.cancelled )
callback.update();
}
while ( ++i < len )
// restore the original event & type
event.type = orig.type;
event.originalEvent = orig.event;
// return all handler results
return drag.flatten( dd.results );
},
// extend the callback object with drag/drop properties...
properties: function( event, dd, ia ){
var obj = ia.callback;
// elements
obj.drag = ia.drag;
obj.proxy = ia.proxy || ia.drag;
// starting mouse position
obj.startX = dd.pageX;
obj.startY = dd.pageY;
// current distance dragged
obj.deltaX = event.pageX - dd.pageX;
obj.deltaY = event.pageY - dd.pageY;
// original element position
obj.originalX = ia.offset.left;
obj.originalY = ia.offset.top;
// adjusted element position
obj.offsetX = obj.originalX + obj.deltaX;
obj.offsetY = obj.originalY + obj.deltaY;
// assign the drop targets information
obj.drop = drag.flatten( ( ia.drop || [] ).slice() );
obj.available = drag.flatten( ( ia.droppable || [] ).slice() );
return obj;
},
// determine is the argument is an element or jquery instance
element: function( arg ){
if ( arg && ( arg.jquery || arg.nodeType == 1 ) )
return arg;
},
// flatten nested jquery objects and arrays into a single dimension array
flatten: function( arr ){
return $.map( arr, function( member ){
return member && member.jquery ? $.makeArray( member ) :
member && member.length ? drag.flatten( member ) : member;
});
},
// toggles text selection attributes ON (true) or OFF (false)
textselect: function( bool ){
$( document )[ bool ? "unbind" : "bind" ]("selectstart", drag.dontstart )
.css("MozUserSelect", bool ? "" : "none" );
// .attr("unselectable", bool ? "off" : "on" )
document.unselectable = bool ? "off" : "on";
},
// suppress "selectstart" and "ondragstart" events
dontstart: function(){
return false;
},
// a callback instance contructor
callback: function(){}
};
// callback methods
drag.callback.prototype = {
update: function(){
if ( $special.drop && this.available.length )
$.each( this.available, function( i ){
$special.drop.locate( this, i );
});
}
};
// patch $.event.$dispatch to allow suppressing clicks
var $dispatch = $event.dispatch;
$event.dispatch = function( event ){
if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){
$.removeData( this, "suppress."+ event.type );
return;
}
return $dispatch.apply( this, arguments );
};
// event fix hooks for touch events...
var touchHooks =
$event.fixHooks.touchstart =
$event.fixHooks.touchmove =
$event.fixHooks.touchend =
$event.fixHooks.touchcancel = {
props: "clientX clientY pageX pageY screenX screenY".split( " " ),
filter: function( event, orig ) {
if ( orig ){
var touched = ( orig.touches && orig.touches[0] )
|| ( orig.changedTouches && orig.changedTouches[0] )
|| null;
// iOS webkit: touchstart, touchmove, touchend
if ( touched )
$.each( touchHooks.props, function( i, prop ){
event[ prop ] = touched[ prop ];
});
}
return event;
}
};
// share the same special event configuration with related events...
$special.draginit = $special.dragstart = $special.dragend = drag;
})( jQuery );
|
'use strict';
/**
* @namespace Divhide
* @module Divhide
*
*/
/**
*
* Divhide Library - An isomorphic library for you to use on javascript supported
* devices.
*
* @type Object
* @alias module:Divhide
* @enum generators
*/
var Common = {
/**
* Type utility
* @type {module:Divhide/Type}
*/
Type: require("./Common/Type"),
/**
* Coerce utility
* @type {module:Divhide/Coerce}
*/
Coerce: require("./Common/Coerce"),
/**
* Array utility
* @type {module:Divhide/Arr}
*/
Arr: require("./Common/Arr"),
/**
* Object helper
* @type {module:Divhide/Obj}
*/
Obj: require("./Common/Obj"),
/**
* I18N utility
*/
I18N: {
/**
* I18NString utility
*/
String: require("./Common/I18N/String"),
},
/**
*
* Exceptions package
*
*/
Exception: {
/**
* Exception Class
*/
Exception: require("./Common/Exception/Exception"),
/**
* ExceptionList
*/
ExceptionList: require("./Common/Exception/ExceptionList"),
},
/**
* Url utility
* @type {module:Divhide/Url}
*/
Url: require("./Common/Url"),
/**
* Chain facility
* @type {module:Divhide/Chain}
*/
Chain: require("./Common/Chain"),
/**
* Default Assertion instance utility. This provides access to the default
* Assert functions.
* @type {module:Divhide/Assert}
*/
Assert: require("./Common/Assert"),
/**
* Assertion utility
* @type {module:Divhide/Assertion}
*/
Assertion: require("./Common/Assertion"),
/**
* Schema utility
* @type {module:Divhide/Schema}
*/
Schema: require("./Common/Schema"),
/**
* Custom Schema
* @type {module:Divhide/CustomSchema}
*/
CustomSchema: require("./Common/CustomSchema"),
/**
* Traverse functions
* @type {module:Divhide/CustomSchema}
*/
Traverse: require("./Common/Traverse")
};
module.exports = Common;
|
'use strict';
const INDEX_PATH = '../src/index';
jest.unmock(INDEX_PATH);
jest.mock('react-native', () => {
//Local store each time the mockule is loaded.
var fakeStore = {};
return ({
AsyncStorage: {
setItem: jest.fn((key, value) => {
return new Promise((resolve, reject) => {
fakeStore[key] = value;
resolve(null);
});
}),
getItem: jest.fn((key) => {
return new Promise((resolve, reject) => {
if (key in fakeStore) {
resolve(fakeStore[key]);
}
resolve(null);
});
}),
removeItem: jest.fn((key) => {
return new Promise((resolve, reject) => {
delete fakeStore[key];
resolve(null);
});
}),
getAllKeys: jest.fn(() => {
var keys = [];
for(var key in fakeStore) {
if(fakeStore.hasOwnProperty(key)) {
keys.push(key);
}
}
return new Promise((resolve) => {
resolve(keys);
});
}),
getStore: jest.fn(() => {
return fakeStore;
}),
}
});
});
const mockUrl = "https://fake.firbase.com/";
const mockDbRefPath = "my/db/ref";
const mockDbRefUrl = mockUrl + mockDbRefPath;
const makeMockDbRef = () => {
return {
root: mockUrl,
toString: function() { return mockDbRefUrl; },
on: function(eventType, callback, cancelCallbackOrContext, context) {
if(context) {
callback.bind(context)("fake-data");
} else if (cancelCallbackOrContext && typeof(cancelCallbackOrContext) !== 'function') {
callback.bind(cancelCallbackOrContext)("fake-data");
} else {
callback("fake-data");
}
},
off: jest.fn(),
once: jest.fn((eventType, callback, cancelCallbackOrContext, context) => {
if(context) {
callback.bind(context)("fake-data");
} else if (cancelCallbackOrContext && typeof(cancelCallbackOrContext) !== 'function') {
callback.bind(cancelCallbackOrContext)("fake-data");
} else {
callback("fake-data");
}
}),
}
}
const makeMultiDataDbRef = () => {
return {
root: mockUrl,
toString: function() { return mockDbRefUrl; },
on: function(eventType, callback, cancelCallbackOrContext, context) {
if(context) {
callback.bind(context)("fake-data1");
callback.bind(context)("fake-data2");
} else if (cancelCallbackOrContext && typeof(cancelCallbackOrContext) !== 'function') {
callback.bind(cancelCallbackOrContext)("fake-data1");
callback.bind(cancelCallbackOrContext)("fake-data2");
} else {
callback("fake-data1");
callback("fake-data2");
}
},
off: jest.fn(),
}
}
var mockForbiddenDbRef = {
root: mockUrl,
toString: function() { return mockDbRefUrl; },
on: function(eventType, callback, cancelCallbackOrContext, context) {
if(context) {
cancelCallbackOrContext.bind(context)("error");
} else {
cancelCallbackOrContext("error");
}
}
}
describe('onValue', () => {
it('should call snapCallback followed by processedCallback', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
const processedCallback = jest.fn();
return cachedDb.onValue(mockDbRef, snapCallback, processedCallback).then(() => {
expect(snapCallback).toBeCalledWith("fake-data");
expect(processedCallback).toBeCalledWith("processed");
});
});
it('should call the cancelled callback if permission is denied', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const snapCallback = jest.fn();
const processedCallback = jest.fn();
const cancelledCallback = jest.fn();
return cachedDb.onValue(mockForbiddenDbRef, snapCallback, processedCallback, cancelledCallback).then(() => {
expect(snapCallback.mock.calls.length).toBe(0);
expect(processedCallback.mock.calls.length).toBe(0);
expect(cancelledCallback.mock.calls.length).toBe(1);
expect(cancelledCallback).toBeCalledWith("error");
});
});
it('should pass context if no cancelled callback is provided', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce('processed');
const snapCallbackWrapper = function(snap) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return snapCallback(snap);
}
const processedCallback = jest.fn();
const processedCallbackWrapper = function(data) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
processedCallback(data);
}
return cachedDb.onValue(mockDbRef, snapCallbackWrapper, processedCallbackWrapper, context).then(() => {
expect(snapCallback.mock.calls.length).toBe(1);
expect(snapCallback).toBeCalledWith("fake-data");
expect(processedCallback.mock.calls.length).toBe(1);
expect(processedCallback).toBeCalledWith("processed");
});
});
it('should pass context to snapCallback and processedCallback if a cancelled callback is provided but not called', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce('processed');
const snapCallbackWrapper = function(snap) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return snapCallback(snap);
}
const processedCallback = jest.fn();
const processedCallbackWrapper = function(data) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
processedCallback(data);
}
const cancelledCallback = jest.fn();
return cachedDb.onValue(mockDbRef, snapCallbackWrapper, processedCallbackWrapper, context).then(() => {
expect(snapCallback.mock.calls.length).toBe(1);
expect(snapCallback).toBeCalledWith("fake-data");
expect(processedCallback.mock.calls.length).toBe(1);
expect(processedCallback).toBeCalledWith("processed");
});
});
it('should pass context to cancelledCallback if a cancelled callback is provided and called', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
const processedCallback = jest.fn();
const cancelledCallback = jest.fn();
const cancelledCallbackWrapper = function(err) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return cancelledCallback(err);
}
return cachedDb.onValue(mockForbiddenDbRef, snapCallback, processedCallback, cancelledCallbackWrapper, context).then(() => {
expect(snapCallback.mock.calls.length).toBe(0);
expect(processedCallback.mock.calls.length).toBe(0);
expect(cancelledCallback.mock.calls.length).toBe(1);
expect(cancelledCallback).toBeCalledWith("error");
});
});
it('should call processedCallback if there is data in the cache, but not snapCallback', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
snapCallback.mockReturnValueOnce("processed2");
const processedCallback = jest.fn();
return cachedDb.onValue(mockDbRef, snapCallback, processedCallback)
.then(() => { return cachedDb.offValue(mockDbRef) })
.then(() => { return cachedDb.onValue(mockDbRef, snapCallback, processedCallback); })
.then(() => {
expect(snapCallback.mock.calls.length).toBe(2);
expect(snapCallback).toBeCalledWith("fake-data");
expect(processedCallback.mock.calls.length).toBe(3);
expect(processedCallback.mock.calls[0][0]).toBe("processed"); //Original call
expect(processedCallback.mock.calls[1][0]).toBe("processed"); //Cached data
expect(processedCallback.mock.calls[2][0]).toBe("processed2"); // second call.
expect(mockDbRef.off.mock.calls.length).toBe(1);
});
});
it('should call processedCallback with correct context if there is data in the cache, but not snapCallback (context as 5th param)', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
snapCallback.mockReturnValueOnce("processed2");
const processedCallback = jest.fn();
const processedCallbackWrapper = function(param) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return processedCallback(param);
}
return cachedDb.onValue(mockDbRef, snapCallback, processedCallback)
.then(() => { return cachedDb.offValue(mockDbRef) })
.then(() => { return cachedDb.onValue(mockDbRef, snapCallback, processedCallbackWrapper, context); })
.then(() => {
expect(snapCallback.mock.calls.length).toBe(2);
expect(snapCallback).toBeCalledWith("fake-data");
expect(processedCallback.mock.calls.length).toBe(3);
expect(processedCallback.mock.calls[0][0]).toBe("processed"); //Original call
expect(processedCallback.mock.calls[1][0]).toBe("processed"); //Cached data
expect(processedCallback.mock.calls[2][0]).toBe("processed2"); // second call.
expect(mockDbRef.off.mock.calls.length).toBe(1);
});
});
it('should call processedCallback with correct context if there is data in the cache, but not snapCallback (context as 6th param)', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
snapCallback.mockReturnValueOnce("processed2");
const processedCallback = jest.fn();
const processedCallbackWrapper = function(param) {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return processedCallback(param);
}
return cachedDb.onValue(mockDbRef, snapCallback, processedCallback)
.then(() => { return cachedDb.offValue(mockDbRef) })
.then(() => { return cachedDb.onValue(mockDbRef, snapCallback, processedCallbackWrapper, ()=>{}, context); })
.then(() => {
expect(snapCallback.mock.calls.length).toBe(2);
expect(snapCallback).toBeCalledWith("fake-data");
expect(processedCallback.mock.calls.length).toBe(3);
expect(processedCallback.mock.calls[0][0]).toBe("processed"); //Original call
expect(processedCallback.mock.calls[1][0]).toBe("processed"); //Cached data
expect(processedCallback.mock.calls[2][0]).toBe("processed2"); // second call.
expect(mockDbRef.off.mock.calls.length).toBe(1);
});
});
});
describe('onChildAdded', () => {
it('should call dataAvailableCallback followed by snapCallback, but not cachedCallback if no cached data is available', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
const cachedCallback = jest.fn();
const dataAvailableCallback = jest.fn();
const snapCallback = jest.fn();
return cachedDb.onChildAdded(mockDbRef, cachedCallback, dataAvailableCallback, snapCallback).then(() => {
expect(cachedCallback.mock.calls.length).toBe(0);
expect(dataAvailableCallback.mock.calls.length).toBe(1);
expect(snapCallback.mock.calls.length).toBe(1);
});
});
it('should call all callbacks if cached data is available', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
//Add something to the cache.
AsyncStorage.setItem(`@FirebaseLocalCache:child_added:${mockDbRefPath}`, JSON.stringify('cached data'));
const cachedCallback = jest.fn();
const dataAvailableCallback = jest.fn();
const snapCallback = jest.fn();
return cachedDb.onChildAdded(mockDbRef, cachedCallback, dataAvailableCallback, snapCallback).then(() => {
expect(cachedCallback.mock.calls.length).toBe(1);
expect(cachedCallback).toBeCalledWith('cached data');
expect(dataAvailableCallback.mock.calls.length).toBe(1);
expect(snapCallback.mock.calls.length).toBe(1);
});
});
it('should call only call dataAvailableCallback once', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
//Make sure multiple sets of data arrive.
var mockDbRef = makeMultiDataDbRef();
//Add something to the cache.
AsyncStorage.setItem(`@FirebaseLocalCache:child_added:${mockDbRefPath}`, JSON.stringify('cached data'));
const cachedCallback = jest.fn();
const dataAvailableCallback = jest.fn();
const snapCallback = jest.fn();
return cachedDb.onChildAdded(mockDbRef, cachedCallback, dataAvailableCallback, snapCallback).then(() => {
expect(cachedCallback.mock.calls.length).toBe(1);
expect(cachedCallback).toBeCalledWith('cached data');
expect(dataAvailableCallback.mock.calls.length).toBe(1);
expect(snapCallback.mock.calls.length).toBe(2);
expect(snapCallback.mock.calls[0][0]).toBe("fake-data1");
expect(snapCallback.mock.calls[1][0]).toBe("fake-data2");
});
});
it('should pass context correctly with no errorCallback', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
//Make sure multiple sets of data arrive.
var mockDbRef = makeMockDbRef();
//Add something to the cache.
AsyncStorage.setItem(`@FirebaseLocalCache:child_added:${mockDbRefPath}`, JSON.stringify('cached data'));
const cachedCallback = jest.fn();
const cachedCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return cachedCallback();
}
const dataAvailableCallback = jest.fn();
const dataAvailableCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return dataAvailableCallback();
}
const snapCallback = jest.fn();
const snapCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return snapCallback();
}
return cachedDb.onChildAdded(mockDbRef, cachedCallbackWrapper, dataAvailableCallbackWrapper, snapCallbackWrapper, context).then(() => {
expect(cachedCallback.mock.calls.length).toBe(1);
expect(dataAvailableCallback.mock.calls.length).toBe(1);
expect(snapCallback.mock.calls.length).toBe(1);
});
});
it('should pass context correctly with errorCallback', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
//Make sure multiple sets of data arrive.
var mockDbRef = makeMockDbRef();
//Add something to the cache.
AsyncStorage.setItem(`@FirebaseLocalCache:child_added:${mockDbRefPath}`, JSON.stringify('cached data'));
const cachedCallback = jest.fn();
const cachedCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return cachedCallback();
}
const dataAvailableCallback = jest.fn();
const dataAvailableCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return dataAvailableCallback();
}
const snapCallback = jest.fn();
const snapCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return snapCallback();
}
const errorCallback = jest.fn();
return cachedDb.onChildAdded(mockDbRef, cachedCallbackWrapper, dataAvailableCallbackWrapper, snapCallbackWrapper, errorCallback, context).then(() => {
expect(errorCallback.mock.calls.length).toBe(0);
expect(cachedCallback.mock.calls.length).toBe(1);
expect(dataAvailableCallback.mock.calls.length).toBe(1);
expect(snapCallback.mock.calls.length).toBe(1);
});
});
it('should call errorCallback if error occurs and pass context', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
//Use forbidden db ref.
var mockDbRef = mockForbiddenDbRef;
const cachedCallback = jest.fn();
const dataAvailableCallback = jest.fn();
const snapCallback = jest.fn();
const errorCallback = jest.fn();
const errorCallbackWrapper = function() {
expect(this).toBeDefined();
expect(this.str).toBe('test');
return errorCallback();
}
return cachedDb.onChildAdded(mockDbRef, cachedCallback, dataAvailableCallback, snapCallback, errorCallbackWrapper, context).then(() => {
expect(errorCallback.mock.calls.length).toBe(1);
expect(cachedCallback.mock.calls.length).toBe(0);
expect(dataAvailableCallback.mock.calls.length).toBe(0);
expect(snapCallback.mock.calls.length).toBe(0);
});
});
});
describe('offChildAdded', () => {
it('should write data to the async store', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
//Expected path to store at.
const storageKey = `@FirebaseLocalCache:child_added:${mockDbRefPath}`
return cachedDb.offChildAdded(mockDbRef, 'amIStored')
.then(() => AsyncStorage.getItem(storageKey))
.then((result) => {
expect(result).toBe(JSON.stringify('amIStored'));
});
});
});
describe('twice', () => {
it('should call snapCallback followed by processedCallback, with no cached data', (done) => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
const processedCallback = function(data) {
expect(snapCallback).toBeCalled();
expect(data).toBe('processed');
done();
};
cachedDb.twice(mockDbRef, snapCallback, processedCallback);
});
it('should call processedCallback with cached data, then snapCallback followed by processedCallback', (done) => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
const context = {str: 'test'};
var mockDbRef = makeMockDbRef();
var count = 0;
AsyncStorage.setItem(`@FirebaseLocalCache:twice:${mockDbRefPath}`, JSON.stringify('cached'));
const snapCallback = jest.fn(function() {
//Check context.
expect(this).toBeDefined();
expect(this.str).toBe('test');
return 'processed';
});
const processedCallback = function(data) {
//Check context.
expect(this).toBeDefined();
expect(this.str).toBe('test');
if(count == 0) {
expect(data).toBe('cached');
count++;
} else {
expect(snapCallback.mock.calls.length).toBe(1);
expect(data).toBe('processed');
AsyncStorage.getItem(`@FirebaseLocalCache:twice:${mockDbRefPath}`).then((item) => {
expect(JSON.parse(item)).toBe('processed');
done();
})
}
};
cachedDb.twice(mockDbRef, snapCallback, processedCallback, context);
});
});
describe('clearCacheForRef', () => {
it('should delete items in the AsyncStorage for a particular db ref', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
const processedCallback = jest.fn();
return cachedDb.onValue(mockDbRef, snapCallback, processedCallback)
.then(() => { return cachedDb.offValue(mockDbRef) }) //put something in the cache.
.then(() => {
var count = 0;
for(var propName in AsyncStorage.getStore()) {
if(AsyncStorage.getStore().hasOwnProperty(propName)) {
count++;
}
}
expect(count).toBe(1);
}).then(() => {
return cachedDb.clearCacheForRef(mockDbRef);
}).then(() => {
for(var propName in AsyncStorage.getStore()) {
if(AsyncStorage.getStore().hasOwnProperty(propName)) {
console.log(propName + ': ' + AsyncStorage.getStore()[propName]);
expect('unreachable code').toBe('not reached...');
}
}
});
});
});
describe('clearCache', () => {
it('should delete all items in the AsyncStorage', () => {
const { AsyncStorage } = require('react-native');
const cachedDb = require(INDEX_PATH);
var mockDbRef = makeMockDbRef();
const snapCallback = jest.fn();
snapCallback.mockReturnValueOnce("processed");
const processedCallback = jest.fn();
return cachedDb.onValue(mockDbRef, snapCallback, processedCallback)
.then(() => { return cachedDb.offValue(mockDbRef) }) //put something in the cache.
.then(() => {
var count = 0;
for(var propName in AsyncStorage.getStore()) {
if(AsyncStorage.getStore().hasOwnProperty(propName)) {
count++;
}
}
expect(count).toBe(1);
}).then(() => {
return cachedDb.clearCache();
}).then(() => {
for(var propName in AsyncStorage.getStore()) {
if(AsyncStorage.getStore().hasOwnProperty(propName)) {
console.log('Uh oh! >>> ' + propName + ': ' + AsyncStorage.getStore()[propName]);
expect('unreachable code').toBe('not reached...');
}
}
});
});
}); |
var fs = require('fs');
var readline = require('readline');
var program = require('commander');
var _ = require('lodash');
program
.arguments('<file>')
.parse(process.argv);
if (program.args.length === 0) {
console.log('No file given');
process.exit(1);
}
var machine = {
sp: 0,
instructions: [],
registers: {
a: 0,
b: 0
},
hlf: function(register) {
this._store(register, this.registers[register] / 2);
this.sp += 1;
},
tpl: function(register) {
this._store(register, this.registers[register] * 3);
this.sp += 1;
},
inc: function(register) {
this._store(register, this.registers[register] + 1);
this.sp += 1;
},
jmp: function(offset) {
this.sp += offset;
},
jie: function(register, offset) {
if (this.registers[register] % 2 == 0) {
this.sp += offset;
} else {
this.sp += 1;
}
},
jio: function(register, offset) {
if (this.registers[register] == 1) {
this.sp += offset;
} else {
this.sp += 1;
}
},
_store: function(register, value) {
this.registers[register] = Math.max(Math.floor(value), 0);
},
run: function(options) {
_.extend(this, _.defaultsDeep(_.pick(options || {}, 'sp', 'registers'), {
sp: 0,
registers: {
a: 0,
b: 0
}
}));
while (this.sp >= 0 && this.sp < this.instructions.length) {
var instruction = this.instructions[this.sp];
instruction.call(this, this);
}
}
};
function parseLine(line) {
var r;
var match;
if (match = line.match(/hlf (\w)/)) {
machine.instructions.push(() => machine.hlf(match[1]));
} else if (match = line.match(/tpl (\w)/)) {
machine.instructions.push(() => machine.tpl(match[1]));
} else if (match = line.match(/inc (\w)/)) {
machine.instructions.push(() => machine.inc(match[1]));
} else if (match = line.match(/jmp ([+-]?\d+)/)) {
var offset = parseInt(match[1]);
machine.instructions.push(() => machine.jmp(offset));
} else if (match = line.match(/jie (\w), ([+-]?\d+)/)) {
var offset = parseInt(match[2]);
machine.instructions.push(() => machine.jie(match[1], offset));
} else if (match = line.match(/jio (\w), ([+-]?\d+)/)) {
var offset = parseInt(match[2]);
machine.instructions.push(() => machine.jio(match[1], offset));
} else {
throw new Error('Unknown instruction: ' + line);
}
}
readline.createInterface({
input: require('fs').createReadStream(program.args[0]),
terminal: false
})
.on('line', parseLine)
.on('close', function() {
console.log('Part 1');
machine.run();
console.log('b: ' + machine.registers.b);
console.log('Part 2');
machine.run({registers: {a: 1 }});
console.log('b: ' + machine.registers.b);
});
|
'use strict';
// Dependencies
var path = require('path');
// Command: env NODE_ENV
// Project configurations
if (process.env.NODE_ENV === 'production') {
module.exports = {
name: 'RESTful API - ExperTIC',
enviroment: 'production',
db: 'mongodb://127.0.0.1/expertic',
keys: {
movil: 'bd90b560496a464c303794163b9cd60b1d301adf17179dd122f994cedeccbe484a0e049acf643c09f3f2f4fcedb04f9c8d3549f95374875e36f531b3874b04b5',
app: 'bd90b560496a464c303794163b9cd60b1d301adf17179dd122f994cedeccbe484a0e049acf643c09f3f2f4fcedb04f9c8d3549f95374875e36f531b3874b04b5'
},
server: {
port: 3000,
host: "0.0.0.0",
distFolder: path.resolve(__dirname, '../app')
},
mail: {
service: 'gmail',
auth: {
user: '',
pass: ''
}
}
};
}
else {
module.exports = {
name: 'RESTful API - ExperTIC',
enviroment: 'development',
db: 'mongodb://127.0.0.1/expertic-dev',
keys: {
movil: 'bd90b560496a464c303794163b9cd60b1d301adf17179dd122f994cedeccbe484a0e049acf643c09f3f2f4fcedb04f9c8d3549f95374875e36f531b3874b04b5',
app: 'bd90b560496a464c303794163b9cd60b1d301adf17179dd122f994cedeccbe484a0e049acf643c09f3f2f4fcedb04f9c8d3549f95374875e36f531b3874b04b5'
},
server: {
port: 3000,
host: "0.0.0.0",
distFolder: path.resolve(__dirname, '../app')
},
mail: {
service: 'gmail',
auth: {
user: '',
pass: ''
}
}
};
}
|
// @flow
import type { Action } from 'redux'
import type { Epic } from 'redux-observable'
import type { Contest, ContestCategory, Venue } from './contests'
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/of'
import 'rxjs/add/operator/catch'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/switchMap'
import ApiService from '../../services/ApiService'
import { SELECT_CONTEST } from './contests'
// Types
export type Appearance = {|
participantName: string,
participantRole: string,
instrumentName: string,
ageGroup: string,
result?: Result,
|}
export type Performance = {|
id: string,
stageTime: string,
categoryName: string,
ageGroup: string,
predecessorHostCountry?: string,
predecessorHostName?: string,
appearances: Array<Appearance>,
pieces: Array<Piece>,
|}
export type PerformancesState = {
fetchTimetablePerformancesError: boolean,
fetchingTimetablePerformances: boolean,
timetablePerformances: ?Array<Performance>,
fetchResultPerformancesError: boolean,
fetchingResultPerformances: boolean,
resultPerformances: ?Array<Performance>,
}
type Piece = {|
title: string,
composerName: string,
composerBorn: string,
composerDied: string,
|}
export type Result = {|
points: number,
prize?: string,
rating?: string,
advancesToNextRound: boolean,
|}
// Actions
const FETCH_TIMETABLE_PERFORMANCES = 'performances/FETCH_TIMETABLE_PERFORMANCES'
const FETCH_TIMETABLE_PERFORMANCES_SUCCESS = 'performances/FETCH_TIMETABLE_PERFORMANCES_SUCCESS'
const FETCH_TIMETABLE_PERFORMANCES_FAILURE = 'performances/FETCH_TIMETABLE_PERFORMANCES_FAILURE'
const FETCH_RESULT_PERFORMANCES = 'performances/FETCH_RESULT_PERFORMANCES'
const FETCH_RESULT_PERFORMANCES_SUCCESS = 'performances/FETCH_RESULT_PERFORMANCES_SUCCESS'
const FETCH_RESULT_PERFORMANCES_FAILURE = 'performances/FETCH_RESULT_PERFORMANCES_FAILURE'
export function fetchTimetablePerformances(contest: Contest, venue: Venue, date: string): Action {
return {
type: FETCH_TIMETABLE_PERFORMANCES,
contest,
venue,
date,
}
}
function fetchTimetablePerformancesSuccess(performances: Array<Performance>): Action {
return {
type: FETCH_TIMETABLE_PERFORMANCES_SUCCESS,
performances,
}
}
function fetchTimetablePerformancesFailure(error: Error): Action {
return {
type: FETCH_TIMETABLE_PERFORMANCES_FAILURE,
error,
}
}
export function fetchResultPerformances(contest: Contest, contestCategory: ContestCategory): Action {
return {
type: FETCH_RESULT_PERFORMANCES,
contest,
contestCategory,
}
}
function fetchResultPerformancesSuccess(performances: Array<Performance>): Action {
return {
type: FETCH_RESULT_PERFORMANCES_SUCCESS,
performances,
}
}
function fetchResultPerformancesFailure(error: Error): Action {
return {
type: FETCH_RESULT_PERFORMANCES_FAILURE,
error,
}
}
// Epics
export const fetchTimetablePerformancesEpic: Epic = action$ =>
action$.ofType(FETCH_TIMETABLE_PERFORMANCES)
.switchMap(action =>
ApiService.get$(`/contests/${action.contest.id}/performances`, {
venue_id: action.venue.id,
date: action.date,
})
.map((performancesJSON) => fetchTimetablePerformancesSuccess(
parsePerformances(performancesJSON))
)
.catch(error => Observable.of(fetchTimetablePerformancesFailure(error)))
)
export const fetchResultPerformancesEpic: Epic = action$ =>
action$.ofType(FETCH_RESULT_PERFORMANCES)
.switchMap(action =>
ApiService.get$(`/contests/${action.contest.id}/performances`, {
contest_category_id: action.contestCategory.id,
results_public: 1,
})
.map((performancesJSON) => fetchResultPerformancesSuccess(
parsePerformances(performancesJSON))
)
.catch(error => Observable.of(fetchResultPerformancesFailure(error)))
)
// Helpers
function parsePerformances(performancesJSON: Array<Object>): Array<Performance> {
return performancesJSON.map(json => {
return {
id: json.id,
stageTime: json.stage_time,
categoryName: json.category_name,
ageGroup: json.age_group,
predecessorHostCountry: json.predecessor_host_country,
predecessorHostName: json.predecessor_host_name,
appearances: json.appearances.map(parseAppearance),
pieces: json.pieces.map(parsePiece),
}
})
}
function parseAppearance(json: Object): Appearance {
return {
participantName: json.participant_name,
participantRole: json.participant_role,
instrumentName: json.instrument_name,
ageGroup: json.age_group,
result: json.result && parseResult(json.result),
}
}
function parsePiece(json: Object): Piece {
return {
title: json.title,
composerName: json.composer_name,
composerBorn: json.composer_born,
composerDied: json.composer_died,
}
}
function parseResult(json: Object): Result {
return {
points: json.points,
prize: json.prize,
rating: json.rating,
advancesToNextRound: json.advances_to_next_round,
}
}
// Reducer
const initialState = {
fetchTimetablePerformancesError: false,
fetchingTimetablePerformances: false,
timetablePerformances: null,
fetchResultPerformancesError: false,
fetchingResultPerformances: false,
resultPerformances: null,
}
export default function performancesReducer(state: PerformancesState = initialState, action: Action): PerformancesState {
switch (action.type) {
case FETCH_TIMETABLE_PERFORMANCES:
return {
...state,
fetchingTimetablePerformances: true,
}
case FETCH_TIMETABLE_PERFORMANCES_SUCCESS:
return {
...state,
timetablePerformances: action.performances,
fetchTimetablePerformancesError: false,
fetchingTimetablePerformances: false,
}
case FETCH_TIMETABLE_PERFORMANCES_FAILURE:
return {
...state,
timetablePerformances: null,
fetchTimetablePerformancesError: true,
fetchingTimetablePerformances: false,
}
case FETCH_RESULT_PERFORMANCES:
return {
...state,
resultPerformances: null,
fetchingResultPerformances: true,
}
case FETCH_RESULT_PERFORMANCES_SUCCESS:
return {
...state,
resultPerformances: action.performances,
fetchResultPerformancesError: false,
fetchingResultPerformances: false,
}
case FETCH_RESULT_PERFORMANCES_FAILURE:
return {
...state,
resultPerformances: null,
fetchResultPerformancesError: true,
fetchingResultPerformances: false,
}
case SELECT_CONTEST:
return initialState
default:
return state
}
}
|
angular
.module('inspinia')
.controller('DashboardCtrl', function ($scope, Restangular) {
$scope.projects = [];
$scope.createProjectForm = true;
$scope.projectForm = null;
Restangular
.all('projects')
.getList()
.then(function(projects) {
$scope.projects = projects;
});
Restangular
.oneUrl('projects', config.api + '/projects/new')
.get()
.then(function(projectForm) {
$scope.projectForm = projectForm.children;
console.log($scope.projectForm);
});
}); |
define(function(require) {
function headerController($rootScope,$scope,user,$location,socket) {
socket.connect();
socket.on('connected',function(res){ console.log(res);
$scope.totalOnlineUsers = res.totalOnlineUsers;
socket.me = res.me;
});
/* Chat controller */
$rootScope.loading = false;
$scope.signout = function(){
user.logout(function(){
$rootScope.usertoken = undefined;
$location.path('login/signin');
});
};
}
return headerController;
}); |
"use strict";
var sqlite3 = require('sqlite3').verbose(),
fs = require('fs'),
path = require('path'),
parse = require('csv-parse'),
xml2js = require('xml2js'),
databaseName = 'hsuehshan.sql',
dataDirectory = 'hsuehshan_data',
vehicleDirectory = 'traffic',
vehicleDetectorFilename = 'Traffic_Vehicle Detector_info.csv',
deviceIds = null,
db = new sqlite3.Database(databaseName)
;
// adapted from http://stackoverflow.com/users/716248/chjj on http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search
function walk(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};
function createDatabase() {
db.run('CREATE TABLE IF NOT EXISTS device (vdid TEXT, roadDir TEXT, roadNum TEXT, lng REAL, lat REAL, queueIndex INT, prev INT, next INT, prevDist INT, nextDist INT)');
db.run('CREATE TABLE IF NOT EXISTS collection (rowid INT PRIMARY KEY, device INT, status SMALLINT, collectTime DATETIME, interval INT) WITHOUT ROWID');
db.run('CREATE TABLE IF NOT EXISTS lane (rowid INT PRIMARY KEY, collection INT, num SMALLINT, speed SMALLINT, occupy SMALLINT, S SMALLINT, T SMALLINT, L SMALLINT) WITHOUT ROWID');
console.log('Database created and tables defined.');
}
function dataDirectoryExists(cb) {
fs.exists('../' + dataDirectory + '/', cb);
}
function importDetectorInfo(cb) {
fs.readFile('../' + dataDirectory + '/' + vehicleDetectorFilename, 'utf8', function (err, data) {
if (err) return console.log(err);
parse(data, { delimiter: ',' }, function(err, output) {
for (var i = 1; i < output.length - 1; i++)
db.run('INSERT INTO device (vdid, roadDir, roadNum, lng, lat) VALUES (\''+output[i][0]+'\', \''+output[i][0][7]+'\', \''+output[i][0][6]+'\', '+output[i][2]+', '+output[i][1]+')');
console.log(output.length + ' devices imported.');
getDeviceList(function(devices) {
var southern = calculateQueuePointers(devices, 'S', 'nfbVD-5S-SDT-1.072'),
northern = calculateQueuePointers(devices, 'N', 'nfbVD-5N-TCIC-I-29.843'),
updateFunction = function(o) {
db.run('UPDATE device SET queueIndex = '+o.queueIndex+', prev = '+o.prev+', next = '+o.next+', prevDist = '+o.prevDist+', nextDist = '+o.nextDist+' WHERE rowid = '+o.id);
};
southern.forEach(updateFunction);
northern.forEach(updateFunction);
console.log('Queue pointers updated on devices.');
createLocalDetectorMapping(cb);
});
});
});
}
// credit: http://www.movable-type.co.uk/scripts/latlong.html
function meterDistance(p1, p2) {
var R = 6371000;
var φ1 = p1.lat * Math.PI / 180;
var φ2 = p2.lat * Math.PI / 180;
var Δφ = (p2.lat-p1.lat) * Math.PI / 180;
var Δλ = (p2.lng-p1.lng) * Math.PI / 180;
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
function calculateQueuePointers(devices, roadDir, startId) {
var start = devices.filter(function(v) {
return v.vdid == startId;
})[0],
pool = devices.filter(function(v) {
return v.roadDir == roadDir && v.vdid != startId;
}),
sorted = [start];
while (pool.length > 0) {
var smallestDistance = 40075000,
smallestIndex = 0;
for (var i = 0; i < pool.length; i++) {
var d = meterDistance(start, pool[i]);
if (d < smallestDistance) {
smallestDistance = d;
smallestIndex = i;
}
}
sorted.push(pool[smallestIndex]);
pool.splice(smallestIndex, 1);
}
for (var i = 0; i < sorted.length; i++) {
sorted[i].queueIndex = i;
sorted[i].prev = (i > 0 ? sorted[i-1].id : null);
sorted[i].prevDist = (i > 0 ? meterDistance(sorted[i-1], sorted[i]) : null);
sorted[i].next = (i < sorted.length - 1 ? sorted[i+1].id : null);
sorted[i].nextDist = (i < sorted.length - 1 ? meterDistance(sorted[i+1], sorted[i]) : null);
}
return sorted;
}
function createLocalDetectorMapping(cb) {
db.all('SELECT rowid AS id, vdid FROM device', function(err, rows) {
deviceIds = {};
for (var i = 0; i < rows.length; i++)
deviceIds[rows[i].vdid] = rows[i].id;
cb();
});
}
function importVehicleInfo(startDate, endDate) {
var numCollections = 0, numLanes = 0,
convertStupidLaneXML = function(xml) {
var lane = {
num: xml.$.vsrid,
speed: xml.$.speed,
occupy: xml.$.laneoccupy
};
for (var i = 0; i < xml.cars.length; i++)
lane[xml.cars[i].$.carid] = xml.cars[i].$.volume;
return lane;
},
insertCollections = function(info, interval, cb) {
// note to self,.. ran into endless trouble using sqlite3 prepared statements. db.run() just works.
info.forEach(function(o, j) {
if (typeof deviceIds[o.$.vdid] == 'undefined') return;
numCollections++;
db.run('INSERT INTO collection VALUES ('+numCollections+','+deviceIds[o.$.vdid]+','+o.$.status+',\''+o.$.datacollecttime+'\','+interval+');');
o.lane.forEach(function(poo, k) {
var lane = convertStupidLaneXML(poo);
db.run('INSERT INTO lane VALUES ('+numLanes+','+numCollections+', '+lane.num+', '+lane.speed+', '+lane.occupy+', '+lane.S+', '+lane.T+', '+lane.L+');');
numLanes++;
});
});
cb();
};
db.get('SELECT MAX(rowid)+1 num FROM collection', function(err, collectionMax) {
numCollections = collectionMax.num | 0;
db.get('SELECT MAX(rowid)+1 num FROM lane', function(err, laneMax) {
numLanes = laneMax.num | 0;
walk('../' + dataDirectory + '/' + vehicleDirectory, function(err, results) {
if (err) return console.log(err);
// filter results to just xml files that are in the specified date range
results = results.filter(function(v) {
var e = v.substr(v.lastIndexOf('/') + 1);
return e.indexOf('.xml') != -1 && e.indexOf('_') == -1 && e > startDate && e < endDate;
});
console.log(numCollections + ':' + numLanes);
var parser = new xml2js.Parser(), counter = 0,
worker = function() {
if (counter < results.length - 1) {
counter++;
} else {
console.log('Finished import: Collections('+numCollections+'), Lanes('+numLanes+')');
return;
}
console.log('Processing: ' + counter + ' of ' + results.length + ' files.');
console.log(results[counter]);
fs.readFile(results[counter], function(err, data) {
try {
parser.parseString(data, function (err, r) {
insertCollections(r.XML_Head.Infos[0].Info, r.XML_Head.$.interval, function() {
setTimeout(worker, 10);
});
});
} catch (error) {
console.log('Error parsing whatever file we found in the directory. Just skip it.');
console.dir(error);
}
});
}
worker();
});
});
});
}
function getDataLimits(callback) {
db.all('SELECT substr(collectTime, 1, 10) date, SUM(L.S) / 155 activity FROM collection C INNER JOIN lane L ON (C.rowid = L.collection) GROUP BY substr(collectTime, 1, 10) ORDER BY collectTime', function(err, dates) {
callback({
dates: dates
});
});
};
function getTrafficForTime(time, callback) {
db.all('SELECT C.device, L.num, L.speed, L.occupy, L.S, L.T, L.L FROM collection C INNER JOIN lane L ON (C.rowid = L.collection) WHERE substr(collectTime, 1, 16) = \''+time+'\'', function(err, data) {
callback(data);
});
};
function getAggregatedTrafficForTime(time, callback) {
db.all('SELECT C.device device, COUNT(L.num) lanes, SUM(L.S) + SUM(L.T) + SUM(L.L) total, AVG(L.speed) speed FROM collection C INNER JOIN lane L ON (C.rowid = L.collection) WHERE substr(collectTime, 1, 16) = \''+time+'\' GROUP BY C.device', function(err, data) {
callback(data);
});
};
function getTimesForDay(date, callback) {
db.all('SELECT DISTINCT substr(collectTime, 12, 5) time FROM collection WHERE substr(collectTime, 1, 10) = \'' + date + '\'', function(err, data) {
callback(data.map(function(o) {
return o.time;
}));
});
};
function getDeviceList(callback) {
db.all("SELECT rowid AS id, * FROM device", function(err, data) {
callback(data);
});
};
function f2s(f) {
return f.toString().replace(/^[^\/]+\/\*!?/, '').replace(/\*\/[^\/]+$/, '');
}
function trainTrafficAtTimeNetwork() {
var synaptic = require('synaptic');
var Neuron = synaptic.Neuron,
Layer = synaptic.Layer,
Network = synaptic.Network,
Trainer = synaptic.Trainer,
Architect = synaptic.Architect,
sql = f2s(function() {/*
SELECT CASE WHEN D.roadDir = 'S' THEN 0 ELSE 1 END roadDir, D.queueIndex,
strftime('%w', replace(C.collectTime, '/', '-')) day, strftime('%H', replace(C.collectTime, '/', '-')) hour,
AVG(L.speed) speed
FROM collection C
INNER JOIN lane L ON (C.rowid = L.collection)
INNER JOIN device D ON (C.device = D.rowid)
WHERE L.speed <> 0
GROUP BY C.device, D.vdid, substr(C.collectTime, 1, 13)
*/});
db.all(sql, function(err, data) {
var set = data.map(function(o) {
return {
input: [parseInt(o.day), parseInt(o.hour), o.roadDir, o.queueIndex],
output: [o.speed]
};
});
console.log('set length: ' + set.length);
var net = new Architect.Perceptron(4, 6, 1);
var trainer = new Trainer(net);
var result = trainer.train(set, {
rate: 0.3,
iterations: 20000,
error: 0.05,
shuffle: true,
log: 100
});
console.log('****************************************');
console.dir(result);
});
}
// trainTrafficAtTimeNetwork();
// public functions
exports.aggregatedTrafficForTime = function(req, res) {
getAggregatedTrafficForTime(req.query.time, function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
});
};
exports.trafficForTime = function(req, res) {
getTrafficForTime(req.query.time, function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
});
};
exports.timesForDay = function(req, res) {
getTimesForDay(req.query.date, function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
});
};
exports.trafficLimits = function(req, res) {
getDataLimits(function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
});
};
exports.trafficVehicleDetectors = function(req, res) {
getDeviceList(function(data) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
});
};
exports.devices = function(req, res) {
getDeviceList(function(data) {
res.render('deviceList', {
title: 'Traffic Vehicle Detectors',
data: data
});
});
};
exports.map = function(req, res) {
res.render('map', {
title: 'Map'
});
};
exports.setup = function(req, res) {
var render = function(dataDirExists, numberOfDetectors) {
res.render('setup', {
title: 'Setup',
dataDirExists: dataDirExists,
numberOfDetectors: numberOfDetectors,
startDate: '20150501',
endDate: '20150504'
});
};
dataDirectoryExists(function(dataDirExists) {
fs.exists(databaseName, function(exists) {
if (exists) {
db.get('SELECT COUNT(vdid) num FROM device', function(err, numberOfDetectors) {
render(dataDirExists, numberOfDetectors ? numberOfDetectors.num : 0);
});
} else {
render(dataDirExists, 0);
}
});
});
};
// http://hsuehshantunnel.devpost.com/details/resources
exports.importDetectors = function(req, res) {
createDatabase();
importDetectorInfo(function() {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({st:'ok'}));
});
};
// http://hsuehshantunnel.devpost.com/details/resources
exports.importTraffic = function(req, res) {
createLocalDetectorMapping(function() {
importVehicleInfo(req.query.startDate, req.query.endDate);
});
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({st:'ok'}));
};
|
import babel from 'rollup-plugin-babel';
import eslint from 'rollup-plugin-eslint';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main.js',
dest: 'dist/main.min.js',
format: 'umd',
moduleName: 'vueBugsnag',
sourceMap: 'inline',
plugins: [
resolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs(),
eslint({ ignore: [ 'dist/**', ], }),
babel({ exclude: 'node_modules/**', }),
uglify(),
],
};
|
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
connect: {
options: {
port: 9999,
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: 'http://localhost:9999/src/devnomi-2015Test.html?coverage=true'
}
}
},
watch: {
update: {
files: ['src/devnomi-2015.js'],
tasks: ['newer:jshint:all']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: ['src/**/*']
}
},
jshint: {
options: {
jshintrc: '.jshintrc',
force: true,
reporter: require('jshint-junit-reporter'),
reporterOutput: "report/jshint-junit-output.xml"
},
all: [
'src/poker-core.js'
]
}
});
grunt.registerTask('default', [
'jshint:all',
'connect:livereload',
'watch'
]);
};
|
import _ from 'lodash';
import * as d3 from 'd3';
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import {BarChartWrapper, BarChartSvg} from './index.styles';
const DEFAULT_CHART_HEIGHT = 300;
const DEFAULT_MARGINS = {top: 40, right: 20, bottom: 60, left: 80};
const DEFAULT_MARGINS_SMALL = {top: 20, right: 10, bottom: 50, left: 60};
const BAR_CHART_BORDER_WIDTH = 6;
class BarChart extends Component {
constructor(props) {
super(props);
this.barChart = null;
this.debouncedResizeBarChart = _.debounce(this.resizeBarChart.bind(this), 350);
}
componentDidMount() {
const {
data,
yMax,
xAxisLabel,
yAxisLabel,
yAxisTicksCount,
showCounts = true,
formatCount = d3.format(',.0f'),
xAxisTickLabels,
} = this.props;
const width = this.getBarChartWidth();
let margins = {...DEFAULT_MARGINS, ...this.props.margins};
if (width < 600) {
margins = {...DEFAULT_MARGINS_SMALL, ..._.get(this.props.margins, 'sm')};
}
this.barChart = d3
.select(this.barChartRef)
.attr('width', width)
.attr('height', DEFAULT_CHART_HEIGHT + margins.top + margins.bottom);
// set the ranges
const xScale = d3
.scaleBand()
.domain(d3.range(0, data.length))
.range([0, width - margins.left - margins.right])
.padding(0.1);
const yScale = d3
.scaleLinear()
.domain([0, yMax || d3.max(data)])
.range([DEFAULT_CHART_HEIGHT, 0]);
const bars = this.barChart
.selectAll('.bar-chart-bar')
.data(data)
.enter()
.append('g')
.attr('class', 'bar-chart-bar')
.attr('transform', (d) => `translate(${margins.left}, ${margins.top})`);
// append the rectangles for the bar chart
bars
.append('rect')
.attr('x', (d, i) => xScale(i))
.attr('width', xScale.bandwidth())
.attr('y', (d) => yScale(d))
.attr('height', (d) => DEFAULT_CHART_HEIGHT - yScale(d));
// add the x-axis
let xAxis = d3.axisBottom(xScale).tickFormat((i) => _.get(xAxisTickLabels, i, i));
this.barChart
.append('g')
.attr('class', 'bar-chart-x-axis')
.attr('transform', `translate(${margins.left}, ${DEFAULT_CHART_HEIGHT + margins.top})`)
.call(xAxis);
// add the y-axis
let yAxis = d3.axisLeft(yScale).tickFormat((d) => formatCount(d));
if (typeof yAxisTicksCount !== 'undefined') {
yAxis = yAxis.ticks(yAxisTicksCount);
}
this.barChart
.append('g')
.attr('class', 'bar-chart-y-axis')
.call(yAxis)
.attr('transform', `translate(${margins.left}, ${margins.top})`);
// Bar height counts
if (showCounts) {
bars
.append('text')
.attr('class', 'bar-chart-height-counts')
.attr('x', (d, i) => xScale(i) + xScale.bandwidth() / 2)
.attr('y', (d) => yScale(d) - 4)
.text((d) => formatCount(d));
}
// X-axis label
this.barChart
.append('text')
.attr('class', 'bar-chart-x-axis-label')
.attr(
'transform',
`translate(${margins.left + (width - margins.left - margins.right) / 2}, ${
DEFAULT_CHART_HEIGHT + margins.top + margins.bottom - 10
})`
)
.text(xAxisLabel);
// Y-axis label
this.barChart
.append('text')
.attr('class', 'bar-chart-y-axis-label')
.attr('transform', 'rotate(-90)')
.attr('x', 0 - (DEFAULT_CHART_HEIGHT + margins.left) / 2)
.attr('y', width < 600 ? 20 : 26)
.text(yAxisLabel);
// Resize the bar chart on page resize.
window.addEventListener('resize', this.debouncedResizeBarChart);
}
componentWillUnmount() {
window.removeEventListener('resize', this.debouncedResizeBarChart);
}
getBarChartWidth() {
// Return width of wrapper element, minus border.
return (
document.querySelector('.bar-chart-wrapper').getBoundingClientRect().width -
BAR_CHART_BORDER_WIDTH
);
}
resizeBarChart() {
this.barChart.attr('width', this.getBarChartWidth());
}
render() {
return (
<BarChartWrapper className="bar-chart-wrapper">
<BarChartSvg ref={(r) => (this.barChartRef = r)} />
</BarChartWrapper>
);
}
}
BarChart.propTypes = {
data: PropTypes.array.isRequired,
yMax: PropTypes.number,
showCounts: PropTypes.bool,
formatCount: PropTypes.func,
xAxisLabel: PropTypes.string.isRequired,
yAxisLabel: PropTypes.string.isRequired,
xAxisTickLabels: PropTypes.array,
yAxisTicksCount: PropTypes.number,
};
export default BarChart;
|
const { Group } = require('../../../lib/db/models')
async function home (req, res, next) {
const groups = await Group.find({})
res.json({
groups
})
}
module.exports = home
|
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used to detect when a function becomes hot. */
var HOT_COUNT = 150;
/** Used as the size to cover large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for the max length and index of an array. */
var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1;
/** Used as the maximum length an array-like object. */
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
/** `Object#toString` result references. */
var funcTag = '[object Function]',
numberTag = '[object Number]',
objectTag = '[object Object]';
/** Used as a reference to the global object. */
var root = (typeof global == 'object' && global) || this;
/** Used to store lodash to test for bad extensions/shims. */
var lodashBizarro = root.lodashBizarro;
/** Used for native method references. */
var arrayProto = Array.prototype,
errorProto = Error.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype,
numberProto = Number.prototype,
stringProto = String.prototype;
/** Method and object shortcuts. */
var phantom = root.phantom,
amd = root.define && define.amd,
argv = root.process && process.argv,
ArrayBuffer = root.ArrayBuffer,
document = !phantom && root.document,
body = root.document && root.document.body,
create = Object.create,
fnToString = funcProto.toString,
freeze = Object.freeze,
JSON = root.JSON,
objToString = objectProto.toString,
noop = function() {},
params = root.arguments,
push = arrayProto.push,
slice = arrayProto.slice,
Symbol = root.Symbol,
system = root.system,
Uint8Array = root.Uint8Array,
WeakMap = root.WeakMap;
/** Math helpers. */
var add = function(x, y) { return x + y; },
doubled = function(n) { return n * 2; },
square = function(n) { return n * n; };
/** Used to set property descriptors. */
var defineProperty = (function() {
try {
var o = {},
func = Object.defineProperty,
result = func(o, o, o) && func;
} catch(e) {}
return result;
}());
/** The file path of the lodash file to test. */
var filePath = (function() {
var min = 0,
result = [];
if (phantom) {
result = params = phantom.args || require('system').args;
} else if (system) {
min = 1;
result = params = system.args;
} else if (argv) {
min = 2;
result = params = argv;
} else if (params) {
result = params;
}
var last = result[result.length - 1];
result = (result.length > min && !/test(?:\.js)?$/.test(last)) ? last : '../lodash.js';
if (!amd) {
try {
result = require('fs').realpathSync(result);
} catch(e) {}
try {
result = require.resolve(result);
} catch(e) {}
}
return result;
}());
/** The `ui` object. */
var ui = root.ui || (root.ui = {
'buildPath': filePath,
'loaderPath': '',
'isModularize': /\b(?:amd|commonjs|es6?|node|npm|(index|main)\.js)\b/.test(filePath),
'isStrict': /\bes6?\b/.test(filePath),
'urlParams': {}
});
/** The basename of the lodash file to test. */
var basename = /[\w.-]+$/.exec(filePath)[0];
/** Detect if in a Java environment. */
var isJava = !document && !!root.java;
/** Used to indicate testing a modularized build. */
var isModularize = ui.isModularize;
/** Detect if testing `npm` modules. */
var isNpm = isModularize && /\bnpm\b/.test([ui.buildPath, ui.urlParams.build]);
/** Detect if running in PhantomJS. */
var isPhantom = phantom || typeof callPhantom == 'function';
/** Detect if running in Rhino. */
var isRhino = isJava && typeof global == 'function' && global().Array === root.Array;
/** Detect if lodash is in strict mode. */
var isStrict = ui.isStrict;
/*--------------------------------------------------------------------------*/
// Exit early if going to run tests in a PhantomJS web page.
if (phantom && isModularize) {
var page = require('webpage').create();
page.onCallback = function(details) {
var coverage = details.coverage;
if (coverage) {
var fs = require('fs'),
cwd = fs.workingDirectory,
sep = fs.separator;
fs.write([cwd, 'coverage', 'coverage.json'].join(sep), JSON.stringify(coverage));
}
phantom.exit(details.failed ? 1 : 0);
};
page.onConsoleMessage = function(message) {
console.log(message);
};
page.onInitialized = function() {
page.evaluate(function() {
document.addEventListener('DOMContentLoaded', function() {
QUnit.done(function(details) {
details.coverage = window.__coverage__;
callPhantom(details);
});
});
});
};
page.open(filePath, function(status) {
if (status != 'success') {
console.log('PhantomJS failed to load page: ' + filePath);
phantom.exit(1);
}
});
console.log('test.js invoked with arguments: ' + JSON.stringify(slice.call(params)));
return;
}
/*--------------------------------------------------------------------------*/
/** Used to test Web Workers. */
var Worker = !(ui.isForeign || ui.isSauceLabs || isModularize) && (document && document.origin != 'null') && root.Worker;
/** Used to test host objects in IE. */
try {
var xml = new ActiveXObject('Microsoft.XMLDOM');
} catch(e) {}
/** Poison the free variable `root` in Node.js */
try {
Object.defineProperty(global.root, 'root', {
'configurable': true,
'enumerable': false,
'get': function() { throw new ReferenceError; }
});
} catch(e) {}
/** Use a single "load" function. */
var load = (!amd && typeof require == 'function')
? require
: (isJava ? root.load : noop);
/** The unit testing framework. */
var QUnit = root.QUnit || (root.QUnit = (
QUnit = load('../node_modules/qunitjs/qunit/qunit.js') || root.QUnit,
QUnit = QUnit.QUnit || QUnit
));
/** Load QUnit Extras and ES6 Set/WeakMap shims. */
(function() {
var paths = [
'./asset/set.js',
'./asset/weakmap.js',
'../node_modules/qunit-extras/qunit-extras.js'
];
var index = -1,
length = paths.length;
while (++index < length) {
var object = load(paths[index]);
if (object) {
object.runInContext(root);
}
}
}());
/** The `lodash` function to test. */
var _ = root._ || (root._ = (
_ = load(filePath) || root._,
_ = _._ || (isStrict = ui.isStrict = isStrict || 'default' in _, _['default']) || _,
(_.runInContext ? _.runInContext(root) : _)
));
/** Used to restore the `_` reference. */
var oldDash = root._;
/** List of latin-1 supplementary letters to basic latin letters. */
var burredLetters = [
'\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce',
'\xcf', '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde',
'\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee',
'\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff'
];
/** List of combining diacritical marks for spanning multiple characters. */
var comboHalfs = [
'\ufe20', '\ufe21', '\ufe22', '\ufe23'
];
/** List of common combining diacritical marks. */
var comboMarks = [
'\u0300', '\u0301', '\u0302', '\u0303', '\u0304', '\u0305', '\u0306', '\u0307', '\u0308', '\u0309', '\u030a', '\u030b', '\u030c', '\u030d', '\u030e', '\u030f',
'\u0310', '\u0311', '\u0312', '\u0313', '\u0314', '\u0315', '\u0316', '\u0317', '\u0318', '\u0319', '\u031a', '\u031b', '\u031c', '\u031d', '\u031e', '\u031f',
'\u0320', '\u0321', '\u0322', '\u0323', '\u0324', '\u0325', '\u0326', '\u0327', '\u0328', '\u0329', '\u032a', '\u032b', '\u032c', '\u032d', '\u032e', '\u032f',
'\u0330', '\u0331', '\u0332', '\u0333', '\u0334', '\u0335', '\u0336', '\u0337', '\u0338', '\u0339', '\u033a', '\u033b', '\u033c', '\u033d', '\u033e', '\u033f',
'\u0340', '\u0341', '\u0342', '\u0343', '\u0344', '\u0345', '\u0346', '\u0347', '\u0348', '\u0349', '\u034a', '\u034b', '\u034c', '\u034d', '\u034e', '\u034f',
'\u0350', '\u0351', '\u0352', '\u0353', '\u0354', '\u0355', '\u0356', '\u0357', '\u0358', '\u0359', '\u035a', '\u035b', '\u035c', '\u035d', '\u035e', '\u035f',
'\u0360', '\u0361', '\u0362', '\u0363', '\u0364', '\u0365', '\u0366', '\u0367', '\u0368', '\u0369', '\u036a', '\u036b', '\u036c', '\u036d', '\u036e', '\u036f'
];
/** List of `burredLetters` translated to basic latin letters. */
var deburredLetters = [
'A', 'A', 'A', 'A', 'A', 'A', 'Ae', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I',
'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'Th',
'ss', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i',
'i', 'd', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'th', 'y'
];
/** Used to provide falsey values to methods. */
var falsey = [, '', 0, false, NaN, null, undefined];
/** Used to provide empty values to methods. */
var empties = [[], {}].concat(falsey.slice(1));
/** Used to test error objects. */
var errors = [
new Error,
new EvalError,
new RangeError,
new ReferenceError,
new SyntaxError,
new TypeError,
new URIError
];
/** Used to check whether methods support typed arrays. */
var typedArrays = [
'Float32Array',
'Float64Array',
'Int8Array',
'Int16Array',
'Int32Array',
'Uint8Array',
'Uint8ClampedArray',
'Uint16Array',
'Uint32Array'
];
/**
* Used to check for problems removing whitespace. For a whitespace reference,
* see [V8's unit test](https://code.google.com/p/v8/source/browse/branches/bleeding_edge/test/mjsunit/whitespaces.js).
*/
var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000';
/**
* Extracts the unwrapped value from its wrapper.
*
* @private
* @param {Object} wrapper The wrapper to unwrap.
* @returns {*} Returns the unwrapped value.
*/
function getUnwrappedValue(wrapper) {
var index = -1,
actions = wrapper.__actions__,
length = actions.length,
result = wrapper.__wrapped__;
while (++index < length) {
var args = [result],
action = actions[index];
push.apply(args, action.args);
result = action.func.apply(action.thisArg, args);
}
return result;
}
/**
* Removes all own enumerable properties from a given object.
*
* @private
* @param {Object} object The object to empty.
*/
function emptyObject(object) {
_.forOwn(object, function(value, key, object) {
delete object[key];
});
}
/**
* Sets a non-enumerable property value on `object`.
*
* Note: This function is used to avoid a bug in older versions of V8 where
* overwriting non-enumerable built-ins makes them enumerable.
* See https://code.google.com/p/v8/issues/detail?id=1623
*
* @private
* @param {Object} object The object augment.
* @param {string} key The name of the property to set.
* @param {*} value The property value.
*/
function setProperty(object, key, value) {
try {
defineProperty(object, key, {
'configurable': true,
'enumerable': false,
'writable': true,
'value': value
});
} catch(e) {
object[key] = value;
}
}
/**
* Skips a given number of tests with a passing result.
*
* @private
* @param {number} [count=1] The number of tests to skip.
*/
function skipTest(count) {
count || (count = 1);
while (count--) {
ok(true, 'test skipped');
}
}
/*--------------------------------------------------------------------------*/
// Add bizarro values.
(function() {
if (document || typeof require != 'function') {
return;
}
var nativeString = fnToString.call(toString),
reToString = /toString/g;
function createToString(funcName) {
return _.constant(nativeString.replace(reToString, funcName));
}
// Allow bypassing native checks.
setProperty(funcProto, 'toString', function wrapper() {
setProperty(funcProto, 'toString', fnToString);
var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);
setProperty(funcProto, 'toString', wrapper);
return result;
});
// Add prototype extensions.
funcProto._method = _.noop;
// Set bad shims.
var _propertyIsEnumerable = objectProto.propertyIsEnumerable;
setProperty(objectProto, 'propertyIsEnumerable', function(key) {
return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);
});
var _Set = root.Set;
setProperty(root, 'Set', _.noop);
var _WeakMap = root.WeakMap;
setProperty(root, 'WeakMap', _.noop);
// Fake `WinRTError`.
setProperty(root, 'WinRTError', Error);
// Clear cache so lodash can be reloaded.
emptyObject(require.cache);
// Load lodash and expose it to the bad extensions/shims.
lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;
root._ = oldDash;
// Restore built-in methods.
setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);
if (_Set) {
setProperty(root, 'Set', Set);
} else {
delete root.Set;
}
if (_WeakMap) {
setProperty(root, 'WeakMap', WeakMap);
} else {
delete root.WeakMap;
}
delete root.WinRTError;
delete funcProto._method;
}());
// Add other realm values from the `vm` module.
_.attempt(function() {
if (process.jsEngine === 'chakra') {
return;
}
_.extend(_, require('vm').runInNewContext([
'(function() {',
' var object = {',
" '_arguments': (function() { return arguments; }(1, 2, 3)),",
" '_array': [1, 2, 3],",
" '_boolean': Object(false),",
" '_date': new Date,",
" '_errors': [new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError],",
" '_function': function() {},",
" '_nan': NaN,",
" '_null': null,",
" '_number': Object(0),",
" '_object': { 'a': 1, 'b': 2, 'c': 3 },",
" '_regexp': /x/,",
" '_string': Object('a'),",
" '_undefined': undefined",
' };',
'',
" ['" + typedArrays.join("', '") + "'].forEach(function(type) {",
" var Ctor = Function('return typeof ' + type + \" != 'undefined' && \" + type)()",
' if (Ctor) {',
" object['_' + type.toLowerCase()] = new Ctor(new ArrayBuffer(24));",
' }',
" });",
'',
' return object;',
'}())'
].join('\n')));
});
// Add other realm values from an iframe.
_.attempt(function() {
var iframe = document.createElement('iframe');
iframe.frameBorder = iframe.height = iframe.width = 0;
body.appendChild(iframe);
var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc;
idoc.write([
'<script>',
'parent._._arguments = (function() { return arguments; }(1, 2, 3));',
'parent._._array = [1, 2, 3];',
'parent._._boolean = Object(false);',
'parent._._date = new Date;',
"parent._._element = document.createElement('div');",
'parent._._errors = [new Error, new EvalError, new RangeError, new ReferenceError, new SyntaxError, new TypeError, new URIError];',
'parent._._function = function() {};',
'parent._._nan = NaN;',
'parent._._null = null;',
'parent._._number = Object(0);',
"parent._._object = { 'a': 1, 'b': 2, 'c': 3 };",
'parent._._regexp = /x/;',
"parent._._string = Object('a');",
'parent._._undefined = undefined;',
'',
'var root = this;',
"parent._.each(['" + typedArrays.join("', '") + "'], function(type) {",
' var Ctor = root[type];',
' if (Ctor) {',
" parent._['_' + type.toLowerCase()] = new Ctor(new ArrayBuffer(24));",
' }',
'});',
'<\/script>'
].join('\n'));
idoc.close();
});
// Add a web worker.
_.attempt(function() {
var worker = new Worker('./asset/worker.js?t=' + (+new Date));
worker.addEventListener('message', function(e) {
_._VERSION = e.data || '';
}, false);
worker.postMessage(ui.buildPath);
});
// Expose internal modules for better code coverage.
_.attempt(function() {
if (isModularize && !(amd || isNpm)) {
_.each(['internal/baseEach', 'internal/isIndex', 'internal/isIterateeCall',
'internal/isLength', 'function/flow', 'function/flowRight'], function(id) {
var func = require(id),
funcName = _.last(id.split('/'));
_['_' + funcName] = func[funcName] || func['default'] || func;
});
}
});
/*--------------------------------------------------------------------------*/
if (params) {
console.log('test.js invoked with arguments: ' + JSON.stringify(slice.call(params)));
}
QUnit.module(basename);
(function() {
test('should support loading ' + basename + ' as the "lodash" module', 1, function() {
if (amd) {
strictEqual((lodashModule || {}).moduleName, 'lodash');
}
else {
skipTest();
}
});
test('should support loading ' + basename + ' with the Require.js "shim" configuration option', 1, function() {
if (amd && _.includes(ui.loaderPath, 'requirejs')) {
strictEqual((shimmedModule || {}).moduleName, 'shimmed');
} else {
skipTest();
}
});
test('should support loading ' + basename + ' as the "underscore" module', 1, function() {
if (amd) {
strictEqual((underscoreModule || {}).moduleName, 'underscore');
}
else {
skipTest();
}
});
asyncTest('should support loading ' + basename + ' in a web worker', 1, function() {
if (Worker) {
var limit = 30000 / QUnit.config.asyncRetries,
start = +new Date;
var attempt = function() {
var actual = _._VERSION;
if ((new Date - start) < limit && typeof actual != 'string') {
setTimeout(attempt, 16);
return;
}
strictEqual(actual, _.VERSION);
QUnit.start();
};
attempt();
}
else {
skipTest();
QUnit.start();
}
});
test('should not add `Function.prototype` extensions to lodash', 1, function() {
if (lodashBizarro) {
ok(!('_method' in lodashBizarro));
}
else {
skipTest();
}
});
test('should avoid overwritten native methods', 2, function() {
function message(lodashMethod, nativeMethod) {
return '`' + lodashMethod + '` should avoid overwritten native `' + nativeMethod + '`';
}
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var object = { 'a': 1 },
otherObject = { 'b': 2 },
largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object));
if (lodashBizarro) {
try {
var actual = _.keysIn(new Foo).sort();
} catch(e) {
actual = null;
}
deepEqual(actual, ['a', 'b'], message('_.keysIn', 'Object#propertyIsEnumerable'));
try {
actual = [
lodashBizarro.difference([object, otherObject], largeArray),
lodashBizarro.intersection(largeArray, [object]),
lodashBizarro.uniq(largeArray)
];
} catch(e) {
actual = null;
}
deepEqual(actual, [[otherObject], [object], [object]], message('_.difference`, `_.intersection`, and `_.uniq', 'Set'));
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('isIndex');
(function() {
var func = _._isIndex;
test('should return `true` for indexes', 4, function() {
if (func) {
strictEqual(func(0), true);
strictEqual(func('1'), true);
strictEqual(func(3, 4), true);
strictEqual(func(MAX_SAFE_INTEGER - 1), true);
}
else {
skipTest(4);
}
});
test('should return `false` for non-indexes', 5, function() {
if (func) {
strictEqual(func('1abc'), false);
strictEqual(func(-1), false);
strictEqual(func(3, 3), false);
strictEqual(func(1.1), false);
strictEqual(func(MAX_SAFE_INTEGER), false);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('isIterateeCall');
(function() {
var array = [1],
func = _._isIterateeCall,
object = { 'a': 1 };
test('should return `true` for iteratee calls', 3, function() {
function Foo() {}
Foo.prototype.a = 1;
if (func) {
strictEqual(func(1, 0, array), true);
strictEqual(func(1, 'a', object), true);
strictEqual(func(1, 'a', new Foo), true);
}
else {
skipTest(3);
}
});
test('should return `false` for non-iteratee calls', 4, function() {
if (func) {
strictEqual(func(2, 0, array), false);
strictEqual(func(1, 1.1, array), false);
strictEqual(func(1, 0, { 'length': MAX_SAFE_INTEGER + 1 }), false);
strictEqual(func(1, 'b', object), false);
}
else {
skipTest(4);
}
});
test('should work with `NaN` values', 2, function() {
if (func) {
strictEqual(func(NaN, 0, [NaN]), true);
strictEqual(func(NaN, 'a', { 'a': NaN }), true);
}
else {
skipTest(2);
}
});
test('should not error when `index` is an object without a `toString` method', 1, function() {
if (func) {
try {
var actual = func(1, { 'toString': null }, [1]);
} catch(e) {
var message = e.message;
}
strictEqual(actual, false, message || '');
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('isLength');
(function() {
var func = _._isLength;
test('should return `true` for lengths', 3, function() {
if (func) {
strictEqual(func(0), true);
strictEqual(func(3), true);
strictEqual(func(MAX_SAFE_INTEGER), true);
}
else {
skipTest(3);
}
});
test('should return `false` for non-lengths', 4, function() {
if (func) {
strictEqual(func(-1), false);
strictEqual(func('1'), false);
strictEqual(func(1.1), false);
strictEqual(func(MAX_SAFE_INTEGER + 1), false);
}
else {
skipTest(4);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash constructor');
(function() {
var values = empties.concat(true, 1, 'a'),
expected = _.map(values, _.constant(true));
test('should create a new instance when called without the `new` operator', 1, function() {
if (!isNpm) {
var actual = _.map(values, function(value) {
return _(value) instanceof _;
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
test('should return provided `lodash` instances', 1, function() {
if (!isNpm) {
var actual = _.map(values, function(value) {
var wrapped = _(value);
return _(wrapped) === wrapped;
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
test('should convert foreign wrapped values to `lodash` instances', 1, function() {
if (!isNpm && lodashBizarro) {
var actual = _.map(values, function(value) {
var wrapped = _(lodashBizarro(value)),
unwrapped = wrapped.value();
return wrapped instanceof _ &&
(unwrapped === value || (_.isNaN(unwrapped) && _.isNaN(value)));
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.add');
(function() {
test('should add two numbers together', 1, function() {
strictEqual(_.add(6, 4), 10);
});
test('should coerce params to numbers', 3, function() {
strictEqual(_.add('6', '4'), 10);
strictEqual(_.add('6', 'y'), 6);
strictEqual(_.add('x', 'y'), 0);
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_(1).add(2), 3);
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(1).chain().add(2) instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.after');
(function() {
function after(n, times) {
var count = 0;
_.times(times, _.after(n, function() { count++; }));
return count;
}
test('should create a function that invokes `func` after `n` calls', 4, function() {
strictEqual(after(5, 5), 1, 'after(n) should invoke `func` after being called `n` times');
strictEqual(after(5, 4), 0, 'after(n) should not invoke `func` before being called `n` times');
strictEqual(after(0, 0), 0, 'after(0) should not invoke `func` immediately');
strictEqual(after(0, 1), 1, 'after(0) should invoke `func` when called once');
});
test('should coerce non-finite `n` values to `0`', 1, function() {
var values = [-Infinity, NaN, Infinity],
expected = _.map(values, _.constant(1));
var actual = _.map(values, function(n) {
return after(n, 1);
});
deepEqual(actual, expected);
});
test('should allow `func` as the first argument', 1, function() {
var count = 0;
try {
var after = _.after(function() { count++; }, 1);
after();
after();
} catch(e) {}
strictEqual(count, 2);
});
test('should not set a `this` binding', 2, function() {
var after = _.after(1, function() { return ++this.count; }),
object = { 'count': 0, 'after': after };
object.after();
strictEqual(object.after(), 2);
strictEqual(object.count, 2);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.ary');
(function() {
function fn(a, b, c) {
return slice.call(arguments);
}
test('should cap the number of params provided to `func`', 2, function() {
var actual = _.map(['6', '8', '10'], _.ary(parseInt, 1));
deepEqual(actual, [6, 8, 10]);
var capped = _.ary(fn, 2);
deepEqual(capped('a', 'b', 'c', 'd'), ['a', 'b']);
});
test('should use `func.length` if `n` is not provided', 1, function() {
var capped = _.ary(fn);
deepEqual(capped('a', 'b', 'c', 'd'), ['a', 'b', 'c']);
});
test('should treat a negative `n` as `0`', 1, function() {
var capped = _.ary(fn, -1);
try {
var actual = capped('a');
} catch(e) {}
deepEqual(actual, []);
});
test('should coerce `n` to an integer', 1, function() {
var values = ['1', 1.6, 'xyz'],
expected = [['a'], ['a'], []];
var actual = _.map(values, function(n) {
var capped = _.ary(fn, n);
return capped('a', 'b');
});
deepEqual(actual, expected);
});
test('should work when provided less than the capped numer of arguments', 1, function() {
var capped = _.ary(fn, 3);
deepEqual(capped('a'), ['a']);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var funcs = _.map([fn], _.ary),
actual = funcs[0]('a', 'b', 'c');
deepEqual(actual, ['a', 'b', 'c']);
});
test('should work when combined with other methods that use metadata', 2, function() {
var array = ['a', 'b', 'c'],
includes = _.curry(_.rearg(_.ary(_.includes, 2), 1, 0), 2);
strictEqual(includes('b')(array, 2), true);
if (!isNpm) {
includes = _(_.includes).ary(2).rearg(1, 0).curry(2).value();
strictEqual(includes('b')(array, 2), true);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.assign and lodash.extend');
_.each(['assign', 'extend'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should assign properties of a source object to the destination object', 1, function() {
deepEqual(func({ 'a': 1 }, { 'b': 2 }), { 'a': 1, 'b': 2 });
});
test('`_.' + methodName + '` should accept multiple source objects', 2, function() {
var expected = { 'a': 1, 'b': 2, 'c': 3 };
deepEqual(func({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }), expected);
deepEqual(func({ 'a': 1 }, { 'b': 2, 'c': 2 }, { 'c': 3 }), expected);
});
test('`_.' + methodName + '` should overwrite destination properties', 1, function() {
var expected = { 'a': 3, 'b': 2, 'c': 1 };
deepEqual(func({ 'a': 1, 'b': 2 }, expected), expected);
});
test('`_.' + methodName + '` should assign source properties with nullish values', 1, function() {
var expected = { 'a': null, 'b': undefined, 'c': null };
deepEqual(func({ 'a': 1, 'b': 2 }, expected), expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.assignWith and lodash.extendWith');
_.each(['assignWith', 'extendWith'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should work with a `customizer` callback', 1, function() {
var actual = func({ 'a': 1, 'b': 2 }, { 'a': 3, 'c': 3 }, function(a, b) {
return typeof a == 'undefined' ? b : a;
});
deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 });
});
test('`_.' + methodName + '` should work with a `customizer` that returns `undefined`', 1, function() {
var expected = { 'a': undefined };
deepEqual(func({}, expected, _.constant(undefined)), expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.at');
(function() {
var args = arguments,
array = ['a', 'b', 'c'];
test('should return the elements corresponding to the specified keys', 1, function() {
var actual = _.at(array, [0, 2]);
deepEqual(actual, ['a', 'c']);
});
test('should return `undefined` for nonexistent keys', 1, function() {
var actual = _.at(array, [2, 4, 0]);
deepEqual(actual, ['c', undefined, 'a']);
});
test('should work with non-index keys on array values', 1, function() {
var values = _.reject(empties, function(value) {
return value === 0 || _.isArray(value);
}).concat(-1, 1.1);
var array = _.transform(values, function(result, value) {
result[value] = 1;
}, []);
var expected = _.map(values, _.constant(1)),
actual = _.at(array, values);
deepEqual(actual, expected);
});
test('should return an empty array when no keys are provided', 2, function() {
deepEqual(_.at(array), []);
deepEqual(_.at(array, [], []), []);
});
test('should accept multiple key arguments', 1, function() {
var actual = _.at(['a', 'b', 'c', 'd'], 3, 0, 2);
deepEqual(actual, ['d', 'a', 'c']);
});
test('should work with a falsey `object` argument when keys are provided', 1, function() {
var expected = _.map(falsey, _.constant(Array(4)));
var actual = _.map(falsey, function(object) {
try {
return _.at(object, 0, 1, 'pop', 'push');
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should work with an `arguments` object for `object`', 1, function() {
var actual = _.at(args, [2, 0]);
deepEqual(actual, [3, 1]);
});
test('should work with `arguments` object as secondary arguments', 1, function() {
var actual = _.at([1, 2, 3, 4, 5], args);
deepEqual(actual, [2, 3, 4]);
});
test('should work with an object for `object`', 1, function() {
var actual = _.at({ 'a': 1, 'b': 2, 'c': 3 }, ['c', 'a']);
deepEqual(actual, [3, 1]);
});
test('should pluck inherited property values', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var actual = _.at(new Foo, 'b');
deepEqual(actual, [2]);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.attempt');
(function() {
test('should return the result of `func`', 1, function() {
strictEqual(_.attempt(_.constant('x')), 'x');
});
test('should provide additional arguments to `func`', 1, function() {
var actual = _.attempt(function() { return slice.call(arguments); }, 1, 2);
deepEqual(actual, [1, 2]);
});
test('should return the caught error', 1, function() {
var expected = _.map(errors, _.constant(true));
var actual = _.map(errors, function(error) {
return _.attempt(function() { throw error; }) === error;
});
deepEqual(actual, expected);
});
test('should coerce errors to error objects', 1, function() {
var actual = _.attempt(function() { throw 'x'; });
ok(_.isEqual(actual, Error('x')));
});
test('should work with an error object from another realm', 1, function() {
if (_._object) {
var expected = _.map(_._errors, _.constant(true));
var actual = _.map(_._errors, function(error) {
return _.attempt(function() { throw error; }) === error;
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_(_.constant('x')).attempt(), 'x');
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(_.constant('x')).chain().attempt() instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.before');
(function() {
function before(n, times) {
var count = 0;
_.times(times, _.before(n, function() { count++; }));
return count;
}
test('should create a function that invokes `func` after `n` calls', 4, function() {
strictEqual(before(5, 4), 4, 'before(n) should invoke `func` before being called `n` times');
strictEqual(before(5, 6), 4, 'before(n) should not invoke `func` after being called `n - 1` times');
strictEqual(before(0, 0), 0, 'before(0) should not invoke `func` immediately');
strictEqual(before(0, 1), 0, 'before(0) should not invoke `func` when called');
});
test('should coerce non-finite `n` values to `0`', 1, function() {
var values = [-Infinity, NaN, Infinity],
expected = _.map(values, _.constant(0));
var actual = _.map(values, function(n) {
return before(n);
});
deepEqual(actual, expected);
});
test('should not set a `this` binding', 2, function() {
var before = _.before(2, function() { return ++this.count; }),
object = { 'count': 0, 'before': before };
object.before();
strictEqual(object.before(), 1);
strictEqual(object.count, 1);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.bind');
(function() {
function fn() {
var result = [this];
push.apply(result, arguments);
return result;
}
test('should bind a function to an object', 1, function() {
var object = {},
bound = _.bind(fn, object);
deepEqual(bound('a'), [object, 'a']);
});
test('should accept a falsey `thisArg` argument', 1, function() {
var values = _.reject(falsey.slice(1), function(value) { return value == null; }),
expected = _.map(values, function(value) { return [value]; });
var actual = _.map(values, function(value) {
try {
var bound = _.bind(fn, value);
return bound();
} catch(e) {}
});
ok(_.every(actual, function(value, index) {
return _.isEqual(value, expected[index]);
}));
});
test('should bind a function to nullish values', 6, function() {
var bound = _.bind(fn, null),
actual = bound('a');
ok(actual[0] === null || actual[0] && actual[0].Array);
strictEqual(actual[1], 'a');
_.times(2, function(index) {
bound = index ? _.bind(fn, undefined) : _.bind(fn);
actual = bound('b');
ok(actual[0] === undefined || actual[0] && actual[0].Array);
strictEqual(actual[1], 'b');
});
});
test('should partially apply arguments ', 4, function() {
var object = {},
bound = _.bind(fn, object, 'a');
deepEqual(bound(), [object, 'a']);
bound = _.bind(fn, object, 'a');
deepEqual(bound('b'), [object, 'a', 'b']);
bound = _.bind(fn, object, 'a', 'b');
deepEqual(bound(), [object, 'a', 'b']);
deepEqual(bound('c', 'd'), [object, 'a', 'b', 'c', 'd']);
});
test('should support placeholders', 4, function() {
var object = {},
ph = _.bind.placeholder,
bound = _.bind(fn, object, ph, 'b', ph);
deepEqual(bound('a', 'c'), [object, 'a', 'b', 'c']);
deepEqual(bound('a'), [object, 'a', 'b', undefined]);
deepEqual(bound('a', 'c', 'd'), [object, 'a', 'b', 'c', 'd']);
deepEqual(bound(), [object, undefined, 'b', undefined]);
});
test('should create a function with a `length` of `0`', 2, function() {
var fn = function(a, b, c) {},
bound = _.bind(fn, {});
strictEqual(bound.length, 0);
bound = _.bind(fn, {}, 1);
strictEqual(bound.length, 0);
});
test('should ignore binding when called with the `new` operator', 3, function() {
function Foo() {
return this;
}
var bound = _.bind(Foo, { 'a': 1 }),
newBound = new bound;
strictEqual(bound().a, 1);
strictEqual(newBound.a, undefined);
ok(newBound instanceof Foo);
});
test('should handle a number of arguments when called with the `new` operator', 1, function() {
function Foo() {
return this;
}
var bound = _.bind(Foo, { 'a': 1 }),
count = 9,
expected = _.times(count, _.constant(undefined));
var actual = _.times(count, function(index) {
try {
switch (index) {
case 0: return (new bound).a;
case 1: return (new bound(1)).a;
case 2: return (new bound(1, 2)).a;
case 3: return (new bound(1, 2, 3)).a;
case 4: return (new bound(1, 2, 3, 4)).a;
case 5: return (new bound(1, 2, 3, 4, 5)).a;
case 6: return (new bound(1, 2, 3, 4, 5, 6)).a;
case 7: return (new bound(1, 2, 3, 4, 5, 6, 7)).a;
case 8: return (new bound(1, 2, 3, 4, 5, 6, 7, 8)).a;
}
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should ensure `new bound` is an instance of `func`', 2, function() {
function Foo(value) {
return value && object;
}
var bound = _.bind(Foo),
object = {};
ok(new bound instanceof Foo);
strictEqual(new bound(true), object);
});
test('should append array arguments to partially applied arguments', 1, function() {
var object = {},
bound = _.bind(fn, object, 'a');
deepEqual(bound(['b'], 'c'), [object, 'a', ['b'], 'c']);
});
test('should not rebind functions', 3, function() {
var object1 = {},
object2 = {},
object3 = {};
var bound1 = _.bind(fn, object1),
bound2 = _.bind(bound1, object2, 'a'),
bound3 = _.bind(bound1, object3, 'b');
deepEqual(bound1(), [object1]);
deepEqual(bound2(), [object1, 'a']);
deepEqual(bound3(), [object1, 'b']);
});
test('should not error when instantiating bound built-ins', 2, function() {
var Ctor = _.bind(Date, null),
expected = new Date(2012, 4, 23, 0, 0, 0, 0);
try {
var actual = new Ctor(2012, 4, 23, 0, 0, 0, 0);
} catch(e) {}
deepEqual(actual, expected);
Ctor = _.bind(Date, null, 2012, 4, 23);
try {
actual = new Ctor(0, 0, 0, 0);
} catch(e) {}
deepEqual(actual, expected);
});
test('should not error when calling bound class constructors with the `new` operator', 1, function() {
var createCtor = _.attempt(Function, '"use strict";return class A{}');
if (typeof createCtor == 'function') {
var bound = _.bind(createCtor()),
count = 8,
expected = _.times(count, _.constant(true));
var actual = _.times(count, function(index) {
try {
switch (index) {
case 0: return !!(new bound);
case 1: return !!(new bound(1));
case 2: return !!(new bound(1, 2));
case 3: return !!(new bound(1, 2, 3));
case 4: return !!(new bound(1, 2, 3, 4));
case 5: return !!(new bound(1, 2, 3, 4, 5));
case 6: return !!(new bound(1, 2, 3, 4, 5, 6));
case 7: return !!(new bound(1, 2, 3, 4, 5, 6, 7));
}
} catch(e) {}
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
test('should return a wrapped value when chaining', 2, function() {
if (!isNpm) {
var object = {},
bound = _(fn).bind({}, 'a', 'b');
ok(bound instanceof _);
var actual = bound.value()('c');
deepEqual(actual, [object, 'a', 'b', 'c']);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.bindAll');
(function() {
var args = arguments;
var source = {
'_a': 1,
'_b': 2,
'_c': 3,
'_d': 4,
'a': function() { return this._a; },
'b': function() { return this._b; },
'c': function() { return this._c; },
'd': function() { return this._d; }
};
test('should accept individual method names', 1, function() {
var object = _.clone(source);
_.bindAll(object, 'a', 'b');
var actual = _.map(['a', 'b', 'c'], function(methodName) {
return object[methodName].call({});
});
deepEqual(actual, [1, 2, undefined]);
});
test('should accept arrays of method names', 1, function() {
var object = _.clone(source);
_.bindAll(object, ['a', 'b'], ['c']);
var actual = _.map(['a', 'b', 'c', 'd'], function(methodName) {
return object[methodName].call({});
});
deepEqual(actual, [1, 2, 3, undefined]);
});
test('should work with an array `object` argument', 1, function() {
var array = ['push', 'pop'];
_.bindAll(array);
strictEqual(array.pop, arrayProto.pop);
});
test('should work with `arguments` objects as secondary arguments', 1, function() {
var object = _.clone(source);
_.bindAll(object, args);
var actual = _.map(args, function(methodName) {
return object[methodName].call({});
});
deepEqual(actual, [1]);
});
}('a'));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.bindKey');
(function() {
test('should work when the target function is overwritten', 2, function() {
var object = {
'user': 'fred',
'greet': function(greeting) {
return this.user + ' says: ' + greeting;
}
};
var bound = _.bindKey(object, 'greet', 'hi');
strictEqual(bound(), 'fred says: hi');
object.greet = function(greeting) {
return this.user + ' says: ' + greeting + '!';
};
strictEqual(bound(), 'fred says: hi!');
});
test('should support placeholders', 4, function() {
var object = {
'fn': function() {
return slice.call(arguments);
}
};
var ph = _.bindKey.placeholder,
bound = _.bindKey(object, 'fn', ph, 'b', ph);
deepEqual(bound('a', 'c'), ['a', 'b', 'c']);
deepEqual(bound('a'), ['a', 'b', undefined]);
deepEqual(bound('a', 'c', 'd'), ['a', 'b', 'c', 'd']);
deepEqual(bound(), [undefined, 'b', undefined]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('case methods');
_.each(['camel', 'kebab', 'snake', 'start'], function(caseName) {
var methodName = caseName + 'Case',
func = _[methodName];
var strings = [
'foo bar', 'Foo bar', 'foo Bar', 'Foo Bar',
'FOO BAR', 'fooBar', '--foo-bar', '__foo_bar__'
];
var converted = (function() {
switch (caseName) {
case 'camel': return 'fooBar';
case 'kebab': return 'foo-bar';
case 'snake': return 'foo_bar';
case 'start': return 'Foo Bar';
}
}());
test('`_.' + methodName + '` should convert `string` to ' + caseName + ' case', 1, function() {
var actual = _.map(strings, function(string) {
var expected = (caseName === 'start' && string === 'FOO BAR') ? string : converted;
return func(string) === expected;
});
deepEqual(actual, _.map(strings, _.constant(true)));
});
test('`_.' + methodName + '` should handle double-converting strings', 1, function() {
var actual = _.map(strings, function(string) {
var expected = (caseName === 'start' && string === 'FOO BAR') ? string : converted;
return func(func(string)) === expected;
});
deepEqual(actual, _.map(strings, _.constant(true)));
});
test('`_.' + methodName + '` should deburr letters', 1, function() {
var actual = _.map(burredLetters, function(burred, index) {
var letter = deburredLetters[index];
letter = caseName == 'start' ? _.capitalize(letter) : letter.toLowerCase();
return func(burred) === letter;
});
deepEqual(actual, _.map(burredLetters, _.constant(true)));
});
test('`_.' + methodName + '` should trim latin-1 mathematical operators', 1, function() {
var actual = _.map(['\xd7', '\xf7'], func);
deepEqual(actual, ['', '']);
});
test('`_.' + methodName + '` should coerce `string` to a string', 2, function() {
var string = 'foo bar';
strictEqual(func(Object(string)), converted);
strictEqual(func({ 'toString': _.constant(string) }), converted);
});
test('`_.' + methodName + '` should return an unwrapped value implicitly when chaining', 1, function() {
if (!isNpm) {
strictEqual(_('foo bar')[methodName](), converted);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_('foo bar').chain()[methodName]() instanceof _);
}
else {
skipTest();
}
});
});
(function() {
test('should get the original value after cycling through all case methods', 1, function() {
var funcs = [_.camelCase, _.kebabCase, _.snakeCase, _.startCase, _.camelCase];
var actual = _.reduce(funcs, function(result, func) {
return func(result);
}, 'enable 24h format');
strictEqual(actual, 'enable24HFormat');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.camelCase');
(function() {
test('should work with numbers', 4, function() {
strictEqual(_.camelCase('enable 24h format'), 'enable24HFormat');
strictEqual(_.camelCase('too legit 2 quit'), 'tooLegit2Quit');
strictEqual(_.camelCase('walk 500 miles'), 'walk500Miles');
strictEqual(_.camelCase('xhr2 request'), 'xhr2Request');
});
test('should handle acronyms', 6, function() {
_.each(['safe HTML', 'safeHTML'], function(string) {
strictEqual(_.camelCase(string), 'safeHtml');
});
_.each(['escape HTML entities', 'escapeHTMLEntities'], function(string) {
strictEqual(_.camelCase(string), 'escapeHtmlEntities');
});
_.each(['XMLHttpRequest', 'XmlHTTPRequest'], function(string) {
strictEqual(_.camelCase(string), 'xmlHttpRequest');
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.capitalize');
(function() {
test('should capitalize the first character of a string', 3, function() {
strictEqual(_.capitalize('fred'), 'Fred');
strictEqual(_.capitalize('Fred'), 'Fred');
strictEqual(_.capitalize(' fred'), ' fred');
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_('fred').capitalize(), 'Fred');
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_('fred').chain().capitalize() instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.chain');
(function() {
test('should return a wrapped value', 1, function() {
if (!isNpm) {
var actual = _.chain({ 'a': 0 });
ok(actual instanceof _);
}
else {
skipTest();
}
});
test('should return existing wrapped values', 2, function() {
if (!isNpm) {
var wrapped = _({ 'a': 0 });
strictEqual(_.chain(wrapped), wrapped);
strictEqual(wrapped.chain(), wrapped);
}
else {
skipTest(2);
}
});
test('should enable chaining of methods that return unwrapped values by default', 6, function() {
if (!isNpm) {
var array = ['c', 'b', 'a'];
ok(_.chain(array).first() instanceof _);
ok(_(array).chain().first() instanceof _);
ok(_.chain(array).isArray() instanceof _);
ok(_(array).chain().isArray() instanceof _);
ok(_.chain(array).sortBy().first() instanceof _);
ok(_(array).chain().sortBy().first() instanceof _);
}
else {
skipTest(6);
}
});
test('should chain multiple methods', 6, function() {
if (!isNpm) {
_.times(2, function(index) {
var array = ['one two three four', 'five six seven eight', 'nine ten eleven twelve'],
expected = { ' ': 9, 'e': 14, 'f': 2, 'g': 1, 'h': 2, 'i': 4, 'l': 2, 'n': 6, 'o': 3, 'r': 2, 's': 2, 't': 5, 'u': 1, 'v': 4, 'w': 2, 'x': 1 },
wrapped = index ? _(array).chain() : _.chain(array);
var actual = wrapped
.chain()
.map(function(value) { return value.split(''); })
.flatten()
.reduce(function(object, chr) {
object[chr] || (object[chr] = 0);
object[chr]++;
return object;
}, {})
.value();
deepEqual(actual, expected);
array = [1, 2, 3, 4, 5, 6];
wrapped = index ? _(array).chain() : _.chain(array);
actual = wrapped
.chain()
.filter(function(n) { return n % 2; })
.reject(function(n) { return n % 3 == 0; })
.sortBy(function(n) { return -n; })
.value();
deepEqual(actual, [5, 1]);
array = [3, 4];
wrapped = index ? _(array).chain() : _.chain(array);
actual = wrapped
.reverse()
.concat([2, 1])
.unshift(5)
.tap(function(value) { value.pop(); })
.map(square)
.value();
deepEqual(actual,[25, 16, 9, 4]);
});
}
else {
skipTest(6);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.chunk');
(function() {
var array = [0, 1, 2, 3, 4, 5];
test('should return chunked arrays', 1, function() {
var actual = _.chunk(array, 3);
deepEqual(actual, [[0, 1, 2], [3, 4, 5]]);
});
test('should return the last chunk as remaining elements', 1, function() {
var actual = _.chunk(array, 4);
deepEqual(actual, [[0, 1, 2, 3], [4, 5]]);
});
test('should ensure the minimum `size` is `0`', 1, function() {
var values = falsey.concat(-1, -Infinity),
expected = _.map(values, _.constant([]));
var actual = _.map(values, function(value, index) {
return index ? _.chunk(array, value) : _.chunk(array);
});
deepEqual(actual, expected);
});
test('should coerce `size` to an integer', 1, function() {
deepEqual(_.chunk(array, array.length / 4), [[0], [1], [2], [3], [4], [5]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('clone methods');
(function() {
function Foo() { this.a = 1; }
Foo.prototype = { 'b': 1 };
Foo.c = function() {};
var objects = {
'`arguments` objects': arguments,
'arrays': ['a', ''],
'array-like-objects': { '0': 'a', '1': '', 'length': 3 },
'booleans': false,
'boolean objects': Object(false),
'Foo instances': new Foo,
'objects': { 'a': 0, 'b': 1, 'c': 3 },
'objects with object values': { 'a': /a/, 'b': ['B'], 'c': { 'C': 1 } },
'objects from another document': _._object || {},
'null values': null,
'numbers': 3,
'number objects': Object(3),
'regexes': /a/gim,
'strings': 'a',
'string objects': Object('a'),
'undefined values': undefined
};
objects['arrays'].length = 3;
var uncloneable = {
'DOM elements': body,
'functions': Foo
};
_.each(errors, function(error) {
uncloneable[error.name + 's'] = error;
});
test('`_.clone` should perform a shallow clone', 2, function() {
var array = [{ 'a': 0 }, { 'b': 1 }],
actual = _.clone(array);
deepEqual(actual, array);
ok(actual !== array && actual[0] === array[0]);
});
test('`_.cloneDeep` should deep clone objects with circular references', 1, function() {
var object = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': {}
};
object.foo.b.c.d = object;
object.bar.b = object.foo.b;
var actual = _.cloneDeep(object);
ok(actual.bar.b === actual.foo.b && actual === actual.foo.b.c.d && actual !== object);
});
_.each(['clone', 'cloneDeep'], function(methodName) {
var func = _[methodName],
isDeep = methodName == 'cloneDeep';
_.forOwn(objects, function(object, key) {
test('`_.' + methodName + '` should clone ' + key, 2, function() {
var actual = func(object);
ok(_.isEqual(actual, object));
if (_.isObject(object)) {
notStrictEqual(actual, object);
} else {
strictEqual(actual, object);
}
});
});
_.forOwn(uncloneable, function(value, key) {
test('`_.' + methodName + '` should not clone ' + key, 3, function() {
var object = { 'a': value, 'b': { 'c': value } },
actual = func(object);
deepEqual(actual, object);
notStrictEqual(actual, object);
var expected = typeof value == 'function' ? { 'c': Foo.c } : (value && {});
deepEqual(func(value), expected);
});
});
test('`_.' + methodName + '` should clone array buffers', 2, function() {
if (ArrayBuffer) {
var buffer = new ArrayBuffer(10),
actual = func(buffer);
strictEqual(actual.byteLength, buffer.byteLength);
notStrictEqual(actual, buffer);
}
else {
skipTest(2);
}
});
_.each(typedArrays, function(type) {
test('`_.' + methodName + '` should clone ' + type + ' arrays', 10, function() {
var Ctor = root[type];
_.times(2, function(index) {
if (Ctor) {
var buffer = new ArrayBuffer(24),
array = index ? new Ctor(buffer, 8, 1) : new Ctor(buffer),
actual = func(array);
deepEqual(actual, array);
notStrictEqual(actual, array);
strictEqual(actual.buffer === array.buffer, !isDeep);
strictEqual(actual.byteOffset, array.byteOffset);
strictEqual(actual.length, array.length);
}
else {
skipTest(5);
}
});
});
});
test('`_.' + methodName + '` should clone `index` and `input` array properties', 2, function() {
var array = /x/.exec('vwxyz'),
actual = func(array);
strictEqual(actual.index, 2);
strictEqual(actual.input, 'vwxyz');
});
test('`_.' + methodName + '` should clone `lastIndex` regexp property', 1, function() {
// Avoid a regexp literal for older Opera and use `exec` for older Safari.
var regexp = RegExp('x', 'g');
regexp.exec('vwxyz');
var actual = func(regexp);
strictEqual(actual.lastIndex, 3);
});
test('`_.' + methodName + '` should not error on DOM elements', 1, function() {
if (document) {
var element = document.createElement('div');
try {
deepEqual(func(element), {});
} catch(e) {
ok(false, e.message);
}
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should perform a ' + (isDeep ? 'deep' : 'shallow') + ' clone when used as an iteratee for methods like `_.map`', 2, function() {
var expected = [{ 'a': [0] }, { 'b': [1] }],
actual = _.map(expected, func);
deepEqual(actual, expected);
if (isDeep) {
ok(actual[0] !== expected[0] && actual[0].a !== expected[0].a && actual[1].b !== expected[1].b);
} else {
ok(actual[0] !== expected[0] && actual[0].a === expected[0].a && actual[1].b === expected[1].b);
}
});
test('`_.' + methodName + '` should create an object from the same realm as `value`', 1, function() {
var props = [];
var objects = _.transform(_, function(result, value, key) {
if (_.startsWith(key, '_') && _.isObject(value) && !_.isArguments(value) && !_.isElement(value) && !_.isFunction(value)) {
props.push(_.capitalize(_.camelCase(key)));
result.push(value);
}
}, []);
var expected = _.times(objects.length, _.constant(true));
var actual = _.map(objects, function(object) {
var Ctor = object.constructor,
result = func(object);
return result !== object && (result instanceof Ctor || !(new Ctor instanceof Ctor));
});
deepEqual(actual, expected, props.join(', '));
});
test('`_.' + methodName + '` should return a unwrapped value when chaining', 2, function() {
if (!isNpm) {
var object = objects['objects'],
actual = _(object)[methodName]();
deepEqual(actual, object);
notStrictEqual(actual, object);
}
else {
skipTest(2);
}
});
});
_.each(['cloneWith', 'cloneDeepWith'], function(methodName) {
var func = _[methodName],
isDeepWith = methodName == 'cloneDeepWith';
test('`_.' + methodName + '` should provide the correct `customizer` arguments', 1, function() {
var argsList = [],
foo = new Foo;
func(foo, function() {
argsList.push(slice.call(arguments));
});
deepEqual(argsList, isDeepWith ? [[foo], [1, 'a', foo, [foo], [{ 'a': 1 }]]] : [[foo]]);
});
test('`_.' + methodName + '` should handle cloning if `customizer` returns `undefined`', 1, function() {
var actual = func({ 'a': { 'b': 'c' } }, _.noop);
deepEqual(actual, { 'a': { 'b': 'c' } });
});
_.forOwn(uncloneable, function(value, key) {
test('`_.' + methodName + '` should work with a `customizer` callback and ' + key, 4, function() {
var customizer = function(value) {
return _.isPlainObject(value) ? undefined : value;
};
var actual = func(value, customizer);
deepEqual(actual, value);
strictEqual(actual, value);
var object = { 'a': value, 'b': { 'c': value } };
actual = func(object, customizer);
deepEqual(actual, object);
notStrictEqual(actual, object);
});
});
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.compact');
(function() {
test('should filter falsey values', 1, function() {
var array = ['0', '1', '2'];
deepEqual(_.compact(falsey.concat(array)), array);
});
test('should work when in between lazy operators', 2, function() {
if (!isNpm) {
var actual = _(falsey).thru(_.slice).compact().thru(_.slice).value();
deepEqual(actual, []);
actual = _(falsey).thru(_.slice).push(true, 1).compact().push('a').value();
deepEqual(actual, [true, 1, 'a']);
}
else {
skipTest(2);
}
});
test('should work in a lazy chain sequence', 1, function() {
if (!isNpm) {
var array = _.range(0, LARGE_ARRAY_SIZE).concat(null),
actual = _(array).slice(1).compact().reverse().take().value();
deepEqual(actual, _.take(_.compact(_.slice(array, 1)).reverse()));
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('flow methods');
_.each(['flow', 'flowRight'], function(methodName) {
var func = _[methodName],
isFlow = methodName == 'flow';
test('`_.' + methodName + '` should supply each function with the return value of the previous', 1, function() {
var fixed = function(n) { return n.toFixed(1); },
combined = isFlow ? func(add, square, fixed) : func(fixed, square, add);
strictEqual(combined(1, 2), '9.0');
});
test('`_.' + methodName + '` should return a new function', 1, function() {
notStrictEqual(func(_.noop), _.noop);
});
test('`_.' + methodName + '` should return an identity function when no arguments are provided', 3, function() {
var combined = func();
try {
strictEqual(combined('a'), 'a');
} catch(e) {
ok(false, e.message);
}
strictEqual(combined.length, 0);
notStrictEqual(combined, _.identity);
});
test('`_.' + methodName + '` should work with a curried function and `_.first`', 1, function() {
var curried = _.curry(_.identity);
var combined = isFlow
? func(_.first, curried)
: func(curried, _.first);
strictEqual(combined([1]), 1);
});
test('`_.' + methodName + '` should support shortcut fusion', 12, function() {
var filterCount,
mapCount;
var iteratee = function(value) {
mapCount++;
return value * value;
};
var predicate = function(value) {
filterCount++;
return value % 2 == 0;
};
_.times(2, function(index) {
var filter1 = _.filter,
filter2 = _.curry(_.rearg(_.ary(_.filter, 2), 1, 0), 2),
filter3 = (_.filter = index ? filter2 : filter1, filter2(predicate));
var map1 = _.map,
map2 = _.curry(_.rearg(_.ary(_.map, 2), 1, 0), 2),
map3 = (_.map = index ? map2 : map1, map2(iteratee));
var take1 = _.take,
take2 = _.curry(_.rearg(_.ary(_.take, 2), 1, 0), 2),
take3 = (_.take = index ? take2 : take1, take2(2));
_.times(2, function(index) {
var fn = index ? _['_' + methodName] : func;
if (!fn) {
skipTest(3);
return;
}
var combined = isFlow
? fn(map3, filter3, _.compact, take3)
: fn(take3, _.compact, filter3, map3);
filterCount = mapCount = 0;
deepEqual(combined(_.range(LARGE_ARRAY_SIZE)), [4, 16]);
if (!isNpm && WeakMap && WeakMap.name) {
strictEqual(filterCount, 5, 'filterCount');
strictEqual(mapCount, 5, 'mapCount');
}
else {
skipTest(2);
}
});
_.filter = filter1;
_.map = map1;
_.take = take1;
});
});
test('`_.' + methodName + '` should work with curried functions with placeholders', 1, function() {
var curried = _.curry(_.ary(_.map, 2), 2),
getProp = curried(curried.placeholder, 'a'),
objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 1 }];
var combined = isFlow
? func(getProp, _.uniq)
: func(_.uniq, getProp);
deepEqual(combined(objects), [1, 2]);
});
test('`_.' + methodName + '` should return a wrapped value when chaining', 1, function() {
if (!isNpm) {
var wrapped = _(_.noop)[methodName]();
ok(wrapped instanceof _);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.constant');
(function() {
test('should create a function that returns `value`', 1, function() {
var object = { 'a': 1 },
values = Array(2).concat(empties, true, 1, 'a'),
constant = _.constant(object),
expected = _.map(values, function() { return true; });
var actual = _.map(values, function(value, index) {
if (index == 0) {
var result = constant();
} else if (index == 1) {
result = constant.call({});
} else {
result = constant(value);
}
return result === object;
});
deepEqual(actual, expected);
});
test('should work with falsey values', 1, function() {
var expected = _.map(falsey, function() { return true; });
var actual = _.map(falsey, function(value, index) {
var constant = index ? _.constant(value) : _.constant(),
result = constant();
return result === value || (_.isNaN(result) && _.isNaN(value));
});
deepEqual(actual, expected);
});
test('should return a wrapped value when chaining', 1, function() {
if (!isNpm) {
var wrapped = _(true).constant();
ok(wrapped instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.countBy');
(function() {
var array = [4.2, 6.1, 6.4];
test('should work with an iteratee', 1, function() {
var actual = _.countBy(array, function(num) {
return Math.floor(num);
}, Math);
deepEqual(actual, { '4': 1, '6': 2 });
});
test('should use `_.identity` when `iteratee` is nullish', 1, function() {
var array = [4, 6, 6],
values = [, null, undefined],
expected = _.map(values, _.constant({ '4': 1, '6': 2 }));
var actual = _.map(values, function(value, index) {
return index ? _.countBy(array, value) : _.countBy(array);
});
deepEqual(actual, expected);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.countBy(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [4.2, 0, array]);
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var actual = _.countBy(['one', 'two', 'three'], 'length');
deepEqual(actual, { '3': 2, '5': 1 });
});
test('should only add values to own, not inherited, properties', 2, function() {
var actual = _.countBy([4.2, 6.1, 6.4], function(num) {
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
});
deepEqual(actual.constructor, 1);
deepEqual(actual.hasOwnProperty, 2);
});
test('should work with a number for `iteratee`', 2, function() {
var array = [
[1, 'a'],
[2, 'a'],
[2, 'b']
];
deepEqual(_.countBy(array, 0), { '1': 1, '2': 2 });
deepEqual(_.countBy(array, 1), { 'a': 2, 'b': 1 });
});
test('should work with an object for `collection`', 1, function() {
var actual = _.countBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) {
return Math.floor(num);
});
deepEqual(actual, { '4': 1, '6': 2 });
});
test('should work in a lazy chain sequence', 1, function() {
if (!isNpm) {
var array = _.range(LARGE_ARRAY_SIZE).concat(
_.range(Math.floor(LARGE_ARRAY_SIZE / 2), LARGE_ARRAY_SIZE),
_.range(Math.floor(LARGE_ARRAY_SIZE / 1.5), LARGE_ARRAY_SIZE)
);
var predicate = function(value) { return value > 2; },
actual = _(array).countBy().map(square).filter(predicate).take().value();
deepEqual(actual, _.take(_.filter(_.map(_.countBy(array), square), predicate)));
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.create');
(function() {
function Shape() {
this.x = 0;
this.y = 0;
}
function Circle() {
Shape.call(this);
}
test('should create an object that inherits from the given `prototype` object', 3, function() {
Circle.prototype = _.create(Shape.prototype);
Circle.prototype.constructor = Circle;
var actual = new Circle;
ok(actual instanceof Circle);
ok(actual instanceof Shape);
notStrictEqual(Circle.prototype, Shape.prototype);
});
test('should assign `properties` to the created object', 3, function() {
var expected = { 'constructor': Circle, 'radius': 0 };
Circle.prototype = _.create(Shape.prototype, expected);
var actual = new Circle;
ok(actual instanceof Circle);
ok(actual instanceof Shape);
deepEqual(Circle.prototype, expected);
});
test('should assign own properties', 1, function() {
function Foo() {
this.a = 1;
this.c = 3;
}
Foo.prototype.b = 2;
deepEqual(_.create({}, new Foo), { 'a': 1, 'c': 3 });
});
test('should accept a falsey `prototype` argument', 1, function() {
var expected = _.map(falsey, _.constant({}));
var actual = _.map(falsey, function(prototype, index) {
return index ? _.create(prototype) : _.create();
});
deepEqual(actual, expected);
});
test('should ignore primitive `prototype` arguments and use an empty object instead', 1, function() {
var primitives = [true, null, 1, 'a', undefined],
expected = _.map(primitives, _.constant(true));
var actual = _.map(primitives, function(value, index) {
return _.isPlainObject(index ? _.create(value) : _.create());
});
deepEqual(actual, expected);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [{ 'a': 1 }, { 'a': 1 }, { 'a': 1 }],
expected = _.map(array, _.constant(true)),
objects = _.map(array, _.create);
var actual = _.map(objects, function(object) {
return object.a === 1 && !_.keys(object).length;
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.curry');
(function() {
function fn(a, b, c, d) {
return slice.call(arguments);
}
test('should curry based on the number of arguments provided', 3, function() {
var curried = _.curry(fn),
expected = [1, 2, 3, 4];
deepEqual(curried(1)(2)(3)(4), expected);
deepEqual(curried(1, 2)(3, 4), expected);
deepEqual(curried(1, 2, 3, 4), expected);
});
test('should allow specifying `arity`', 3, function() {
var curried = _.curry(fn, 3),
expected = [1, 2, 3];
deepEqual(curried(1)(2, 3), expected);
deepEqual(curried(1, 2)(3), expected);
deepEqual(curried(1, 2, 3), expected);
});
test('should coerce `arity` to an integer', 2, function() {
var values = ['0', 0.6, 'xyz'],
expected = _.map(values, _.constant([]));
var actual = _.map(values, function(arity) {
return _.curry(fn, arity)();
});
deepEqual(actual, expected);
deepEqual(_.curry(fn, '2')(1)(2), [1, 2]);
});
test('should support placeholders', 4, function() {
var curried = _.curry(fn),
ph = curried.placeholder;
deepEqual(curried(1)(ph, 3)(ph, 4)(2), [1, 2, 3, 4]);
deepEqual(curried(ph, 2)(1)(ph, 4)(3), [1, 2, 3, 4]);
deepEqual(curried(ph, ph, 3)(ph, 2)(ph, 4)(1), [1, 2, 3, 4]);
deepEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), [1, 2, 3, 4]);
});
test('should provide additional arguments after reaching the target arity', 3, function() {
var curried = _.curry(fn, 3);
deepEqual(curried(1)(2, 3, 4), [1, 2, 3, 4]);
deepEqual(curried(1, 2)(3, 4, 5), [1, 2, 3, 4, 5]);
deepEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]);
});
test('should return a function with a `length` of `0`', 6, function() {
_.times(2, function(index) {
var curried = index ? _.curry(fn, 4) : _.curry(fn);
strictEqual(curried.length, 0);
strictEqual(curried(1).length, 0);
strictEqual(curried(1, 2).length, 0);
});
});
test('should ensure `new curried` is an instance of `func`', 2, function() {
var Foo = function(value) {
return value && object;
};
var curried = _.curry(Foo),
object = {};
ok(new curried(false) instanceof Foo);
strictEqual(new curried(true), object);
});
test('should not set a `this` binding', 9, function() {
var fn = function(a, b, c) {
var value = this || {};
return [value[a], value[b], value[c]];
};
var object = { 'a': 1, 'b': 2, 'c': 3 },
expected = [1, 2, 3];
deepEqual(_.curry(_.bind(fn, object), 3)('a')('b')('c'), expected);
deepEqual(_.curry(_.bind(fn, object), 3)('a', 'b')('c'), expected);
deepEqual(_.curry(_.bind(fn, object), 3)('a', 'b', 'c'), expected);
deepEqual(_.bind(_.curry(fn), object)('a')('b')('c'), Array(3));
deepEqual(_.bind(_.curry(fn), object)('a', 'b')('c'), Array(3));
deepEqual(_.bind(_.curry(fn), object)('a', 'b', 'c'), expected);
object.curried = _.curry(fn);
deepEqual(object.curried('a')('b')('c'), Array(3));
deepEqual(object.curried('a', 'b')('c'), Array(3));
deepEqual(object.curried('a', 'b', 'c'), expected);
});
test('should work with partialed methods', 2, function() {
var curried = _.curry(fn),
expected = [1, 2, 3, 4];
var a = _.partial(curried, 1),
b = _.bind(a, null, 2),
c = _.partialRight(b, 4),
d = _.partialRight(b(3), 4);
deepEqual(c(3), expected);
deepEqual(d(), expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.curryRight');
(function() {
function fn(a, b, c, d) {
return slice.call(arguments);
}
test('should curry based on the number of arguments provided', 3, function() {
var curried = _.curryRight(fn),
expected = [1, 2, 3, 4];
deepEqual(curried(4)(3)(2)(1), expected);
deepEqual(curried(3, 4)(1, 2), expected);
deepEqual(curried(1, 2, 3, 4), expected);
});
test('should allow specifying `arity`', 3, function() {
var curried = _.curryRight(fn, 3),
expected = [1, 2, 3];
deepEqual(curried(3)(1, 2), expected);
deepEqual(curried(2, 3)(1), expected);
deepEqual(curried(1, 2, 3), expected);
});
test('should coerce `arity` to an integer', 2, function() {
var values = ['0', 0.6, 'xyz'],
expected = _.map(values, _.constant([]));
var actual = _.map(values, function(arity) {
return _.curryRight(fn, arity)();
});
deepEqual(actual, expected);
deepEqual(_.curryRight(fn, '2')(1)(2), [2, 1]);
});
test('should support placeholders', 4, function() {
var curried = _.curryRight(fn),
expected = [1, 2, 3, 4],
ph = curried.placeholder;
deepEqual(curried(4)(2, ph)(1, ph)(3), expected);
deepEqual(curried(3, ph)(4)(1, ph)(2), expected);
deepEqual(curried(ph, ph, 4)(ph, 3)(ph, 2)(1), expected);
deepEqual(curried(ph, ph, ph, 4)(ph, ph, 3)(ph, 2)(1), expected);
});
test('should provide additional arguments after reaching the target arity', 3, function() {
var curried = _.curryRight(fn, 3);
deepEqual(curried(4)(1, 2, 3), [1, 2, 3, 4]);
deepEqual(curried(4, 5)(1, 2, 3), [1, 2, 3, 4, 5]);
deepEqual(curried(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]);
});
test('should return a function with a `length` of `0`', 6, function() {
_.times(2, function(index) {
var curried = index ? _.curryRight(fn, 4) : _.curryRight(fn);
strictEqual(curried.length, 0);
strictEqual(curried(4).length, 0);
strictEqual(curried(3, 4).length, 0);
});
});
test('should ensure `new curried` is an instance of `func`', 2, function() {
var Foo = function(value) {
return value && object;
};
var curried = _.curryRight(Foo),
object = {};
ok(new curried(false) instanceof Foo);
strictEqual(new curried(true), object);
});
test('should not set a `this` binding', 9, function() {
var fn = function(a, b, c) {
var value = this || {};
return [value[a], value[b], value[c]];
};
var object = { 'a': 1, 'b': 2, 'c': 3 },
expected = [1, 2, 3];
deepEqual(_.curryRight(_.bind(fn, object), 3)('c')('b')('a'), expected);
deepEqual(_.curryRight(_.bind(fn, object), 3)('b', 'c')('a'), expected);
deepEqual(_.curryRight(_.bind(fn, object), 3)('a', 'b', 'c'), expected);
deepEqual(_.bind(_.curryRight(fn), object)('c')('b')('a'), Array(3));
deepEqual(_.bind(_.curryRight(fn), object)('b', 'c')('a'), Array(3));
deepEqual(_.bind(_.curryRight(fn), object)('a', 'b', 'c'), expected);
object.curried = _.curryRight(fn);
deepEqual(object.curried('c')('b')('a'), Array(3));
deepEqual(object.curried('b', 'c')('a'), Array(3));
deepEqual(object.curried('a', 'b', 'c'), expected);
});
test('should work with partialed methods', 2, function() {
var curried = _.curryRight(fn),
expected = [1, 2, 3, 4];
var a = _.partialRight(curried, 4),
b = _.partialRight(a, 3),
c = _.bind(b, null, 1),
d = _.partial(b(2), 1);
deepEqual(c(2), expected);
deepEqual(d(), expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('curry methods');
_.each(['curry', 'curryRight'], function(methodName) {
var func = _[methodName],
fn = function(a, b) { return slice.call(arguments); },
isCurry = methodName == 'curry';
test('`_.' + methodName + '` should not error on functions with the same name as lodash methods', 1, function() {
function run(a, b) {
return a + b;
}
var curried = func(run);
try {
var actual = curried(1)(2);
} catch(e) {}
strictEqual(actual, 3);
});
test('`_.' + methodName + '` should work as an iteratee for methods like `_.map`', 2, function() {
var array = [fn, fn, fn],
object = { 'a': fn, 'b': fn, 'c': fn };
_.each([array, object], function(collection) {
var curries = _.map(collection, func),
expected = _.map(collection, _.constant(isCurry ? ['a', 'b'] : ['b', 'a']));
var actual = _.map(curries, function(curried) {
return curried('a')('b');
});
deepEqual(actual, expected);
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.debounce');
(function() {
asyncTest('should debounce a function', 2, function() {
if (!(isRhino && isModularize)) {
var callCount = 0,
debounced = _.debounce(function() { callCount++; }, 32);
debounced();
debounced();
debounced();
strictEqual(callCount, 0);
setTimeout(function() {
strictEqual(callCount, 1);
QUnit.start();
}, 96);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('subsequent debounced calls return the last `func` result', 2, function() {
if (!(isRhino && isModularize)) {
var debounced = _.debounce(_.identity, 32);
debounced('x');
setTimeout(function() {
notEqual(debounced('y'), 'y');
}, 64);
setTimeout(function() {
notEqual(debounced('z'), 'z');
QUnit.start();
}, 128);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('subsequent "immediate" debounced calls return the last `func` result', 2, function() {
if (!(isRhino && isModularize)) {
var debounced = _.debounce(_.identity, 32, { 'leading': true, 'trailing': false }),
result = [debounced('x'), debounced('y')];
deepEqual(result, ['x', 'x']);
setTimeout(function() {
var result = [debounced('a'), debounced('b')];
deepEqual(result, ['a', 'a']);
QUnit.start();
}, 64);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('should apply default options', 2, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var debounced = _.debounce(function(value) {
callCount++;
return value;
}, 32, {});
strictEqual(debounced('x'), undefined);
setTimeout(function() {
strictEqual(callCount, 1);
QUnit.start();
}, 64);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('should support a `leading` option', 5, function() {
if (!(isRhino && isModularize)) {
var callCounts = [0, 0];
var withLeading = _.debounce(function(value) {
callCounts[0]++;
return value;
}, 32, { 'leading': true });
strictEqual(withLeading('x'), 'x');
var withoutLeading = _.debounce(_.identity, 32, { 'leading': false });
strictEqual(withoutLeading('x'), undefined);
var withLeadingAndTrailing = _.debounce(function() {
callCounts[1]++;
}, 32, { 'leading': true });
withLeadingAndTrailing();
withLeadingAndTrailing();
strictEqual(callCounts[1], 1);
setTimeout(function() {
deepEqual(callCounts, [1, 2]);
withLeading('x');
strictEqual(callCounts[0], 2);
QUnit.start();
}, 64);
}
else {
skipTest(5);
QUnit.start();
}
});
asyncTest('should support a `trailing` option', 4, function() {
if (!(isRhino && isModularize)) {
var withCount = 0,
withoutCount = 0;
var withTrailing = _.debounce(function(value) {
withCount++;
return value;
}, 32, { 'trailing': true });
var withoutTrailing = _.debounce(function(value) {
withoutCount++;
return value;
}, 32, { 'trailing': false });
strictEqual(withTrailing('x'), undefined);
strictEqual(withoutTrailing('x'), undefined);
setTimeout(function() {
strictEqual(withCount, 1);
strictEqual(withoutCount, 0);
QUnit.start();
}, 64);
}
else {
skipTest(4);
QUnit.start();
}
});
asyncTest('should support a `maxWait` option', 1, function() {
if (!(isRhino && isModularize)) {
var limit = (argv || isPhantom) ? 1000 : 320,
withCount = 0,
withoutCount = 0;
var withMaxWait = _.debounce(function() {
withCount++;
}, 64, { 'maxWait': 128 });
var withoutMaxWait = _.debounce(function() {
withoutCount++;
}, 96);
var start = +new Date;
while ((new Date - start) < limit) {
withMaxWait();
withoutMaxWait();
}
var actual = [Boolean(withCount), Boolean(withoutCount)];
setTimeout(function() {
deepEqual(actual, [true, false]);
QUnit.start();
}, 1);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('should cancel `maxDelayed` when `delayed` is invoked', 1, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var debounced = _.debounce(function() {
callCount++;
}, 32, { 'maxWait': 64 });
debounced();
setTimeout(function() {
strictEqual(callCount, 1);
QUnit.start();
}, 128);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('should invoke the `trailing` call with the correct arguments and `this` binding', 2, function() {
if (!(isRhino && isModularize)) {
var actual,
callCount = 0,
object = {};
var debounced = _.debounce(function(value) {
actual = [this];
push.apply(actual, arguments);
return ++callCount != 2;
}, 32, { 'leading': true, 'maxWait': 64 });
while (true) {
if (!debounced.call(object, 'a')) {
break;
}
}
setTimeout(function() {
strictEqual(callCount, 2);
deepEqual(actual, [object, 'a']);
QUnit.start();
}, 64);
}
else {
skipTest(2);
QUnit.start();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.deburr');
(function() {
test('should convert latin-1 supplementary letters to basic latin', 1, function() {
var actual = _.map(burredLetters, _.deburr);
deepEqual(actual, deburredLetters);
});
test('should not deburr latin-1 mathematical operators', 1, function() {
var operators = ['\xd7', '\xf7'],
actual = _.map(operators, _.deburr);
deepEqual(actual, operators);
});
test('should deburr combining diacritical marks', 1, function() {
var values = comboMarks.concat(comboHalfs),
expected = _.map(values, _.constant('ei'));
var actual = _.map(values, function(chr) {
return _.deburr('e' + chr + 'i');
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.defaults');
(function() {
test('should assign properties of a source object if missing on the destination object', 1, function() {
deepEqual(_.defaults({ 'a': 1 }, { 'a': 2, 'b': 2 }), { 'a': 1, 'b': 2 });
});
test('should accept multiple source objects', 2, function() {
var expected = { 'a': 1, 'b': 2, 'c': 3 };
deepEqual(_.defaults({ 'a': 1, 'b': 2 }, { 'b': 3 }, { 'c': 3 }), expected);
deepEqual(_.defaults({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 3 }, { 'c': 2 }), expected);
});
test('should not overwrite `null` values', 1, function() {
var actual = _.defaults({ 'a': null }, { 'a': 1 });
strictEqual(actual.a, null);
});
test('should overwrite `undefined` values', 1, function() {
var actual = _.defaults({ 'a': undefined }, { 'a': 1 });
strictEqual(actual.a, 1);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.defaultsDeep');
(function() {
test('should deep assign properties of a source object if missing on the destination object', 1, function() {
var object = { 'a': { 'b': 2 }, 'd': 4 },
source = { 'a': { 'b': 1, 'c': 3 }, 'e': 5 },
expected = { 'a': { 'b': 2, 'c': 3 }, 'd': 4, 'e': 5 };
deepEqual(_.defaultsDeep(object, source), expected);
});
test('should accept multiple source objects', 2, function() {
var source1 = { 'a': { 'b': 3 } },
source2 = { 'a': { 'c': 3 } },
source3 = { 'a': { 'b': 3, 'c': 3 } },
source4 = { 'a': { 'c': 4 } },
expected = { 'a': { 'b': 2, 'c': 3 } };
deepEqual(_.defaultsDeep({ 'a': { 'b': 2 } }, source1, source2), expected);
deepEqual(_.defaultsDeep({ 'a': { 'b': 2 } }, source3, source4), expected);
});
test('should not overwrite `null` values', 1, function() {
var object = { 'a': { 'b': null } },
source = { 'a': { 'b': 2 } },
actual = _.defaultsDeep(object, source);
strictEqual(actual.a.b, null);
});
test('should overwrite `undefined` values', 1, function() {
var object = { 'a': { 'b': undefined } },
source = { 'a': { 'b': 2 } },
actual = _.defaultsDeep(object, source);
strictEqual(actual.a.b, 2);
});
test('should merge sources containing circular references', 1, function() {
var object = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': { 'a': 2 }
};
var source = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': {}
};
object.foo.b.c.d = object;
source.foo.b.c.d = source;
source.bar.b = source.foo.b;
var actual = _.defaultsDeep(object, source);
ok(actual.bar.b === source.foo.b && actual.foo.b.c.d === actual.foo.b.c.d.foo.b.c.d);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.defer');
(function() {
asyncTest('should defer `func` execution', 1, function() {
if (!(isRhino && isModularize)) {
var pass = false;
_.defer(function() { pass = true; });
setTimeout(function() {
ok(pass);
QUnit.start();
}, 32);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('should provide additional arguments to `func`', 1, function() {
if (!(isRhino && isModularize)) {
var args;
_.defer(function() {
args = slice.call(arguments);
}, 1, 2);
setTimeout(function() {
deepEqual(args, [1, 2]);
QUnit.start();
}, 32);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('should be cancelable', 1, function() {
if (!(isRhino && isModularize)) {
var pass = true;
var timerId = _.defer(function() {
pass = false;
});
clearTimeout(timerId);
setTimeout(function() {
ok(pass);
QUnit.start();
}, 32);
}
else {
skipTest();
QUnit.start();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.delay');
(function() {
asyncTest('should delay `func` execution', 2, function() {
if (!(isRhino && isModularize)) {
var pass = false;
_.delay(function() { pass = true; }, 32);
setTimeout(function() {
ok(!pass);
}, 1);
setTimeout(function() {
ok(pass);
QUnit.start();
}, 64);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('should provide additional arguments to `func`', 1, function() {
if (!(isRhino && isModularize)) {
var args;
_.delay(function() {
args = slice.call(arguments);
}, 32, 1, 2);
setTimeout(function() {
deepEqual(args, [1, 2]);
QUnit.start();
}, 64);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('should be cancelable', 1, function() {
if (!(isRhino && isModularize)) {
var pass = true;
var timerId = _.delay(function() {
pass = false;
}, 32);
clearTimeout(timerId);
setTimeout(function() {
ok(pass);
QUnit.start();
}, 64);
}
else {
skipTest();
QUnit.start();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.difference');
(function() {
var args = arguments;
test('should return the difference of the given arrays', 2, function() {
var actual = _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
deepEqual(actual, [1, 3, 4]);
actual = _.difference([1, 2, 3, 4, 5], [5, 2, 10], [8, 4]);
deepEqual(actual, [1, 3]);
});
test('should match `NaN`', 1, function() {
deepEqual(_.difference([1, NaN, 3], [NaN, 5, NaN]), [1, 3]);
});
test('should work with large arrays', 1, function() {
var array1 = _.range(LARGE_ARRAY_SIZE + 1),
array2 = _.range(LARGE_ARRAY_SIZE),
a = {},
b = {},
c = {};
array1.push(a, b, c);
array2.push(b, c, a);
deepEqual(_.difference(array1, array2), [LARGE_ARRAY_SIZE]);
});
test('should work with large arrays of objects', 1, function() {
var object1 = {},
object2 = {},
largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object1));
deepEqual(_.difference([object1, object2], largeArray), [object2]);
});
test('should work with large arrays of `NaN`', 1, function() {
var largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(NaN));
deepEqual(_.difference([1, NaN, 3], largeArray), [1, 3]);
});
test('should ignore values that are not array-like', 3, function() {
var array = [1, null, 3];
deepEqual(_.difference(args, 3, { '0': 1 }), [1, 2, 3]);
deepEqual(_.difference(null, array, 1), []);
deepEqual(_.difference(array, args, null), [null]);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.drop');
(function() {
var array = [1, 2, 3];
test('should drop the first two elements', 1, function() {
deepEqual(_.drop(array, 2), [3]);
});
test('should treat falsey `n` values, except nullish, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value == null ? [2, 3] : array;
});
var actual = _.map(falsey, function(n) {
return _.drop(array, n);
});
deepEqual(actual, expected);
});
test('should return all elements when `n` < `1`', 3, function() {
_.each([0, -1, -Infinity], function(n) {
deepEqual(_.drop(array, n), array);
});
});
test('should return an empty array when `n` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(n) {
deepEqual(_.drop(array, n), []);
});
});
test('should coerce `n` to an integer', 1, function() {
deepEqual(_.drop(array, 1.2), [2, 3]);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.drop);
deepEqual(actual, [[2, 3], [5, 6], [8, 9]]);
});
test('should work in a lazy chain sequence', 6, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
values = [],
predicate = function(value) { values.push(value); return value > 2; },
actual = _(array).drop(2).drop().value();
deepEqual(actual, array.slice(3));
actual = _(array).filter(predicate).drop(2).drop().value();
deepEqual(values, array);
deepEqual(actual, _.drop(_.drop(_.filter(array, predicate), 2)));
actual = _(array).drop(2).dropRight().drop().dropRight(2).value();
deepEqual(actual, _.dropRight(_.drop(_.dropRight(_.drop(array, 2))), 2));
values = [];
actual = _(array).drop().filter(predicate).drop(2).dropRight().drop().dropRight(2).value();
deepEqual(values, array.slice(1));
deepEqual(actual, _.dropRight(_.drop(_.dropRight(_.drop(_.filter(_.drop(array), predicate), 2))), 2));
}
else {
skipTest(6);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.dropRight');
(function() {
var array = [1, 2, 3];
test('should drop the last two elements', 1, function() {
deepEqual(_.dropRight(array, 2), [1]);
});
test('should treat falsey `n` values, except nullish, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value == null ? [1, 2] : array;
});
var actual = _.map(falsey, function(n) {
return _.dropRight(array, n);
});
deepEqual(actual, expected);
});
test('should return all elements when `n` < `1`', 3, function() {
_.each([0, -1, -Infinity], function(n) {
deepEqual(_.dropRight(array, n), array);
});
});
test('should return an empty array when `n` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(n) {
deepEqual(_.dropRight(array, n), []);
});
});
test('should coerce `n` to an integer', 1, function() {
deepEqual(_.dropRight(array, 1.2), [1, 2]);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.dropRight);
deepEqual(actual, [[1, 2], [4, 5], [7, 8]]);
});
test('should work in a lazy chain sequence', 6, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
values = [],
predicate = function(value) { values.push(value); return value < 9; },
actual = _(array).dropRight(2).dropRight().value();
deepEqual(actual, array.slice(0, -3));
actual = _(array).filter(predicate).dropRight(2).dropRight().value();
deepEqual(values, array);
deepEqual(actual, _.dropRight(_.dropRight(_.filter(array, predicate), 2)));
actual = _(array).dropRight(2).drop().dropRight().drop(2).value();
deepEqual(actual, _.drop(_.dropRight(_.drop(_.dropRight(array, 2))), 2));
values = [];
actual = _(array).dropRight().filter(predicate).dropRight(2).drop().dropRight().drop(2).value();
deepEqual(values, array.slice(0, -1));
deepEqual(actual, _.drop(_.dropRight(_.drop(_.dropRight(_.filter(_.dropRight(array), predicate), 2))), 2));
}
else {
skipTest(6);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.dropRightWhile');
(function() {
var array = [1, 2, 3, 4];
var objects = [
{ 'a': 0, 'b': 0 },
{ 'a': 1, 'b': 1 },
{ 'a': 2, 'b': 2 }
];
test('should drop elements while `predicate` returns truthy', 1, function() {
var actual = _.dropRightWhile(array, function(num) {
return num > 2;
});
deepEqual(actual, [1, 2]);
});
test('should provide the correct `predicate` arguments', 1, function() {
var args;
_.dropRightWhile(array, function() {
args = slice.call(arguments);
});
deepEqual(args, [4, 3, array]);
});
test('should work with a "_.matches" style `predicate`', 1, function() {
deepEqual(_.dropRightWhile(objects, { 'b': 2 }), objects.slice(0, 2));
});
test('should work with a "_.matchesProperty" style `predicate`', 1, function() {
deepEqual(_.dropRightWhile(objects, ['b', 2]), objects.slice(0, 2));
});
test('should work with a "_.property" style `predicate`', 1, function() {
deepEqual(_.dropRightWhile(objects, 'b'), objects.slice(0, 1));
});
test('should return a wrapped value when chaining', 2, function() {
if (!isNpm) {
var wrapped = _(array).dropRightWhile(function(num) {
return num > 2;
});
ok(wrapped instanceof _);
deepEqual(wrapped.value(), [1, 2]);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.dropWhile');
(function() {
var array = [1, 2, 3, 4];
var objects = [
{ 'a': 2, 'b': 2 },
{ 'a': 1, 'b': 1 },
{ 'a': 0, 'b': 0 }
];
test('should drop elements while `predicate` returns truthy', 1, function() {
var actual = _.dropWhile(array, function(num) {
return num < 3;
});
deepEqual(actual, [3, 4]);
});
test('should provide the correct `predicate` arguments', 1, function() {
var args;
_.dropWhile(array, function() {
args = slice.call(arguments);
});
deepEqual(args, [1, 0, array]);
});
test('should work with a "_.matches" style `predicate`', 1, function() {
deepEqual(_.dropWhile(objects, { 'b': 2 }), objects.slice(1));
});
test('should work with a "_.matchesProperty" style `predicate`', 1, function() {
deepEqual(_.dropWhile(objects, ['b', 2]), objects.slice(1));
});
test('should work with a "_.property" style `predicate`', 1, function() {
deepEqual(_.dropWhile(objects, 'b'), objects.slice(2));
});
test('should work in a lazy chain sequence', 3, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 3),
predicate = function(num) { return num < 3; },
expected = _.dropWhile(array, predicate),
wrapped = _(array).dropWhile(predicate);
deepEqual(wrapped.value(), expected);
deepEqual(wrapped.reverse().value(), expected.slice().reverse());
strictEqual(wrapped.last(), _.last(expected));
}
else {
skipTest(3);
}
});
test('should work in a lazy chain sequence with `drop`', 1, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 3);
var actual = _(array)
.dropWhile(function(num) { return num == 1; })
.drop()
.dropWhile(function(num) { return num == 3; })
.value();
deepEqual(actual, array.slice(3));
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.endsWith');
(function() {
var string = 'abc';
test('should return `true` if a string ends with `target`', 1, function() {
strictEqual(_.endsWith(string, 'c'), true);
});
test('should return `false` if a string does not end with `target`', 1, function() {
strictEqual(_.endsWith(string, 'b'), false);
});
test('should work with a `position` argument', 1, function() {
strictEqual(_.endsWith(string, 'b', 2), true);
});
test('should work with `position` >= `string.length`', 4, function() {
_.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position) {
strictEqual(_.endsWith(string, 'c', position), true);
});
});
test('should treat falsey `position` values, except `undefined`, as `0`', 1, function() {
var expected = _.map(falsey, _.constant(true));
var actual = _.map(falsey, function(position) {
return _.endsWith(string, position === undefined ? 'c' : '', position);
});
deepEqual(actual, expected);
});
test('should treat a negative `position` as `0`', 6, function() {
_.each([-1, -3, -Infinity], function(position) {
ok(_.every(string, function(chr) {
return _.endsWith(string, chr, position) === false;
}));
strictEqual(_.endsWith(string, '', position), true);
});
});
test('should coerce `position` to an integer', 1, function() {
strictEqual(_.endsWith(string, 'ab', 2.2), true);
});
test('should return `true` when `target` is an empty string regardless of `position`', 1, function() {
ok(_.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) {
return _.endsWith(string, '', position, true);
}));
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.eq');
(function() {
test('should perform a `SameValueZero` comparison of two values', 11, function() {
strictEqual(_.eq(), true);
strictEqual(_.eq(undefined), true);
strictEqual(_.eq(0, -0), true);
strictEqual(_.eq(NaN, NaN), true);
strictEqual(_.eq(1, 1), true);
strictEqual(_.eq(null, undefined), false);
strictEqual(_.eq(1, Object(1)), false);
strictEqual(_.eq(1, '1'), false);
strictEqual(_.eq(1, '1'), false);
var object = { 'a': 1 };
strictEqual(_.eq(object, object), true);
strictEqual(_.eq(object, { 'a': 1 }), false);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.escape');
(function() {
var escaped = '&<>"'`\/',
unescaped = '&<>"\'`\/';
escaped += escaped;
unescaped += unescaped;
test('should escape values', 1, function() {
strictEqual(_.escape(unescaped), escaped);
});
test('should not escape the "/" character', 1, function() {
strictEqual(_.escape('/'), '/');
});
test('should handle strings with nothing to escape', 1, function() {
strictEqual(_.escape('abc'), 'abc');
});
test('should escape the same characters unescaped by `_.unescape`', 1, function() {
strictEqual(_.escape(_.unescape(escaped)), escaped);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.escapeRegExp');
(function() {
var escaped = '\\^\\$\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\\\',
unescaped = '^$.*+?()[]{}|\\';
test('should escape values', 1, function() {
strictEqual(_.escapeRegExp(unescaped + unescaped), escaped + escaped);
});
test('should handle strings with nothing to escape', 1, function() {
strictEqual(_.escapeRegExp('ghi'), 'ghi');
});
test('should return an empty string for empty values', 1, function() {
var values = [, null, undefined, ''],
expected = _.map(values, _.constant(''));
var actual = _.map(values, function(value, index) {
return index ? _.escapeRegExp(value) : _.escapeRegExp();
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.every');
(function() {
test('should return `true` for empty collections', 1, function() {
var expected = _.map(empties, _.constant(true));
var actual = _.map(empties, function(value) {
try {
return _.every(value, _.identity);
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should return `true` if `predicate` returns truthy for all elements in the collection', 1, function() {
strictEqual(_.every([true, 1, 'a'], _.identity), true);
});
test('should return `false` as soon as `predicate` returns falsey', 1, function() {
strictEqual(_.every([true, null, true], _.identity), false);
});
test('should work with collections of `undefined` values (test in IE < 9)', 1, function() {
strictEqual(_.every([undefined, undefined, undefined], _.identity), false);
});
test('should use `_.identity` when `predicate` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value, index) {
var array = [0];
return index ? _.every(array, value) : _.every(array);
});
deepEqual(actual, expected);
expected = _.map(values, _.constant(true));
actual = _.map(values, function(value, index) {
var array = [1];
return index ? _.every(array, value) : _.every(array);
});
deepEqual(actual, expected);
});
test('should work with a "_.property" style `predicate`', 2, function() {
var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }];
strictEqual(_.every(objects, 'a'), false);
strictEqual(_.every(objects, 'b'), true);
});
test('should work with a "_.matches" style `predicate`', 2, function() {
var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }];
strictEqual(_.every(objects, { 'a': 0 }), true);
strictEqual(_.every(objects, { 'b': 1 }), false);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var actual = _.map([[1]], _.every);
deepEqual(actual, [true]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('strict mode checks');
_.each(['assign', 'extend', 'bindAll', 'defaults'], function(methodName) {
var func = _[methodName],
isBindAll = methodName == 'bindAll';
test('`_.' + methodName + '` should ' + (isStrict ? '' : 'not ') + 'throw strict mode errors', 1, function() {
if (freeze) {
var object = freeze({ 'a': undefined, 'b': function() {} }),
pass = !isStrict;
try {
func(object, isBindAll ? 'b' : { 'a': 1 });
} catch(e) {
pass = !pass;
}
ok(pass);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.fill');
(function() {
test('should use a default `start` of `0` and a default `end` of `array.length`', 1, function() {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a'), ['a', 'a', 'a']);
});
test('should use `undefined` for `value` if not provided', 2, function() {
var array = [1, 2, 3],
actual = _.fill(array);
deepEqual(actual, Array(3));
ok(_.every(actual, function(value, index) { return index in actual; }));
});
test('should work with a positive `start`', 1, function() {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', 1), [1, 'a', 'a']);
});
test('should work with a `start` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(start) {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', start), [1, 2, 3]);
});
});
test('should treat falsey `start` values as `0`', 1, function() {
var expected = _.map(falsey, _.constant(['a', 'a', 'a']));
var actual = _.map(falsey, function(start) {
var array = [1, 2, 3];
return _.fill(array, 'a', start);
});
deepEqual(actual, expected);
});
test('should work with a negative `start`', 1, function() {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', -1), [1, 2, 'a']);
});
test('should work with a negative `start` <= negative `array.length`', 3, function() {
_.each([-3, -4, -Infinity], function(start) {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', start), ['a', 'a', 'a']);
});
});
test('should work with `start` >= `end`', 2, function() {
_.each([2, 3], function(start) {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', start, 2), [1, 2, 3]);
});
});
test('should work with a positive `end`', 1, function() {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', 0, 1), ['a', 2, 3]);
});
test('should work with a `end` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(end) {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', 0, end), ['a', 'a', 'a']);
});
});
test('should treat falsey `end` values, except `undefined`, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value === undefined ? ['a', 'a', 'a'] : [1, 2, 3];
});
var actual = _.map(falsey, function(end) {
var array = [1, 2, 3];
return _.fill(array, 'a', 0, end);
});
deepEqual(actual, expected);
});
test('should work with a negative `end`', 1, function() {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', 0, -1), ['a', 'a', 3]);
});
test('should work with a negative `end` <= negative `array.length`', 3, function() {
_.each([-3, -4, -Infinity], function(end) {
var array = [1, 2, 3];
deepEqual(_.fill(array, 'a', 0, end), [1, 2, 3]);
});
});
test('should coerce `start` and `end` to integers', 1, function() {
var positions = [[0.1, 1.6], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]];
var actual = _.map(positions, function(pos) {
var array = [1, 2, 3];
return _.fill.apply(_, [array, 'a'].concat(pos));
});
deepEqual(actual, [['a', 2, 3], ['a', 2, 3], ['a', 2, 3], [1, 'a', 'a'], ['a', 2, 3], [1, 2, 3]]);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2], [3, 4]],
actual = _.map(array, _.fill);
deepEqual(actual, [[0, 0], [1, 1]]);
});
test('should return a wrapped value when chaining', 3, function() {
if (!isNpm) {
var array = [1, 2, 3],
wrapped = _(array).fill('a'),
actual = wrapped.value();
ok(wrapped instanceof _);
deepEqual(actual, ['a', 'a', 'a']);
strictEqual(actual, array);
}
else {
skipTest(3);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.filter');
(function() {
var array = [1, 2, 3];
test('should return elements `predicate` returns truthy for', 1, function() {
var actual = _.filter(array, function(num) {
return num % 2;
});
deepEqual(actual, [1, 3]);
});
test('should iterate over an object with numeric keys (test in Mobile Safari 8)', 1, function() {
// Trigger a Mobile Safari 8 JIT bug.
// See https://github.com/lodash/lodash/issues/799.
var counter = 0,
object = { '1': 'foo', '8': 'bar', '50': 'baz' };
_.times(1000, function() {
_.filter([], _.constant(true));
});
_.filter(object, function() {
counter++;
return true;
});
strictEqual(counter, 3);
});
}());
/*--------------------------------------------------------------------------*/
_.each(['find', 'findLast', 'findIndex', 'findLastIndex', 'findKey', 'findLastKey'], function(methodName) {
QUnit.module('lodash.' + methodName);
var func = _[methodName],
isFindKey = /Key$/.test(methodName);
(function() {
var objects = [
{ 'a': 0, 'b': 0 },
{ 'a': 1, 'b': 1 },
{ 'a': 2, 'b': 2 }
];
var expected = ({
'find': [objects[1], undefined, objects[2], objects[1]],
'findLast': [objects[2], undefined, objects[2], objects[2]],
'findIndex': [1, -1, 2, 1],
'findLastIndex': [2, -1, 2, 2],
'findKey': ['1', undefined, '2', '1'],
'findLastKey': ['2', undefined, '2', '2']
})[methodName];
test('should return the found value', 1, function() {
strictEqual(func(objects, function(object) { return object.a; }), expected[0]);
});
test('should return `' + expected[1] + '` if value is not found', 1, function() {
strictEqual(func(objects, function(object) { return object.a === 3; }), expected[1]);
});
test('should work with a "_.matches" style `predicate`', 1, function() {
strictEqual(func(objects, { 'b': 2 }), expected[2]);
});
test('should work with a "_.matchesProperty" style `predicate`', 1, function() {
strictEqual(func(objects, ['b', 2]), expected[2]);
});
test('should work with a "_.property" style `predicate`', 1, function() {
strictEqual(func(objects, 'b'), expected[3]);
});
test('should return `' + expected[1] + '` for empty collections', 1, function() {
var emptyValues = _.endsWith(methodName, 'Index') ? _.reject(empties, _.isPlainObject) : empties,
expecting = _.map(emptyValues, _.constant(expected[1]));
var actual = _.map(emptyValues, function(value) {
try {
return func(value, { 'a': 3 });
} catch(e) {}
});
deepEqual(actual, expecting);
});
}());
(function() {
var array = [1, 2, 3, 4];
var expected = ({
'find': 1,
'findLast': 4,
'findIndex': 0,
'findLastIndex': 3,
'findKey': '0',
'findLastKey': '3'
})[methodName];
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_(array)[methodName](), expected);
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(array).chain()[methodName]() instanceof _);
}
else {
skipTest();
}
});
test('should not execute immediately when explicitly chaining', 1, function() {
if (!isNpm) {
var wrapped = _(array).chain()[methodName]();
strictEqual(wrapped.__wrapped__, array);
}
else {
skipTest();
}
});
test('should work in a lazy chain sequence', 2, function() {
if (!isNpm) {
var largeArray = _.range(1, LARGE_ARRAY_SIZE + 1),
smallArray = array;
_.times(2, function(index) {
var array = index ? largeArray : smallArray,
predicate = function(value) { return value % 2; },
wrapped = _(array).filter(predicate);
strictEqual(wrapped[methodName](), func(_.filter(array, predicate)));
});
}
else {
skipTest(2);
}
});
}());
(function() {
var expected = ({
'find': 1,
'findLast': 2,
'findKey': 'a',
'findLastKey': 'b'
})[methodName];
if (expected != null) {
test('should work with an object for `collection`', 1, function() {
var actual = func({ 'a': 1, 'b': 2, 'c': 3 }, function(num) {
return num < 3;
});
strictEqual(actual, expected);
});
}
}());
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.find and lodash.findLast');
_.each(['find', 'findLast'], function(methodName) {
var isFind = methodName == 'find';
test('`_.' + methodName + '` should support shortcut fusion', 3, function() {
if (!isNpm) {
var findCount = 0,
mapCount = 0;
var iteratee = function(value) {
mapCount++;
return value * value;
};
var predicate = function(value) {
findCount++;
return value % 2 == 0;
};
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
result = _(array).map(iteratee)[methodName](predicate);
strictEqual(findCount, isFind ? 2 : 1);
strictEqual(mapCount, isFind ? 2 : 1);
strictEqual(result, isFind ? 4 : square(LARGE_ARRAY_SIZE));
}
else {
skipTest(3);
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.first');
(function() {
var array = [1, 2, 3, 4];
test('should return the first element', 1, function() {
strictEqual(_.first(array), 1);
});
test('should return `undefined` when querying empty arrays', 1, function() {
var array = [];
array['-1'] = 1;
strictEqual(_.first(array), undefined);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.first);
deepEqual(actual, [1, 4, 7]);
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_(array).first(), 1);
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(array).chain().first() instanceof _);
}
else {
skipTest();
}
});
test('should not execute immediately when explicitly chaining', 1, function() {
if (!isNpm) {
var wrapped = _(array).chain().first();
strictEqual(wrapped.__wrapped__, array);
}
else {
skipTest();
}
});
test('should work in a lazy chain sequence', 2, function() {
if (!isNpm) {
var largeArray = _.range(1, LARGE_ARRAY_SIZE + 1),
smallArray = array;
_.times(2, function(index) {
var array = index ? largeArray : smallArray,
predicate = function(value) { return value % 2; },
wrapped = _(array).filter(predicate);
strictEqual(wrapped.first(), _.first(_.filter(array, predicate)));
});
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.take');
(function() {
var array = [1, 2, 3];
test('should take the first two elements', 1, function() {
deepEqual(_.take(array, 2), [1, 2]);
});
test('should treat falsey `n` values, except nullish, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value == null ? [1] : [];
});
var actual = _.map(falsey, function(n) {
return _.take(array, n);
});
deepEqual(actual, expected);
});
test('should return an empty array when `n` < `1`', 3, function() {
_.each([0, -1, -Infinity], function(n) {
deepEqual(_.take(array, n), []);
});
});
test('should return all elements when `n` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(n) {
deepEqual(_.take(array, n), array);
});
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.take);
deepEqual(actual, [[1], [4], [7]]);
});
test('should work in a lazy chain sequence', 6, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
values = [],
predicate = function(value) { values.push(value); return value > 2; },
actual = _(array).take(2).take().value();
deepEqual(actual, _.take(_.take(array, 2)));
actual = _(array).filter(predicate).take(2).take().value();
deepEqual(values, [1, 2, 3]);
deepEqual(actual, _.take(_.take(_.filter(array, predicate), 2)));
actual = _(array).take(6).takeRight(4).take(2).takeRight().value();
deepEqual(actual, _.takeRight(_.take(_.takeRight(_.take(array, 6), 4), 2)));
values = [];
actual = _(array).take(array.length - 1).filter(predicate).take(6).takeRight(4).take(2).takeRight().value();
deepEqual(values, [1, 2, 3, 4, 5, 6, 7, 8]);
deepEqual(actual, _.takeRight(_.take(_.takeRight(_.take(_.filter(_.take(array, array.length - 1), predicate), 6), 4), 2)));
}
else {
skipTest(6);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.takeRight');
(function() {
var array = [1, 2, 3];
test('should take the last two elements', 1, function() {
deepEqual(_.takeRight(array, 2), [2, 3]);
});
test('should treat falsey `n` values, except nullish, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value == null ? [3] : [];
});
var actual = _.map(falsey, function(n) {
return _.takeRight(array, n);
});
deepEqual(actual, expected);
});
test('should return an empty array when `n` < `1`', 3, function() {
_.each([0, -1, -Infinity], function(n) {
deepEqual(_.takeRight(array, n), []);
});
});
test('should return all elements when `n` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(n) {
deepEqual(_.takeRight(array, n), array);
});
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.takeRight);
deepEqual(actual, [[3], [6], [9]]);
});
test('should work in a lazy chain sequence', 6, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
values = [],
predicate = function(value) { values.push(value); return value < 9; },
actual = _(array).takeRight(2).takeRight().value();
deepEqual(actual, _.takeRight(_.takeRight(array)));
actual = _(array).filter(predicate).takeRight(2).takeRight().value();
deepEqual(values, array);
deepEqual(actual, _.takeRight(_.takeRight(_.filter(array, predicate), 2)));
actual = _(array).takeRight(6).take(4).takeRight(2).take().value();
deepEqual(actual, _.take(_.takeRight(_.take(_.takeRight(array, 6), 4), 2)));
values = [];
actual = _(array).filter(predicate).takeRight(6).take(4).takeRight(2).take().value();
deepEqual(values, array);
deepEqual(actual, _.take(_.takeRight(_.take(_.takeRight(_.filter(array, predicate), 6), 4), 2)));
}
else {
skipTest(6);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.takeRightWhile');
(function() {
var array = [1, 2, 3, 4];
var objects = [
{ 'a': 0, 'b': 0 },
{ 'a': 1, 'b': 1 },
{ 'a': 2, 'b': 2 }
];
test('should take elements while `predicate` returns truthy', 1, function() {
var actual = _.takeRightWhile(array, function(num) {
return num > 2;
});
deepEqual(actual, [3, 4]);
});
test('should provide the correct `predicate` arguments', 1, function() {
var args;
_.takeRightWhile(array, function() {
args = slice.call(arguments);
});
deepEqual(args, [4, 3, array]);
});
test('should work with a "_.matches" style `predicate`', 1, function() {
deepEqual(_.takeRightWhile(objects, { 'b': 2 }), objects.slice(2));
});
test('should work with a "_.matchesProperty" style `predicate`', 1, function() {
deepEqual(_.takeRightWhile(objects, ['b', 2]), objects.slice(2));
});
test('should work with a "_.property" style `predicate`', 1, function() {
deepEqual(_.takeRightWhile(objects, 'b'), objects.slice(1));
});
test('should work in a lazy chain sequence', 3, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
predicate = function(num) { return num > 2; },
expected = _.takeRightWhile(array, predicate),
wrapped = _(array).takeRightWhile(predicate);
deepEqual(wrapped.value(), expected);
deepEqual(wrapped.reverse().value(), expected.slice().reverse());
strictEqual(wrapped.last(), _.last(expected));
}
else {
skipTest(3);
}
});
test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() {
if (!isNpm) {
var args,
array = _.range(0, LARGE_ARRAY_SIZE + 1),
expected = [square(LARGE_ARRAY_SIZE), LARGE_ARRAY_SIZE - 1, _.map(array.slice(1), square)];
_(array).slice(1).takeRightWhile(function(value, index, array) {
args = slice.call(arguments)
}).value();
deepEqual(args, [LARGE_ARRAY_SIZE, LARGE_ARRAY_SIZE - 1, array.slice(1)]);
_(array).slice(1).map(square).takeRightWhile(function(value, index, array) {
args = slice.call(arguments)
}).value();
deepEqual(args, expected);
_(array).slice(1).map(square).takeRightWhile(function(value, index) {
args = slice.call(arguments)
}).value();
deepEqual(args, expected);
_(array).slice(1).map(square).takeRightWhile(function(index) {
args = slice.call(arguments);
}).value();
deepEqual(args, [square(LARGE_ARRAY_SIZE)]);
_(array).slice(1).map(square).takeRightWhile(function() {
args = slice.call(arguments);
}).value();
deepEqual(args, expected);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.takeWhile');
(function() {
var array = [1, 2, 3, 4];
var objects = [
{ 'a': 2, 'b': 2 },
{ 'a': 1, 'b': 1 },
{ 'a': 0, 'b': 0 }
];
test('should take elements while `predicate` returns truthy', 1, function() {
var actual = _.takeWhile(array, function(num) {
return num < 3;
});
deepEqual(actual, [1, 2]);
});
test('should provide the correct `predicate` arguments', 1, function() {
var args;
_.takeWhile(array, function() {
args = slice.call(arguments);
});
deepEqual(args, [1, 0, array]);
});
test('should work with a "_.matches" style `predicate`', 1, function() {
deepEqual(_.takeWhile(objects, { 'b': 2 }), objects.slice(0, 1));
});
test('should work with a "_.matchesProperty" style `predicate`', 1, function() {
deepEqual(_.takeWhile(objects, ['b', 2]), objects.slice(0, 1));
});
test('should work with a "_.property" style `predicate`', 1, function() {
deepEqual(_.takeWhile(objects, 'b'), objects.slice(0, 2));
});
test('should work in a lazy chain sequence', 3, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
predicate = function(num) { return num < 3; },
expected = _.takeWhile(array, predicate),
wrapped = _(array).takeWhile(predicate);
deepEqual(wrapped.value(), expected);
deepEqual(wrapped.reverse().value(), expected.slice().reverse());
strictEqual(wrapped.last(), _.last(expected));
}
else {
skipTest(3);
}
});
test('should work in a lazy chain sequence with `take`', 1, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1);
var actual = _(array)
.takeWhile(function(num) { return num < 4; })
.take(2)
.takeWhile(function(num) { return num == 1; })
.value();
deepEqual(actual, [1]);
}
else {
skipTest();
}
});
test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() {
if (!isNpm) {
var args,
array = _.range(0, LARGE_ARRAY_SIZE + 1),
expected = [1, 0, _.map(array.slice(1), square)];
_(array).slice(1).takeWhile(function(value, index, array) {
args = slice.call(arguments);
}).value();
deepEqual(args, [1, 0, array.slice(1)]);
_(array).slice(1).map(square).takeWhile(function(value, index, array) {
args = slice.call(arguments);
}).value();
deepEqual(args, expected);
_(array).slice(1).map(square).takeWhile(function(value, index) {
args = slice.call(arguments);
}).value();
deepEqual(args, expected);
_(array).slice(1).map(square).takeWhile(function(value) {
args = slice.call(arguments);
}).value();
deepEqual(args, [1]);
_(array).slice(1).map(square).takeWhile(function() {
args = slice.call(arguments);
}).value();
deepEqual(args, expected);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('flatten methods');
(function() {
var args = arguments;
test('should perform a shallow flatten', 1, function() {
var array = [[['a']], [['b']]];
deepEqual(_.flatten(array), [['a'], ['b']]);
});
test('should flatten `arguments` objects', 2, function() {
var array = [args, [args]];
deepEqual(_.flatten(array), [1, 2, 3, args]);
deepEqual(_.flattenDeep(array), [1, 2, 3, 1, 2, 3]);
});
test('should treat sparse arrays as dense', 6, function() {
var array = [[1, 2, 3], Array(3)],
expected = [1, 2, 3];
expected.push(undefined, undefined, undefined);
_.each([_.flatten(array), _.flatten(array, true), _.flattenDeep(array)], function(actual) {
deepEqual(actual, expected);
ok('4' in actual);
});
});
test('should work with extremely large arrays', 3, function() {
// Test in modern browsers only to avoid browser hangs.
_.times(3, function(index) {
if (freeze) {
var expected = Array(5e5);
try {
if (index) {
var actual = actual == 1 ? _.flatten([expected], true) : _.flattenDeep([expected]);
} else {
actual = _.flatten(expected);
}
deepEqual(actual, expected);
} catch(e) {
ok(false, e.message);
}
}
else {
skipTest();
}
});
});
test('should work with empty arrays', 2, function() {
var array = [[], [[]], [[], [[[]]]]];
deepEqual(_.flatten(array), [[], [], [[[]]]]);
deepEqual(_.flattenDeep(array), []);
});
test('should support flattening of nested arrays', 2, function() {
var array = [1, [2, 3], 4, [[5]]];
deepEqual(_.flatten(array), [1, 2, 3, 4, [5]]);
deepEqual(_.flattenDeep(array), [1, 2, 3, 4, 5]);
});
test('should return an empty array for non array-like objects', 3, function() {
var expected = [];
deepEqual(_.flatten({ 'a': 1 }), expected);
deepEqual(_.flatten({ 'a': 1 }, true), expected);
deepEqual(_.flattenDeep({ 'a': 1 }), expected);
});
test('should return a wrapped value when chaining', 4, function() {
if (!isNpm) {
var wrapped = _([1, [2], [3, [4]]]),
actual = wrapped.flatten();
ok(actual instanceof _);
deepEqual(actual.value(), [1, 2, 3, [4]]);
actual = wrapped.flattenDeep();
ok(actual instanceof _);
deepEqual(actual.value(), [1, 2, 3, 4]);
}
else {
skipTest(4);
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.forEach');
(function() {
test('should be aliased', 1, function() {
strictEqual(_.each, _.forEach);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.forEachRight');
(function() {
test('should be aliased', 1, function() {
strictEqual(_.eachRight, _.forEachRight);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('forIn methods');
_.each(['forIn', 'forInRight'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` iterates over inherited properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var keys = [];
func(new Foo, function(value, key) { keys.push(key); });
deepEqual(keys.sort(), ['a', 'b']);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('forOwn methods');
_.each(['forOwn', 'forOwnRight'], function(methodName) {
var func = _[methodName];
test('should iterate over `length` properties', 1, function() {
var object = { '0': 'zero', '1': 'one', 'length': 2 },
props = [];
func(object, function(value, prop) { props.push(prop); });
deepEqual(props.sort(), ['0', '1', 'length']);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('iteration methods');
(function() {
var methods = [
'_baseEach',
'countBy',
'every',
'filter',
'find',
'findIndex',
'findKey',
'findLast',
'findLastIndex',
'findLastKey',
'forEach',
'forEachRight',
'forIn',
'forInRight',
'forOwn',
'forOwnRight',
'groupBy',
'indexBy',
'map',
'mapKeys',
'mapValues',
'maxBy',
'minBy',
'omitBy',
'partition',
'pickBy',
'reject',
'some'
];
var arrayMethods = [
'findIndex',
'findLastIndex',
'maxBy',
'minBy'
];
var collectionMethods = [
'_baseEach',
'countBy',
'every',
'filter',
'find',
'findLast',
'forEach',
'forEachRight',
'groupBy',
'indexBy',
'map',
'partition',
'reduce',
'reduceRight',
'reject',
'some'
];
var forInMethods = [
'forIn',
'forInRight',
'omitBy',
'pickBy'
];
var iterationMethods = [
'_baseEach',
'forEach',
'forEachRight',
'forIn',
'forInRight',
'forOwn',
'forOwnRight'
]
var objectMethods = [
'findKey',
'findLastKey',
'forIn',
'forInRight',
'forOwn',
'forOwnRight',
'mapKeys',
'mapValues',
'omitBy',
'pickBy'
];
var rightMethods = [
'findLast',
'findLastIndex',
'findLastKey',
'forEachRight',
'forInRight',
'forOwnRight'
];
var unwrappedMethods = [
'every',
'find',
'findIndex',
'findKey',
'findLast',
'findLastIndex',
'findLastKey',
'forEach',
'forEachRight',
'forIn',
'forInRight',
'forOwn',
'forOwnRight',
'max',
'maxBy',
'min',
'minBy',
'some'
];
_.each(methods, function(methodName) {
var array = [1, 2, 3],
func = _[methodName],
isExtremum = /^(?:max|min)/.test(methodName),
isFind = /^find/.test(methodName),
isSome = methodName == 'some';
test('`_.' + methodName + '` should provide the correct iteratee arguments', 1, function() {
if (func) {
var args,
expected = [1, 0, array];
func(array, function() {
args || (args = slice.call(arguments));
});
if (_.includes(rightMethods, methodName)) {
expected[0] = 3;
expected[1] = 2;
}
if (_.includes(objectMethods, methodName)) {
expected[1] += '';
}
if (isExtremum) {
expected.length = 1;
}
deepEqual(args, expected);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() {
if (func) {
var array = [1];
array[2] = 3;
var expected = [[1, 0, array], [undefined, 1, array], [3, 2, array]];
if (isExtremum) {
expected = _.map(expected, function(args) {
return args.slice(0, 1);
});
}
if (_.includes(objectMethods, methodName)) {
expected = _.map(expected, function(args) {
args[1] += '';
return args;
});
}
if (_.includes(rightMethods, methodName)) {
expected.reverse();
}
var argsList = [];
func(array, function() {
argsList.push(slice.call(arguments));
return !(isFind || isSome);
});
deepEqual(argsList, expected);
}
else {
skipTest();
}
});
});
_.each(_.difference(methods, objectMethods), function(methodName) {
var array = [1, 2, 3],
func = _[methodName],
isEvery = methodName == 'every';
array.a = 1;
test('`_.' + methodName + '` should not iterate custom properties on arrays', 1, function() {
if (func) {
var keys = [];
func(array, function(value, key) {
keys.push(key);
return isEvery;
});
ok(!_.includes(keys, 'a'));
}
else {
skipTest();
}
});
});
_.each(_.difference(methods, unwrappedMethods), function(methodName) {
var array = [1, 2, 3],
func = _[methodName],
isBaseEach = methodName == '_baseEach';
test('`_.' + methodName + '` should return a wrapped value when implicitly chaining', 1, function() {
if (!(isBaseEach || isNpm)) {
var wrapped = _(array)[methodName](_.noop);
ok(wrapped instanceof _);
}
else {
skipTest();
}
});
});
_.each(unwrappedMethods, function(methodName) {
var array = [1, 2, 3],
func = _[methodName];
test('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
var actual = _(array)[methodName](_.noop);
ok(!(actual instanceof _));
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 2, function() {
if (!isNpm) {
var wrapped = _(array).chain(),
actual = wrapped[methodName](_.noop);
ok(actual instanceof _);
notStrictEqual(actual, wrapped);
}
else {
skipTest(2);
}
});
});
_.each(_.difference(methods, arrayMethods, forInMethods), function(methodName) {
var array = [1, 2, 3],
func = _[methodName];
test('`_.' + methodName + '` iterates over own properties of objects', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
if (func) {
var keys = [];
func(new Foo, function(value, key) { keys.push(key); });
deepEqual(keys, ['a']);
}
else {
skipTest();
}
});
});
_.each(iterationMethods, function(methodName) {
var array = [1, 2, 3],
func = _[methodName];
test('`_.' + methodName + '` should return the collection', 1, function() {
if (func) {
strictEqual(func(array, Boolean), array);
}
else {
skipTest();
}
});
});
_.each(collectionMethods, function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should use `isArrayLike` to determine whether a value is array-like', 3, function() {
if (func) {
var isIteratedAsObject = function(object) {
var result = false;
func(object, function() { result = true; }, 0);
return result;
};
var values = [-1, '1', 1.1, Object(1), MAX_SAFE_INTEGER + 1],
expected = _.map(values, _.constant(true));
var actual = _.map(values, function(length) {
return isIteratedAsObject({ 'length': length });
});
var Foo = function(a) {};
Foo.a = 1;
deepEqual(actual, expected);
ok(isIteratedAsObject(Foo));
ok(!isIteratedAsObject({ 'length': 0 }));
}
else {
skipTest(3);
}
});
});
_.each(methods, function(methodName) {
var array = [1, 2, 3],
func = _[methodName],
isFind = /^find/.test(methodName),
isSome = methodName == 'some',
isReduce = /^reduce/.test(methodName);
test('`_.' + methodName + '` should ignore changes to `array.length`', 1, function() {
if (func) {
var count = 0,
array = [1];
func(array, function() {
if (++count == 1) {
array.push(2);
}
return !(isFind || isSome);
}, isReduce ? array : null);
strictEqual(count, 1);
}
else {
skipTest();
}
});
});
_.each(_.difference(_.union(methods, collectionMethods), arrayMethods), function(methodName) {
var func = _[methodName],
isFind = /^find/.test(methodName),
isSome = methodName == 'some',
isReduce = /^reduce/.test(methodName);
test('`_.' + methodName + '` should ignore added `object` properties', 1, function() {
if (func) {
var count = 0,
object = { 'a': 1 };
func(object, function() {
if (++count == 1) {
object.b = 2;
}
return !(isFind || isSome);
}, isReduce ? object : null);
strictEqual(count, 1);
}
else {
skipTest();
}
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('object assignments');
_.each(['assign', 'defaults', 'extend', 'merge'], function(methodName) {
var func = _[methodName],
isAssign = methodName == 'assign',
isDefaults = methodName == 'defaults';
test('`_.' + methodName + '` should coerce primitives to objects', 1, function() {
var expected = _.map(falsey, _.constant(true));
var actual = _.map(falsey, function(object, index) {
var result = index ? func(object) : func();
return _.isEqual(result, Object(object));
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should assign own ' + (isAssign ? '' : 'and inherited ') + 'source properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var expected = isAssign ? { 'a': 1 } : { 'a': 1, 'b': 2 };
deepEqual(func({}, new Foo), expected);
});
test('`_.' + methodName + '` should not error on nullish sources', 1, function() {
try {
deepEqual(func({ 'a': 1 }, undefined, { 'b': 2 }, null), { 'a': 1, 'b': 2 });
} catch(e) {
ok(false, e.message);
}
});
test('`_.' + methodName + '` should not error when `object` is nullish and source objects are provided', 1, function() {
var expected = _.times(2, _.constant(true));
var actual = _.map([null, undefined], function(value) {
try {
return _.isEqual(func(value, { 'a': 1 }), {});
} catch(e) {
return false;
}
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should work as an iteratee for methods like `_.reduce`', 1, function() {
var array = [{ 'a': 1 }, { 'b': 2 }, { 'c': 3 }],
expected = { 'a': 1, 'b': 2, 'c': 3 };
expected.a = isDefaults ? 0 : 1;
deepEqual(_.reduce(array, func, { 'a': 0 }), expected);
});
test('`_.' + methodName + '` should not return the existing wrapped value when chaining', 1, function() {
if (!isNpm) {
var wrapped = _({ 'a': 1 }),
actual = wrapped[methodName]({ 'b': 2 });
notStrictEqual(actual, wrapped);
}
else {
skipTest();
}
});
});
_.each(['assign', 'extend', 'merge'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should not treat `object` as `source`', 1, function() {
function Foo() {}
Foo.prototype.a = 1;
var actual = func(new Foo, { 'b': 2 });
ok(!_.has(actual, 'a'));
});
});
_.each(['assign', 'assignWith', 'defaults', 'extend', 'extendWith', 'merge', 'mergeWith'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should not assign values that are the same as their destinations', 4, function() {
_.each(['a', ['a'], { 'a': 1 }, NaN], function(value) {
if (defineProperty) {
var object = {},
pass = true;
defineProperty(object, 'a', {
'get': _.constant(value),
'set': function() { pass = false; }
});
func(object, { 'a': value });
ok(pass, value);
}
else {
skipTest();
}
});
});
});
_.each(['assignWith', 'extendWith', 'mergeWith'], function(methodName) {
var func = _[methodName],
isMergeWith = methodName == 'mergeWith';
test('`_.' + methodName + '` should provide the correct `customizer` arguments', 3, function() {
var args,
object = { 'a': 1 },
source = { 'a': 2 },
expected = [1, 2, 'a', object, source];
func(object, source, function() {
args || (args = slice.call(arguments));
});
if (isMergeWith) {
expected.push(undefined, undefined);
}
deepEqual(args, expected, 'primitive property values');
args = null;
object = { 'a': 1 };
source = { 'b': 2 };
func(object, source, function() {
args || (args = slice.call(arguments));
});
expected = [undefined, 2, 'b', object, source];
if (isMergeWith) {
expected.push(undefined, undefined);
}
deepEqual(args, expected, 'missing destination property');
var argsList = [],
objectValue = [1, 2],
sourceValue = { 'b': 2 };
object = { 'a': objectValue };
source = { 'a': sourceValue };
func(object, source, function() {
argsList.push(slice.call(arguments));
});
expected = [[objectValue, sourceValue, 'a', object, source]];
if (isMergeWith) {
expected[0].push([sourceValue], [sourceValue]);
expected.push([undefined, 2, 'b', sourceValue, sourceValue, [sourceValue], [sourceValue]]);
}
deepEqual(argsList, expected, 'object property values');
});
test('`_.' + methodName + '` should not treat the second argument as a `customizer` callback', 2, function() {
function callback() {}
callback.b = 2;
var actual = func({ 'a': 1 }, callback);
deepEqual(actual, { 'a': 1, 'b': 2 });
actual = func({ 'a': 1 }, callback, { 'c': 3 });
deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 });
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('exit early');
_.each(['_baseEach', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'transform'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` can exit early when iterating arrays', 1, function() {
if (func) {
var array = [1, 2, 3],
values = [];
func(array, function(value, other) {
values.push(_.isArray(value) ? other : value);
return false;
});
deepEqual(values, [_.endsWith(methodName, 'Right') ? 3 : 1]);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` can exit early when iterating objects', 1, function() {
if (func) {
var object = { 'a': 1, 'b': 2, 'c': 3 },
values = [];
func(object, function(value, other) {
values.push(_.isArray(value) ? other : value);
return false;
});
strictEqual(values.length, 1);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('`__proto__` property bugs');
(function() {
test('internal data objects should work with the `__proto__` key', 4, function() {
var stringLiteral = '__proto__',
stringObject = Object(stringLiteral),
expected = [stringLiteral, stringObject];
var largeArray = _.times(LARGE_ARRAY_SIZE, function(count) {
return count % 2 ? stringObject : stringLiteral;
});
deepEqual(_.difference(largeArray, largeArray), []);
deepEqual(_.intersection(largeArray, largeArray), expected);
deepEqual(_.uniq(largeArray), expected);
deepEqual(_.without.apply(_, [largeArray].concat(largeArray)), []);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.functions');
(function() {
test('should return the function names of an object', 1, function() {
var object = { 'a': 'a', 'b': _.identity, 'c': /x/, 'd': _.each };
deepEqual(_.functions(object).sort(), ['b', 'd']);
});
test('should include inherited functions', 1, function() {
function Foo() {
this.a = _.identity;
this.b = 'b';
}
Foo.prototype.c = _.noop;
deepEqual(_.functions(new Foo).sort(), ['a', 'c']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.groupBy');
(function() {
var array = [4.2, 6.1, 6.4];
test('should use `_.identity` when `iteratee` is nullish', 1, function() {
var array = [4, 6, 6],
values = [, null, undefined],
expected = _.map(values, _.constant({ '4': [4], '6': [6, 6] }));
var actual = _.map(values, function(value, index) {
return index ? _.groupBy(array, value) : _.groupBy(array);
});
deepEqual(actual, expected);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.groupBy(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [4.2, 0, array]);
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var actual = _.groupBy(['one', 'two', 'three'], 'length');
deepEqual(actual, { '3': ['one', 'two'], '5': ['three'] });
});
test('should only add values to own, not inherited, properties', 2, function() {
var actual = _.groupBy([4.2, 6.1, 6.4], function(num) {
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
});
deepEqual(actual.constructor, [4.2]);
deepEqual(actual.hasOwnProperty, [6.1, 6.4]);
});
test('should work with a number for `iteratee`', 2, function() {
var array = [
[1, 'a'],
[2, 'a'],
[2, 'b']
];
deepEqual(_.groupBy(array, 0), { '1': [[1, 'a']], '2': [[2, 'a'], [2, 'b']] });
deepEqual(_.groupBy(array, 1), { 'a': [[1, 'a'], [2, 'a']], 'b': [[2, 'b']] });
});
test('should work with an object for `collection`', 1, function() {
var actual = _.groupBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) {
return Math.floor(num);
});
deepEqual(actual, { '4': [4.2], '6': [6.1, 6.4] });
});
test('should work in a lazy chain sequence', 1, function() {
if (!isNpm) {
var array = _.range(LARGE_ARRAY_SIZE).concat(
_.range(Math.floor(LARGE_ARRAY_SIZE / 2), LARGE_ARRAY_SIZE),
_.range(Math.floor(LARGE_ARRAY_SIZE / 1.5), LARGE_ARRAY_SIZE)
);
var iteratee = function(value) { value.push(value[0]); return value; },
predicate = function(value) { return value[0] > 1; },
actual = _(array).groupBy().map(iteratee).filter(predicate).take().value();
deepEqual(actual, _.take(_.filter(_.map(_.groupBy(array), iteratee), predicate)));
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.gt');
(function() {
test('should return `true` if `value` is greater than `other`', 2, function() {
strictEqual(_.gt(3, 1), true);
strictEqual(_.gt('def', 'abc'), true);
});
test('should return `false` if `value` is less than or equal to `other`', 4, function() {
strictEqual(_.gt(1, 3), false);
strictEqual(_.gt(3, 3), false);
strictEqual(_.gt('abc', 'def'), false);
strictEqual(_.gt('def', 'def'), false);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.gte');
(function() {
test('should return `true` if `value` is greater than or equal to `other`', 4, function() {
strictEqual(_.gte(3, 1), true);
strictEqual(_.gte(3, 3), true);
strictEqual(_.gte('def', 'abc'), true);
strictEqual(_.gte('def', 'def'), true);
});
test('should return `false` if `value` is less than `other`', 2, function() {
strictEqual(_.gte(1, 3), false);
strictEqual(_.gte('abc', 'def'), false);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('has methods');
_.each(['has', 'hasIn'], function(methodName) {
var args = (function() { return arguments; }(1, 2, 3)),
func = _[methodName],
isHas = methodName == 'has';
test('`_.' + methodName + '` should check for own properties', 2, function() {
var object = { 'a': 1 };
_.each(['a', ['a']], function(path) {
strictEqual(func(object, path), true);
});
});
test('`_.' + methodName + '` should not use the `hasOwnProperty` method of the object', 1, function() {
var object = { 'hasOwnProperty': null, 'a': 1 };
strictEqual(func(object, 'a'), true);
});
test('`_.' + methodName + '` should support deep paths', 2, function() {
var object = { 'a': { 'b': { 'c': 3 } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
strictEqual(func(object, path), true);
});
});
test('`_.' + methodName + '` should work with non-string `path` arguments', 2, function() {
var array = [1, 2, 3];
_.each([1, [1]], function(path) {
strictEqual(func(array, path), true);
});
});
test('`_.' + methodName + '` should coerce key to a string', 1, function() {
function fn() {}
fn.toString = _.constant('fn');
var expected = [1, 1, 2, 2, 3, 3, 4, 4],
objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }],
values = [null, undefined, fn, {}];
var actual = _.transform(objects, function(result, object, index) {
var key = values[index];
_.each([key, [key]], function(path) {
var prop = _.property(key);
result.push(prop(object));
});
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should return `' + (isHas ? 'false' : 'true') + '` for inherited properties', 2, function() {
function Foo() {}
Foo.prototype.a = 1;
_.each(['a', ['a']], function(path) {
strictEqual(func(new Foo, path), !isHas);
});
});
test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() {
strictEqual(func(Array(1), 0), true);
});
test('`_.' + methodName + '` should work with `arguments` objects', 1, function() {
strictEqual(func(args, 1), true);
});
test('`_.' + methodName + '` should check for a key over a path', 2, function() {
var object = { 'a.b.c': 3, 'a': { 'b': { 'c': 4 } } };
_.each(['a.b.c', ['a.b.c']], function(path) {
strictEqual(func(object, path), true);
});
});
test('`_.' + methodName + '` should return `false` when `object` is nullish', 2, function() {
var values = [null, undefined],
expected = _.map(values, _.constant(false));
_.each(['constructor', ['constructor']], function(path) {
var actual = _.map(values, function(value) {
return func(value, path);
});
deepEqual(actual, expected);
});
});
test('`_.' + methodName + '` should return `false` with deep paths when `object` is nullish', 2, function() {
var values = [null, undefined],
expected = _.map(values, _.constant(false));
_.each(['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']], function(path) {
var actual = _.map(values, function(value) {
return func(value, path);
});
deepEqual(actual, expected);
});
});
test('`_.' + methodName + '` should return `false` if parts of `path` are missing', 4, function() {
var object = {};
_.each(['a', 'a[1].b.c', ['a'], ['a', '1', 'b', 'c']], function(path) {
strictEqual(func(object, path), false);
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.identity');
(function() {
test('should return the first argument provided', 1, function() {
var object = { 'name': 'fred' };
strictEqual(_.identity(object), object);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.includes');
(function() {
_.each({
'an `arguments` object': arguments,
'an array': [1, 2, 3, 4],
'an object': { 'a': 1, 'b': 2, 'c': 3, 'd': 4 },
'a string': '1234'
},
function(collection, key) {
var isStr = typeof collection == 'string',
values = _.toArray(collection),
length = values.length;
test('should work with ' + key + ' and return `true` for matched values', 1, function() {
strictEqual(_.includes(collection, 3), true);
});
test('should work with ' + key + ' and return `false` for unmatched values', 1, function() {
strictEqual(_.includes(collection, 5), false);
});
test('should work with ' + key + ' and a positive `fromIndex`', 2, function() {
strictEqual(_.includes(collection, values[2], 2), true);
strictEqual(_.includes(collection, values[1], 2), false);
});
test('should work with ' + key + ' and a `fromIndex` >= `collection.length`', 12, function() {
_.each([4, 6, Math.pow(2, 32), Infinity], function(fromIndex) {
strictEqual(_.includes(collection, 1, fromIndex), false);
strictEqual(_.includes(collection, undefined, fromIndex), false);
strictEqual(_.includes(collection, '', fromIndex), (isStr && fromIndex == length));
});
});
test('should work with ' + key + ' and treat falsey `fromIndex` values as `0`', 1, function() {
var expected = _.map(falsey, _.constant(true));
var actual = _.map(falsey, function(fromIndex) {
return _.includes(collection, values[0], fromIndex);
});
deepEqual(actual, expected);
});
test('should work with ' + key + ' and treat non-number `fromIndex` values as `0`', 1, function() {
strictEqual(_.includes(collection, values[0], '1'), true);
});
test('should work with ' + key + ' and a negative `fromIndex`', 2, function() {
strictEqual(_.includes(collection, values[2], -2), true);
strictEqual(_.includes(collection, values[1], -2), false);
});
test('should work with ' + key + ' and a negative `fromIndex` <= negative `collection.length`', 3, function() {
_.each([-4, -6, -Infinity], function(fromIndex) {
strictEqual(_.includes(collection, values[0], fromIndex), true);
});
});
test('should work with ' + key + ' and floor `position` values', 1, function() {
strictEqual(_.includes(collection, 2, 1.2), true);
});
test('should work with ' + key + ' and return an unwrapped value implicitly when chaining', 1, function() {
if (!isNpm) {
strictEqual(_(collection).includes(3), true);
}
else {
skipTest();
}
});
test('should work with ' + key + ' and return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(collection).chain().includes(3) instanceof _);
}
else {
skipTest();
}
});
});
_.each({
'literal': 'abc',
'object': Object('abc')
},
function(collection, key) {
test('should work with a string ' + key + ' for `collection`', 2, function() {
strictEqual(_.includes(collection, 'bc'), true);
strictEqual(_.includes(collection, 'd'), false);
});
});
test('should return `false` for empty collections', 1, function() {
var expected = _.map(empties, _.constant(false));
var actual = _.map(empties, function(value) {
try {
return _.includes(value);
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should not be possible to perform a binary search', 1, function() {
strictEqual(_.includes([3, 2, 1], 3, true), true);
});
test('should match `NaN`', 1, function() {
strictEqual(_.includes([1, NaN, 3], NaN), true);
});
test('should match `-0` as `0`', 2, function() {
strictEqual(_.includes([-0], 0), true);
strictEqual(_.includes([0], -0), true);
});
test('should work as an iteratee for methods like `_.reduce`', 1, function() {
var array1 = [1, 2, 3],
array2 = [2, 3, 1];
ok(_.every(array1, _.partial(_.includes, array2)));
});
}(1, 2, 3, 4));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.indexBy');
(function() {
test('should use `_.identity` when `iteratee` is nullish', 1, function() {
var array = [4, 6, 6],
values = [, null, undefined],
expected = _.map(values, _.constant({ '4': 4, '6': 6 }));
var actual = _.map(values, function(value, index) {
return index ? _.indexBy(array, value) : _.indexBy(array);
});
deepEqual(actual, expected);
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var actual = _.indexBy(['one', 'two', 'three'], 'length');
deepEqual(actual, { '3': 'two', '5': 'three' });
});
test('should only add values to own, not inherited, properties', 2, function() {
var actual = _.indexBy([4.2, 6.1, 6.4], function(num) {
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
});
deepEqual(actual.constructor, 4.2);
deepEqual(actual.hasOwnProperty, 6.4);
});
test('should work with a number for `iteratee`', 2, function() {
var array = [
[1, 'a'],
[2, 'a'],
[2, 'b']
];
deepEqual(_.indexBy(array, 0), { '1': [1, 'a'], '2': [2, 'b'] });
deepEqual(_.indexBy(array, 1), { 'a': [2, 'a'], 'b': [2, 'b'] });
});
test('should work with an object for `collection`', 1, function() {
var actual = _.indexBy({ 'a': 4.2, 'b': 6.1, 'c': 6.4 }, function(num) {
return Math.floor(num);
});
deepEqual(actual, { '4': 4.2, '6': 6.4 });
});
test('should work in a lazy chain sequence', 1, function() {
if (!isNpm) {
var array = _.range(LARGE_ARRAY_SIZE).concat(
_.range(Math.floor(LARGE_ARRAY_SIZE / 2), LARGE_ARRAY_SIZE),
_.range(Math.floor(LARGE_ARRAY_SIZE / 1.5), LARGE_ARRAY_SIZE)
);
var predicate = function(value) { return value > 2; },
actual = _(array).indexBy().map(square).filter(predicate).take().value();
deepEqual(actual, _.take(_.filter(_.map(_.indexBy(array), square), predicate)));
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.indexOf');
(function() {
var array = [1, 2, 3, 1, 2, 3];
test('should return the index of the first matched value', 1, function() {
strictEqual(_.indexOf(array, 3), 2);
});
test('should work with a positive `fromIndex`', 1, function() {
strictEqual(_.indexOf(array, 1, 2), 3);
});
test('should work with `fromIndex` >= `array.length`', 1, function() {
var values = [6, 8, Math.pow(2, 32), Infinity],
expected = _.map(values, _.constant([-1, -1, -1]));
var actual = _.map(values, function(fromIndex) {
return [
_.indexOf(array, undefined, fromIndex),
_.indexOf(array, 1, fromIndex),
_.indexOf(array, '', fromIndex)
];
});
deepEqual(actual, expected);
});
test('should work with a negative `fromIndex`', 1, function() {
strictEqual(_.indexOf(array, 2, -3), 4);
});
test('should work with a negative `fromIndex` <= `-array.length`', 1, function() {
var values = [-6, -8, -Infinity],
expected = _.map(values, _.constant(0));
var actual = _.map(values, function(fromIndex) {
return _.indexOf(array, 1, fromIndex);
});
deepEqual(actual, expected);
});
test('should treat falsey `fromIndex` values as `0`', 1, function() {
var expected = _.map(falsey, _.constant(0));
var actual = _.map(falsey, function(fromIndex) {
return _.indexOf(array, 1, fromIndex);
});
deepEqual(actual, expected);
});
test('should coerce `fromIndex` to an integer', 1, function() {
strictEqual(_.indexOf(array, 2, 1.2), 1);
});
test('should perform a binary search when `fromIndex` is a non-number truthy value', 1, function() {
var sorted = [4, 4, 5, 5, 6, 6],
values = [true, '1', {}],
expected = _.map(values, _.constant(2));
var actual = _.map(values, function(value) {
return _.indexOf(sorted, 5, value);
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('custom `_.indexOf` methods');
(function() {
function Foo() {}
function custom(array, value, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array.length;
while (++index < length) {
var other = array[index];
if (other === value || (value instanceof Foo && other instanceof Foo)) {
return index;
}
}
return -1;
}
var array = [1, new Foo, 3, new Foo],
indexOf = _.indexOf;
var largeArray = _.times(LARGE_ARRAY_SIZE, function() {
return new Foo;
});
test('`_.includes` should work with a custom `_.indexOf` method', 2, function() {
if (!isModularize) {
_.indexOf = custom;
ok(_.includes(array, new Foo));
ok(_.includes({ 'a': 1, 'b': new Foo, 'c': 3 }, new Foo));
_.indexOf = indexOf;
}
else {
skipTest(2);
}
});
test('`_.difference` should work with a custom `_.indexOf` method', 2, function() {
if (!isModularize) {
_.indexOf = custom;
deepEqual(_.difference(array, [new Foo]), [1, 3]);
deepEqual(_.difference(array, largeArray), [1, 3]);
_.indexOf = indexOf;
}
else {
skipTest(2);
}
});
test('`_.intersection` should work with a custom `_.indexOf` method', 2, function() {
if (!isModularize) {
_.indexOf = custom;
deepEqual(_.intersection(array, [new Foo]), [array[1]]);
deepEqual(_.intersection(largeArray, [new Foo]), [array[1]]);
_.indexOf = indexOf;
}
else {
skipTest(2);
}
});
test('`_.uniq` should work with a custom `_.indexOf` method', 4, function() {
_.each([false, true], function(param) {
if (!isModularize) {
_.indexOf = custom;
deepEqual(_.uniq(array, param), array.slice(0, 3));
deepEqual(_.uniq(largeArray, param), [largeArray[0]]);
_.indexOf = indexOf;
}
else {
skipTest(2);
}
});
});
test('`_.uniqBy` should work with a custom `_.indexOf` method', 6, function() {
_.each([[false, _.identity], [true, _.identity], [_.identity]], function(params) {
if (!isModularize) {
_.indexOf = custom;
deepEqual(_.uniqBy.apply(_, [array].concat(params)), array.slice(0, 3));
deepEqual(_.uniqBy.apply(_, [largeArray].concat(params)), [largeArray[0]]);
_.indexOf = indexOf;
}
else {
skipTest(2);
}
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.initial');
(function() {
var array = [1, 2, 3];
test('should accept a falsey `array` argument', 1, function() {
var expected = _.map(falsey, _.constant([]));
var actual = _.map(falsey, function(array, index) {
try {
return index ? _.initial(array) : _.initial();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should exclude last element', 1, function() {
deepEqual(_.initial(array), [1, 2]);
});
test('should return an empty when querying empty arrays', 1, function() {
deepEqual(_.initial([]), []);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.initial);
deepEqual(actual, [[1, 2], [4, 5], [7, 8]]);
});
test('should work in a lazy chain sequence', 4, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
values = [];
var actual = _(array).initial().filter(function(value) {
values.push(value);
return false;
})
.value();
deepEqual(actual, []);
deepEqual(values, _.initial(array));
values = [];
actual = _(array).filter(function(value) {
values.push(value);
return value < 3;
})
.initial()
.value();
deepEqual(actual, [1]);
deepEqual(values, array);
}
else {
skipTest(4);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.inRange');
(function() {
test('should work with an `end` argument', 3, function() {
strictEqual(_.inRange(3, 5), true);
strictEqual(_.inRange(5, 5), false);
strictEqual(_.inRange(6, 5), false);
});
test('should work with `start` and `end` arguments', 4, function() {
strictEqual(_.inRange(1, 1, 5), true);
strictEqual(_.inRange(3, 1, 5), true);
strictEqual(_.inRange(0, 1, 5), false);
strictEqual(_.inRange(5, 1, 5), false);
});
test('should treat falsey `start` arguments as `0`', 13, function() {
_.each(falsey, function(value, index) {
if (index) {
strictEqual(_.inRange(0, value), false);
strictEqual(_.inRange(0, value, 1), true);
} else {
strictEqual(_.inRange(0), false);
}
});
});
test('should swap `start` and `end` when `start` is greater than `end`', 2, function() {
strictEqual(_.inRange(2, 5, 1), true);
strictEqual(_.inRange(-3, -2, -6), true);
});
test('should work with a floating point `n` value', 4, function() {
strictEqual(_.inRange(0.5, 5), true);
strictEqual(_.inRange(1.2, 1, 5), true);
strictEqual(_.inRange(5.2, 5), false);
strictEqual(_.inRange(0.5, 1, 5), false);
});
test('should coerce arguments to finite numbers', 1, function() {
var actual = [_.inRange(0, '0', 1), _.inRange(0, '1'), _.inRange(0, 0, '1'), _.inRange(0, NaN, 1), _.inRange(-1, -1, NaN)],
expected = _.map(actual, _.constant(true));
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.intersection');
(function() {
var args = arguments;
test('should return the intersection of the given arrays', 1, function() {
var actual = _.intersection([1, 3, 2], [5, 2, 1, 4], [2, 1]);
deepEqual(actual, [1, 2]);
});
test('should return an array of unique values', 1, function() {
var actual = _.intersection([1, 1, 3, 2, 2], [5, 2, 2, 1, 4], [2, 1, 1]);
deepEqual(actual, [1, 2]);
});
test('should match `NaN`', 1, function() {
var actual = _.intersection([1, NaN, 3], [NaN, 5, NaN]);
deepEqual(actual, [NaN]);
});
test('should work with large arrays of objects', 2, function() {
var object = {},
largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(object));
deepEqual(_.intersection([object], largeArray), [object]);
deepEqual(_.intersection(_.range(LARGE_ARRAY_SIZE), [1]), [1]);
});
test('should work with large arrays of `NaN`', 1, function() {
var largeArray = _.times(LARGE_ARRAY_SIZE, _.constant(NaN));
deepEqual(_.intersection([1, NaN, 3], largeArray), [NaN]);
});
test('should work with `arguments` objects', 2, function() {
var array = [0, 1, null, 3],
expected = [1, 3];
deepEqual(_.intersection(array, args), expected);
deepEqual(_.intersection(args, array), expected);
});
test('should work with a single array', 1, function() {
var actual = _.intersection([1, 1, 3, 2, 2]);
deepEqual(actual, [1, 3, 2]);
});
test('should treat values that are not arrays or `arguments` objects as empty', 3, function() {
var array = [0, 1, null, 3],
values = [3, null, { '0': 1 }];
_.each(values, function(value) {
deepEqual(_.intersection(array, value), []);
});
});
test('should return a wrapped value when chaining', 2, function() {
if (!isNpm) {
var wrapped = _([1, 3, 2]).intersection([5, 2, 1, 4]);
ok(wrapped instanceof _);
deepEqual(wrapped.value(), [1, 2]);
}
else {
skipTest(2);
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.invert');
(function() {
test('should invert an object', 2, function() {
var object = { 'a': 1, 'b': 2 },
actual = _.invert(object);
deepEqual(actual, { '1': 'a', '2': 'b' });
deepEqual(_.invert(actual), { 'a': '1', 'b': '2' });
});
test('should work with an object that has a `length` property', 1, function() {
var object = { '0': 'a', '1': 'b', 'length': 2 };
deepEqual(_.invert(object), { 'a': '0', 'b': '1', '2': 'length' });
});
test('should accept a `multiValue` flag', 1, function() {
var object = { 'a': 1, 'b': 2, 'c': 1 };
deepEqual(_.invert(object, true), { '1': ['a', 'c'], '2': ['b'] });
});
test('should only add multiple values to own, not inherited, properties', 2, function() {
var object = { 'a': 'hasOwnProperty', 'b': 'constructor' };
deepEqual(_.invert(object), { 'hasOwnProperty': 'a', 'constructor': 'b' });
ok(_.isEqual(_.invert(object, true), { 'hasOwnProperty': ['a'], 'constructor': ['b'] }));
});
test('should work as an iteratee for methods like `_.map`', 2, function() {
var regular = { 'a': 1, 'b': 2, 'c': 1 },
inverted = { '1': 'c', '2': 'b' };
var array = [regular, regular, regular],
object = { 'a': regular, 'b': regular, 'c': regular },
expected = _.map(array, _.constant(inverted));
_.each([array, object], function(collection) {
var actual = _.map(collection, _.invert);
deepEqual(actual, expected);
});
});
test('should return a wrapped value when chaining', 2, function() {
if (!isNpm) {
var object = { 'a': 1, 'b': 2 },
wrapped = _(object).invert();
ok(wrapped instanceof _);
deepEqual(wrapped.value(), { '1': 'a', '2': 'b' });
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.invoke');
(function() {
test('should invoke a methods on each element of a collection', 1, function() {
var array = ['a', 'b', 'c'];
deepEqual(_.invoke(array, 'toUpperCase'), ['A', 'B', 'C']);
});
test('should support invoking with arguments', 1, function() {
var array = [function() { return slice.call(arguments); }],
actual = _.invoke(array, 'call', null, 'a', 'b', 'c');
deepEqual(actual, [['a', 'b', 'c']]);
});
test('should work with a function for `methodName`', 1, function() {
var array = ['a', 'b', 'c'];
var actual = _.invoke(array, function(left, right) {
return left + this.toUpperCase() + right;
}, '(', ')');
deepEqual(actual, ['(A)', '(B)', '(C)']);
});
test('should work with an object for `collection`', 1, function() {
var object = { 'a': 1, 'b': 2, 'c': 3 };
deepEqual(_.invoke(object, 'toFixed', 1), ['1.0', '2.0', '3.0']);
});
test('should treat number values for `collection` as empty', 1, function() {
deepEqual(_.invoke(1), []);
});
test('should not error on nullish elements', 1, function() {
var array = ['a', null, undefined, 'd'];
try {
var actual = _.invoke(array, 'toUpperCase');
} catch(e) {}
deepEqual(_.invoke(array, 'toUpperCase'), ['A', undefined, undefined, 'D']);
});
test('should not error on elements with missing properties', 1, function() {
var objects = _.map([null, undefined, _.constant(1)], function(value) {
return { 'a': value };
});
var expected = _.times(objects.length - 1, _.constant(undefined)).concat(1);
try {
var actual = _.invoke(objects, 'a');
} catch(e) {}
deepEqual(actual, expected);
});
test('should invoke deep property methods with the correct `this` binding', 2, function() {
var object = { 'a': { 'b': function() { return this.c; }, 'c': 1 } };
_.each(['a.b', ['a', 'b']], function(path) {
deepEqual(_.invoke([object], path), [1]);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isArguments');
(function() {
var args = arguments;
test('should return `true` for `arguments` objects', 1, function() {
strictEqual(_.isArguments(args), true);
});
test('should return `false` for non `arguments` objects', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isArguments(value) : _.isArguments();
});
deepEqual(actual, expected);
strictEqual(_.isArguments([1, 2, 3]), false);
strictEqual(_.isArguments(true), false);
strictEqual(_.isArguments(new Date), false);
strictEqual(_.isArguments(new Error), false);
strictEqual(_.isArguments(_), false);
strictEqual(_.isArguments(slice), false);
strictEqual(_.isArguments({ '0': 1, 'callee': _.noop, 'length': 1 }), false);
strictEqual(_.isArguments(1), false);
strictEqual(_.isArguments(NaN), false);
strictEqual(_.isArguments(/x/), false);
strictEqual(_.isArguments('a'), false);
});
test('should work with an `arguments` object from another realm', 1, function() {
if (_._object) {
strictEqual(_.isArguments(_._arguments), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isArray');
(function() {
var args = arguments;
test('should return `true` for arrays', 1, function() {
strictEqual(_.isArray([1, 2, 3]), true);
});
test('should return `false` for non-arrays', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isArray(value) : _.isArray();
});
deepEqual(actual, expected);
strictEqual(_.isArray(args), false);
strictEqual(_.isArray(true), false);
strictEqual(_.isArray(new Date), false);
strictEqual(_.isArray(new Error), false);
strictEqual(_.isArray(_), false);
strictEqual(_.isArray(slice), false);
strictEqual(_.isArray({ '0': 1, 'length': 1 }), false);
strictEqual(_.isArray(1), false);
strictEqual(_.isArray(NaN), false);
strictEqual(_.isArray(/x/), false);
strictEqual(_.isArray('a'), false);
});
test('should work with an array from another realm', 1, function() {
if (_._object) {
strictEqual(_.isArray(_._array), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isBoolean');
(function() {
var args = arguments;
test('should return `true` for booleans', 4, function() {
strictEqual(_.isBoolean(true), true);
strictEqual(_.isBoolean(false), true);
strictEqual(_.isBoolean(Object(true)), true);
strictEqual(_.isBoolean(Object(false)), true);
});
test('should return `false` for non-booleans', 12, function() {
var expected = _.map(falsey, function(value) { return value === false; });
var actual = _.map(falsey, function(value, index) {
return index ? _.isBoolean(value) : _.isBoolean();
});
deepEqual(actual, expected);
strictEqual(_.isBoolean(args), false);
strictEqual(_.isBoolean([1, 2, 3]), false);
strictEqual(_.isBoolean(new Date), false);
strictEqual(_.isBoolean(new Error), false);
strictEqual(_.isBoolean(_), false);
strictEqual(_.isBoolean(slice), false);
strictEqual(_.isBoolean({ 'a': 1 }), false);
strictEqual(_.isBoolean(1), false);
strictEqual(_.isBoolean(NaN), false);
strictEqual(_.isBoolean(/x/), false);
strictEqual(_.isBoolean('a'), false);
});
test('should work with a boolean from another realm', 1, function() {
if (_._object) {
strictEqual(_.isBoolean(_._boolean), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isDate');
(function() {
var args = arguments;
test('should return `true` for dates', 1, function() {
strictEqual(_.isDate(new Date), true);
});
test('should return `false` for non-dates', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isDate(value) : _.isDate();
});
deepEqual(actual, expected);
strictEqual(_.isDate(args), false);
strictEqual(_.isDate([1, 2, 3]), false);
strictEqual(_.isDate(true), false);
strictEqual(_.isDate(new Error), false);
strictEqual(_.isDate(_), false);
strictEqual(_.isDate(slice), false);
strictEqual(_.isDate({ 'a': 1 }), false);
strictEqual(_.isDate(1), false);
strictEqual(_.isDate(NaN), false);
strictEqual(_.isDate(/x/), false);
strictEqual(_.isDate('a'), false);
});
test('should work with a date object from another realm', 1, function() {
if (_._object) {
strictEqual(_.isDate(_._date), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isElement');
(function() {
var args = arguments;
function Element() {
this.nodeType = 1;
}
test('should return `false` for plain objects', 7, function() {
var element = body || new Element;
strictEqual(_.isElement(element), true);
strictEqual(_.isElement({ 'nodeType': 1 }), false);
strictEqual(_.isElement({ 'nodeType': Object(1) }), false);
strictEqual(_.isElement({ 'nodeType': true }), false);
strictEqual(_.isElement({ 'nodeType': [1] }), false);
strictEqual(_.isElement({ 'nodeType': '1' }), false);
strictEqual(_.isElement({ 'nodeType': '001' }), false);
});
test('should return `false` for non DOM elements', 13, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isElement(value) : _.isElement();
});
deepEqual(actual, expected);
strictEqual(_.isElement(args), false);
strictEqual(_.isElement([1, 2, 3]), false);
strictEqual(_.isElement(true), false);
strictEqual(_.isElement(new Date), false);
strictEqual(_.isElement(new Error), false);
strictEqual(_.isElement(_), false);
strictEqual(_.isElement(slice), false);
strictEqual(_.isElement({ 'a': 1 }), false);
strictEqual(_.isElement(1), false);
strictEqual(_.isElement(NaN), false);
strictEqual(_.isElement(/x/), false);
strictEqual(_.isElement('a'), false);
});
test('should work with a DOM element from another realm', 1, function() {
if (_._element) {
strictEqual(_.isElement(_._element), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isEmpty');
(function() {
var args = arguments;
test('should return `true` for empty values', 7, function() {
var expected = _.map(empties, _.constant(true));
var actual = _.map(empties, function(value) {
return _.isEmpty(value);
});
deepEqual(actual, expected);
strictEqual(_.isEmpty(true), true);
strictEqual(_.isEmpty(slice), true);
strictEqual(_.isEmpty(1), true);
strictEqual(_.isEmpty(NaN), true);
strictEqual(_.isEmpty(/x/), true);
strictEqual(_.isEmpty(), true);
});
test('should return `false` for non-empty values', 3, function() {
strictEqual(_.isEmpty([0]), false);
strictEqual(_.isEmpty({ 'a': 0 }), false);
strictEqual(_.isEmpty('a'), false);
});
test('should work with an object that has a `length` property', 1, function() {
strictEqual(_.isEmpty({ 'length': 0 }), false);
});
test('should work with `arguments` objects', 1, function() {
strictEqual(_.isEmpty(args), false);
});
test('should work with jQuery/MooTools DOM query collections', 1, function() {
function Foo(elements) { push.apply(this, elements); }
Foo.prototype = { 'length': 0, 'splice': arrayProto.splice };
strictEqual(_.isEmpty(new Foo([])), true);
});
test('should not treat objects with negative lengths as array-like', 1, function() {
function Foo() {}
Foo.prototype.length = -1;
strictEqual(_.isEmpty(new Foo), true);
});
test('should not treat objects with lengths larger than `MAX_SAFE_INTEGER` as array-like', 1, function() {
function Foo() {}
Foo.prototype.length = MAX_SAFE_INTEGER + 1;
strictEqual(_.isEmpty(new Foo), true);
});
test('should not treat objects with non-number lengths as array-like', 1, function() {
strictEqual(_.isEmpty({ 'length': '0' }), false);
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_({}).isEmpty(), true);
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_({}).chain().isEmpty() instanceof _);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isEqual');
(function() {
test('should perform comparisons between primitive values', 1, function() {
var pairs = [
[1, 1, true], [1, Object(1), true], [1, '1', false], [1, 2, false],
[-0, -0, true], [0, 0, true], [0, Object(0), true], [Object(0), Object(0), true], [-0, 0, true], [0, '0', false], [0, null, false],
[NaN, NaN, true], [NaN, Object(NaN), true], [Object(NaN), Object(NaN), true], [NaN, 'a', false], [NaN, Infinity, false],
['a', 'a', true], ['a', Object('a'), true], [Object('a'), Object('a'), true], ['a', 'b', false], ['a', ['a'], false],
[true, true, true], [true, Object(true), true], [Object(true), Object(true), true], [true, 1, false], [true, 'a', false],
[false, false, true], [false, Object(false), true], [Object(false), Object(false), true], [false, 0, false], [false, '', false],
[null, null, true], [null, undefined, false], [null, {}, false], [null, '', false],
[undefined, undefined, true], [undefined, null, false], [undefined, '', false]
];
var expected = _.map(pairs, function(pair) {
return pair[2];
});
var actual = _.map(pairs, function(pair) {
return _.isEqual(pair[0], pair[1]);
});
deepEqual(actual, expected);
});
test('should perform comparisons between arrays', 6, function() {
var array1 = [true, null, 1, 'a', undefined],
array2 = [true, null, 1, 'a', undefined];
strictEqual(_.isEqual(array1, array2), true);
array1 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { 'e': 1 }];
array2 = [[1, 2, 3], new Date(2012, 4, 23), /x/, { 'e': 1 }];
strictEqual(_.isEqual(array1, array2), true);
array1 = [1];
array1[2] = 3;
array2 = [1];
array2[1] = undefined;
array2[2] = 3;
strictEqual(_.isEqual(array1, array2), true);
array1 = [Object(1), false, Object('a'), /x/, new Date(2012, 4, 23), ['a', 'b', [Object('c')]], { 'a': 1 }];
array2 = [1, Object(false), 'a', /x/, new Date(2012, 4, 23), ['a', Object('b'), ['c']], { 'a': 1 }];
strictEqual(_.isEqual(array1, array2), true);
array1 = [1, 2, 3];
array2 = [3, 2, 1];
strictEqual(_.isEqual(array1, array2), false);
array1 = [1, 2];
array2 = [1, 2, 3];
strictEqual(_.isEqual(array1, array2), false);
});
test('should treat arrays with identical values but different non-index properties as equal', 3, function() {
var array1 = [1, 2, 3],
array2 = [1, 2, 3];
array1.every = array1.filter = array1.forEach =
array1.indexOf = array1.lastIndexOf = array1.map =
array1.some = array1.reduce = array1.reduceRight = null;
array2.concat = array2.join = array2.pop =
array2.reverse = array2.shift = array2.slice =
array2.sort = array2.splice = array2.unshift = null;
strictEqual(_.isEqual(array1, array2), true);
array1 = [1, 2, 3];
array1.a = 1;
array2 = [1, 2, 3];
array2.b = 1;
strictEqual(_.isEqual(array1, array2), true);
array1 = /x/.exec('vwxyz');
array2 = ['x'];
strictEqual(_.isEqual(array1, array2), true);
});
test('should work with sparse arrays', 3, function() {
var array = Array(1);
strictEqual(_.isEqual(array, Array(1)), true);
strictEqual(_.isEqual(array, [undefined]), true);
strictEqual(_.isEqual(array, Array(2)), false);
});
test('should perform comparisons between plain objects', 5, function() {
var object1 = { 'a': true, 'b': null, 'c': 1, 'd': 'a', 'e': undefined },
object2 = { 'a': true, 'b': null, 'c': 1, 'd': 'a', 'e': undefined };
strictEqual(_.isEqual(object1, object2), true);
object1 = { 'a': [1, 2, 3], 'b': new Date(2012, 4, 23), 'c': /x/, 'd': { 'e': 1 } };
object2 = { 'a': [1, 2, 3], 'b': new Date(2012, 4, 23), 'c': /x/, 'd': { 'e': 1 } };
strictEqual(_.isEqual(object1, object2), true);
object1 = { 'a': 1, 'b': 2, 'c': 3 };
object2 = { 'a': 3, 'b': 2, 'c': 1 };
strictEqual(_.isEqual(object1, object2), false);
object1 = { 'a': 1, 'b': 2, 'c': 3 };
object2 = { 'd': 1, 'e': 2, 'f': 3 };
strictEqual(_.isEqual(object1, object2), false);
object1 = { 'a': 1, 'b': 2 };
object2 = { 'a': 1, 'b': 2, 'c': 3 };
strictEqual(_.isEqual(object1, object2), false);
});
test('should perform comparisons of nested objects', 1, function() {
var object1 = {
'a': [1, 2, 3],
'b': true,
'c': Object(1),
'd': 'a',
'e': {
'f': ['a', Object('b'), 'c'],
'g': Object(false),
'h': new Date(2012, 4, 23),
'i': _.noop,
'j': 'a'
}
};
var object2 = {
'a': [1, Object(2), 3],
'b': Object(true),
'c': 1,
'd': Object('a'),
'e': {
'f': ['a', 'b', 'c'],
'g': false,
'h': new Date(2012, 4, 23),
'i': _.noop,
'j': 'a'
}
};
strictEqual(_.isEqual(object1, object2), true);
});
test('should perform comparisons between object instances', 4, function() {
function Foo() { this.a = 1; }
Foo.prototype.a = 1;
function Bar() { this.a = 1; }
Bar.prototype.a = 2;
strictEqual(_.isEqual(new Foo, new Foo), true);
strictEqual(_.isEqual(new Foo, new Bar), false);
strictEqual(_.isEqual({ 'a': 1 }, new Foo), false);
strictEqual(_.isEqual({ 'a': 2 }, new Bar), false);
});
test('should perform comparisons between objects with constructor properties', 5, function() {
strictEqual(_.isEqual({ 'constructor': 1 }, { 'constructor': 1 }), true);
strictEqual(_.isEqual({ 'constructor': 1 }, { 'constructor': '1' }), false);
strictEqual(_.isEqual({ 'constructor': [1] }, { 'constructor': [1] }), true);
strictEqual(_.isEqual({ 'constructor': [1] }, { 'constructor': ['1'] }), false);
strictEqual(_.isEqual({ 'constructor': Object }, {}), false);
});
test('should perform comparisons between arrays with circular references', 4, function() {
var array1 = [],
array2 = [];
array1.push(array1);
array2.push(array2);
strictEqual(_.isEqual(array1, array2), true);
array1.push('b');
array2.push('b');
strictEqual(_.isEqual(array1, array2), true);
array1.push('c');
array2.push('d');
strictEqual(_.isEqual(array1, array2), false);
array1 = ['a', 'b', 'c'];
array1[1] = array1;
array2 = ['a', ['a', 'b', 'c'], 'c'];
strictEqual(_.isEqual(array1, array2), false);
});
test('should perform comparisons between objects with circular references', 4, function() {
var object1 = {},
object2 = {};
object1.a = object1;
object2.a = object2;
strictEqual(_.isEqual(object1, object2), true);
object1.b = 0;
object2.b = Object(0);
strictEqual(_.isEqual(object1, object2), true);
object1.c = Object(1);
object2.c = Object(2);
strictEqual(_.isEqual(object1, object2), false);
object1 = { 'a': 1, 'b': 2, 'c': 3 };
object1.b = object1;
object2 = { 'a': 1, 'b': { 'a': 1, 'b': 2, 'c': 3 }, 'c': 3 };
strictEqual(_.isEqual(object1, object2), false);
});
test('should perform comparisons between objects with multiple circular references', 3, function() {
var array1 = [{}],
array2 = [{}];
(array1[0].a = array1).push(array1);
(array2[0].a = array2).push(array2);
strictEqual(_.isEqual(array1, array2), true);
array1[0].b = 0;
array2[0].b = Object(0);
strictEqual(_.isEqual(array1, array2), true);
array1[0].c = Object(1);
array2[0].c = Object(2);
strictEqual(_.isEqual(array1, array2), false);
});
test('should perform comparisons between objects with complex circular references', 1, function() {
var object1 = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': { 'a': 2 }
};
var object2 = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': { 'a': 2 }
};
object1.foo.b.c.d = object1;
object1.bar.b = object1.foo.b;
object2.foo.b.c.d = object2;
object2.bar.b = object2.foo.b;
strictEqual(_.isEqual(object1, object2), true);
});
test('should perform comparisons between objects with shared property values', 1, function() {
var object1 = {
'a': [1, 2]
};
var object2 = {
'a': [1, 2],
'b': [1, 2]
};
object1.b = object1.a;
strictEqual(_.isEqual(object1, object2), true);
});
test('should work with `arguments` objects', 2, function() {
var args1 = (function() { return arguments; }(1, 2, 3)),
args2 = (function() { return arguments; }(1, 2, 3)),
args3 = (function() { return arguments; }(1, 2));
strictEqual(_.isEqual(args1, args2), true);
strictEqual(_.isEqual(args1, args3), false);
});
test('should treat `arguments` objects like `Object` objects', 4, function() {
var args = (function() { return arguments; }(1, 2, 3)),
object = { '0': 1, '1': 2, '2': 3 };
function Foo() {}
Foo.prototype = object;
strictEqual(_.isEqual(args, object), true);
strictEqual(_.isEqual(object, args), true);
strictEqual(_.isEqual(args, new Foo), false);
strictEqual(_.isEqual(new Foo, args), false);
});
test('should perform comparisons between date objects', 4, function() {
strictEqual(_.isEqual(new Date(2012, 4, 23), new Date(2012, 4, 23)), true);
strictEqual(_.isEqual(new Date(2012, 4, 23), new Date(2013, 3, 25)), false);
strictEqual(_.isEqual(new Date(2012, 4, 23), { 'getTime': _.constant(1337756400000) }), false);
strictEqual(_.isEqual(new Date('a'), new Date('a')), false);
});
test('should perform comparisons between error objects', 1, function() {
var pairs = _.map([
'Error',
'EvalError',
'RangeError',
'ReferenceError',
'SyntaxError',
'TypeError',
'URIError'
], function(type, index, errorTypes) {
var otherType = errorTypes[++index % errorTypes.length],
CtorA = root[type],
CtorB = root[otherType];
return [new CtorA('a'), new CtorA('a'), new CtorB('a'), new CtorB('b')];
});
var expected = _.times(pairs.length, _.constant([true, false, false]));
var actual = _.map(pairs, function(pair) {
return [_.isEqual(pair[0], pair[1]), _.isEqual(pair[0], pair[2]), _.isEqual(pair[2], pair[3])];
});
deepEqual(actual, expected);
});
test('should perform comparisons between functions', 2, function() {
function a() { return 1 + 2; }
function b() { return 1 + 2; }
strictEqual(_.isEqual(a, a), true);
strictEqual(_.isEqual(a, b), false);
});
test('should perform comparisons between regexes', 5, function() {
strictEqual(_.isEqual(/x/gim, /x/gim), true);
strictEqual(_.isEqual(/x/gim, /x/mgi), true);
strictEqual(_.isEqual(/x/gi, /x/g), false);
strictEqual(_.isEqual(/x/, /y/), false);
strictEqual(_.isEqual(/x/g, { 'global': true, 'ignoreCase': false, 'multiline': false, 'source': 'x' }), false);
});
test('should perform comparisons between typed arrays', 1, function() {
var pairs = _.map(typedArrays, function(type, index) {
var otherType = typedArrays[(index + 1) % typedArrays.length],
CtorA = root[type] || function(n) { this.n = n; },
CtorB = root[otherType] || function(n) { this.n = n; },
bufferA = root[type] ? new ArrayBuffer(8) : 8,
bufferB = root[otherType] ? new ArrayBuffer(8) : 8,
bufferC = root[otherType] ? new ArrayBuffer(16) : 16;
return [new CtorA(bufferA), new CtorA(bufferA), new CtorB(bufferB), new CtorB(bufferC)];
});
var expected = _.times(pairs.length, _.constant([true, false, false]));
var actual = _.map(pairs, function(pair) {
return [_.isEqual(pair[0], pair[1]), _.isEqual(pair[0], pair[2]), _.isEqual(pair[2], pair[3])];
});
deepEqual(actual, expected);
});
test('should avoid common type coercions', 9, function() {
strictEqual(_.isEqual(true, Object(false)), false);
strictEqual(_.isEqual(Object(false), Object(0)), false);
strictEqual(_.isEqual(false, Object('')), false);
strictEqual(_.isEqual(Object(36), Object('36')), false);
strictEqual(_.isEqual(0, ''), false);
strictEqual(_.isEqual(1, true), false);
strictEqual(_.isEqual(1337756400000, new Date(2012, 4, 23)), false);
strictEqual(_.isEqual('36', 36), false);
strictEqual(_.isEqual(36, '36'), false);
});
test('should return `false` for objects with custom `toString` methods', 1, function() {
var primitive,
object = { 'toString': function() { return primitive; } },
values = [true, null, 1, 'a', undefined],
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value) {
primitive = value;
return _.isEqual(object, value);
});
deepEqual(actual, expected);
});
test('should work as an iteratee for `_.every`', 1, function() {
var actual = _.every([1, 1, 1], _.partial(_.isEqual, 1));
ok(actual);
});
test('should treat objects created by `Object.create(null)` like any other plain object', 2, function() {
function Foo() { this.a = 1; }
Foo.prototype.constructor = null;
var object2 = { 'a': 1 };
strictEqual(_.isEqual(new Foo, object2), false);
if (create) {
var object1 = create(null);
object1.a = 1;
strictEqual(_.isEqual(object1, object2), true);
}
else {
skipTest();
}
});
test('should return `true` for like-objects from different documents', 4, function() {
// Ensure `_._object` is assigned (unassigned in Opera 10.00).
if (_._object) {
strictEqual(_.isEqual({ 'a': 1, 'b': 2, 'c': 3 }, _._object), true);
strictEqual(_.isEqual({ 'a': 1, 'b': 2, 'c': 2 }, _._object), false);
strictEqual(_.isEqual([1, 2, 3], _._array), true);
strictEqual(_.isEqual([1, 2, 2], _._array), false);
}
else {
skipTest(4);
}
});
test('should not error on DOM elements', 1, function() {
if (document) {
var element1 = document.createElement('div'),
element2 = element1.cloneNode(true);
try {
strictEqual(_.isEqual(element1, element2), false);
} catch(e) {
ok(false, e.message);
}
}
else {
skipTest();
}
});
test('should perform comparisons between wrapped values', 32, function() {
var stamp = +new Date;
var values = [
[[1, 2], [1, 2], [1, 2, 3]],
[true, true, false],
[new Date(stamp), new Date(stamp), new Date(stamp - 100)],
[{ 'a': 1, 'b': 2 }, { 'a': 1, 'b': 2 }, { 'a': 1, 'b': 1 }],
[1, 1, 2],
[NaN, NaN, Infinity],
[/x/, /x/, /x/i],
['a', 'a', 'A']
];
_.each(values, function(vals) {
if (!isNpm) {
var wrapped1 = _(vals[0]),
wrapped2 = _(vals[1]),
actual = wrapped1.isEqual(wrapped2);
strictEqual(actual, true);
strictEqual(_.isEqual(_(actual), _(true)), true);
wrapped1 = _(vals[0]);
wrapped2 = _(vals[2]);
actual = wrapped1.isEqual(wrapped2);
strictEqual(actual, false);
strictEqual(_.isEqual(_(actual), _(false)), true);
}
else {
skipTest(4);
}
});
});
test('should perform comparisons between wrapped and non-wrapped values', 4, function() {
if (!isNpm) {
var object1 = _({ 'a': 1, 'b': 2 }),
object2 = { 'a': 1, 'b': 2 };
strictEqual(object1.isEqual(object2), true);
strictEqual(_.isEqual(object1, object2), true);
object1 = _({ 'a': 1, 'b': 2 });
object2 = { 'a': 1, 'b': 1 };
strictEqual(object1.isEqual(object2), false);
strictEqual(_.isEqual(object1, object2), false);
}
else {
skipTest(4);
}
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_('a').isEqual('a'), true);
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_('a').chain().isEqual('a') instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isEqualWith');
(function() {
test('should provide the correct `customizer` arguments', 1, function() {
var argsList = [],
object1 = { 'a': [1, 2], 'b': null },
object2 = { 'a': [1, 2], 'b': null };
object1.b = object2;
object2.b = object1;
var expected = [
[object1, object2],
[object1.a, object2.a, 'a', object1, object2, [], []],
[object1.a[0], object2.a[0], 0, object1.a, object2.a, [], []],
[object1.a[1], object2.a[1], 1, object1.a, object2.a, [], []],
[object1.b, object2.b, 'b', object1.b, object2.b, [], []],
[object1.b.a, object2.b.a, 'a', object1.b, object2.b, [], []],
[object1.b.a[0], object2.b.a[0], 0, object1.b.a, object2.b.a, [], []],
[object1.b.a[1], object2.b.a[1], 1, object1.b.a, object2.b.a, [], []],
[object1.b.b, object2.b.b, 'b', object1.b.b, object2.b.b, [], []]
];
_.isEqualWith(object1, object2, function() {
argsList.push(slice.call(arguments));
});
deepEqual(argsList, expected);
});
test('should handle comparisons if `customizer` returns `undefined`', 3, function() {
strictEqual(_.isEqualWith('a', 'a', _.noop), true);
strictEqual(_.isEqualWith(['a'], ['a'], _.noop), true);
strictEqual(_.isEqualWith({ '0': 'a' }, { '0': 'a' }, _.noop), true);
});
test('should not handle comparisons if `customizer` returns `true`', 3, function() {
var customizer = function(value) {
return _.isString(value) || undefined;
};
strictEqual(_.isEqualWith('a', 'b', customizer), true);
strictEqual(_.isEqualWith(['a'], ['b'], customizer), true);
strictEqual(_.isEqualWith({ '0': 'a' }, { '0': 'b' }, customizer), true);
});
test('should not handle comparisons if `customizer` returns `false`', 3, function() {
var customizer = function(value) {
return _.isString(value) ? false : undefined;
};
strictEqual(_.isEqualWith('a', 'a', customizer), false);
strictEqual(_.isEqualWith(['a'], ['a'], customizer), false);
strictEqual(_.isEqualWith({ '0': 'a' }, { '0': 'a' }, customizer), false);
});
test('should return a boolean value even if `customizer` does not', 2, function() {
var actual = _.isEqualWith('a', 'b', _.constant('c'));
strictEqual(actual, true);
var values = _.without(falsey, undefined),
expected = _.map(values, _.constant(false));
actual = [];
_.each(values, function(value) {
actual.push(_.isEqualWith('a', 'a', _.constant(value)));
});
deepEqual(actual, expected);
});
test('should ensure `customizer` is a function', 1, function() {
var array = [1, 2, 3],
eq = _.partial(_.isEqualWith, array),
actual = _.map([array, [1, 0, 3]], eq);
deepEqual(actual, [true, false]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isError');
(function() {
var args = arguments;
test('should return `true` for error objects', 1, function() {
var expected = _.map(errors, _.constant(true));
var actual = _.map(errors, function(error) {
return _.isError(error) === true;
});
deepEqual(actual, expected);
});
test('should return `false` for non error objects', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isError(value) : _.isError();
});
deepEqual(actual, expected);
strictEqual(_.isError(args), false);
strictEqual(_.isError([1, 2, 3]), false);
strictEqual(_.isError(true), false);
strictEqual(_.isError(new Date), false);
strictEqual(_.isError(_), false);
strictEqual(_.isError(slice), false);
strictEqual(_.isError({ 'a': 1 }), false);
strictEqual(_.isError(1), false);
strictEqual(_.isError(NaN), false);
strictEqual(_.isError(/x/), false);
strictEqual(_.isError('a'), false);
});
test('should work with an error object from another realm', 1, function() {
if (_._object) {
var expected = _.map(_._errors, _.constant(true));
var actual = _.map(_._errors, function(error) {
return _.isError(error) === true;
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isFinite');
(function() {
var args = arguments;
test('should return `true` for finite values', 1, function() {
var values = [0, 1, 3.14, -1],
expected = _.map(values, _.constant(true));
var actual = _.map(values, function(value) {
return _.isFinite(value);
});
deepEqual(actual, expected);
});
test('should return `false` for non-finite values', 9, function() {
var values = [NaN, Infinity, -Infinity, Object(1)],
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value) {
return _.isFinite(value);
});
deepEqual(actual, expected);
strictEqual(_.isFinite(args), false);
strictEqual(_.isFinite([1, 2, 3]), false);
strictEqual(_.isFinite(true), false);
strictEqual(_.isFinite(new Date), false);
strictEqual(_.isFinite(new Error), false);
strictEqual(_.isFinite({ 'a': 1 }), false);
strictEqual(_.isFinite(/x/), false);
strictEqual(_.isFinite('a'), false);
});
test('should return `false` for non-numeric values', 1, function() {
var values = [undefined, [], true, new Date, new Error, '', ' ', '2px'],
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value) {
return _.isFinite(value);
});
deepEqual(actual, expected);
});
test('should return `false` for numeric string values', 1, function() {
var values = ['2', '0', '08'],
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value) {
return _.isFinite(value);
});
deepEqual(actual, expected);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isFunction');
(function() {
var args = arguments;
test('should return `true` for functions', 2, function() {
strictEqual(_.isFunction(_), true);
strictEqual(_.isFunction(slice), true);
});
test('should return `true` for typed array constructors', 1, function() {
var expected = _.map(typedArrays, function(type) {
return objToString.call(root[type]) == funcTag;
});
var actual = _.map(typedArrays, function(type) {
return _.isFunction(root[type]);
});
deepEqual(actual, expected);
});
test('should return `false` for non-functions', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isFunction(value) : _.isFunction();
});
deepEqual(actual, expected);
strictEqual(_.isFunction(args), false);
strictEqual(_.isFunction([1, 2, 3]), false);
strictEqual(_.isFunction(true), false);
strictEqual(_.isFunction(new Date), false);
strictEqual(_.isFunction(new Error), false);
strictEqual(_.isFunction({ 'a': 1 }), false);
strictEqual(_.isFunction(1), false);
strictEqual(_.isFunction(NaN), false);
strictEqual(_.isFunction(/x/), false);
strictEqual(_.isFunction('a'), false);
if (document) {
strictEqual(_.isFunction(document.getElementsByTagName('body')), false);
} else {
skipTest();
}
});
test('should work with host objects in IE 8 document mode (test in IE 11)', 2, function() {
// Trigger a Chakra JIT bug.
// See https://github.com/jashkenas/underscore/issues/1621.
_.each([body, xml], function(object) {
if (object) {
_.times(100, _.isFunction);
strictEqual(_.isFunction(object), false);
}
else {
skipTest();
}
});
});
test('should work with a function from another realm', 1, function() {
if (_._object) {
strictEqual(_.isFunction(_._function), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isMatch');
(function() {
test('should perform a deep comparison between `object` and `source`', 5, function() {
var object = { 'a': 1, 'b': 2, 'c': 3 };
strictEqual(_.isMatch(object, { 'a': 1 }), true);
strictEqual(_.isMatch(object, { 'b': 1 }), false);
strictEqual(_.isMatch(object, { 'a': 1, 'c': 3 }), true);
strictEqual(_.isMatch(object, { 'c': 3, 'd': 4 }), false);
object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 };
strictEqual(_.isMatch(object, { 'a': { 'b': { 'c': 1 } } }), true);
});
test('should match inherited `object` properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
strictEqual(_.isMatch({ 'a': new Foo }, { 'a': { 'b': 2 } }), true);
});
test('should match `-0` as `0`', 2, function() {
var object1 = { 'a': -0 },
object2 = { 'a': 0 };
strictEqual(_.isMatch(object1, object2), true);
strictEqual(_.isMatch(object2, object1), true);
});
test('should not match by inherited `source` properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var objects = [{ 'a': 1 }, { 'a': 1, 'b': 2 }],
source = new Foo,
expected = _.map(objects, _.constant(true));
var actual = _.map(objects, function(object) {
return _.isMatch(object, source);
});
deepEqual(actual, expected);
});
test('should return `false` when `object` is nullish', 1, function() {
var values = [null, undefined],
expected = _.map(values, _.constant(false)),
source = { 'a': 1 };
var actual = _.map(values, function(value) {
try {
return _.isMatch(value, source);
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should return `true` when comparing an empty `source`', 1, function() {
var object = { 'a': 1 },
expected = _.map(empties, _.constant(true));
var actual = _.map(empties, function(value) {
return _.isMatch(object, value);
});
deepEqual(actual, expected);
});
test('should compare a variety of `source` property values', 2, function() {
var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } },
object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } };
strictEqual(_.isMatch(object1, object1), true);
strictEqual(_.isMatch(object1, object2), false);
});
test('should work with a function for `source`', 1, function() {
function source() {}
source.a = 1;
source.b = function() {};
source.c = 3;
var objects = [{ 'a': 1 }, { 'a': 1, 'b': source.b, 'c': 3 }];
var actual = _.map(objects, function(object) {
return _.isMatch(object, source);
});
deepEqual(actual, [false, true]);
});
test('should return `true` when comparing a `source` of empty arrays and objects', 1, function() {
var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }],
source = { 'a': [], 'b': {} };
var actual = _.filter(objects, function(object) {
return _.isMatch(object, source);
});
deepEqual(actual, objects);
});
test('should return `true` when comparing an empty `source` to a nullish `object`', 1, function() {
var values = [null, undefined],
expected = _.map(values, _.constant(true)),
source = {};
var actual = _.map(values, function(value) {
try {
return _.isMatch(value, source);
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should search arrays of `source` for values', 3, function() {
var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }],
source = { 'a': ['d'] },
predicate = function(object) { return _.isMatch(object, source); },
actual = _.filter(objects, predicate);
deepEqual(actual, [objects[1]]);
source = { 'a': ['b', 'd'] };
actual = _.filter(objects, predicate);
deepEqual(actual, []);
source = { 'a': ['d', 'b'] };
actual = _.filter(objects, predicate);
deepEqual(actual, []);
});
test('should perform a partial comparison of all objects within arrays of `source`', 1, function() {
var source = { 'a': [{ 'b': 1 }, { 'b': 4, 'c': 5 }] };
var objects = [
{ 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 5, 'd': 6 }] },
{ 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 6, 'd': 7 }] }
];
var actual = _.filter(objects, function(object) {
return _.isMatch(object, source);
});
deepEqual(actual, [objects[0]]);
});
test('should handle a `source` with `undefined` values', 3, function() {
var objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }],
source = { 'b': undefined },
predicate = function(object) { return _.isMatch(object, source); },
actual = _.map(objects, predicate),
expected = [false, false, true];
deepEqual(actual, expected);
source = { 'a': 1, 'b': undefined };
actual = _.map(objects, predicate);
deepEqual(actual, expected);
objects = [{ 'a': { 'b': 1 } }, { 'a':{ 'b':1, 'c': 1 } }, { 'a': { 'b': 1, 'c': undefined } }];
source = { 'a': { 'c': undefined } };
actual = _.map(objects, predicate);
deepEqual(actual, expected);
});
test('should match properties when `value` is a function', 1, function() {
function Foo() {}
Foo.a = { 'b': 1, 'c': 2 };
var matches = _.matches({ 'a': { 'b': 1 } });
strictEqual(matches(Foo), true);
});
test('should match properties when `value` is not a plain object', 1, function() {
function Foo(object) { _.assign(this, object); }
var object = new Foo({ 'a': new Foo({ 'b': 1, 'c': 2 }) }),
matches = _.matches({ 'a': { 'b': 1 } });
strictEqual(matches(object), true);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isMatchWith');
(function() {
test('should provide the correct `customizer` arguments', 1, function() {
var argsList = [],
object1 = { 'a': [1, 2], 'b': null },
object2 = { 'a': [1, 2], 'b': null };
object1.b = object2;
object2.b = object1;
var expected = [
[object1.a, object2.a, 'a', object1, object2, [], []],
[object1.a[0], object2.a[0], 0, object1.a, object2.a, [], []],
[object1.a[1], object2.a[1], 1, object1.a, object2.a, [], []],
[object1.b, object2.b, 'b', object1, object2, [], []],
[object1.b.a, object2.b.a, 'a', object1.b, object2.b, [], []],
[object1.b.a[0], object2.b.a[0], 0, object1.b.a, object2.b.a, [], []],
[object1.b.a[1], object2.b.a[1], 1, object1.b.a, object2.b.a, [], []],
[object1.b.b, object2.b.b, 'b', object1.b, object2.b, [], []],
[object1.b.b.a, object2.b.b.a, 'a', object1.b.b, object2.b.b, [], []],
[object1.b.b.a[0], object2.b.b.a[0], 0, object1.b.b.a, object2.b.b.a, [], []],
[object1.b.b.a[1], object2.b.b.a[1], 1, object1.b.b.a, object2.b.b.a, [], []],
[object1.b.b.b, object2.b.b.b, 'b', object1.b.b, object2.b.b, [], []]
];
_.isMatchWith(object1, object2, function() {
argsList.push(slice.call(arguments));
});
deepEqual(argsList, expected);
});
test('should handle comparisons if `customizer` returns `undefined`', 1, function() {
strictEqual(_.isMatchWith({ 'a': 1 }, { 'a': 1 }, _.noop), true);
});
test('should return a boolean value even if `customizer` does not', 2, function() {
var object = { 'a': 1 },
actual = _.isMatchWith(object, { 'a': 1 }, _.constant('a'));
strictEqual(actual, true);
var expected = _.map(falsey, _.constant(false));
actual = [];
_.each(falsey, function(value) {
actual.push(_.isMatchWith(object, { 'a': 2 }, _.constant(value)));
});
deepEqual(actual, expected);
});
test('should ensure `customizer` is a function', 1, function() {
var object = { 'a': 1 },
matches = _.partial(_.isMatchWith, object),
actual = _.map([object, { 'a': 2 }], matches);
deepEqual(actual, [true, false]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isNaN');
(function() {
var args = arguments;
test('should return `true` for NaNs', 2, function() {
strictEqual(_.isNaN(NaN), true);
strictEqual(_.isNaN(Object(NaN)), true);
});
test('should return `false` for non-NaNs', 13, function() {
var expected = _.map(falsey, function(value) { return value !== value; });
var actual = _.map(falsey, function(value, index) {
return index ? _.isNaN(value) : _.isNaN();
});
deepEqual(actual, expected);
strictEqual(_.isNaN(args), false);
strictEqual(_.isNaN([1, 2, 3]), false);
strictEqual(_.isNaN(true), false);
strictEqual(_.isNaN(new Date), false);
strictEqual(_.isNaN(new Error), false);
strictEqual(_.isNaN(_), false);
strictEqual(_.isNaN(slice), false);
strictEqual(_.isNaN({ 'a': 1 }), false);
strictEqual(_.isNaN(1), false);
strictEqual(_.isNaN(Object(1)), false);
strictEqual(_.isNaN(/x/), false);
strictEqual(_.isNaN('a'), false);
});
test('should work with `NaN` from another realm', 1, function() {
if (_._object) {
strictEqual(_.isNaN(_._nan), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isNative');
(function() {
var args = arguments;
test('should return `true` for native methods', 6, function() {
_.each([Array, create, root.encodeURI, slice, Uint8Array], function(func) {
if (func) {
strictEqual(_.isNative(func), true);
}
else {
skipTest();
}
});
if (body) {
strictEqual(_.isNative(body.cloneNode), true);
}
else {
skipTest();
}
});
test('should return `false` for non-native methods', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isNative(value) : _.isNative();
});
deepEqual(actual, expected);
strictEqual(_.isNative(args), false);
strictEqual(_.isNative([1, 2, 3]), false);
strictEqual(_.isNative(true), false);
strictEqual(_.isNative(new Date), false);
strictEqual(_.isNative(new Error), false);
strictEqual(_.isNative(_), false);
strictEqual(_.isNative({ 'a': 1 }), false);
strictEqual(_.isNative(1), false);
strictEqual(_.isNative(NaN), false);
strictEqual(_.isNative(/x/), false);
strictEqual(_.isNative('a'), false);
});
test('should work with native functions from another realm', 2, function() {
if (_._element) {
strictEqual(_.isNative(_._element.cloneNode), true);
}
else {
skipTest();
}
if (_._object) {
strictEqual(_.isNative(_._object.valueOf), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isNull');
(function() {
var args = arguments;
test('should return `true` for nulls', 1, function() {
strictEqual(_.isNull(null), true);
});
test('should return `false` for non-nulls', 13, function() {
var expected = _.map(falsey, function(value) { return value === null; });
var actual = _.map(falsey, function(value, index) {
return index ? _.isNull(value) : _.isNull();
});
deepEqual(actual, expected);
strictEqual(_.isNull(args), false);
strictEqual(_.isNull([1, 2, 3]), false);
strictEqual(_.isNull(true), false);
strictEqual(_.isNull(new Date), false);
strictEqual(_.isNull(new Error), false);
strictEqual(_.isNull(_), false);
strictEqual(_.isNull(slice), false);
strictEqual(_.isNull({ 'a': 1 }), false);
strictEqual(_.isNull(1), false);
strictEqual(_.isNull(NaN), false);
strictEqual(_.isNull(/x/), false);
strictEqual(_.isNull('a'), false);
});
test('should work with nulls from another realm', 1, function() {
if (_._object) {
strictEqual(_.isNull(_._null), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isNil');
(function() {
var args = arguments;
test('should return `true` for nulls', 1, function() {
strictEqual(_.isNil(null), true);
});
test('should return `true` for undefinitions', 2, function() {
strictEqual(_.isNil(), true);
strictEqual(_.isNil(undefined), true);
});
test('should return `false` for non-nils', 13, function() {
var expected = _.map(falsey, function(value) {
return undefined === value || null === value;
});
var actual = _.map(falsey, function(value) {
return _.isNil(value);
});
deepEqual(actual, expected);
strictEqual(_.isNull(args), false);
strictEqual(_.isNull([1, 2, 3]), false);
strictEqual(_.isNull(true), false);
strictEqual(_.isNull(new Date), false);
strictEqual(_.isNull(new Error), false);
strictEqual(_.isNull(_), false);
strictEqual(_.isNull(slice), false);
strictEqual(_.isNull({ 'a': 1 }), false);
strictEqual(_.isNull(1), false);
strictEqual(_.isNull(NaN), false);
strictEqual(_.isNull(/x/), false);
strictEqual(_.isNull('a'), false);
});
test('should work with nulls from another realm', 2, function() {
if (_._object) {
strictEqual(_.isNil(_._null), true);
strictEqual(_.isNil(_._undefined), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isNumber');
(function() {
var args = arguments;
test('should return `true` for numbers', 3, function() {
strictEqual(_.isNumber(0), true);
strictEqual(_.isNumber(Object(0)), true);
strictEqual(_.isNumber(NaN), true);
});
test('should return `false` for non-numbers', 11, function() {
var expected = _.map(falsey, function(value) { return typeof value == 'number'; });
var actual = _.map(falsey, function(value, index) {
return index ? _.isNumber(value) : _.isNumber();
});
deepEqual(actual, expected);
strictEqual(_.isNumber(args), false);
strictEqual(_.isNumber([1, 2, 3]), false);
strictEqual(_.isNumber(true), false);
strictEqual(_.isNumber(new Date), false);
strictEqual(_.isNumber(new Error), false);
strictEqual(_.isNumber(_), false);
strictEqual(_.isNumber(slice), false);
strictEqual(_.isNumber({ 'a': 1 }), false);
strictEqual(_.isNumber(/x/), false);
strictEqual(_.isNumber('a'), false);
});
test('should work with numbers from another realm', 1, function() {
if (_._object) {
strictEqual(_.isNumber(_._number), true);
}
else {
skipTest();
}
});
test('should avoid `[xpconnect wrapped native prototype]` in Firefox', 1, function() {
strictEqual(_.isNumber(+"2"), true);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isObject');
(function() {
var args = arguments;
test('should return `true` for objects', 12, function() {
strictEqual(_.isObject(args), true);
strictEqual(_.isObject([1, 2, 3]), true);
strictEqual(_.isObject(Object(false)), true);
strictEqual(_.isObject(new Date), true);
strictEqual(_.isObject(new Error), true);
strictEqual(_.isObject(_), true);
strictEqual(_.isObject(slice), true);
strictEqual(_.isObject({ 'a': 1 }), true);
strictEqual(_.isObject(Object(0)), true);
strictEqual(_.isObject(/x/), true);
strictEqual(_.isObject(Object('a')), true);
if (document) {
strictEqual(_.isObject(body), true);
} else {
skipTest();
}
});
test('should return `false` for non-objects', 1, function() {
var symbol = (Symbol || noop)(),
values = falsey.concat(true, 1, 'a', symbol),
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value, index) {
return index ? _.isObject(value) : _.isObject();
});
deepEqual(actual, expected);
});
test('should work with objects from another realm', 8, function() {
if (_._element) {
strictEqual(_.isObject(_._element), true);
}
else {
skipTest();
}
if (_._object) {
strictEqual(_.isObject(_._object), true);
strictEqual(_.isObject(_._boolean), true);
strictEqual(_.isObject(_._date), true);
strictEqual(_.isObject(_._function), true);
strictEqual(_.isObject(_._number), true);
strictEqual(_.isObject(_._regexp), true);
strictEqual(_.isObject(_._string), true);
}
else {
skipTest(7);
}
});
test('should avoid V8 bug #2291 (test in Chrome 19-20)', 1, function() {
// Trigger a V8 JIT bug.
// See https://code.google.com/p/v8/issues/detail?id=2291.
var object = {};
// 1: Useless comparison statement, this is half the trigger.
object == object;
// 2: Initial check with object, this is the other half of the trigger.
_.isObject(object);
strictEqual(_.isObject('x'), false);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isPlainObject');
(function() {
var element = document && document.createElement('div');
test('should detect plain objects', 5, function() {
function Foo(a) {
this.a = 1;
}
strictEqual(_.isPlainObject({}), true);
strictEqual(_.isPlainObject({ 'a': 1 }), true);
strictEqual(_.isPlainObject({ 'constructor': Foo }), true);
strictEqual(_.isPlainObject([1, 2, 3]), false);
strictEqual(_.isPlainObject(new Foo(1)), false);
});
test('should return `true` for objects with a `[[Prototype]]` of `null`', 2, function() {
if (create) {
var object = create(null);
strictEqual(_.isPlainObject(object), true);
object.constructor = objectProto.constructor;
strictEqual(_.isPlainObject(object), true);
}
else {
skipTest(2);
}
});
test('should return `true` for plain objects with a custom `valueOf` property', 2, function() {
strictEqual(_.isPlainObject({ 'valueOf': 0 }), true);
if (element) {
var valueOf = element.valueOf;
element.valueOf = 0;
strictEqual(_.isPlainObject(element), false);
element.valueOf = valueOf;
}
else {
skipTest();
}
});
test('should return `false` for DOM elements', 1, function() {
if (element) {
strictEqual(_.isPlainObject(element), false);
} else {
skipTest();
}
});
test('should return `false` for Object objects without a `toStringTag` of "Object"', 3, function() {
strictEqual(_.isPlainObject(arguments), false);
strictEqual(_.isPlainObject(Error), false);
strictEqual(_.isPlainObject(Math), false);
});
test('should return `false` for non-objects', 3, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isPlainObject(value) : _.isPlainObject();
});
deepEqual(actual, expected);
strictEqual(_.isPlainObject(true), false);
strictEqual(_.isPlainObject('a'), false);
});
test('should work with objects from another realm', 1, function() {
if (_._object) {
strictEqual(_.isPlainObject(_._object), true);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isRegExp');
(function() {
var args = arguments;
test('should return `true` for regexes', 2, function() {
strictEqual(_.isRegExp(/x/), true);
strictEqual(_.isRegExp(RegExp('x')), true);
});
test('should return `false` for non-regexes', 12, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isRegExp(value) : _.isRegExp();
});
deepEqual(actual, expected);
strictEqual(_.isRegExp(args), false);
strictEqual(_.isRegExp([1, 2, 3]), false);
strictEqual(_.isRegExp(true), false);
strictEqual(_.isRegExp(new Date), false);
strictEqual(_.isRegExp(new Error), false);
strictEqual(_.isRegExp(_), false);
strictEqual(_.isRegExp(slice), false);
strictEqual(_.isRegExp({ 'a': 1 }), false);
strictEqual(_.isRegExp(1), false);
strictEqual(_.isRegExp(NaN), false);
strictEqual(_.isRegExp('a'), false);
});
test('should work with regexes from another realm', 1, function() {
if (_._object) {
strictEqual(_.isRegExp(_._regexp), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isString');
(function() {
var args = arguments;
test('should return `true` for strings', 2, function() {
strictEqual(_.isString('a'), true);
strictEqual(_.isString(Object('a')), true);
});
test('should return `false` for non-strings', 12, function() {
var expected = _.map(falsey, function(value) { return value === ''; });
var actual = _.map(falsey, function(value, index) {
return index ? _.isString(value) : _.isString();
});
deepEqual(actual, expected);
strictEqual(_.isString(args), false);
strictEqual(_.isString([1, 2, 3]), false);
strictEqual(_.isString(true), false);
strictEqual(_.isString(new Date), false);
strictEqual(_.isString(new Error), false);
strictEqual(_.isString(_), false);
strictEqual(_.isString(slice), false);
strictEqual(_.isString({ '0': 1, 'length': 1 }), false);
strictEqual(_.isString(1), false);
strictEqual(_.isString(NaN), false);
strictEqual(_.isString(/x/), false);
});
test('should work with strings from another realm', 1, function() {
if (_._object) {
strictEqual(_.isString(_._string), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isTypedArray');
(function() {
var args = arguments;
test('should return `true` for typed arrays', 1, function() {
var expected = _.map(typedArrays, function(type) {
return type in root;
});
var actual = _.map(typedArrays, function(type) {
var Ctor = root[type];
return Ctor ? _.isTypedArray(new Ctor(new ArrayBuffer(8))) : false;
});
deepEqual(actual, expected);
});
test('should return `false` for non typed arrays', 13, function() {
var expected = _.map(falsey, _.constant(false));
var actual = _.map(falsey, function(value, index) {
return index ? _.isTypedArray(value) : _.isTypedArray();
});
deepEqual(actual, expected);
strictEqual(_.isTypedArray(args), false);
strictEqual(_.isTypedArray([1, 2, 3]), false);
strictEqual(_.isTypedArray(true), false);
strictEqual(_.isTypedArray(new Date), false);
strictEqual(_.isTypedArray(new Error), false);
strictEqual(_.isTypedArray(_), false);
strictEqual(_.isTypedArray(slice), false);
strictEqual(_.isTypedArray({ 'a': 1 }), false);
strictEqual(_.isTypedArray(1), false);
strictEqual(_.isTypedArray(NaN), false);
strictEqual(_.isTypedArray(/x/), false);
strictEqual(_.isTypedArray('a'), false);
});
test('should work with typed arrays from another realm', 1, function() {
if (_._object) {
var props = _.map(typedArrays, function(type) {
return '_' + type.toLowerCase();
});
var expected = _.map(props, function(key) {
return key in _;
});
var actual = _.map(props, function(key) {
var value = _[key];
return value ? _.isTypedArray(value) : false;
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.isUndefined');
(function() {
var args = arguments;
test('should return `true` for `undefined` values', 2, function() {
strictEqual(_.isUndefined(), true);
strictEqual(_.isUndefined(undefined), true);
});
test('should return `false` for non `undefined` values', 13, function() {
var expected = _.map(falsey, function(value) { return value === undefined; });
var actual = _.map(falsey, function(value, index) {
return index ? _.isUndefined(value) : _.isUndefined();
});
deepEqual(actual, expected);
strictEqual(_.isUndefined(args), false);
strictEqual(_.isUndefined([1, 2, 3]), false);
strictEqual(_.isUndefined(true), false);
strictEqual(_.isUndefined(new Date), false);
strictEqual(_.isUndefined(new Error), false);
strictEqual(_.isUndefined(_), false);
strictEqual(_.isUndefined(slice), false);
strictEqual(_.isUndefined({ 'a': 1 }), false);
strictEqual(_.isUndefined(1), false);
strictEqual(_.isUndefined(NaN), false);
strictEqual(_.isUndefined(/x/), false);
strictEqual(_.isUndefined('a'), false);
});
test('should work with `undefined` from another realm', 1, function() {
if (_._object) {
strictEqual(_.isUndefined(_._undefined), true);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('isType checks');
(function() {
test('should return `false` for subclassed values', 8, function() {
var funcs = [
'isArray', 'isBoolean', 'isDate', 'isError',
'isFunction', 'isNumber', 'isRegExp', 'isString'
];
_.each(funcs, function(methodName) {
function Foo() {}
Foo.prototype = root[methodName.slice(2)].prototype;
var object = new Foo;
if (objToString.call(object) == objectTag) {
strictEqual(_[methodName](object), false, '`_.' + methodName + '` returns `false`');
} else {
skipTest();
}
});
});
test('should not error on host objects (test in IE)', 15, function() {
var funcs = [
'isArguments', 'isArray', 'isBoolean', 'isDate', 'isElement',
'isError', 'isFinite', 'isFunction', 'isNaN', 'isNull', 'isNumber',
'isObject', 'isRegExp', 'isString', 'isUndefined'
];
_.each(funcs, function(methodName) {
if (xml) {
var pass = true;
try {
_[methodName](xml);
} catch(e) {
pass = false;
}
ok(pass, '`_.' + methodName + '` should not error');
}
else {
skipTest();
}
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.iteratee');
(function() {
test('should provide arguments to `func`', 1, function() {
var fn = function() { return slice.call(arguments); },
iteratee = _.iteratee(fn),
actual = iteratee('a', 'b', 'c', 'd', 'e', 'f');
deepEqual(actual, ['a', 'b', 'c', 'd', 'e', 'f']);
});
test('should return `_.identity` when `func` is nullish', 1, function() {
var object = {},
values = [, null, undefined],
expected = _.map(values, _.constant([!isNpm && _.identity, object]));
var actual = _.map(values, function(value, index) {
var identity = index ? _.iteratee(value) : _.iteratee();
return [!isNpm && identity, identity(object)];
});
deepEqual(actual, expected);
});
test('should return an iteratee created by `_.matches` when `func` is an object', 2, function() {
var matches = _.iteratee({ 'a': 1, 'b': 2 });
strictEqual(matches({ 'a': 1, 'b': 2, 'c': 3 }), true);
strictEqual(matches({ 'b': 2 }), false);
});
test('should not change match behavior if `source` is augmented', 9, function() {
var sources = [
{ 'a': { 'b': 2, 'c': 3 } },
{ 'a': 1, 'b': 2 },
{ 'a': 1 }
];
_.each(sources, function(source, index) {
var object = _.cloneDeep(source),
matches = _.iteratee(source);
strictEqual(matches(object), true);
if (index) {
source.a = 2;
source.b = 1;
source.c = 3;
} else {
source.a.b = 1;
source.a.c = 2;
source.a.d = 3;
}
strictEqual(matches(object), true);
strictEqual(matches(source), false);
});
});
test('should return an iteratee created by `_.matchesProperty` when `func` is a number or string and a value is provided', 3, function() {
var array = ['a', undefined],
matches = _.iteratee([0, 'a']);
strictEqual(matches(array), true);
matches = _.iteratee(['0', 'a']);
strictEqual(matches(array), true);
matches = _.iteratee([1, undefined]);
strictEqual(matches(array), true);
});
test('should support deep paths for "_.matchesProperty" shorthands', 1, function() {
var object = { 'a': { 'b': { 'c': { 'd': 1, 'e': 2 } } } },
matches = _.iteratee(['a.b.c', { 'e': 2 }]);
strictEqual(matches(object), true);
});
test('should return an iteratee created by `_.property` when `func` is a number or string', 2, function() {
var array = ['a'],
prop = _.iteratee(0);
strictEqual(prop(array), 'a');
prop = _.iteratee('0');
strictEqual(prop(array), 'a');
});
test('should support deep paths for "_.property" shorthands', 1, function() {
var object = { 'a': { 'b': { 'c': 3 } } },
prop = _.iteratee('a.b.c');
strictEqual(prop(object), 3);
});
test('should work with functions created by `_.partial` and `_.partialRight`', 2, function() {
var fn = function() {
var result = [this.a];
push.apply(result, arguments);
return result;
};
var expected = [1, 2, 3],
object = { 'a': 1 , 'iteratee': _.iteratee(_.partial(fn, 2)) };
deepEqual(object.iteratee(3), expected);
object.iteratee = _.iteratee(_.partialRight(fn, 3));
deepEqual(object.iteratee(2), expected);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var fn = function() { return this instanceof Number; },
array = [fn, fn, fn],
iteratees = _.map(array, _.iteratee),
expected = _.map(array, _.constant(false));
var actual = _.map(iteratees, function(iteratee) {
return iteratee();
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('custom `_.iteratee` methods');
(function() {
var array = ['one', 'two', 'three'],
getPropA = _.partial(_.property, 'a'),
getPropB = _.partial(_.property, 'b'),
getLength = _.partial(_.property, 'length'),
iteratee = _.iteratee;
var getSum = function() {
return function(result, object) {
return result + object.a;
};
};
var objects = [
{ 'a': 0, 'b': 0 },
{ 'a': 1, 'b': 0 },
{ 'a': 1, 'b': 1 }
];
test('`_.countBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getLength;
deepEqual(_.countBy(array), { '3': 2, '5': 1 });
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.dropRightWhile` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.dropRightWhile(objects), objects.slice(0, 2));
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.dropWhile` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.dropWhile(objects.reverse()).reverse(), objects.reverse().slice(0, 2));
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.every` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
strictEqual(_.every(objects.slice(1)), true);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.filter` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
var objects = [{ 'a': 0 }, { 'a': 1 }];
_.iteratee = getPropA;
deepEqual(_.filter(objects), [objects[1]]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.find` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
strictEqual(_.find(objects), objects[1]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.findIndex` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
strictEqual(_.findIndex(objects), 1);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.findLast` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
strictEqual(_.findLast(objects), objects[2]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.findLastIndex` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
strictEqual(_.findLastIndex(objects), 2);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.findLastKey` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
strictEqual(_.findKey(objects), '2');
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.findKey` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
strictEqual(_.findLastKey(objects), '2');
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.groupBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getLength;
deepEqual(_.groupBy(array), { '3': ['one', 'two'], '5': ['three'] });
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.indexBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getLength;
deepEqual(_.indexBy(array), { '3': 'two', '5': 'three' });
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.map` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
deepEqual(_.map(objects), [0, 1, 1]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.mapKeys` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.mapKeys({ 'a': { 'b': 1 } }), { '1': { 'b': 1 } });
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.mapValues` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.mapValues({ 'a': { 'b': 1 } }), { 'a': 1 });
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.maxBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.maxBy(objects), objects[2]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.minBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.minBy(objects), objects[0]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.partition` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
var objects = [{ 'a': 1 }, { 'a': 1 }, { 'b': 2 }];
_.iteratee = getPropA;
deepEqual(_.partition(objects), [objects.slice(0, 2), objects.slice(2)]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.reduce` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getSum;
strictEqual(_.reduce(objects, undefined, 0), 2);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.reduceRight` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getSum;
strictEqual(_.reduceRight(objects, undefined, 0), 2);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.reject` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
var objects = [{ 'a': 0 }, { 'a': 1 }];
_.iteratee = getPropA;
deepEqual(_.reject(objects), [objects[0]]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.remove` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
var objects = [{ 'a': 0 }, { 'a': 1 }];
_.iteratee = getPropA;
_.remove(objects);
deepEqual(objects, [{ 'a': 0 }]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.some` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
strictEqual(_.some(objects), true);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.sortBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropA;
deepEqual(_.sortBy(objects.slice().reverse()), [objects[0], objects[2], objects[1]]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.sortedIndexBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
var objects = [{ 'a': 30 }, { 'a': 50 }];
_.iteratee = getPropA;
strictEqual(_.sortedIndexBy(objects, { 'a': 40 }), 1);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.sortedLastIndexBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
var objects = [{ 'a': 30 }, { 'a': 50 }];
_.iteratee = getPropA;
strictEqual(_.sortedLastIndexBy(objects, { 'a': 40 }), 1);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.sumBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
strictEqual(_.sumBy(objects), 1);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.takeRightWhile` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.takeRightWhile(objects), objects.slice(2));
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.takeWhile` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.takeWhile(objects.reverse()), objects.reverse().slice(2));
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.transform` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = function() {
return function(result, object) {
result.sum += object.a;
};
};
deepEqual(_.transform(objects, undefined, { 'sum': 0 }), { 'sum': 2 });
_.iteratee = iteratee;
}
else {
skipTest();
}
});
test('`_.uniqBy` should use `_.iteratee` internally', 1, function() {
if (!isModularize) {
_.iteratee = getPropB;
deepEqual(_.uniqBy(objects), [objects[0], objects[2]]);
_.iteratee = iteratee;
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('keys methods');
_.each(['keys', 'keysIn'], function(methodName) {
var args = arguments,
func = _[methodName],
isKeys = methodName == 'keys';
test('`_.' + methodName + '` should return the keys of an object', 1, function() {
deepEqual(func({ 'a': 1, 'b': 1 }).sort(), ['a', 'b']);
});
test('`_.' + methodName + '` should coerce primitives to objects (test in IE 9)', 2, function() {
deepEqual(func('abc').sort(), ['0', '1', '2']);
// IE 9 doesn't box numbers in for-in loops.
numberProto.a = 1;
deepEqual(func(0), isKeys ? [] : ['a']);
delete numberProto.a;
});
test('`_.' + methodName + '` should treat sparse arrays as dense', 1, function() {
var array = [1];
array[2] = 3;
deepEqual(func(array).sort(), ['0', '1', '2']);
});
test('`_.' + methodName + '` should coerce nullish values to objects', 2, function() {
objectProto.a = 1;
_.each([null, undefined], function(value) {
deepEqual(func(value), isKeys ? [] : ['a']);
});
delete objectProto.a;
});
test('`_.' + methodName + '` should return keys for custom properties on arrays', 1, function() {
var array = [1];
array.a = 1;
deepEqual(func(array).sort(), ['0', 'a']);
});
test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of arrays', 1, function() {
var expected = isKeys ? ['0'] : ['0', 'a'];
arrayProto.a = 1;
deepEqual(func([1]).sort(), expected);
delete arrayProto.a;
});
test('`_.' + methodName + '` should work with `arguments` objects', 1, function() {
if (!isStrict) {
deepEqual(func(args).sort(), ['0', '1', '2']);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should return keys for custom properties on `arguments` objects', 1, function() {
if (!isStrict) {
args.a = 1;
deepEqual(func(args).sort(), ['0', '1', '2', 'a']);
delete args.a;
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of `arguments` objects', 1, function() {
if (!isStrict) {
var expected = isKeys ? ['0', '1', '2'] : ['0', '1', '2', 'a'];
objectProto.a = 1;
deepEqual(func(args).sort(), expected);
delete objectProto.a;
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should work with string objects', 1, function() {
deepEqual(func(Object('abc')).sort(), ['0', '1', '2']);
});
test('`_.' + methodName + '` should return keys for custom properties on string objects', 1, function() {
var object = Object('a');
object.a = 1;
deepEqual(func(object).sort(), ['0', 'a']);
});
test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties of string objects', 1, function() {
var expected = isKeys ? ['0'] : ['0', 'a'];
stringProto.a = 1;
deepEqual(func(Object('a')).sort(), expected);
delete stringProto.a;
});
test('`_.' + methodName + '` skips the `constructor` property on prototype objects', 3, function() {
function Foo() {}
Foo.prototype.a = 1;
var expected = ['a'];
deepEqual(func(Foo.prototype), expected);
Foo.prototype = { 'constructor': Foo, 'a': 1 };
deepEqual(func(Foo.prototype), expected);
var Fake = { 'prototype': {} };
Fake.prototype.constructor = Fake;
deepEqual(func(Fake.prototype), ['constructor']);
});
test('`_.' + methodName + '` should ' + (isKeys ? 'not' : '') + ' include inherited properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var expected = isKeys ? ['a'] : ['a', 'b'];
deepEqual(func(new Foo).sort(), expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.last');
(function() {
var array = [1, 2, 3, 4];
test('should return the last element', 1, function() {
strictEqual(_.last(array), 4);
});
test('should return `undefined` when querying empty arrays', 1, function() {
var array = [];
array['-1'] = 1;
strictEqual(_.last([]), undefined);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.last);
deepEqual(actual, [3, 6, 9]);
});
test('should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
strictEqual(_(array).last(), 4);
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(array).chain().last() instanceof _);
}
else {
skipTest();
}
});
test('should not execute immediately when explicitly chaining', 1, function() {
if (!isNpm) {
var wrapped = _(array).chain().last();
strictEqual(wrapped.__wrapped__, array);
}
else {
skipTest();
}
});
test('should work in a lazy chain sequence', 2, function() {
if (!isNpm) {
var largeArray = _.range(1, LARGE_ARRAY_SIZE + 1),
smallArray = array;
_.times(2, function(index) {
var array = index ? largeArray : smallArray,
predicate = function(value) { return value % 2; },
wrapped = _(array).filter(predicate);
strictEqual(wrapped.last(), _.last(_.filter(array, predicate)));
});
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.lt');
(function() {
test('should return `true` if `value` is less than `other`', 2, function() {
strictEqual(_.lt(1, 3), true);
strictEqual(_.lt('abc', 'def'), true);
});
test('should return `false` if `value` is greater than or equal to `other`', 4, function() {
strictEqual(_.lt(3, 1), false);
strictEqual(_.lt(3, 3), false);
strictEqual(_.lt('def', 'abc'), false);
strictEqual(_.lt('def', 'def'), false);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.lte');
(function() {
test('should return `true` if `value` is less than or equal to `other`', 4, function() {
strictEqual(_.lte(1, 3), true);
strictEqual(_.lte(3, 3), true);
strictEqual(_.lte('abc', 'def'), true);
strictEqual(_.lte('def', 'def'), true);
});
test('should return `false` if `value` is greater than `other`', 2, function() {
strictEqual(_.lt(3, 1), false);
strictEqual(_.lt('def', 'abc'), false);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.lastIndexOf');
(function() {
var array = [1, 2, 3, 1, 2, 3];
test('should return the index of the last matched value', 1, function() {
strictEqual(_.lastIndexOf(array, 3), 5);
});
test('should work with a positive `fromIndex`', 1, function() {
strictEqual(_.lastIndexOf(array, 1, 2), 0);
});
test('should work with `fromIndex` >= `array.length`', 1, function() {
var values = [6, 8, Math.pow(2, 32), Infinity],
expected = _.map(values, _.constant([-1, 3, -1]));
var actual = _.map(values, function(fromIndex) {
return [
_.lastIndexOf(array, undefined, fromIndex),
_.lastIndexOf(array, 1, fromIndex),
_.lastIndexOf(array, '', fromIndex)
];
});
deepEqual(actual, expected);
});
test('should work with a negative `fromIndex`', 1, function() {
strictEqual(_.lastIndexOf(array, 2, -3), 1);
});
test('should work with a negative `fromIndex` <= `-array.length`', 1, function() {
var values = [-6, -8, -Infinity],
expected = _.map(values, _.constant(0));
var actual = _.map(values, function(fromIndex) {
return _.lastIndexOf(array, 1, fromIndex);
});
deepEqual(actual, expected);
});
test('should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`', 1, function() {
var expected = _.map(falsey, function(value) {
return typeof value == 'number' ? -1 : 5;
});
var actual = _.map(falsey, function(fromIndex) {
return _.lastIndexOf(array, 3, fromIndex);
});
deepEqual(actual, expected);
});
test('should coerce `fromIndex` to an integer', 1, function() {
strictEqual(_.lastIndexOf(array, 2, 4.2), 4);
});
test('should perform a binary search when `fromIndex` is a non-number truthy value', 1, function() {
var sorted = [4, 4, 5, 5, 6, 6],
values = [true, '1', {}],
expected = _.map(values, _.constant(3));
var actual = _.map(values, function(value) {
return _.lastIndexOf(sorted, 5, value);
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('indexOf methods');
_.each(['indexOf', 'lastIndexOf'], function(methodName) {
var func = _[methodName],
isIndexOf = methodName == 'indexOf';
test('`_.' + methodName + '` should accept a falsey `array` argument', 1, function() {
var expected = _.map(falsey, _.constant(-1));
var actual = _.map(falsey, function(array, index) {
try {
return index ? func(array) : func();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should return `-1` for an unmatched value', 5, function() {
var array = [1, 2, 3],
empty = [];
strictEqual(func(array, 4), -1);
strictEqual(func(array, 4, true), -1);
strictEqual(func(array, undefined, true), -1);
strictEqual(func(empty, undefined), -1);
strictEqual(func(empty, undefined, true), -1);
});
test('`_.' + methodName + '` should not match values on empty arrays', 2, function() {
var array = [];
array[-1] = 0;
strictEqual(func(array, undefined), -1);
strictEqual(func(array, 0, true), -1);
});
test('`_.' + methodName + '` should match `NaN`', 4, function() {
var array = [1, NaN, 3, NaN, 5, NaN];
strictEqual(func(array, NaN), isIndexOf ? 1 : 5);
strictEqual(func(array, NaN, 2), isIndexOf ? 3 : 1);
strictEqual(func(array, NaN, -2), isIndexOf ? 5 : 3);
strictEqual(func([1, 2, NaN, NaN], NaN, true), isIndexOf ? 2 : 3);
});
test('`_.' + methodName + '` should match `-0` as `0`', 2, function() {
strictEqual(func([-0], 0), 0);
strictEqual(func([0], -0), 0);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.map');
(function() {
var array = [1, 2, 3];
test('should map values in `collection` to a new array', 2, function() {
var object = { 'a': 1, 'b': 2, 'c': 3 },
expected = ['1', '2', '3'];
deepEqual(_.map(array, String), expected);
deepEqual(_.map(object, String), expected);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.map(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [1, 0, array]);
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var objects = [{ 'a': 'x' }, { 'a': 'y' }];
deepEqual(_.map(objects, 'a'), ['x', 'y']);
});
test('should iterate over own properties of objects', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var actual = _.map(new Foo, function(value, key) { return key; });
deepEqual(actual, ['a']);
});
test('should work on an object with no `iteratee`', 1, function() {
var actual = _.map({ 'a': 1, 'b': 2, 'c': 3 });
deepEqual(actual, array);
});
test('should handle object arguments with non-numeric length properties', 1, function() {
var value = { 'value': 'x' },
object = { 'length': { 'value': 'x' } };
deepEqual(_.map(object, _.identity), [value]);
});
test('should treat a nodelist as an array-like object', 1, function() {
if (document) {
var actual = _.map(document.getElementsByTagName('body'), function(element) {
return element.nodeName.toLowerCase();
});
deepEqual(actual, ['body']);
}
else {
skipTest();
}
});
test('should accept a falsey `collection` argument', 1, function() {
var expected = _.map(falsey, _.constant([]));
var actual = _.map(falsey, function(collection, index) {
try {
return index ? _.map(collection) : _.map();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should treat number values for `collection` as empty', 1, function() {
deepEqual(_.map(1), []);
});
test('should return a wrapped value when chaining', 1, function() {
if (!isNpm) {
ok(_(array).map(_.noop) instanceof _);
}
else {
skipTest();
}
});
test('should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() {
if (!isNpm) {
var args,
array = _.range(0, LARGE_ARRAY_SIZE + 1),
expected = [1, 0, _.map(array.slice(1), square)];
_(array).slice(1).map(function(value, index, array) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, [1, 0, array.slice(1)]);
args = null;
_(array).slice(1).map(square).map(function(value, index, array) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, expected);
args = null;
_(array).slice(1).map(square).map(function(value, index) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, expected);
args = null;
_(array).slice(1).map(square).map(function(value) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, [1]);
args = null;
_(array).slice(1).map(square).map(function() {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, expected);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.mapKeys');
(function() {
var array = [1, 2],
object = { 'a': 1, 'b': 2, 'c': 3 };
test('should map keys in `object` to a new object', 1, function() {
var actual = _.mapKeys(object, String);
deepEqual(actual, { '1': 1, '2': 2, '3': 3 });
});
test('should treat arrays like objects', 1, function() {
var actual = _.mapKeys(array, String);
deepEqual(actual, { '1': 1, '2': 2 });
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var actual = _.mapKeys({ 'a': { 'b': 'c' } }, 'b');
deepEqual(actual, { 'c': { 'b': 'c' } });
});
test('should work on an object with no `iteratee`', 1, function() {
var actual = _.mapKeys({ 'a': 1, 'b': 2, 'c': 3 });
deepEqual(actual, { '1': 1, '2': 2, '3': 3 });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.mapValues');
(function() {
var array = [1, 2],
object = { 'a': 1, 'b': 2, 'c': 3 };
test('should map values in `object` to a new object', 1, function() {
var actual = _.mapValues(object, String);
deepEqual(actual, { 'a': '1', 'b': '2', 'c': '3' });
});
test('should treat arrays like objects', 1, function() {
var actual = _.mapValues(array, String);
deepEqual(actual, { '0': '1', '1': '2' });
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var actual = _.mapValues({ 'a': { 'b': 1 } }, 'b');
deepEqual(actual, { 'a': 1 });
});
test('should work on an object with no `iteratee`', 2, function() {
var actual = _.mapValues({ 'a': 1, 'b': 2, 'c': 3 });
deepEqual(actual, object);
notStrictEqual(actual, object);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.mapKeys and lodash.mapValues');
_.each(['mapKeys', 'mapValues'], function(methodName) {
var array = [1, 2],
func = _[methodName],
object = { 'a': 1, 'b': 2, 'c': 3 };
test('should iterate over own properties of objects', 1, function() {
function Foo() { this.a = 'a'; }
Foo.prototype.b = 'b';
var actual = func(new Foo, function(value, key) { return key; });
deepEqual(actual, { 'a': 'a' });
});
test('should accept a falsey `object` argument', 1, function() {
var expected = _.map(falsey, _.constant({}));
var actual = _.map(falsey, function(object, index) {
try {
return index ? func(object) : func();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should provide the correct `iteratee` arguments', 2, function() {
_.each([object, array], function(value, index) {
var args;
_.mapValues(value, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [1, index ? '0' : 'a', value]);
});
});
test('should return a wrapped value when chaining', 1, function() {
if (!isNpm) {
ok(_(object)[methodName](_.noop) instanceof _);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.matches');
(function() {
test('should create a function that performs a deep comparison between a given object and `source`', 6, function() {
var object = { 'a': 1, 'b': 2, 'c': 3 },
matches = _.matches({ 'a': 1 });
strictEqual(matches.length, 1);
strictEqual(matches(object), true);
matches = _.matches({ 'b': 1 });
strictEqual(matches(object), false);
matches = _.matches({ 'a': 1, 'c': 3 });
strictEqual(matches(object), true);
matches = _.matches({ 'c': 3, 'd': 4 });
strictEqual(matches(object), false);
object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 };
matches = _.matches({ 'a': { 'b': { 'c': 1 } } });
strictEqual(matches(object), true);
});
test('should match inherited `value` properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var object = { 'a': new Foo },
matches = _.matches({ 'a': { 'b': 2 } });
strictEqual(matches(object), true);
});
test('should match `-0` as `0`', 2, function() {
var object1 = { 'a': -0 },
object2 = { 'a': 0 },
matches = _.matches(object1);
strictEqual(matches(object2), true);
matches = _.matches(object2);
strictEqual(matches(object1), true);
});
test('should not match by inherited `source` properties', 1, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var objects = [{ 'a': 1 }, { 'a': 1, 'b': 2 }],
source = new Foo,
matches = _.matches(source),
actual = _.map(objects, matches),
expected = _.map(objects, _.constant(true));
deepEqual(actual, expected);
});
test('should return `false` when `object` is nullish', 1, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(false)),
matches = _.matches({ 'a': 1 });
var actual = _.map(values, function(value, index) {
try {
return index ? matches(value) : matches();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should return `true` when comparing an empty `source`', 1, function() {
var object = { 'a': 1 },
expected = _.map(empties, _.constant(true));
var actual = _.map(empties, function(value) {
var matches = _.matches(value);
return matches(object);
});
deepEqual(actual, expected);
});
test('should compare a variety of `source` property values', 2, function() {
var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } },
object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } },
matches = _.matches(object1);
strictEqual(matches(object1), true);
strictEqual(matches(object2), false);
});
test('should compare functions by reference', 3, function() {
var object1 = { 'a': _.noop },
object2 = { 'a': noop },
object3 = { 'a': {} },
matches = _.matches(object1);
strictEqual(matches(object1), true);
strictEqual(matches(object2), false);
strictEqual(matches(object3), false);
});
test('should not change match behavior if `source` is augmented', 9, function() {
var sources = [
{ 'a': { 'b': 2, 'c': 3 } },
{ 'a': 1, 'b': 2 },
{ 'a': 1 }
];
_.each(sources, function(source, index) {
var object = _.cloneDeep(source),
matches = _.matches(source);
strictEqual(matches(object), true);
if (index) {
source.a = 2;
source.b = 1;
source.c = 3;
} else {
source.a.b = 1;
source.a.c = 2;
source.a.d = 3;
}
strictEqual(matches(object), true);
strictEqual(matches(source), false);
});
});
test('should return `true` when comparing a `source` of empty arrays and objects', 1, function() {
var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }],
matches = _.matches({ 'a': [], 'b': {} }),
actual = _.filter(objects, matches);
deepEqual(actual, objects);
});
test('should return `true` when comparing an empty `source` to a nullish `object`', 1, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(true)),
matches = _.matches({});
var actual = _.map(values, function(value, index) {
try {
return index ? matches(value) : matches();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should search arrays of `source` for values', 3, function() {
var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }],
matches = _.matches({ 'a': ['d'] }),
actual = _.filter(objects, matches);
deepEqual(actual, [objects[1]]);
matches = _.matches({ 'a': ['b', 'd'] });
actual = _.filter(objects, matches);
deepEqual(actual, []);
matches = _.matches({ 'a': ['d', 'b'] });
actual = _.filter(objects, matches);
deepEqual(actual, []);
});
test('should perform a partial comparison of all objects within arrays of `source`', 1, function() {
var objects = [
{ 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 5, 'd': 6 }] },
{ 'a': [{ 'b': 1, 'c': 2 }, { 'b': 4, 'c': 6, 'd': 7 }] }
];
var matches = _.matches({ 'a': [{ 'b': 1 }, { 'b': 4, 'c': 5 }] }),
actual = _.filter(objects, matches);
deepEqual(actual, [objects[0]]);
});
test('should handle a `source` with `undefined` values', 3, function() {
var objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }],
matches = _.matches({ 'b': undefined }),
actual = _.map(objects, matches),
expected = [false, false, true];
deepEqual(actual, expected);
matches = _.matches({ 'a': 1, 'b': undefined });
actual = _.map(objects, matches);
deepEqual(actual, expected);
objects = [{ 'a': { 'b': 1 } }, { 'a': { 'b':1, 'c': 1 } }, { 'a': { 'b': 1, 'c': undefined } }];
matches = _.matches({ 'a': { 'c': undefined } });
actual = _.map(objects, matches);
deepEqual(actual, expected);
});
test('should handle a primitive `object` and a `source` with `undefined` values', 3, function() {
numberProto.a = 1;
numberProto.b = undefined;
try {
var matches = _.matches({ 'b': undefined });
strictEqual(matches(1), true);
} catch(e) {
ok(false, e.message);
}
try {
matches = _.matches({ 'a': 1, 'b': undefined });
strictEqual(matches(1), true);
} catch(e) {
ok(false, e.message);
}
numberProto.a = { 'b': 1, 'c': undefined };
try {
matches = _.matches({ 'a': { 'c': undefined } });
strictEqual(matches(1), true);
} catch(e) {
ok(false, e.message);
}
delete numberProto.a;
delete numberProto.b;
});
test('should match properties when `value` is a function', 1, function() {
function Foo() {}
Foo.a = { 'b': 1, 'c': 2 };
var matches = _.matches({ 'a': { 'b': 1 } });
strictEqual(matches(Foo), true);
});
test('should match properties when `value` is not a plain object', 1, function() {
function Foo(object) { _.assign(this, object); }
var object = new Foo({ 'a': new Foo({ 'b': 1, 'c': 2 }) }),
matches = _.matches({ 'a': { 'b': 1 } });
strictEqual(matches(object), true);
});
test('should work with a function for `source`', 1, function() {
function source() {}
source.a = 1;
source.b = function() {};
source.c = 3;
var matches = _.matches(source),
objects = [{ 'a': 1 }, { 'a': 1, 'b': source.b, 'c': 3 }],
actual = _.map(objects, matches);
deepEqual(actual, [false, true]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.matchesProperty');
(function() {
test('should create a function that performs a deep comparison between a property value and `value`', 6, function() {
var object = { 'a': 1, 'b': 2, 'c': 3 },
matches = _.matchesProperty('a', 1);
strictEqual(matches.length, 1);
strictEqual(matches(object), true);
matches = _.matchesProperty('b', 3);
strictEqual(matches(object), false);
matches = _.matchesProperty('a', { 'a': 1, 'c': 3 });
strictEqual(matches({ 'a': object }), true);
matches = _.matchesProperty('a', { 'c': 3, 'd': 4 });
strictEqual(matches(object), false);
object = { 'a': { 'b': { 'c': 1, 'd': 2 }, 'e': 3 }, 'f': 4 };
matches = _.matchesProperty('a', { 'b': { 'c': 1 } });
strictEqual(matches(object), true);
});
test('should support deep paths', 2, function() {
var object = { 'a': { 'b': { 'c': 3 } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
var matches = _.matchesProperty(path, 3);
strictEqual(matches(object), true);
});
});
test('should coerce key to a string', 1, function() {
function fn() {}
fn.toString = _.constant('fn');
var objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }],
values = [null, undefined, fn, {}];
var expected = _.transform(values, function(result) {
result.push(true, true);
});
var actual = _.transform(objects, function(result, object, index) {
var key = values[index];
_.each([key, [key]], function(path) {
var matches = _.matchesProperty(path, object[key]);
result.push(matches(object));
});
});
deepEqual(actual, expected);
});
test('should match a key over a path', 2, function() {
var object = { 'a.b.c': 3, 'a': { 'b': { 'c': 4 } } };
_.each(['a.b.c', ['a.b.c']], function(path) {
var matches = _.matchesProperty(path, 3);
strictEqual(matches(object), true);
});
});
test('should work with non-string `path` arguments', 2, function() {
var array = [1, 2, 3];
_.each([1, [1]], function(path) {
var matches = _.matchesProperty(path, 2);
strictEqual(matches(array), true);
});
});
test('should return `false` if parts of `path` are missing', 4, function() {
var object = {};
_.each(['a', 'a[1].b.c', ['a'], ['a', '1', 'b', 'c']], function(path) {
var matches = _.matchesProperty(path, 1);
strictEqual(matches(object), false);
});
});
test('should match inherited `value` properties', 2, function() {
function Foo() {}
Foo.prototype.b = 2;
var object = { 'a': new Foo };
_.each(['a', ['a']], function(path) {
var matches = _.matchesProperty(path, { 'b': 2 });
strictEqual(matches(object), true);
});
});
test('should match `-0` as `0`', 2, function() {
var matches = _.matchesProperty('a', -0);
strictEqual(matches({ 'a': 0 }), true);
matches = _.matchesProperty('a', 0);
strictEqual(matches({ 'a': -0 }), true);
});
test('should not match by inherited `source` properties', 2, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': 2 } }],
expected = _.map(objects, _.constant(true));
_.each(['a', ['a']], function(path) {
var matches = _.matchesProperty(path, new Foo);
deepEqual(_.map(objects, matches), expected);
});
});
test('should return `false` when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(false));
_.each(['constructor', ['constructor']], function(path) {
var matches = _.matchesProperty(path, 1);
var actual = _.map(values, function(value, index) {
try {
return index ? matches(value) : matches();
} catch(e) {}
});
deepEqual(actual, expected);
});
});
test('should return `false` with deep paths when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(false));
_.each(['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']], function(path) {
var matches = _.matchesProperty(path, 1);
var actual = _.map(values, function(value, index) {
try {
return index ? matches(value) : matches();
} catch(e) {}
});
deepEqual(actual, expected);
});
});
test('should compare a variety of values', 2, function() {
var object1 = { 'a': false, 'b': true, 'c': '3', 'd': 4, 'e': [5], 'f': { 'g': 6 } },
object2 = { 'a': 0, 'b': 1, 'c': 3, 'd': '4', 'e': ['5'], 'f': { 'g': '6' } },
matches = _.matchesProperty('a', object1);
strictEqual(matches({ 'a': object1 }), true);
strictEqual(matches({ 'a': object2 }), false);
});
test('should compare functions by reference', 3, function() {
var object1 = { 'a': _.noop },
object2 = { 'a': noop },
object3 = { 'a': {} },
matches = _.matchesProperty('a', object1);
strictEqual(matches({ 'a': object1 }), true);
strictEqual(matches({ 'a': object2 }), false);
strictEqual(matches({ 'a': object3 }), false);
});
test('should not change match behavior if `value` is augmented', 9, function() {
_.each([{ 'a': { 'b': 2, 'c': 3 } }, { 'a': 1, 'b': 2 }, { 'a': 1 }], function(source, index) {
var object = _.cloneDeep(source),
matches = _.matchesProperty('a', source);
strictEqual(matches({ 'a': object }), true);
if (index) {
source.a = 2;
source.b = 1;
source.c = 3;
} else {
source.a.b = 1;
source.a.c = 2;
source.a.d = 3;
}
strictEqual(matches({ 'a': object }), true);
strictEqual(matches({ 'a': source }), false);
});
});
test('should return `true` when comparing a `value` of empty arrays and objects', 1, function() {
var objects = [{ 'a': [1], 'b': { 'c': 1 } }, { 'a': [2, 3], 'b': { 'd': 2 } }],
matches = _.matchesProperty('a', { 'a': [], 'b': {} });
var actual = _.filter(objects, function(object) {
return matches({ 'a': object });
});
deepEqual(actual, objects);
});
test('should search arrays of `value` for values', 3, function() {
var objects = [{ 'a': ['b'] }, { 'a': ['c', 'd'] }],
matches = _.matchesProperty('a', ['d']),
actual = _.filter(objects, matches);
deepEqual(actual, [objects[1]]);
matches = _.matchesProperty('a', ['b', 'd']);
actual = _.filter(objects, matches);
deepEqual(actual, []);
matches = _.matchesProperty('a', ['d', 'b']);
actual = _.filter(objects, matches);
deepEqual(actual, []);
});
test('should perform a partial comparison of all objects within arrays of `value`', 1, function() {
var objects = [
{ 'a': [{ 'a': 1, 'b': 2 }, { 'a': 4, 'b': 5, 'c': 6 }] },
{ 'a': [{ 'a': 1, 'b': 2 }, { 'a': 4, 'b': 6, 'c': 7 }] }
];
var matches = _.matchesProperty('a', [{ 'a': 1 }, { 'a': 4, 'b': 5 }]),
actual = _.filter(objects, matches);
deepEqual(actual, [objects[0]]);
});
test('should handle a `value` with `undefined` values', 2, function() {
var objects = [{ 'a': 1 }, { 'a': 1, 'b': 1 }, { 'a': 1, 'b': undefined }],
matches = _.matchesProperty('b', undefined),
actual = _.map(objects, matches),
expected = [false, false, true];
deepEqual(actual, expected);
objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': 1 } }, { 'a': { 'a': 1, 'b': undefined } }];
matches = _.matchesProperty('a', { 'b': undefined });
actual = _.map(objects, matches);
deepEqual(actual, expected);
});
test('should handle a primitive `object` and a `source` with `undefined` values', 2, function() {
numberProto.a = 1;
numberProto.b = undefined;
try {
var matches = _.matchesProperty('b', undefined);
strictEqual(matches(1), true);
} catch(e) {
ok(false, e.message);
}
numberProto.a = { 'b': 1, 'c': undefined };
try {
matches = _.matchesProperty('a', { 'c': undefined });
strictEqual(matches(1), true);
} catch(e) {
ok(false, e.message);
}
delete numberProto.a;
delete numberProto.b;
});
test('should work with a function for `value`', 1, function() {
function source() {}
source.a = 1;
source.b = function() {};
source.c = 3;
var matches = _.matchesProperty('a', source),
objects = [{ 'a': { 'a': 1 } }, { 'a': { 'a': 1, 'b': source.b, 'c': 3 } }],
actual = _.map(objects, matches);
deepEqual(actual, [false, true]);
});
test('should match properties when `value` is not a plain object', 1, function() {
function Foo(object) { _.assign(this, object); }
var object = new Foo({ 'a': new Foo({ 'b': 1, 'c': 2 }) }),
matches = _.matchesProperty('a', { 'b': 1 });
strictEqual(matches(object), true);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.max');
(function() {
test('should return the largest value from a collection', 1, function() {
strictEqual(_.max([1, 2, 3]), 3);
});
test('should return `-Infinity` for empty collections', 1, function() {
var values = falsey.concat([[]]),
expected = _.map(values, _.constant(-Infinity));
var actual = _.map(values, function(value, index) {
try {
return index ? _.max(value) : _.max();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should return `-Infinity` for non-numeric collection values', 1, function() {
strictEqual(_.max(['a', 'b']), -Infinity);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.memoize');
(function() {
test('should memoize results based on the first argument provided', 2, function() {
var memoized = _.memoize(function(a, b, c) {
return a + b + c;
});
strictEqual(memoized(1, 2, 3), 6);
strictEqual(memoized(1, 3, 5), 6);
});
test('should support a `resolver` argument', 2, function() {
var fn = function(a, b, c) { return a + b + c; },
memoized = _.memoize(fn, fn);
strictEqual(memoized(1, 2, 3), 6);
strictEqual(memoized(1, 3, 5), 9);
});
test('should throw a TypeError if `resolve` is truthy and not a function', function() {
raises(function() { _.memoize(_.noop, {}); }, TypeError);
});
test('should not error if `resolver` is falsey', function() {
var expected = _.map(falsey, _.constant(true));
var actual = _.map(falsey, function(resolver, index) {
try {
return _.isFunction(index ? _.memoize(_.noop, resolver) : _.memoize(_.noop));
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should not set a `this` binding', 2, function() {
var memoized = _.memoize(function(a, b, c) {
return a + this.b + this.c;
});
var object = { 'b': 2, 'c': 3, 'memoized': memoized };
strictEqual(object.memoized(1), 6);
strictEqual(object.memoized(2), 7);
});
test('should check cache for own properties', 1, function() {
var props = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
var memoized = _.memoize(_.identity);
var actual = _.map(props, function(value) {
return memoized(value);
});
deepEqual(actual, props);
});
test('should expose a `cache` object on the `memoized` function which implements `Map` interface', 18, function() {
_.times(2, function(index) {
var resolver = index ? _.identity : null;
var memoized = _.memoize(function(value) {
return 'value:' + value;
}, resolver);
var cache = memoized.cache;
memoized('a');
strictEqual(cache.has('a'), true);
strictEqual(cache.get('a'), 'value:a');
strictEqual(cache['delete']('a'), true);
strictEqual(cache['delete']('b'), false);
strictEqual(cache.set('b', 'value:b'), cache);
strictEqual(cache.has('b'), true);
strictEqual(cache.get('b'), 'value:b');
strictEqual(cache['delete']('b'), true);
strictEqual(cache['delete']('a'), false);
});
});
test('should skip the `__proto__` key', 8, function() {
_.times(2, function(index) {
var count = 0,
key = '__proto__',
resolver = index && _.identity;
var memoized = _.memoize(function() {
count++;
return [];
}, resolver);
var cache = memoized.cache;
memoized(key);
memoized(key);
strictEqual(count, 2);
strictEqual(cache.get(key), undefined);
strictEqual(cache['delete'](key), false);
ok(!(cache.__data__ instanceof Array));
});
});
test('should allow `_.memoize.Cache` to be customized', 5, function() {
var oldCache = _.memoize.Cache
function Cache() {
this.__data__ = [];
}
Cache.prototype = {
'delete': function(key) {
var data = this.__data__;
var index = _.findIndex(data, function(entry) {
return key === entry.key;
});
if (index < 0) {
return false;
}
data.splice(index, 1);
return true;
},
'get': function(key) {
return _.find(this.__data__, function(entry) {
return key === entry.key;
}).value;
},
'has': function(key) {
return _.some(this.__data__, function(entry) {
return key === entry.key;
});
},
'set': function(key, value) {
this.__data__.push({ 'key': key, 'value': value });
return this;
}
};
_.memoize.Cache = Cache;
var memoized = _.memoize(function(object) {
return 'value:' + object.id;
});
var cache = memoized.cache,
key1 = { 'id': 'a' },
key2 = { 'id': 'b' };
strictEqual(memoized(key1), 'value:a');
strictEqual(cache.has(key1), true);
strictEqual(memoized(key2), 'value:b');
strictEqual(cache.has(key2), true);
cache['delete'](key2);
strictEqual(cache.has(key2), false);
_.memoize.Cache = oldCache;
});
test('should works with an immutable `_.memoize.Cache` ', 2, function() {
var oldCache = _.memoize.Cache
function Cache() {
this.__data__ = [];
}
Cache.prototype = {
'get': function(key) {
return _.find(this.__data__, function(entry) {
return key === entry.key;
}).value;
},
'has': function(key) {
return _.some(this.__data__, function(entry) {
return key === entry.key;
});
},
'set': function(key, value) {
var result = new Cache;
result.__data__ = this.__data__.concat({ 'key': key, 'value': value });
return result;
}
};
_.memoize.Cache = Cache;
var memoized = _.memoize(function(object) {
return object.id;
});
var key1 = { 'id': 'a' },
key2 = { 'id': 'b' };
memoized(key1);
memoized(key2);
var cache = memoized.cache;
strictEqual(cache.has(key1), true);
strictEqual(cache.has(key2), true);
_.memoize.Cache = oldCache;
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.merge');
(function() {
var args = arguments;
test('should merge `source` into the destination object', 1, function() {
var names = {
'characters': [
{ 'name': 'barney' },
{ 'name': 'fred' }
]
};
var ages = {
'characters': [
{ 'age': 36 },
{ 'age': 40 }
]
};
var heights = {
'characters': [
{ 'height': '5\'4"' },
{ 'height': '5\'5"' }
]
};
var expected = {
'characters': [
{ 'name': 'barney', 'age': 36, 'height': '5\'4"' },
{ 'name': 'fred', 'age': 40, 'height': '5\'5"' }
]
};
deepEqual(_.merge(names, ages, heights), expected);
});
test('should merge sources containing circular references', 1, function() {
var object = {
'foo': { 'a': 1 },
'bar': { 'a': 2 }
};
var source = {
'foo': { 'b': { 'c': { 'd': {} } } },
'bar': {}
};
source.foo.b.c.d = source;
source.bar.b = source.foo.b;
var actual = _.merge(object, source);
ok(actual.bar.b === actual.foo.b && actual.foo.b.c.d === actual.foo.b.c.d.foo.b.c.d);
});
test('should treat sources that are sparse arrays as dense', 2, function() {
var array = Array(3);
array[0] = 1;
array[2] = 3;
var actual = _.merge([], array),
expected = array.slice();
expected[1] = undefined;
ok('1' in actual);
deepEqual(actual, expected);
});
test('should skip `undefined` values in arrays if a destination value exists', 2, function() {
var array = Array(3);
array[0] = 1;
array[2] = 3;
var actual = _.merge([4, 5, 6], array),
expected = [1, 5, 3];
deepEqual(actual, expected);
array = [1, , 3];
array[1] = undefined;
actual = _.merge([4, 5, 6], array);
deepEqual(actual, expected);
});
test('should merge `arguments` objects', 3, function() {
var object1 = { 'value': args },
object2 = { 'value': { '3': 4 } },
expected = { '0': 1, '1': 2, '2': 3, '3': 4 },
actual = _.merge(object1, object2);
ok(!_.isArguments(actual.value));
deepEqual(actual.value, expected);
delete object1.value[3];
actual = _.merge(object2, object1);
deepEqual(actual.value, expected);
});
test('should merge typed arrays', 4, function() {
var array1 = [0],
array2 = [0, 0],
array3 = [0, 0, 0, 0],
array4 = _.range(0, 8, 0);
var arrays = [array2, array1, array4, array3, array2, array4, array4, array3, array2],
buffer = ArrayBuffer && new ArrayBuffer(8);
// juggle for `Float64Array` shim
if (root.Float64Array && (new Float64Array(buffer)).length == 8) {
arrays[1] = array4;
}
var expected = _.map(typedArrays, function(type, index) {
var array = arrays[index].slice();
array[0] = 1;
return root[type] ? { 'value': array } : false;
});
var actual = _.map(typedArrays, function(type) {
var Ctor = root[type];
return Ctor ? _.merge({ 'value': new Ctor(buffer) }, { 'value': [1] }) : false;
});
ok(_.isArray(actual));
deepEqual(actual, expected);
expected = _.map(typedArrays, function(type, index) {
var array = arrays[index].slice();
array.push(1);
return root[type] ? { 'value': array } : false;
});
actual = _.map(typedArrays, function(type, index) {
var Ctor = root[type],
array = _.range(arrays[index].length);
array.push(1);
return Ctor ? _.merge({ 'value': array }, { 'value': new Ctor(buffer) }) : false;
});
ok(_.isArray(actual));
deepEqual(actual, expected);
});
test('should work with four arguments', 1, function() {
var expected = { 'a': 4 },
actual = _.merge({ 'a': 1 }, { 'a': 2 }, { 'a': 3 }, expected);
deepEqual(actual, expected);
});
test('should assign `null` values', 1, function() {
var actual = _.merge({ 'a': 1 }, { 'a': null });
strictEqual(actual.a, null);
});
test('should not assign `undefined` values', 1, function() {
var actual = _.merge({ 'a': 1 }, { 'a': undefined, 'b': undefined });
deepEqual(actual, { 'a': 1 });
});
test('should not error on DOM elements', 1, function() {
var object1 = { 'el': document && document.createElement('div') },
object2 = { 'el': document && document.createElement('div') },
pairs = [[{}, object1], [object1, object2]],
expected = _.map(pairs, _.constant(true));
var actual = _.map(pairs, function(pair) {
try {
return _.merge(pair[0], pair[1]).el === pair[1].el;
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should assign non array/plain-object values directly', 1, function() {
function Foo() {}
var values = [new Foo, new Boolean, new Date, Foo, new Number, new String, new RegExp],
expected = _.map(values, _.constant(true));
var actual = _.map(values, function(value) {
var object = _.merge({}, { 'a': value });
return object.a === value;
});
deepEqual(actual, expected);
});
test('should convert values to arrays when merging with arrays of `source`', 2, function() {
var object = { 'a': { '1': 'y', 'b': 'z', 'length': 2 } },
actual = _.merge(object, { 'a': ['x'] });
deepEqual(actual, { 'a': ['x', 'y'] });
actual = _.merge({ 'a': {} }, { 'a': [] });
deepEqual(actual, { 'a': [] });
});
test('should not convert strings to arrays when merging with arrays of `source`', 1, function() {
var object = { 'a': 'abcdef' },
actual = _.merge(object, { 'a': ['x', 'y', 'z'] });
deepEqual(actual, { 'a': ['x', 'y', 'z'] });
});
test('should work with a function for `object`', 2, function() {
function Foo() {}
var source = { 'a': 1 },
actual = _.merge(Foo, source);
strictEqual(actual, Foo);
strictEqual(Foo.a, 1);
});
test('should work with a non-plain `object` value', 2, function() {
function Foo() {}
var object = new Foo,
source = { 'a': 1 },
actual = _.merge(object, source);
strictEqual(actual, object);
strictEqual(object.a, 1);
});
test('should pass thru primitive `object` values', 1, function() {
var values = [true, 1, '1'];
var actual = _.map(values, function(value) {
return _.merge(value, { 'a': 1 });
});
deepEqual(actual, values);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.mergeWith');
(function() {
test('should handle merging if `customizer` returns `undefined`', 2, function() {
var actual = _.mergeWith({ 'a': { 'b': [1, 1] } }, { 'a': { 'b': [0] } }, _.noop);
deepEqual(actual, { 'a': { 'b': [0, 1] } });
actual = _.mergeWith([], [undefined], _.identity);
deepEqual(actual, [undefined]);
});
test('should defer to `customizer` when it returns a value other than `undefined`', 1, function() {
var actual = _.mergeWith({ 'a': { 'b': [0, 1] } }, { 'a': { 'b': [2] } }, function(a, b) {
return _.isArray(a) ? a.concat(b) : undefined;
});
deepEqual(actual, { 'a': { 'b': [0, 1, 2] } });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.method');
(function() {
test('should create a function that calls a method of a given object', 4, function() {
var object = { 'a': _.constant(1) };
_.each(['a', ['a']], function(path) {
var method = _.method(path);
strictEqual(method.length, 1);
strictEqual(method(object), 1);
});
});
test('should work with deep property values', 2, function() {
var object = { 'a': { 'b': { 'c': _.constant(3) } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
var method = _.method(path);
strictEqual(method(object), 3);
});
});
test('should work with non-string `path` arguments', 2, function() {
var array = _.times(3, _.constant);
_.each([1, [1]], function(path) {
var method = _.method(path);
strictEqual(method(array), 1);
});
});
test('should coerce key to a string', 1, function() {
function fn() {}
fn.toString = _.constant('fn');
var expected = [1, 1, 2, 2, 3, 3, 4, 4],
objects = [{ 'null': _.constant(1) }, { 'undefined': _.constant(2) }, { 'fn': _.constant(3) }, { '[object Object]': _.constant(4) }],
values = [null, undefined, fn, {}];
var actual = _.transform(objects, function(result, object, index) {
var key = values[index];
_.each([key, [key]], function(path) {
var method = _.method(key);
result.push(method(object));
});
});
deepEqual(actual, expected);
});
test('should work with inherited property values', 2, function() {
function Foo() {}
Foo.prototype.a = _.constant(1);
_.each(['a', ['a']], function(path) {
var method = _.method(path);
strictEqual(method(new Foo), 1);
});
});
test('should use a key over a path', 2, function() {
var object = { 'a.b.c': _.constant(3), 'a': { 'b': { 'c': _.constant(4) } } };
_.each(['a.b.c', ['a.b.c']], function(path) {
var method = _.method(path);
strictEqual(method(object), 3);
});
});
test('should return `undefined` when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor', ['constructor']], function(path) {
var method = _.method(path);
var actual = _.map(values, function(value, index) {
return index ? method(value) : method();
});
deepEqual(actual, expected);
});
});
test('should return `undefined` with deep paths when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']], function(path) {
var method = _.method(path);
var actual = _.map(values, function(value, index) {
return index ? method(value) : method();
});
deepEqual(actual, expected);
});
});
test('should return `undefined` if parts of `path` are missing', 4, function() {
var object = {};
_.each(['a', 'a[1].b.c', ['a'], ['a', '1', 'b', 'c']], function(path) {
var method = _.method(path);
strictEqual(method(object), undefined);
});
});
test('should apply partial arguments to function', 2, function() {
var object = {
'fn': function() {
return slice.call(arguments);
}
};
_.each(['fn', ['fn']], function(path) {
var method = _.method(path, 1, 2, 3);
deepEqual(method(object), [1, 2, 3]);
});
});
test('should invoke deep property methods with the correct `this` binding', 2, function() {
var object = { 'a': { 'b': function() { return this.c; }, 'c': 1 } };
_.each(['a.b', ['a', 'b']], function(path) {
var method = _.method(path);
strictEqual(method(object), 1);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.methodOf');
(function() {
test('should create a function that calls a method of a given key', 4, function() {
var object = { 'a': _.constant(1) };
_.each(['a', ['a']], function(path) {
var methodOf = _.methodOf(object);
strictEqual(methodOf.length, 1);
strictEqual(methodOf(path), 1);
});
});
test('should work with deep property values', 2, function() {
var object = { 'a': { 'b': { 'c': _.constant(3) } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
var methodOf = _.methodOf(object);
strictEqual(methodOf(path), 3);
});
});
test('should work with non-string `path` arguments', 2, function() {
var array = _.times(3, _.constant);
_.each([1, [1]], function(path) {
var methodOf = _.methodOf(array);
strictEqual(methodOf(path), 1);
});
});
test('should coerce key to a string', 1, function() {
function fn() {}
fn.toString = _.constant('fn');
var expected = [1, 1, 2, 2, 3, 3, 4, 4],
objects = [{ 'null': _.constant(1) }, { 'undefined': _.constant(2) }, { 'fn': _.constant(3) }, { '[object Object]': _.constant(4) }],
values = [null, undefined, fn, {}];
var actual = _.transform(objects, function(result, object, index) {
var key = values[index];
_.each([key, [key]], function(path) {
var methodOf = _.methodOf(object);
result.push(methodOf(key));
});
});
deepEqual(actual, expected);
});
test('should work with inherited property values', 2, function() {
function Foo() {}
Foo.prototype.a = _.constant(1);
_.each(['a', ['a']], function(path) {
var methodOf = _.methodOf(new Foo);
strictEqual(methodOf(path), 1);
});
});
test('should use a key over a path', 2, function() {
var object = { 'a.b.c': _.constant(3), 'a': { 'b': { 'c': _.constant(4) } } };
_.each(['a.b.c', ['a.b.c']], function(path) {
var methodOf = _.methodOf(object);
strictEqual(methodOf(path), 3);
});
});
test('should return `undefined` when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor', ['constructor']], function(path) {
var actual = _.map(values, function(value, index) {
var methodOf = index ? _.methodOf() : _.methodOf(value);
return methodOf(path);
});
deepEqual(actual, expected);
});
});
test('should return `undefined` with deep paths when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']], function(path) {
var actual = _.map(values, function(value, index) {
var methodOf = index ? _.methodOf() : _.methodOf(value);
return methodOf(path);
});
deepEqual(actual, expected);
});
});
test('should return `undefined` if parts of `path` are missing', 4, function() {
var object = {},
methodOf = _.methodOf(object);
_.each(['a', 'a[1].b.c', ['a'], ['a', '1', 'b', 'c']], function(path) {
strictEqual(methodOf(path), undefined);
});
});
test('should apply partial arguments to function', 2, function() {
var object = {
'fn': function() {
return slice.call(arguments);
}
};
var methodOf = _.methodOf(object, 1, 2, 3);
_.each(['fn', ['fn']], function(path) {
deepEqual(methodOf(path), [1, 2, 3]);
});
});
test('should invoke deep property methods with the correct `this` binding', 2, function() {
var object = { 'a': { 'b': function() { return this.c; }, 'c': 1 } },
methodOf = _.methodOf(object);
_.each(['a.b', ['a', 'b']], function(path) {
strictEqual(methodOf(path), 1);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.min');
(function() {
test('should return the smallest value from a collection', 1, function() {
strictEqual(_.min([1, 2, 3]), 1);
});
test('should return `Infinity` for empty collections', 1, function() {
var values = falsey.concat([[]]),
expected = _.map(values, _.constant(Infinity));
var actual = _.map(values, function(value, index) {
try {
return index ? _.min(value) : _.min();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should return `Infinity` for non-numeric collection values', 1, function() {
strictEqual(_.min(['a', 'b']), Infinity);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('extremum methods');
_.each(['max', 'maxBy', 'min', 'minBy'], function(methodName) {
var array = [1, 2, 3],
func = _[methodName],
isMax = /^max/.test(methodName);
test('`_.' + methodName + '` should work with Date objects', 1, function() {
var curr = new Date,
past = new Date(0);
strictEqual(func([curr, past]), isMax ? curr : past);
});
test('`_.' + methodName + '` should work with extremely large arrays', 1, function() {
var array = _.range(0, 5e5);
strictEqual(func(array), isMax ? 499999 : 0);
});
test('`_.' + methodName + '` should work when chaining on an array with only one value', 1, function() {
if (!isNpm) {
var actual = _([40])[methodName]();
strictEqual(actual, 40);
}
else {
skipTest();
}
});
});
_.each(['maxBy', 'minBy'], function(methodName) {
var array = [1, 2, 3],
func = _[methodName],
isMax = methodName == 'maxBy';
test('`_.' + methodName + '` should work with an `iteratee` argument', 1, function() {
var actual = func(array, function(num) {
return -num;
});
strictEqual(actual, isMax ? 1 : 3);
});
test('should work with a "_.property" style `iteratee`', 2, function() {
var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }],
actual = func(objects, 'a');
deepEqual(actual, objects[isMax ? 1 : 2]);
var arrays = [[2], [3], [1]];
actual = func(arrays, 0);
deepEqual(actual, arrays[isMax ? 1 : 2]);
});
test('`_.' + methodName + '` should work when `iteratee` returns +/-Infinity', 1, function() {
var value = isMax ? -Infinity : Infinity,
object = { 'a': value };
var actual = func([object, { 'a': value }], function(object) {
return object.a;
});
strictEqual(actual, object);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.mixin');
(function() {
function Wrapper(value) {
if (!(this instanceof Wrapper)) {
return new Wrapper(value);
}
if (_.has(value, '__wrapped__')) {
var actions = _.slice(value.__actions__),
chain = value.__chain__;
value = value.__wrapped__;
}
this.__actions__ = actions || [];
this.__chain__ = chain || false;
this.__wrapped__ = value;
}
Wrapper.prototype.value = function() {
return getUnwrappedValue(this);
};
var array = ['a'],
source = { 'a': function(array) { return array[0]; }, 'b': 'B' };
test('should mixin `source` methods into lodash', 4, function() {
if (!isNpm) {
_.mixin(source);
strictEqual(_.a(array), 'a');
strictEqual(_(array).a().value(), 'a');
delete _.a;
delete _.prototype.a;
ok(!('b' in _));
ok(!('b' in _.prototype));
delete _.b;
delete _.prototype.b;
}
else {
skipTest(4);
}
});
test('should mixin chaining methods by reference', 2, function() {
if (!isNpm) {
_.mixin(source);
_.a = _.constant('b');
strictEqual(_.a(array), 'b');
strictEqual(_(array).a().value(), 'a');
delete _.a;
delete _.prototype.a;
}
else {
skipTest(2);
}
});
test('should use `this` as the default `object` value', 3, function() {
var object = _.create(_);
object.mixin(source);
strictEqual(object.a(array), 'a');
ok(!('a' in _));
ok(!('a' in _.prototype));
delete Wrapper.a;
delete Wrapper.prototype.a;
delete Wrapper.b;
delete Wrapper.prototype.b;
});
test('should accept an `object` argument', 1, function() {
var object = {};
_.mixin(object, source);
strictEqual(object.a(array), 'a');
});
test('should return `object`', 2, function() {
var object = {};
strictEqual(_.mixin(object, source), object);
strictEqual(_.mixin(), _);
});
test('should work with a function for `object`', 2, function() {
_.mixin(Wrapper, source);
var wrapped = Wrapper(array),
actual = wrapped.a();
strictEqual(actual.value(), 'a');
ok(actual instanceof Wrapper);
delete Wrapper.a;
delete Wrapper.prototype.a;
delete Wrapper.b;
delete Wrapper.prototype.b;
});
test('should not assign inherited `source` methods', 1, function() {
function Foo() {}
Foo.prototype.a = _.noop;
var object = {};
strictEqual(_.mixin(object, new Foo), object);
});
test('should accept an `options` argument', 8, function() {
function message(func, chain) {
return (func === _ ? 'lodash' : 'provided') + ' function should ' + (chain ? '' : 'not ') + 'chain';
}
_.each([_, Wrapper], function(func) {
_.each([{ 'chain': false }, { 'chain': true }], function(options) {
if (!isNpm) {
if (func === _) {
_.mixin(source, options);
} else {
_.mixin(func, source, options);
}
var wrapped = func(array),
actual = wrapped.a();
if (options.chain) {
strictEqual(actual.value(), 'a', message(func, true));
ok(actual instanceof func, message(func, true));
} else {
strictEqual(actual, 'a', message(func, false));
ok(!(actual instanceof func), message(func, false));
}
delete func.a;
delete func.prototype.a;
delete func.b;
delete func.prototype.b;
}
else {
skipTest(2);
}
});
});
});
test('should not extend lodash when an `object` is provided with an empty `options` object', 1, function() {
_.mixin({ 'a': _.noop }, {});
ok(!('a' in _));
delete _.a;
});
test('should not error for non-object `options` values', 2, function() {
var pass = true;
try {
_.mixin({}, source, 1);
} catch(e) {
pass = false;
}
ok(pass);
pass = true;
try {
_.mixin(source, 1);
} catch(e) {
pass = false;
}
delete _.a;
delete _.prototype.a;
delete _.b;
delete _.prototype.b;
ok(pass);
});
test('should not return the existing wrapped value when chaining', 2, function() {
_.each([_, Wrapper], function(func) {
if (!isNpm) {
if (func === _) {
var wrapped = _(source),
actual = wrapped.mixin();
strictEqual(actual.value(), _);
}
else {
wrapped = _(func);
actual = wrapped.mixin(source);
notStrictEqual(actual, wrapped);
}
delete func.a;
delete func.prototype.a;
delete func.b;
delete func.prototype.b;
}
else {
skipTest();
}
});
});
test('should produce methods that work in a lazy chain sequence', 1, function() {
if (!isNpm) {
_.mixin({ 'a': _.countBy, 'b': _.filter });
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
predicate = function(value) { return value > 2; },
actual = _(array).a().map(square).b(predicate).take().value();
deepEqual(actual, _.take(_.b(_.map(_.a(array), square), predicate)));
delete _.a;
delete _.prototype.a;
delete _.b;
delete _.prototype.b;
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.modArgs');
(function() {
function fn() {
return slice.call(arguments);
}
test('should transform each argument', 1, function() {
var modded = _.modArgs(fn, doubled, square);
deepEqual(modded(5, 10), [10, 100]);
});
test('should flatten `transforms`', 1, function() {
var modded = _.modArgs(fn, [doubled, square], String);
deepEqual(modded(5, 10, 15), [10, 100, '15']);
});
test('should not transform any argument greater than the number of transforms', 1, function() {
var modded = _.modArgs(fn, doubled, square);
deepEqual(modded(5, 10, 18), [10, 100, 18]);
});
test('should not transform any arguments if no transforms are provided', 1, function() {
var modded = _.modArgs(fn);
deepEqual(modded(5, 10, 18), [5, 10, 18]);
});
test('should not pass `undefined` if there are more `transforms` than `arguments`', 1, function() {
var modded = _.modArgs(fn, doubled, _.identity);
deepEqual(modded(5), [10]);
});
test('should not set a `this` binding', 1, function() {
var modded = _.modArgs(function(x) {
return this[x];
}, function(x) {
return this === x;
});
var object = { 'modded': modded, 'false': 1 };
strictEqual(object.modded(object), 1);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.negate');
(function() {
test('should create a function that negates the result of `func`', 2, function() {
var negate = _.negate(function(n) {
return n % 2 == 0;
});
strictEqual(negate(1), true);
strictEqual(negate(2), false);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.noop');
(function() {
test('should return `undefined`', 1, function() {
var values = empties.concat(true, new Date, _, 1, /x/, 'a'),
expected = _.map(values, _.constant());
var actual = _.map(values, function(value, index) {
return index ? _.noop(value) : _.noop();
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.noConflict');
(function() {
test('should return the `lodash` function', 2, function() {
if (!isModularize) {
strictEqual(_.noConflict(), oldDash);
if (!(isRhino && typeof require == 'function')) {
notStrictEqual(root._, oldDash);
}
else {
skipTest();
}
root._ = oldDash;
}
else {
skipTest(2);
}
});
test('should work with a `root` of `this`', 2, function() {
if (!isModularize && !document && _._object) {
var fs = require('fs'),
vm = require('vm'),
expected = {},
context = vm.createContext({ '_': expected, 'console': console }),
source = fs.readFileSync(filePath);
vm.runInContext(source + '\nthis.lodash = this._.noConflict()', context);
strictEqual(context._, expected);
ok(!!context.lodash);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.now');
(function() {
asyncTest('should return the number of milliseconds that have elapsed since the Unix epoch', 2, function() {
var stamp = +new Date,
actual = _.now();
ok(actual >= stamp);
if (!(isRhino && isModularize)) {
setTimeout(function() {
ok(_.now() > actual);
QUnit.start();
}, 32);
}
else {
skipTest();
QUnit.start();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.omit');
(function() {
var args = arguments,
object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };
test('should flatten `props`', 2, function() {
deepEqual(_.omit(object, 'a', 'c'), { 'b': 2, 'd': 4 });
deepEqual(_.omit(object, ['a', 'd'], 'c'), { 'b': 2 });
});
test('should work with a primitive `object` argument', 1, function() {
stringProto.a = 1;
stringProto.b = 2;
deepEqual(_.omit('', 'b'), { 'a': 1 });
delete stringProto.a;
delete stringProto.b;
});
test('should return an empty object when `object` is nullish', 2, function() {
objectProto.a = 1;
_.each([null, undefined], function(value) {
deepEqual(_.omit(value, 'valueOf'), {});
});
delete objectProto.a;
});
test('should work with `arguments` objects as secondary arguments', 1, function() {
deepEqual(_.omit(object, args), { 'b': 2, 'd': 4 });
});
test('should coerce property names to strings', 1, function() {
deepEqual(_.omit({ '0': 'a' }, 0), {});
});
}('a', 'c'));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.omitBy');
(function() {
test('should work with a predicate argument', 1, function() {
var object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };
var actual = _.omitBy(object, function(num) {
return num != 2 && num != 4;
});
deepEqual(actual, { 'b': 2, 'd': 4 });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('omit methods');
_.each(['omit', 'omitBy'], function(methodName) {
var expected = { 'b': 2, 'd': 4 },
func = _[methodName],
object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };
var prop = methodName == 'omit' ? _.identity : function(props) {
props = typeof props == 'string' ? [props] : props;
return function(value, key) {
return _.includes(props, key);
};
};
test('`_.' + methodName + '` should create an object with omitted properties', 2, function() {
deepEqual(func(object, prop('a')), { 'b': 2, 'c': 3, 'd': 4 });
deepEqual(func(object, prop(['a', 'c'])), expected);
});
test('`_.' + methodName + '` should iterate over inherited properties', 1, function() {
function Foo() {}
Foo.prototype = object;
deepEqual(func(new Foo, prop(['a', 'c'])), expected);
});
test('`_.' + methodName + '` should work with an array `object` argument', 1, function() {
deepEqual(func([1, 2, 3], prop(['0', '2'])), { '1': 2 });
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.once');
(function() {
test('should invoke `func` once', 2, function() {
var count = 0,
once = _.once(function() { return ++count; });
once();
strictEqual(once(), 1);
strictEqual(count, 1);
});
test('should not set a `this` binding', 2, function() {
var once = _.once(function() { return ++this.count; }),
object = { 'count': 0, 'once': once };
object.once();
strictEqual(object.once(), 1);
strictEqual(object.count, 1);
});
test('should ignore recursive calls', 2, function() {
var count = 0;
var once = _.once(function() {
once();
return ++count;
});
strictEqual(once(), 1);
strictEqual(count, 1);
});
test('should not throw more than once', 2, function() {
var pass = true;
var once = _.once(function() {
throw new Error;
});
raises(function() { once(); }, Error);
try {
once();
} catch(e) {
pass = false;
}
ok(pass);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.pad');
(function() {
test('should pad a string to a given length', 1, function() {
strictEqual(_.pad('abc', 9), ' abc ');
});
test('should truncate pad characters to fit the pad length', 2, function() {
strictEqual(_.pad('abc', 8), ' abc ');
strictEqual(_.pad('abc', 8, '_-'), '_-abc_-_');
});
test('should coerce `string` to a string', 2, function() {
strictEqual(_.pad(Object('abc'), 4), 'abc ');
strictEqual(_.pad({ 'toString': _.constant('abc') }, 5), ' abc ');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.padLeft');
(function() {
test('should pad a string to a given length', 1, function() {
strictEqual(_.padLeft('abc', 6), ' abc');
});
test('should truncate pad characters to fit the pad length', 1, function() {
strictEqual(_.padLeft('abc', 6, '_-'), '_-_abc');
});
test('should coerce `string` to a string', 2, function() {
strictEqual(_.padLeft(Object('abc'), 4), ' abc');
strictEqual(_.padLeft({ 'toString': _.constant('abc') }, 5), ' abc');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.padRight');
(function() {
test('should pad a string to a given length', 1, function() {
strictEqual(_.padRight('abc', 6), 'abc ');
});
test('should truncate pad characters to fit the pad length', 1, function() {
strictEqual(_.padRight('abc', 6, '_-'), 'abc_-_');
});
test('should coerce `string` to a string', 2, function() {
strictEqual(_.padRight(Object('abc'), 4), 'abc ');
strictEqual(_.padRight({ 'toString': _.constant('abc') }, 5), 'abc ');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('pad methods');
_.each(['pad', 'padLeft', 'padRight'], function(methodName) {
var func = _[methodName],
isPad = methodName == 'pad',
isPadLeft = methodName == 'padLeft';
test('`_.' + methodName + '` should not pad is string is >= `length`', 2, function() {
strictEqual(func('abc', 2), 'abc');
strictEqual(func('abc', 3), 'abc');
});
test('`_.' + methodName + '` should treat negative `length` as `0`', 2, function() {
_.each([0, -2], function(length) {
strictEqual(func('abc', length), 'abc');
});
});
test('`_.' + methodName + '` should coerce `length` to a number', 2, function() {
_.each(['', '4'], function(length) {
var actual = length ? (isPadLeft ? ' abc' : 'abc ') : 'abc';
strictEqual(func('abc', length), actual);
});
});
test('`_.' + methodName + '` should treat nullish values as empty strings', 6, function() {
_.each([null, '_-'], function(chars) {
var expected = chars ? (isPad ? '__' : chars) : ' ';
strictEqual(func(null, 2, chars), expected);
strictEqual(func(undefined, 2, chars), expected);
strictEqual(func('', 2, chars), expected);
});
});
test('`_.' + methodName + '` should work with nullish or empty string values for `chars`', 3, function() {
notStrictEqual(func('abc', 6, null), 'abc');
notStrictEqual(func('abc', 6, undefined), 'abc');
strictEqual(func('abc', 6, ''), 'abc');
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.pairs');
(function() {
test('should create a two dimensional array of key-value pairs', 1, function() {
var object = { 'a': 1, 'b': 2 };
deepEqual(_.pairs(object), [['a', 1], ['b', 2]]);
});
test('should work with an object that has a `length` property', 1, function() {
var object = { '0': 'a', '1': 'b', 'length': 2 };
deepEqual(_.pairs(object), [['0', 'a'], ['1', 'b'], ['length', 2]]);
});
test('should work with strings', 2, function() {
_.each(['xo', Object('xo')], function(string) {
deepEqual(_.pairs(string), [['0', 'x'], ['1', 'o']]);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.parseInt');
(function() {
test('should accept a `radix` argument', 1, function() {
var expected = _.range(2, 37);
var actual = _.map(expected, function(radix) {
return _.parseInt('10', radix);
});
deepEqual(actual, expected);
});
test('should use a radix of `10`, for non-hexadecimals, if `radix` is `undefined` or `0`', 4, function() {
strictEqual(_.parseInt('10'), 10);
strictEqual(_.parseInt('10', 0), 10);
strictEqual(_.parseInt('10', 10), 10);
strictEqual(_.parseInt('10', undefined), 10);
});
test('should use a radix of `16`, for hexadecimals, if `radix` is `undefined` or `0`', 8, function() {
_.each(['0x20', '0X20'], function(string) {
strictEqual(_.parseInt(string), 32);
strictEqual(_.parseInt(string, 0), 32);
strictEqual(_.parseInt(string, 16), 32);
strictEqual(_.parseInt(string, undefined), 32);
});
});
test('should use a radix of `10` for string with leading zeros', 2, function() {
strictEqual(_.parseInt('08'), 8);
strictEqual(_.parseInt('08', 10), 8);
});
test('should parse strings with leading whitespace (test in Chrome, Firefox, and Opera)', 2, function() {
var expected = [8, 8, 10, 10, 32, 32, 32, 32];
_.times(2, function(index) {
var actual = [],
func = (index ? (lodashBizarro || {}) : _).parseInt;
if (func) {
_.times(2, function(otherIndex) {
var string = otherIndex ? '10' : '08';
actual.push(
func(whitespace + string, 10),
func(whitespace + string)
);
});
_.each(['0x20', '0X20'], function(string) {
actual.push(
func(whitespace + string),
func(whitespace + string, 16)
);
});
deepEqual(actual, expected);
}
else {
skipTest();
}
});
});
test('should coerce `radix` to a number', 2, function() {
var object = { 'valueOf': _.constant(0) };
strictEqual(_.parseInt('08', object), 8);
strictEqual(_.parseInt('0x20', object), 32);
});
test('should work as an iteratee for methods like `_.map`', 2, function() {
var strings = _.map(['6', '08', '10'], Object),
actual = _.map(strings, _.parseInt);
deepEqual(actual, [6, 8, 10]);
actual = _.map('123', _.parseInt);
deepEqual(actual, [1, 2, 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('partial methods');
_.each(['partial', 'partialRight'], function(methodName) {
var func = _[methodName],
isPartial = methodName == 'partial',
ph = func.placeholder;
test('`_.' + methodName + '` partially applies arguments', 1, function() {
var par = func(_.identity, 'a');
strictEqual(par(), 'a');
});
test('`_.' + methodName + '` creates a function that can be invoked with additional arguments', 1, function() {
var fn = function(a, b) { return [a, b]; },
par = func(fn, 'a'),
expected = ['a', 'b'];
deepEqual(par('b'), isPartial ? expected : expected.reverse());
});
test('`_.' + methodName + '` works when there are no partially applied arguments and the created function is invoked without additional arguments', 1, function() {
var fn = function() { return arguments.length; },
par = func(fn);
strictEqual(par(), 0);
});
test('`_.' + methodName + '` works when there are no partially applied arguments and the created function is invoked with additional arguments', 1, function() {
var par = func(_.identity);
strictEqual(par('a'), 'a');
});
test('`_.' + methodName + '` should support placeholders', 4, function() {
var fn = function() { return slice.call(arguments); },
par = func(fn, ph, 'b', ph);
deepEqual(par('a', 'c'), ['a', 'b', 'c']);
deepEqual(par('a'), ['a', 'b', undefined]);
deepEqual(par(), [undefined, 'b', undefined]);
if (isPartial) {
deepEqual(par('a', 'c', 'd'), ['a', 'b', 'c', 'd']);
} else {
par = func(fn, ph, 'c', ph);
deepEqual(par('a', 'b', 'd'), ['a', 'b', 'c', 'd']);
}
});
test('`_.' + methodName + '` should not set a `this` binding', 3, function() {
var fn = function() { return this.a; },
object = { 'a': 1 };
var par = func(_.bind(fn, object));
strictEqual(par(), object.a);
par = _.bind(func(fn), object);
strictEqual(par(), object.a);
object.par = func(fn);
strictEqual(object.par(), object.a);
});
test('`_.' + methodName + '` creates a function with a `length` of `0`', 1, function() {
var fn = function(a, b, c) {},
par = func(fn, 'a');
strictEqual(par.length, 0);
});
test('`_.' + methodName + '` ensure `new partialed` is an instance of `func`', 2, function() {
function Foo(value) {
return value && object;
}
var object = {},
par = func(Foo);
ok(new par instanceof Foo);
strictEqual(new par(true), object);
});
test('`_.' + methodName + '` should clone metadata for created functions', 3, function() {
function greet(greeting, name) {
return greeting + ' ' + name;
}
var par1 = func(greet, 'hi'),
par2 = func(par1, 'barney'),
par3 = func(par1, 'pebbles');
strictEqual(par1('fred'), isPartial ? 'hi fred' : 'fred hi');
strictEqual(par2(), isPartial ? 'hi barney' : 'barney hi');
strictEqual(par3(), isPartial ? 'hi pebbles' : 'pebbles hi');
});
test('`_.' + methodName + '` should work with curried functions', 2, function() {
var fn = function(a, b, c) { return a + b + c; },
curried = _.curry(func(fn, 1), 2);
strictEqual(curried(2, 3), 6);
strictEqual(curried(2)(3), 6);
});
test('should work with placeholders and curried functions', 1, function() {
var fn = function() { return slice.call(arguments); },
curried = _.curry(fn),
par = func(curried, ph, 'b', ph, 'd');
deepEqual(par('a', 'c'), ['a', 'b', 'c', 'd']);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.partialRight');
(function() {
test('should work as a deep `_.defaults`', 1, function() {
var object = { 'a': { 'b': 1 } },
source = { 'a': { 'b': 2, 'c': 3 } },
expected = { 'a': { 'b': 1, 'c': 3 } };
var defaultsDeep = _.partialRight(_.mergeWith, function deep(value, other) {
return _.isObject(value) ? _.mergeWith(value, other, deep) : value;
});
deepEqual(defaultsDeep(object, source), expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('methods using `createWrapper`');
(function() {
function fn() {
return slice.call(arguments);
}
var ph1 = _.bind.placeholder,
ph2 = _.bindKey.placeholder,
ph3 = _.partial.placeholder,
ph4 = _.partialRight.placeholder;
test('should work with combinations of partial functions', 1, function() {
var a = _.partial(fn),
b = _.partialRight(a, 3),
c = _.partial(b, 1);
deepEqual(c(2), [1, 2, 3]);
});
test('should work with combinations of bound and partial functions', 3, function() {
var fn = function() {
var result = [this.a];
push.apply(result, arguments);
return result;
};
var expected = [1, 2, 3, 4],
object = { 'a': 1, 'fn': fn };
var a = _.bindKey(object, 'fn'),
b = _.partialRight(a, 4),
c = _.partial(b, 2);
deepEqual(c(3), expected);
a = _.bind(fn, object);
b = _.partialRight(a, 4);
c = _.partial(b, 2);
deepEqual(c(3), expected);
a = _.partial(fn, 2);
b = _.bind(a, object);
c = _.partialRight(b, 4);
deepEqual(c(3), expected);
});
test('should work with combinations of functions with placeholders', 3, function() {
var expected = [1, 2, 3, 4, 5, 6],
object = { 'fn': fn };
var a = _.bindKey(object, 'fn', ph2, 2),
b = _.partialRight(a, ph4, 6),
c = _.partial(b, 1, ph3, 4);
deepEqual(c(3, 5), expected);
a = _.bind(fn, object, ph1, 2);
b = _.partialRight(a, ph4, 6);
c = _.partial(b, 1, ph3, 4);
deepEqual(c(3, 5), expected);
a = _.partial(fn, ph3, 2);
b = _.bind(a, object, 1, ph1, 4);
c = _.partialRight(b, ph4, 6);
deepEqual(c(3, 5), expected);
});
test('should work with combinations of functions with overlaping placeholders', 3, function() {
var expected = [1, 2, 3, 4],
object = { 'fn': fn };
var a = _.bindKey(object, 'fn', ph2, 2),
b = _.partialRight(a, ph4, 4),
c = _.partial(b, ph3, 3);
deepEqual(c(1), expected);
a = _.bind(fn, object, ph1, 2);
b = _.partialRight(a, ph4, 4);
c = _.partial(b, ph3, 3);
deepEqual(c(1), expected);
a = _.partial(fn, ph3, 2);
b = _.bind(a, object, ph1, 3);
c = _.partialRight(b, ph4, 4);
deepEqual(c(1), expected);
});
test('should work with recursively bound functions', 1, function() {
var fn = function() {
return this.a;
};
var a = _.bind(fn, { 'a': 1 }),
b = _.bind(a, { 'a': 2 }),
c = _.bind(b, { 'a': 3 });
strictEqual(c(), 1);
});
test('should work when hot', 12, function() {
_.times(2, function(index) {
var fn = function() {
var result = [this];
push.apply(result, arguments);
return result;
};
var object = {},
bound1 = index ? _.bind(fn, object, 1) : _.bind(fn, object),
expected = [object, 1, 2, 3];
var actual = _.last(_.times(HOT_COUNT, function() {
var bound2 = index ? _.bind(bound1, null, 2) : _.bind(bound1);
return index ? bound2(3) : bound2(1, 2, 3);
}));
deepEqual(actual, expected);
actual = _.last(_.times(HOT_COUNT, function() {
var bound1 = index ? _.bind(fn, object, 1) : _.bind(fn, object),
bound2 = index ? _.bind(bound1, null, 2) : _.bind(bound1);
return index ? bound2(3) : bound2(1, 2, 3);
}));
deepEqual(actual, expected);
});
_.each(['curry', 'curryRight'], function(methodName, index) {
var fn = function(a, b, c) { return [a, b, c]; },
curried = _[methodName](fn),
expected = index ? [3, 2, 1] : [1, 2, 3];
var actual = _.last(_.times(HOT_COUNT, function() {
return curried(1)(2)(3);
}));
deepEqual(actual, expected);
actual = _.last(_.times(HOT_COUNT, function() {
var curried = _[methodName](fn);
return curried(1)(2)(3);
}));
deepEqual(actual, expected);
});
_.each(['partial', 'partialRight'], function(methodName, index) {
var func = _[methodName],
fn = function() { return slice.call(arguments); },
par1 = func(fn, 1),
expected = index ? [3, 2, 1] : [1, 2, 3];
var actual = _.last(_.times(HOT_COUNT, function() {
var par2 = func(par1, 2);
return par2(3);
}));
deepEqual(actual, expected);
actual = _.last(_.times(HOT_COUNT, function() {
var par1 = func(fn, 1),
par2 = func(par1, 2);
return par2(3);
}));
deepEqual(actual, expected);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.partition');
(function() {
var array = [1, 0, 1];
test('should return two groups of elements', 3, function() {
deepEqual(_.partition([], _.identity), [[], []]);
deepEqual(_.partition(array, _.constant(true)), [array, []]);
deepEqual(_.partition(array, _.constant(false)), [[], array]);
});
test('should use `_.identity` when `predicate` is nullish', 1, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant([[1, 1], [0]]));
var actual = _.map(values, function(value, index) {
return index ? _.partition(array, value) : _.partition(array);
});
deepEqual(actual, expected);
});
test('should provide the correct `predicate` arguments', 1, function() {
var args;
_.partition(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [1, 0, array]);
});
test('should work with a "_.property" style `predicate`', 1, function() {
var objects = [{ 'a': 1 }, { 'a': 1 }, { 'b': 2 }],
actual = _.partition(objects, 'a');
deepEqual(actual, [objects.slice(0, 2), objects.slice(2)]);
});
test('should work with a number for `predicate`', 2, function() {
var array = [
[1, 0],
[0, 1],
[1, 0]
];
deepEqual(_.partition(array, 0), [[array[0], array[2]], [array[1]]]);
deepEqual(_.partition(array, 1), [[array[1]], [array[0], array[2]]]);
});
test('should work with an object for `collection`', 1, function() {
var actual = _.partition({ 'a': 1.1, 'b': 0.2, 'c': 1.3 }, function(num) {
return Math.floor(num);
});
deepEqual(actual, [[1.1, 1.3], [0.2]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.pick');
(function() {
var args = arguments,
object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };
test('should flatten `props`', 2, function() {
deepEqual(_.pick(object, 'a', 'c'), { 'a': 1, 'c': 3 });
deepEqual(_.pick(object, ['a', 'd'], 'c'), { 'a': 1, 'c': 3, 'd': 4 });
});
test('should work with a primitive `object` argument', 1, function() {
deepEqual(_.pick('', 'slice'), { 'slice': ''.slice });
});
test('should return an empty object when `object` is nullish', 2, function() {
_.each([null, undefined], function(value) {
deepEqual(_.pick(value, 'valueOf'), {});
});
});
test('should work with `arguments` objects as secondary arguments', 1, function() {
deepEqual(_.pick(object, args), { 'a': 1, 'c': 3 });
});
test('should coerce property names to strings', 1, function() {
deepEqual(_.pick({ '0': 'a', '1': 'b' }, 0), { '0': 'a' });
});
}('a', 'c'));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.pickBy');
(function() {
test('should work with a predicate argument', 1, function() {
var object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };
var actual = _.pickBy(object, function(num) {
return num == 1 || num == 3;
});
deepEqual(actual, { 'a': 1, 'c': 3 });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('pick methods');
_.each(['pick', 'pickBy'], function(methodName) {
var expected = { 'a': 1, 'c': 3 },
func = _[methodName],
object = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 };
var prop = methodName == 'pick' ? _.identity : function(props) {
props = typeof props == 'string' ? [props] : props;
return function(value, key) {
return _.includes(props, key);
};
};
test('`_.' + methodName + '` should create an object of picked properties', 2, function() {
deepEqual(func(object, prop('a')), { 'a': 1 });
deepEqual(func(object, prop(['a', 'c'])), expected);
});
test('`_.' + methodName + '` should iterate over inherited properties', 1, function() {
function Foo() {}
Foo.prototype = object;
deepEqual(func(new Foo, prop(['a', 'c'])), expected);
});
test('`_.' + methodName + '` should work with an array `object` argument', 1, function() {
deepEqual(func([1, 2, 3], prop('1')), { '1': 2 });
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.property');
(function() {
test('should create a function that plucks a property value of a given object', 4, function() {
var object = { 'a': 1 };
_.each(['a', ['a']], function(path) {
var prop = _.property(path);
strictEqual(prop.length, 1);
strictEqual(prop(object), 1);
});
});
test('should pluck deep property values', 2, function() {
var object = { 'a': { 'b': { 'c': 3 } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
var prop = _.property(path);
strictEqual(prop(object), 3);
});
});
test('should work with non-string `path` arguments', 2, function() {
var array = [1, 2, 3];
_.each([1, [1]], function(path) {
var prop = _.property(path);
strictEqual(prop(array), 2);
});
});
test('should coerce key to a string', 1, function() {
function fn() {}
fn.toString = _.constant('fn');
var expected = [1, 1, 2, 2, 3, 3, 4, 4],
objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }],
values = [null, undefined, fn, {}];
var actual = _.transform(objects, function(result, object, index) {
var key = values[index];
_.each([key, [key]], function(path) {
var prop = _.property(key);
result.push(prop(object));
});
});
deepEqual(actual, expected);
});
test('should pluck inherited property values', 2, function() {
function Foo() {}
Foo.prototype.a = 1;
_.each(['a', ['a']], function(path) {
var prop = _.property(path);
strictEqual(prop(new Foo), 1);
});
});
test('should pluck a key over a path', 2, function() {
var object = { 'a.b.c': 3, 'a': { 'b': { 'c': 4 } } };
_.each(['a.b.c', ['a.b.c']], function(path) {
var prop = _.property(path);
strictEqual(prop(object), 3);
});
});
test('should return `undefined` when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor', ['constructor']], function(path) {
var prop = _.property(path);
var actual = _.map(values, function(value, index) {
return index ? prop(value) : prop();
});
deepEqual(actual, expected);
});
});
test('should return `undefined` with deep paths when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']], function(path) {
var prop = _.property(path);
var actual = _.map(values, function(value, index) {
return index ? prop(value) : prop();
});
deepEqual(actual, expected);
});
});
test('should return `undefined` if parts of `path` are missing', 4, function() {
var object = {};
_.each(['a', 'a[1].b.c', ['a'], ['a', '1', 'b', 'c']], function(path) {
var prop = _.property(path);
strictEqual(prop(object), undefined);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.propertyOf');
(function() {
test('should create a function that plucks a property value of a given key', 3, function() {
var object = { 'a': 1 },
propOf = _.propertyOf(object);
strictEqual(propOf.length, 1);
_.each(['a', ['a']], function(path) {
strictEqual(propOf(path), 1);
});
});
test('should pluck deep property values', 2, function() {
var object = { 'a': { 'b': { 'c': 3 } } },
propOf = _.propertyOf(object);
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
strictEqual(propOf(path), 3);
});
});
test('should work with non-string `path` arguments', 2, function() {
var array = [1, 2, 3],
propOf = _.propertyOf(array);
_.each([1, [1]], function(path) {
strictEqual(propOf(path), 2);
});
});
test('should coerce key to a string', 1, function() {
function fn() {}
fn.toString = _.constant('fn');
var expected = [1, 1, 2, 2, 3, 3, 4, 4],
objects = [{ 'null': 1 }, { 'undefined': 2 }, { 'fn': 3 }, { '[object Object]': 4 }],
values = [null, undefined, fn, {}];
var actual = _.transform(objects, function(result, object, index) {
var key = values[index];
_.each([key, [key]], function(path) {
var propOf = _.propertyOf(object);
result.push(propOf(key));
});
});
deepEqual(actual, expected);
});
test('should pluck inherited property values', 2, function() {
function Foo() { this.a = 1; }
Foo.prototype.b = 2;
var propOf = _.propertyOf(new Foo);
_.each(['b', ['b']], function(path) {
strictEqual(propOf(path), 2);
});
});
test('should pluck a key over a path', 2, function() {
var object = { 'a.b.c': 3, 'a': { 'b': { 'c': 4 } } },
propOf = _.propertyOf(object);
_.each(['a.b.c', ['a.b.c']], function(path) {
strictEqual(propOf(path), 3);
});
});
test('should return `undefined` when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor', ['constructor']], function(path) {
var actual = _.map(values, function(value, index) {
var propOf = index ? _.propertyOf(value) : _.propertyOf();
return propOf(path);
});
deepEqual(actual, expected);
});
});
test('should return `undefined` with deep paths when `object` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(undefined));
_.each(['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']], function(path) {
var actual = _.map(values, function(value, index) {
var propOf = index ? _.propertyOf(value) : _.propertyOf();
return propOf(path);
});
deepEqual(actual, expected);
});
});
test('should return `undefined` if parts of `path` are missing', 4, function() {
var propOf = _.propertyOf({});
_.each(['a', 'a[1].b.c', ['a'], ['a', '1', 'b', 'c']], function(path) {
strictEqual(propOf(path), undefined);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.pull');
(function() {
test('should modify and return the array', 2, function() {
var array = [1, 2, 3],
actual = _.pull(array, 1, 3);
deepEqual(array, [2]);
ok(actual === array);
});
test('should preserve holes in arrays', 2, function() {
var array = [1, 2, 3, 4];
delete array[1];
delete array[3];
_.pull(array, 1);
ok(!('0' in array));
ok(!('2' in array));
});
test('should treat holes as `undefined`', 1, function() {
var array = [1, 2, 3];
delete array[1];
_.pull(array, undefined);
deepEqual(array, [1, 3]);
});
test('should match `NaN`', 1, function() {
var array = [1, NaN, 3, NaN];
_.pull(array, NaN);
deepEqual(array, [1, 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.pullAt');
(function() {
test('should modify the array and return removed elements', 2, function() {
var array = [1, 2, 3],
actual = _.pullAt(array, [0, 1]);
deepEqual(array, [3]);
deepEqual(actual, [1, 2]);
});
test('should work with unsorted indexes', 2, function() {
var array = [1, 2, 3, 4],
actual = _.pullAt(array, [1, 3, 0]);
deepEqual(array, [3]);
deepEqual(actual, [2, 4, 1]);
});
test('should work with repeated indexes', 2, function() {
var array = [1, 2, 3, 4],
actual = _.pullAt(array, [0, 2, 0, 1, 0, 2]);
deepEqual(array, [4]);
deepEqual(actual, [1, 3, 1, 2, 1, 3]);
});
test('should use `undefined` for nonexistent indexes', 2, function() {
var array = ['a', 'b', 'c'],
actual = _.pullAt(array, [2, 4, 0]);
deepEqual(array, ['b']);
deepEqual(actual, ['c', undefined, 'a']);
});
test('should flatten `indexes`', 4, function() {
var array = ['a', 'b', 'c'];
deepEqual(_.pullAt(array, 2, 0), ['c', 'a']);
deepEqual(array, ['b']);
array = ['a', 'b', 'c', 'd'];
deepEqual(_.pullAt(array, [3, 0], 2), ['d', 'a', 'c']);
deepEqual(array, ['b']);
});
test('should return an empty array when no indexes are provided', 4, function() {
var array = ['a', 'b', 'c'],
actual = _.pullAt(array);
deepEqual(array, ['a', 'b', 'c']);
deepEqual(actual, []);
actual = _.pullAt(array, [], []);
deepEqual(array, ['a', 'b', 'c']);
deepEqual(actual, []);
});
test('should work with non-index paths', 2, function() {
var values = _.reject(empties, function(value) {
return value === 0 || _.isArray(value);
}).concat(-1, 1.1);
var array = _.transform(values, function(result, value) {
result[value] = 1;
}, []);
var expected = _.map(values, _.constant(1)),
actual = _.pullAt(array, values);
deepEqual(actual, expected);
expected = _.map(values, _.constant(undefined)),
actual = _.at(array, values);
deepEqual(actual, expected);
});
test('should work with deep paths', 2, function() {
var array = [];
array.a = { 'b': { 'c': 3 } };
var actual = _.pullAt(array, 'a.b.c');
deepEqual(actual, [3]);
deepEqual(array.a, { 'b': {} });
});
test('should work with a falsey `array` argument when keys are provided', 1, function() {
var values = falsey.slice(),
expected = _.map(values, _.constant(Array(4)));
var actual = _.map(values, function(array) {
try {
return _.pullAt(array, 0, 1, 'pop', 'push');
} catch(e) {}
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.random');
(function() {
var array = Array(1000);
test('should return `0` or `1` when arguments are not provided', 1, function() {
var actual = _.map(array, function() {
return _.random();
});
deepEqual(_.uniq(actual).sort(), [0, 1]);
});
test('should support a `min` and `max` argument', 1, function() {
var min = 5,
max = 10;
ok(_.some(array, function() {
var result = _.random(min, max);
return result >= min && result <= max;
}));
});
test('should support not providing a `max` argument', 1, function() {
var min = 0,
max = 5;
ok(_.some(array, function() {
var result = _.random(max);
return result >= min && result <= max;
}));
});
test('should support large integer values', 2, function() {
var min = Math.pow(2, 31),
max = Math.pow(2, 62);
ok(_.every(array, function() {
var result = _.random(min, max);
return result >= min && result <= max;
}));
ok(_.some(array, function() {
return _.random(Number.MAX_VALUE) > 0;
}));
});
test('should coerce arguments to numbers', 1, function() {
strictEqual(_.random('1', '1'), 1);
});
test('should support floats', 2, function() {
var min = 1.5,
max = 1.6,
actual = _.random(min, max);
ok(actual % 1);
ok(actual >= min && actual <= max);
});
test('should support providing a `floating` argument', 3, function() {
var actual = _.random(true);
ok(actual % 1 && actual >= 0 && actual <= 1);
actual = _.random(2, true);
ok(actual % 1 && actual >= 0 && actual <= 2);
actual = _.random(2, 4, true);
ok(actual % 1 && actual >= 2 && actual <= 4);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [1, 2, 3],
expected = _.map(array, _.constant(true)),
randoms = _.map(array, _.random);
var actual = _.map(randoms, function(result, index) {
return result >= 0 && result <= array[index] && (result % 1) == 0;
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.range');
(function() {
test('should work with an `end` argument', 1, function() {
deepEqual(_.range(4), [0, 1, 2, 3]);
});
test('should work with `start` and `end` arguments', 1, function() {
deepEqual(_.range(1, 5), [1, 2, 3, 4]);
});
test('should work with `start`, `end`, and `step` arguments', 1, function() {
deepEqual(_.range(0, 20, 5), [0, 5, 10, 15]);
});
test('should support a `step` of `0`', 1, function() {
deepEqual(_.range(1, 4, 0), [1, 1, 1]);
});
test('should work with a `step` larger than `end`', 1, function() {
deepEqual(_.range(1, 5, 20), [1]);
});
test('should work with a negative `step` argument', 2, function() {
deepEqual(_.range(0, -4, -1), [0, -1, -2, -3]);
deepEqual(_.range(21, 10, -3), [21, 18, 15, 12]);
});
test('should treat falsey `start` arguments as `0`', 13, function() {
_.each(falsey, function(value, index) {
if (index) {
deepEqual(_.range(value), []);
deepEqual(_.range(value, 1), [0]);
} else {
deepEqual(_.range(), []);
}
});
});
test('should coerce arguments to finite numbers', 1, function() {
var actual = [_.range('0', 1), _.range('1'), _.range(0, 1, '1'), _.range(NaN), _.range(NaN, NaN)];
deepEqual(actual, [[0], [0], [0], [], []]);
});
test('should work as an iteratee for methods like `_.map`', 2, function() {
var array = [1, 2, 3],
object = { 'a': 1, 'b': 2, 'c': 3 },
expected = [[0], [0, 1], [0, 1, 2]];
_.each([array, object], function(collection) {
var actual = _.map(collection, _.range);
deepEqual(actual, expected);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.rearg');
(function() {
function fn() {
return slice.call(arguments);
}
test('should reorder arguments provided to `func`', 1, function() {
var rearged = _.rearg(fn, [2, 0, 1]);
deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']);
});
test('should work with repeated indexes', 1, function() {
var rearged = _.rearg(fn, [1, 1, 1]);
deepEqual(rearged('c', 'a', 'b'), ['a', 'a', 'a']);
});
test('should use `undefined` for nonexistent indexes', 1, function() {
var rearged = _.rearg(fn, [1, 4]);
deepEqual(rearged('b', 'a', 'c'), ['a', undefined, 'c']);
});
test('should use `undefined` for non-index values', 1, function() {
var values = _.reject(empties, function(value) {
return value === 0 || _.isArray(value);
}).concat(-1, 1.1);
var expected = _.map(values, _.constant([undefined, 'b', 'c']));
var actual = _.map(values, function(value) {
var rearged = _.rearg(fn, [value]);
return rearged('a', 'b', 'c');
});
deepEqual(actual, expected);
});
test('should not rearrange arguments when no indexes are provided', 2, function() {
var rearged = _.rearg(fn);
deepEqual(rearged('a', 'b', 'c'), ['a', 'b', 'c']);
rearged = _.rearg(fn, [], []);
deepEqual(rearged('a', 'b', 'c'), ['a', 'b', 'c']);
});
test('should accept multiple index arguments', 1, function() {
var rearged = _.rearg(fn, 2, 0, 1);
deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']);
});
test('should accept multiple arrays of indexes', 1, function() {
var rearged = _.rearg(fn, [2], [0, 1]);
deepEqual(rearged('b', 'c', 'a'), ['a', 'b', 'c']);
});
test('should work with fewer indexes than arguments', 1, function() {
var rearged = _.rearg(fn, [1, 0]);
deepEqual(rearged('b', 'a', 'c'), ['a', 'b', 'c']);
});
test('should work on functions that have been rearged', 1, function() {
var rearged1 = _.rearg(fn, 2, 1, 0),
rearged2 = _.rearg(rearged1, 1, 0, 2);
deepEqual(rearged2('b', 'c', 'a'), ['a', 'b', 'c']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.reduce');
(function() {
var array = [1, 2, 3];
test('should use the first element of a collection as the default `accumulator`', 1, function() {
strictEqual(_.reduce(array), 1);
});
test('should provide the correct `iteratee` arguments when iterating an array', 2, function() {
var args;
_.reduce(array, function() {
args || (args = slice.call(arguments));
}, 0);
deepEqual(args, [0, 1, 0, array]);
args = null;
_.reduce(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [1, 2, 1, array]);
});
test('should provide the correct `iteratee` arguments when iterating an object', 2, function() {
var args,
object = { 'a': 1, 'b': 2 },
firstKey = _.first(_.keys(object));
var expected = firstKey == 'a'
? [0, 1, 'a', object]
: [0, 2, 'b', object];
_.reduce(object, function() {
args || (args = slice.call(arguments));
}, 0);
deepEqual(args, expected);
args = null;
expected = firstKey == 'a'
? [1, 2, 'b', object]
: [2, 1, 'a', object];
_.reduce(object, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.reduceRight');
(function() {
var array = [1, 2, 3];
test('should use the last element of a collection as the default `accumulator`', 1, function() {
strictEqual(_.reduceRight(array), 3);
});
test('should provide the correct `iteratee` arguments when iterating an array', 2, function() {
var args;
_.reduceRight(array, function() {
args || (args = slice.call(arguments));
}, 0);
deepEqual(args, [0, 3, 2, array]);
args = null;
_.reduceRight(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [3, 2, 1, array]);
});
test('should provide the correct `iteratee` arguments when iterating an object', 2, function() {
var args,
object = { 'a': 1, 'b': 2 },
lastKey = _.last(_.keys(object));
var expected = lastKey == 'b'
? [0, 2, 'b', object]
: [0, 1, 'a', object];
_.reduceRight(object, function() {
args || (args = slice.call(arguments));
}, 0);
deepEqual(args, expected);
args = null;
expected = lastKey == 'b'
? [2, 1, 'a', object]
: [1, 2, 'b', object];
_.reduceRight(object, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('reduce methods');
_.each(['reduce', 'reduceRight'], function(methodName) {
var func = _[methodName],
array = [1, 2, 3],
isReduce = methodName == 'reduce';
test('`_.' + methodName + '` should reduce a collection to a single value', 1, function() {
var actual = func(['a', 'b', 'c'], function(accumulator, value) {
return accumulator + value;
}, '');
strictEqual(actual, isReduce ? 'abc' : 'cba');
});
test('`_.' + methodName + '` should support empty collections without an initial `accumulator` value', 1, function() {
var actual = [],
expected = _.map(empties, _.constant());
_.each(empties, function(value) {
try {
actual.push(func(value, _.noop));
} catch(e) {}
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should support empty collections with an initial `accumulator` value', 1, function() {
var expected = _.map(empties, _.constant('x'));
var actual = _.map(empties, function(value) {
try {
return func(value, _.noop, 'x');
} catch(e) {}
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should handle an initial `accumulator` value of `undefined`', 1, function() {
var actual = func([], _.noop, undefined);
strictEqual(actual, undefined);
});
test('`_.' + methodName + '` should return `undefined` for empty collections when no `accumulator` is provided (test in IE > 9 and modern browsers)', 2, function() {
var array = [],
object = { '0': 1, 'length': 0 };
if ('__proto__' in array) {
array.__proto__ = object;
strictEqual(_.reduce(array, _.noop), undefined);
}
else {
skipTest();
}
strictEqual(_.reduce(object, _.noop), undefined);
});
test('`_.' + methodName + '` should return an unwrapped value when implicityly chaining', 1, function() {
if (!isNpm) {
strictEqual(_(array)[methodName](add), 6);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(array).chain()[methodName](add) instanceof _);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.reject');
(function() {
var array = [1, 2, 3];
test('should return elements the `predicate` returns falsey for', 1, function() {
var actual = _.reject(array, function(num) {
return num % 2;
});
deepEqual(actual, [2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('filter methods');
_.each(['filter', 'reject'], function(methodName) {
var array = [1, 2, 3, 4],
func = _[methodName],
isFilter = methodName == 'filter',
objects = [{ 'a': 0 }, { 'a': 1 }];
test('`_.' + methodName + '` should not modify the resulting value from within `predicate`', 1, function() {
var actual = func([0], function(num, index, array) {
array[index] = 1;
return isFilter;
});
deepEqual(actual, [0]);
});
test('`_.' + methodName + '` should work with a "_.property" style `predicate`', 1, function() {
deepEqual(func(objects, 'a'), [objects[isFilter ? 1 : 0]]);
});
test('`_.' + methodName + '` should work with a "_.matches" style `predicate`', 1, function() {
deepEqual(func(objects, objects[1]), [objects[isFilter ? 1 : 0]]);
});
test('`_.' + methodName + '` should not modify wrapped values', 2, function() {
if (!isNpm) {
var wrapped = _(array);
var actual = wrapped[methodName](function(num) {
return num < 3;
});
deepEqual(actual.value(), isFilter ? [1, 2] : [3, 4]);
actual = wrapped[methodName](function(num) {
return num > 2;
});
deepEqual(actual.value(), isFilter ? [3, 4] : [1, 2]);
}
else {
skipTest(2);
}
});
test('`_.' + methodName + '` should work in a lazy chain sequence', 2, function() {
if (!isNpm) {
var array = _.range(0, LARGE_ARRAY_SIZE + 1),
predicate = function(value) { return isFilter ? (value > 6) : (value < 6); },
actual = _(array).slice(1).map(square)[methodName](predicate).value();
deepEqual(actual, _[methodName](_.map(array.slice(1), square), predicate));
var object = _.zipObject(_.times(LARGE_ARRAY_SIZE, function(index) {
return ['key' + index, index];
}));
actual = _(object).mapValues(square)[methodName](predicate).value();
deepEqual(actual, _[methodName](_.mapValues(object, square), predicate));
}
else {
skipTest(2);
}
});
test('`_.' + methodName + '` should provide the correct `predicate` arguments in a lazy chain sequence', 5, function() {
if (!isNpm) {
var args,
array = _.range(0, LARGE_ARRAY_SIZE + 1),
expected = [1, 0, _.map(array.slice(1), square)];
_(array).slice(1)[methodName](function(value, index, array) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, [1, 0, array.slice(1)]);
args = null;
_(array).slice(1).map(square)[methodName](function(value, index, array) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, expected);
args = null;
_(array).slice(1).map(square)[methodName](function(value, index) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, expected);
args = null;
_(array).slice(1).map(square)[methodName](function(value) {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, [1]);
args = null;
_(array).slice(1).map(square)[methodName](function() {
args || (args = slice.call(arguments));
}).value();
deepEqual(args, expected);
}
else {
skipTest(5);
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.remove');
(function() {
test('should modify the array and return removed elements', 2, function() {
var array = [1, 2, 3];
var actual = _.remove(array, function(num) {
return num < 3;
});
deepEqual(array, [3]);
deepEqual(actual, [1, 2]);
});
test('should provide the correct `predicate` arguments', 1, function() {
var argsList = [],
array = [1, 2, 3],
clone = array.slice();
_.remove(array, function(value, index) {
var args = slice.call(arguments);
args[2] = args[2].slice();
argsList.push(args);
return index % 2 == 0;
});
deepEqual(argsList, [[1, 0, clone], [2, 1, clone], [3, 2, clone]]);
});
test('should work with a "_.matches" style `predicate`', 1, function() {
var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }];
_.remove(objects, { 'a': 1 });
deepEqual(objects, [{ 'a': 0, 'b': 1 }]);
});
test('should work with a "_.matchesProperty" style `predicate`', 1, function() {
var objects = [{ 'a': 0, 'b': 1 }, { 'a': 1, 'b': 2 }];
_.remove(objects, ['a', 1]);
deepEqual(objects, [{ 'a': 0, 'b': 1 }]);
});
test('should work with a "_.property" style `predicate`', 1, function() {
var objects = [{ 'a': 0 }, { 'a': 1 }];
_.remove(objects, 'a');
deepEqual(objects, [{ 'a': 0 }]);
});
test('should preserve holes in arrays', 2, function() {
var array = [1, 2, 3, 4];
delete array[1];
delete array[3];
_.remove(array, function(num) { return num === 1; });
ok(!('0' in array));
ok(!('2' in array));
});
test('should treat holes as `undefined`', 1, function() {
var array = [1, 2, 3];
delete array[1];
_.remove(array, function(num) { return num == null; });
deepEqual(array, [1, 3]);
});
test('should not mutate the array until all elements to remove are determined', 1, function() {
var array = [1, 2, 3];
_.remove(array, function(num, index) { return index % 2 == 0; });
deepEqual(array, [2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.repeat');
(function() {
test('should repeat a string `n` times', 2, function() {
strictEqual(_.repeat('*', 3), '***');
strictEqual(_.repeat('abc', 2), 'abcabc');
});
test('should return an empty string for negative `n` or `n` of `0`', 2, function() {
strictEqual(_.repeat('abc', 0), '');
strictEqual(_.repeat('abc', -2), '');
});
test('should coerce `n` to a number', 3, function() {
strictEqual(_.repeat('abc'), '');
strictEqual(_.repeat('abc', '2'), 'abcabc');
strictEqual(_.repeat('*', { 'valueOf': _.constant(3) }), '***');
});
test('should coerce `string` to a string', 2, function() {
strictEqual(_.repeat(Object('abc'), 2), 'abcabc');
strictEqual(_.repeat({ 'toString': _.constant('*') }, 3), '***');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.result');
(function() {
var object = {
'a': 1,
'b': function() { return this.a; }
};
test('should invoke function values', 1, function() {
strictEqual(_.result(object, 'b'), 1);
});
test('should invoke default function values', 1, function() {
var actual = _.result(object, 'c', object.b);
strictEqual(actual, 1);
});
test('should invoke deep property methods with the correct `this` binding', 2, function() {
var value = { 'a': object };
_.each(['a.b', ['a', 'b']], function(path) {
strictEqual(_.result(value, path), 1);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.get and lodash.result');
_.each(['get', 'result'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should get property values', 2, function() {
var object = { 'a': 1 };
_.each(['a', ['a']], function(path) {
strictEqual(func(object, path), 1);
});
});
test('`_.' + methodName + '` should get deep property values', 2, function() {
var object = { 'a': { 'b': { 'c': 3 } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
strictEqual(func(object, path), 3);
});
});
test('`_.' + methodName + '` should get a key over a path', 2, function() {
var object = { 'a.b.c': 3, 'a': { 'b': { 'c': 4 } } };
_.each(['a.b.c', ['a.b.c']], function(path) {
strictEqual(func(object, path), 3);
});
});
test('`_.' + methodName + '` should not coerce array paths to strings', 1, function() {
var object = { 'a,b,c': 3, 'a': { 'b': { 'c': 4 } } };
strictEqual(func(object, ['a', 'b', 'c']), 4);
});
test('`_.' + methodName + '` should ignore empty brackets', 1, function() {
var object = { 'a': 1 };
strictEqual(func(object, 'a[]'), 1);
});
test('`_.' + methodName + '` should handle empty paths', 4, function() {
_.each([['', ''], [[], ['']]], function(pair) {
strictEqual(func({}, pair[0]), undefined);
strictEqual(func({ '': 3 }, pair[1]), 3);
});
});
test('`_.' + methodName + '` should handle complex paths', 2, function() {
var object = { 'a': { '-1.23': { '["b"]': { 'c': { "['d']": { '\ne\n': { 'f': { 'g': 8 } } } } } } } };
var paths = [
'a[-1.23]["[\\"b\\"]"].c[\'[\\\'d\\\']\'][\ne\n][f].g',
['a', '-1.23', '["b"]', 'c', "['d']", '\ne\n', 'f', 'g']
];
_.each(paths, function(path) {
strictEqual(func(object, path), 8);
});
});
test('`_.' + methodName + '` should return `undefined` when `object` is nullish', 4, function() {
_.each(['constructor', ['constructor']], function(path) {
strictEqual(func(null, path), undefined);
strictEqual(func(undefined, path), undefined);
});
});
test('`_.' + methodName + '` should return `undefined` with deep paths when `object` is nullish', 2, function() {
var values = [null, undefined],
expected = _.map(values, _.constant(undefined)),
paths = ['constructor.prototype.valueOf', ['constructor', 'prototype', 'valueOf']];
_.each(paths, function(path) {
var actual = _.map(values, function(value) {
return func(value, path);
});
deepEqual(actual, expected);
});
});
test('`_.' + methodName + '` should return `undefined` if parts of `path` are missing', 2, function() {
var object = { 'a': [, null] };
_.each(['a[1].b.c', ['a', '1', 'b', 'c']], function(path) {
strictEqual(func(object, path), undefined);
});
});
test('`_.' + methodName + '` should be able to return `null` values', 2, function() {
var object = { 'a': { 'b': null } };
_.each(['a.b', ['a', 'b']], function(path) {
strictEqual(func(object, path), null);
});
});
test('`_.' + methodName + '` should follow `path` over non-plain objects', 4, function() {
var object = { 'a': '' },
paths = ['constructor.prototype.a', ['constructor', 'prototype', 'a']];
_.each(paths, function(path) {
numberProto.a = 1;
var actual = func(0, path);
strictEqual(actual, 1);
delete numberProto.a;
});
_.each(['a.a.a', ['a', 'a', 'a']], function(path) {
stringProto.a = '_';
var actual = func(object, path);
strictEqual(actual, '_');
delete stringProto.a;
});
});
test('`_.' + methodName + '` should return the specified default value for `undefined` values', 1, function() {
var object = { 'a': {} },
values = empties.concat(true, new Date, 1, /x/, 'a');
var expected = _.transform(values, function(result, value) {
result.push(value, value, value, value);
});
var actual = _.transform(values, function(result, value) {
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
result.push(
func(object, path, value),
func(null, path, value)
);
});
});
deepEqual(actual, expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.rest');
(function() {
var array = [1, 2, 3];
test('should accept a falsey `array` argument', 1, function() {
var expected = _.map(falsey, _.constant([]));
var actual = _.map(falsey, function(array, index) {
try {
return index ? _.rest(array) : _.rest();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should exclude the first element', 1, function() {
deepEqual(_.rest(array), [2, 3]);
});
test('should return an empty when querying empty arrays', 1, function() {
deepEqual(_.rest([]), []);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
actual = _.map(array, _.rest);
deepEqual(actual, [[2, 3], [5, 6], [8, 9]]);
});
test('should work in a lazy chain sequence', 4, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
values = [];
var actual = _(array).rest().filter(function(value) {
values.push(value);
return false;
})
.value();
deepEqual(actual, []);
deepEqual(values, array.slice(1));
values = [];
actual = _(array).filter(function(value) {
values.push(value);
return value > 1;
})
.rest()
.value();
deepEqual(actual, array.slice(2));
deepEqual(values, array);
}
else {
skipTest(4);
}
});
test('should not execute subsequent iteratees on an empty array in a lazy chain sequence', 4, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
iteratee = function() { pass = false },
pass = true,
actual = _(array).slice(0, 1).rest().map(iteratee).value();
ok(pass);
deepEqual(actual, []);
pass = true;
actual = _(array).filter().slice(0, 1).rest().map(iteratee).value();
ok(pass);
deepEqual(actual, []);
}
else {
skipTest(4);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.restParam');
(function() {
function fn(a, b, c) {
return slice.call(arguments);
}
test('should apply a rest parameter to `func`', 1, function() {
var rp = _.restParam(fn);
deepEqual(rp(1, 2, 3, 4), [1, 2, [3, 4]]);
});
test('should work with `start`', 1, function() {
var rp = _.restParam(fn, 1);
deepEqual(rp(1, 2, 3, 4), [1, [2, 3, 4]]);
});
test('should treat `start` as `0` for negative or `NaN` values', 1, function() {
var values = [-1, NaN, 'x'],
expected = _.map(values, _.constant([[1, 2, 3, 4]]));
var actual = _.map(values, function(value) {
var rp = _.restParam(fn, value);
return rp(1, 2, 3, 4);
});
deepEqual(actual, expected);
});
test('should coerce `start` to an integer', 1, function() {
var rp = _.restParam(fn, 1.6);
deepEqual(rp(1, 2, 3), [1, [2, 3]])
});
test('should use an empty array when `start` is not reached', 1, function() {
var rp = _.restParam(fn);
deepEqual(rp(1), [1, undefined, []]);
});
test('should work on functions with more than three params', 1, function() {
var rp = _.restParam(function(a, b, c, d) {
return slice.call(arguments);
});
deepEqual(rp(1, 2, 3, 4, 5), [1, 2, 3, [4, 5]]);
});
test('should not set a `this` binding', 1, function() {
var rp = _.restParam(function(x, y) {
return this[x] + this[y[0]];
});
var object = { 'rp': rp, 'x': 4, 'y': 2 };
strictEqual(object.rp('x', 'y'), 6);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('round methods');
_.each(['ceil', 'floor', 'round'], function(methodName) {
var func = _[methodName],
isCeil = methodName == 'ceil',
isFloor = methodName == 'floor';
test('`_.' + methodName + '` should return a rounded number without a precision', 1, function() {
var actual = func(4.006);
strictEqual(actual, isCeil ? 5 : 4);
});
test('`_.' + methodName + '` should return a rounded number with a precision of `0`', 1, function() {
var actual = func(4.006, 0);
strictEqual(actual, isCeil ? 5 : 4);
});
test('`_.' + methodName + '` should coerce `precision` to an integer', 3, function() {
var actual = func(4.006, NaN);
strictEqual(actual, isCeil ? 5 : 4);
var expected = isFloor ? 4.01 : 4.02;
actual = func(4.016, 2.6);
strictEqual(actual, expected);
actual = func(4.016, '+2');
strictEqual(actual, expected);
});
test('`_.' + methodName + '` should return a rounded number with a positive precision', 1, function() {
var actual = func(4.016, 2);
strictEqual(actual, isFloor ? 4.01 : 4.02);
});
test('`_.' + methodName + '` should return a rounded number with a negative precision', 1, function() {
var actual = func(4160, -2);
strictEqual(actual, isFloor ? 4100 : 4200);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.runInContext');
(function() {
test('should not require a fully populated `context` object', 1, function() {
if (!isModularize) {
var lodash = _.runInContext({
'setTimeout': function(callback) {
callback();
}
});
var pass = false;
lodash.delay(function() { pass = true; }, 32);
ok(pass);
}
else {
skipTest();
}
});
test('should use a zeroed `_.uniqueId` counter', 3, function() {
if (!isModularize) {
_.times(2, _.uniqueId);
var oldId = Number(_.uniqueId()),
lodash = _.runInContext();
ok(_.uniqueId() > oldId);
var id = lodash.uniqueId();
strictEqual(id, '1');
ok(id < oldId);
}
else {
skipTest(3);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.sample');
(function() {
var array = [1, 2, 3];
test('should return a random element', 1, function() {
var actual = _.sample(array);
ok(_.includes(array, actual));
});
test('should return two random elements', 1, function() {
var actual = _.sample(array, 2);
ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1]));
});
test('should contain elements of the collection', 1, function() {
var actual = _.sample(array, array.length);
deepEqual(actual.sort(), array);
});
test('should treat falsey `n` values, except nullish, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value == null ? 1 : [];
});
var actual = _.map(falsey, function(n) {
return _.sample([1], n);
});
deepEqual(actual, expected);
});
test('should return an empty array when `n` < `1` or `NaN`', 3, function() {
_.each([0, -1, -Infinity], function(n) {
deepEqual(_.sample(array, n), []);
});
});
test('should return all elements when `n` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(n) {
deepEqual(_.sample(array, n).sort(), array);
});
});
test('should coerce `n` to an integer', 1, function() {
var actual = _.sample(array, 1.6);
strictEqual(actual.length, 1);
});
test('should return `undefined` when sampling an empty array', 1, function() {
strictEqual(_.sample([]), undefined);
});
test('should return an empty array for empty collections', 1, function() {
var expected = _.transform(empties, function(result) {
result.push(undefined, []);
});
var actual = [];
_.each(empties, function(value) {
try {
actual.push(_.sample(value), _.sample(value, 1));
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should sample an object', 2, function() {
var object = { 'a': 1, 'b': 2, 'c': 3 },
actual = _.sample(object);
ok(_.includes(array, actual));
actual = _.sample(object, 2);
ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1]));
});
test('should work as an iteratee for methods like `_.map`', 2, function() {
var array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
array2 = ['abc', 'def', 'ghi'];
_.each([array1, array2], function(values) {
var a = values[0],
b = values[1],
c = values[2],
actual = _.map(values, _.sample);
ok(_.includes(a, actual[0]) && _.includes(b, actual[1]) && _.includes(c, actual[2]));
});
});
test('should return a wrapped value when chaining and `n` is provided', 2, function() {
if (!isNpm) {
var wrapped = _(array).sample(2),
actual = wrapped.value();
ok(wrapped instanceof _);
ok(actual.length == 2 && actual[0] !== actual[1] && _.includes(array, actual[0]) && _.includes(array, actual[1]));
}
else {
skipTest(2);
}
});
test('should return an unwrapped value when chaining and `n` is not provided', 1, function() {
if (!isNpm) {
var actual = _(array).sample();
ok(_.includes(array, actual));
}
else {
skipTest();
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(array).chain().sample() instanceof _);
}
else {
skipTest();
}
});
test('should use a stored reference to `_.sample` when chaining', 2, function() {
if (!isNpm) {
var sample = _.sample;
_.sample = _.noop;
var wrapped = _(array);
notStrictEqual(wrapped.sample(), undefined);
notStrictEqual(wrapped.sample(2).value(), undefined);
_.sample = sample;
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.setWith');
(function() {
test('should work with a `customizer` callback', 1, function() {
var actual = _.setWith({ '0': { 'length': 2 } }, '[0][1][2]', 3, function(value) {
if (!_.isObject(value)) {
return {};
}
});
deepEqual(actual, { '0': { '1': { '2': 3 }, 'length': 2 } });
});
test('should work with a `customizer` that returns `undefined`', 1, function() {
var actual = _.setWith({}, 'a[0].b.c', 4, _.constant(undefined));
deepEqual(actual, { 'a': [{ 'b': { 'c': 4 } }] });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('set methods');
_.each(['set', 'setWith'], function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should set property values', 4, function() {
var object = { 'a': 1 };
_.each(['a', ['a']], function(path) {
var actual = func(object, path, 2);
strictEqual(actual, object);
strictEqual(object.a, 2);
object.a = 1;
});
});
test('`_.' + methodName + '` should set deep property values', 4, function() {
var object = { 'a': { 'b': { 'c': 3 } } };
_.each(['a.b.c', ['a', 'b', 'c']], function(path) {
var actual = func(object, path, 4);
strictEqual(actual, object);
strictEqual(object.a.b.c, 4);
object.a.b.c = 3;
});
});
test('`_.' + methodName + '` should set a key over a path', 4, function() {
var object = { 'a.b.c': 3 };
_.each(['a.b.c', ['a.b.c']], function(path) {
var actual = func(object, path, 4);
strictEqual(actual, object);
deepEqual(object, { 'a.b.c': 4 });
object['a.b.c'] = 3;
});
});
test('`_.' + methodName + '` should not coerce array paths to strings', 1, function() {
var object = { 'a,b,c': 3, 'a': { 'b': { 'c': 3 } } };
func(object, ['a', 'b', 'c'], 4);
strictEqual(object.a.b.c, 4);
});
test('`_.' + methodName + '` should ignore empty brackets', 1, function() {
var object = {};
func(object, 'a[]', 1);
deepEqual(object, { 'a': 1 });
});
test('`_.' + methodName + '` should handle empty paths', 4, function() {
_.each([['', ''], [[], ['']]], function(pair, index) {
var object = {};
func(object, pair[0], 1);
deepEqual(object, index ? {} : { '': 1 });
func(object, pair[1], 2);
deepEqual(object, { '': 2 });
});
});
test('`_.' + methodName + '` should handle complex paths', 2, function() {
var object = { 'a': { '1.23': { '["b"]': { 'c': { "['d']": { '\ne\n': { 'f': { 'g': 8 } } } } } } } };
var paths = [
'a[-1.23]["[\\"b\\"]"].c[\'[\\\'d\\\']\'][\ne\n][f].g',
['a', '-1.23', '["b"]', 'c', "['d']", '\ne\n', 'f', 'g']
];
_.each(paths, function(path) {
func(object, path, 10);
strictEqual(object.a[-1.23]['["b"]'].c["['d']"]['\ne\n'].f.g, 10);
object.a[-1.23]['["b"]'].c["['d']"]['\ne\n'].f.g = 8;
});
});
test('`_.' + methodName + '` should create parts of `path` that are missing', 6, function() {
var object = {};
_.each(['a[1].b.c', ['a', '1', 'b', 'c']], function(path) {
var actual = func(object, path, 4);
strictEqual(actual, object);
deepEqual(actual, { 'a': [undefined, { 'b': { 'c': 4 } }] });
ok(!(0 in object.a));
delete object.a;
});
});
test('`_.' + methodName + '` should not error when `object` is nullish', 1, function() {
var values = [null, undefined],
expected = [[null, null], [undefined, undefined]];
var actual = _.map(values, function(value) {
try {
return [func(value, 'a.b', 1), func(value, ['a', 'b'], 1)];
} catch(e) {
return e.message;
}
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should follow `path` over non-plain objects', 4, function() {
var object = { 'a': '' },
paths = ['constructor.prototype.a', ['constructor', 'prototype', 'a']];
_.each(paths, function(path) {
func(0, path, 1);
strictEqual(0..a, 1);
delete numberProto.a;
});
_.each(['a.replace.b', ['a', 'replace', 'b']], function(path) {
func(object, path, 1);
strictEqual(stringProto.replace.b, 1);
delete stringProto.replace.b;
});
});
test('`_.' + methodName + '` should not error on paths over primitive values in strict mode', 2, function() {
numberProto.a = 0;
_.each(['a', 'a.a.a'], function(path) {
try {
func(0, path, 1);
strictEqual(0..a, 0);
} catch(e) {
ok(false, e.message);
}
numberProto.a = 0;
});
delete numberProto.a;
});
test('`_.' + methodName + '` should not create an array for missing non-index property names that start with numbers', 1, function() {
var object = {};
func(object, ['1a', '2b', '3c'], 1);
deepEqual(object, { '1a': { '2b': { '3c': 1 } } });
});
test('`_.' + methodName + '` should not assign values that are the same as their destinations', 4, function() {
_.each(['a', ['a'], { 'a': 1 }, NaN], function(value) {
if (defineProperty) {
var object = {},
pass = true;
defineProperty(object, 'a', {
'get': _.constant(value),
'set': function() { pass = false; }
});
func(object, 'a', value);
ok(pass, value);
}
else {
skipTest();
}
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.shuffle');
(function() {
var array = [1, 2, 3],
object = { 'a': 1, 'b': 2, 'c': 3 };
test('should return a new array', 1, function() {
notStrictEqual(_.shuffle(array), array);
});
test('should contain the same elements after a collection is shuffled', 2, function() {
deepEqual(_.shuffle(array).sort(), array);
deepEqual(_.shuffle(object).sort(), array);
});
test('should shuffle small collections', 1, function() {
var actual = _.times(1000, function() {
return _.shuffle([1, 2]);
});
deepEqual(_.sortBy(_.uniqBy(actual, String), '0'), [[1, 2], [2, 1]]);
});
test('should treat number values for `collection` as empty', 1, function() {
deepEqual(_.shuffle(1), []);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.size');
(function() {
var args = arguments,
array = [1, 2, 3];
test('should return the number of own enumerable properties of an object', 1, function() {
strictEqual(_.size({ 'one': 1, 'two': 2, 'three': 3 }), 3);
});
test('should return the length of an array', 1, function() {
strictEqual(_.size(array), 3);
});
test('should accept a falsey `object` argument', 1, function() {
var expected = _.map(falsey, _.constant(0));
var actual = _.map(falsey, function(object, index) {
try {
return index ? _.size(object) : _.size();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should work with `arguments` objects', 1, function() {
strictEqual(_.size(args), 3);
});
test('should work with jQuery/MooTools DOM query collections', 1, function() {
function Foo(elements) { push.apply(this, elements); }
Foo.prototype = { 'length': 0, 'splice': arrayProto.splice };
strictEqual(_.size(new Foo(array)), 3);
});
test('should not treat objects with negative lengths as array-like', 1, function() {
strictEqual(_.size({ 'length': -1 }), 1);
});
test('should not treat objects with lengths larger than `MAX_SAFE_INTEGER` as array-like', 1, function() {
strictEqual(_.size({ 'length': MAX_SAFE_INTEGER + 1 }), 1);
});
test('should not treat objects with non-number lengths as array-like', 1, function() {
strictEqual(_.size({ 'length': '0' }), 1);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.slice');
(function() {
var array = [1, 2, 3];
test('should use a default `start` of `0` and a default `end` of `array.length`', 2, function() {
var actual = _.slice(array);
deepEqual(actual, array);
notStrictEqual(actual, array);
});
test('should work with a positive `start`', 2, function() {
deepEqual(_.slice(array, 1), [2, 3]);
deepEqual(_.slice(array, 1, 3), [2, 3]);
});
test('should work with a `start` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(start) {
deepEqual(_.slice(array, start), []);
});
});
test('should treat falsey `start` values as `0`', 1, function() {
var expected = _.map(falsey, _.constant(array));
var actual = _.map(falsey, function(start) {
return _.slice(array, start);
});
deepEqual(actual, expected);
});
test('should work with a negative `start`', 1, function() {
deepEqual(_.slice(array, -1), [3]);
});
test('should work with a negative `start` <= negative `array.length`', 3, function() {
_.each([-3, -4, -Infinity], function(start) {
deepEqual(_.slice(array, start), array);
});
});
test('should work with `start` >= `end`', 2, function() {
_.each([2, 3], function(start) {
deepEqual(_.slice(array, start, 2), []);
});
});
test('should work with a positive `end`', 1, function() {
deepEqual(_.slice(array, 0, 1), [1]);
});
test('should work with a `end` >= `array.length`', 4, function() {
_.each([3, 4, Math.pow(2, 32), Infinity], function(end) {
deepEqual(_.slice(array, 0, end), array);
});
});
test('should treat falsey `end` values, except `undefined`, as `0`', 1, function() {
var expected = _.map(falsey, function(value) {
return value === undefined ? array : [];
});
var actual = _.map(falsey, function(end) {
return _.slice(array, 0, end);
});
deepEqual(actual, expected);
});
test('should work with a negative `end`', 1, function() {
deepEqual(_.slice(array, 0, -1), [1, 2]);
});
test('should work with a negative `end` <= negative `array.length`', 3, function() {
_.each([-3, -4, -Infinity], function(end) {
deepEqual(_.slice(array, 0, end), []);
});
});
test('should coerce `start` and `end` to integers', 1, function() {
var positions = [[0.1, 1.6], ['0', 1], [0, '1'], ['1'], [NaN, 1], [1, NaN]];
var actual = _.map(positions, function(pos) {
return _.slice.apply(_, [array].concat(pos));
});
deepEqual(actual, [[1], [1], [1], [2, 3], [1], []]);
});
test('should work as an iteratee for methods like `_.map`', 2, function() {
var array = [[1], [2, 3]],
actual = _.map(array, _.slice);
deepEqual(actual, array);
notStrictEqual(actual, array);
});
test('should work in a lazy chain sequence', 38, function() {
if (!isNpm) {
var array = _.range(1, LARGE_ARRAY_SIZE + 1),
length = array.length,
wrapped = _(array);
_.each(['map', 'filter'], function(methodName) {
deepEqual(wrapped[methodName]().slice(0, -1).value(), array.slice(0, -1));
deepEqual(wrapped[methodName]().slice(1).value(), array.slice(1));
deepEqual(wrapped[methodName]().slice(1, 3).value(), array.slice(1, 3));
deepEqual(wrapped[methodName]().slice(-1).value(), array.slice(-1));
deepEqual(wrapped[methodName]().slice(length).value(), array.slice(length));
deepEqual(wrapped[methodName]().slice(3, 2).value(), array.slice(3, 2));
deepEqual(wrapped[methodName]().slice(0, -length).value(), array.slice(0, -length));
deepEqual(wrapped[methodName]().slice(0, null).value(), array.slice(0, null));
deepEqual(wrapped[methodName]().slice(0, length).value(), array.slice(0, length));
deepEqual(wrapped[methodName]().slice(-length).value(), array.slice(-length));
deepEqual(wrapped[methodName]().slice(null).value(), array.slice(null));
deepEqual(wrapped[methodName]().slice(0, 1).value(), array.slice(0, 1));
deepEqual(wrapped[methodName]().slice(NaN, '1').value(), array.slice(NaN, '1'));
deepEqual(wrapped[methodName]().slice(0.1, 1.1).value(), array.slice(0.1, 1.1));
deepEqual(wrapped[methodName]().slice('0', 1).value(), array.slice('0', 1));
deepEqual(wrapped[methodName]().slice(0, '1').value(), array.slice(0, '1'));
deepEqual(wrapped[methodName]().slice('1').value(), array.slice('1'));
deepEqual(wrapped[methodName]().slice(NaN, 1).value(), array.slice(NaN, 1));
deepEqual(wrapped[methodName]().slice(1, NaN).value(), array.slice(1, NaN));
});
}
else {
skipTest(38);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.some');
(function() {
test('should return `false` for empty collections', 1, function() {
var expected = _.map(empties, _.constant(false));
var actual = _.map(empties, function(value) {
try {
return _.some(value, _.identity);
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should return `true` if `predicate` returns truthy for any element in the collection', 2, function() {
strictEqual(_.some([false, 1, ''], _.identity), true);
strictEqual(_.some([null, 'x', 0], _.identity), true);
});
test('should return `false` if `predicate` returns falsey for all elements in the collection', 2, function() {
strictEqual(_.some([false, false, false], _.identity), false);
strictEqual(_.some([null, 0, ''], _.identity), false);
});
test('should return `true` as soon as `predicate` returns truthy', 1, function() {
strictEqual(_.some([null, true, null], _.identity), true);
});
test('should work with a "_.property" style `predicate`', 2, function() {
var objects = [{ 'a': 0, 'b': 0 }, { 'a': 0, 'b': 1 }];
strictEqual(_.some(objects, 'a'), false);
strictEqual(_.some(objects, 'b'), true);
});
test('should work with a "_.matches" style `predicate`', 2, function() {
var objects = [{ 'a': 0, 'b': 0 }, { 'a': 1, 'b': 1}];
strictEqual(_.some(objects, { 'a': 0 }), true);
strictEqual(_.some(objects, { 'b': 2 }), false);
});
test('should use `_.identity` when `predicate` is nullish', 2, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value, index) {
var array = [0, 0];
return index ? _.some(array, value) : _.some(array);
});
deepEqual(actual, expected);
expected = _.map(values, _.constant(true));
actual = _.map(values, function(value, index) {
var array = [0, 1];
return index ? _.some(array, value) : _.some(array);
});
deepEqual(actual, expected);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var actual = _.map([[1]], _.some);
deepEqual(actual, [true]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.sortBy');
(function() {
var objects = [
{ 'a': 'x', 'b': 3 },
{ 'a': 'y', 'b': 4 },
{ 'a': 'x', 'b': 1 },
{ 'a': 'y', 'b': 2 }
];
test('should sort in ascending order', 1, function() {
var actual = _.map(_.sortBy(objects, function(object) {
return object.b;
}), 'b');
deepEqual(actual, [1, 2, 3, 4]);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.sortBy(objects, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [objects[0], 0, objects]);
});
test('should use `_.identity` when `iteratee` is nullish', 1, function() {
var array = [3, 2, 1],
values = [, null, undefined],
expected = _.map(values, _.constant([1, 2, 3]));
var actual = _.map(values, function(value, index) {
return index ? _.sortBy(array, value) : _.sortBy(array);
});
deepEqual(actual, expected);
});
test('should work with a "_.property" style `iteratee`', 1, function() {
var actual = _.map(_.sortBy(objects.concat(undefined), 'b'), 'b');
deepEqual(actual, [1, 2, 3, 4, undefined]);
});
test('should work with an object for `collection`', 1, function() {
var actual = _.sortBy({ 'a': 1, 'b': 2, 'c': 3 }, function(num) {
return Math.sin(num);
});
deepEqual(actual, [3, 1, 2]);
});
test('should move `null`, `undefined`, and `NaN` values to the end', 2, function() {
var array = [NaN, undefined, null, 4, null, 1, undefined, 3, NaN, 2];
deepEqual(_.sortBy(array), [1, 2, 3, 4, null, null, undefined, undefined, NaN, NaN]);
array = [NaN, undefined, null, 'd', null, 'a', undefined, 'c', NaN, 'b'];
deepEqual(_.sortBy(array), ['a', 'b', 'c', 'd', null, null, undefined, undefined, NaN, NaN]);
});
test('should treat number values for `collection` as empty', 1, function() {
deepEqual(_.sortBy(1), []);
});
test('should coerce arrays returned from `iteratee`', 1, function() {
var actual = _.sortBy(objects, function(object) {
var result = [object.a, object.b];
result.toString = function() { return String(this[0]); };
return result;
});
deepEqual(actual, [objects[0], objects[2], objects[1], objects[3]]);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var actual = _.map([[2, 1, 3], [3, 2, 1]], _.sortBy);
deepEqual(actual, [[1, 2, 3], [1, 2, 3]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.sortByOrder');
(function() {
var objects = [
{ 'a': 'x', 'b': 3 },
{ 'a': 'y', 'b': 4 },
{ 'a': 'x', 'b': 1 },
{ 'a': 'y', 'b': 2 }
];
test('should sort multiple properties by specified orders', 1, function() {
var actual = _.sortByOrder(objects, ['a', 'b'], ['desc', 'asc']);
deepEqual(actual, [objects[3], objects[1], objects[2], objects[0]]);
});
test('should sort a property in ascending order when its order is not specified', 1, function() {
var actual = _.sortByOrder(objects, ['a', 'b'], ['desc']);
deepEqual(actual, [objects[3], objects[1], objects[2], objects[0]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('sortBy methods');
_.each(['sortBy', 'sortByOrder'], function(methodName) {
var func = _[methodName];
function Pair(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}
var objects = [
{ 'a': 'x', 'b': 3 },
{ 'a': 'y', 'b': 4 },
{ 'a': 'x', 'b': 1 },
{ 'a': 'y', 'b': 2 }
];
var stableArray = [
new Pair(1, 1, 1), new Pair(1, 2, 1),
new Pair(1, 1, 1), new Pair(1, 2, 1),
new Pair(1, 3, 1), new Pair(1, 4, 1),
new Pair(1, 5, 1), new Pair(1, 6, 1),
new Pair(2, 1, 2), new Pair(2, 2, 2),
new Pair(2, 3, 2), new Pair(2, 4, 2),
new Pair(2, 5, 2), new Pair(2, 6, 2),
new Pair(undefined, 1, 1), new Pair(undefined, 2, 1),
new Pair(undefined, 3, 1), new Pair(undefined, 4, 1),
new Pair(undefined, 5, 1), new Pair(undefined, 6, 1)
];
var stableObject = _.zipObject('abcdefghijklmnopqrst'.split(''), stableArray);
test('`_.' + methodName + '` should sort mutliple properties in ascending order', 1, function() {
var actual = func(objects, ['a', 'b']);
deepEqual(actual, [objects[2], objects[0], objects[3], objects[1]]);
});
test('`_.' + methodName + '` should support iteratees', 1, function() {
var actual = func(objects, ['a', function(object) { return object.b; }]);
deepEqual(actual, [objects[2], objects[0], objects[3], objects[1]]);
});
test('`_.' + methodName + '` should perform a stable sort (test in IE > 8, Opera, and V8)', 2, function() {
_.each([stableArray, stableObject], function(value, index) {
var actual = func(value, ['a', 'c']);
deepEqual(actual, stableArray, index ? 'object' : 'array');
});
});
test('`_.' + methodName + '` should not error on nullish elements', 1, function() {
try {
var actual = func(objects.concat(null, undefined), ['a', 'b']);
} catch(e) {}
deepEqual(actual, [objects[2], objects[0], objects[3], objects[1], null, undefined]);
});
test('`_.' + methodName + '` should work as an iteratee for methods like `_.reduce`', 3, function() {
var objects = [
{ 'a': 'x', '0': 3 },
{ 'a': 'y', '0': 4 },
{ 'a': 'x', '0': 1 },
{ 'a': 'y', '0': 2 }
];
var funcs = [func, _.partialRight(func, 'bogus')];
_.each(['a', 0, [0]], function(props, index) {
var expected = _.map(funcs, _.constant(index
? [objects[2], objects[3], objects[0], objects[1]]
: [objects[0], objects[2], objects[1], objects[3]]
));
var actual = _.map(funcs, function(func) {
return _.reduce([props], func, objects);
});
deepEqual(actual, expected);
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('sortedIndex methods');
_.each(['sortedIndex', 'sortedLastIndex'], function(methodName) {
var func = _[methodName],
isSortedIndex = methodName == 'sortedIndex';
test('`_.' + methodName + '` should return the insert index', 1, function() {
var array = [30, 50],
values = [30, 40, 50],
expected = isSortedIndex ? [0, 1, 1] : [1, 1, 2];
var actual = _.map(values, function(value) {
return func(array, value);
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should work with an array of strings', 1, function() {
var array = ['a', 'c'],
values = ['a', 'b', 'c'],
expected = isSortedIndex ? [0, 1, 1] : [1, 1, 2];
var actual = _.map(values, function(value) {
return func(array, value);
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should accept a falsey `array` argument and a `value`', 1, function() {
var expected = _.map(falsey, _.constant([0, 0, 0]));
var actual = _.map(falsey, function(array) {
return [func(array, 1), func(array, undefined), func(array, NaN)];
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should align with `_.sortBy`', 10, function() {
var expected = [1, '2', {}, null, undefined, NaN, NaN];
_.each([
[NaN, null, 1, '2', {}, NaN, undefined],
['2', null, 1, NaN, {}, NaN, undefined]
], function(array) {
deepEqual(_.sortBy(array), expected);
strictEqual(func(expected, 3), 2);
strictEqual(func(expected, null), isSortedIndex ? 3 : 4);
strictEqual(func(expected, undefined), isSortedIndex ? 4 : 5);
strictEqual(func(expected, NaN), isSortedIndex ? 5 : 7);
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('sortedIndexBy methods');
_.each(['sortedIndexBy', 'sortedLastIndexBy'], function(methodName) {
var func = _[methodName],
isSortedIndexBy = methodName == 'sortedIndexBy';
test('`_.' + methodName + '` should provide the correct `iteratee` arguments', 1, function() {
var args;
func([30, 50], 40, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [40]);
});
test('`_.' + methodName + '` should work with a "_.property" style `iteratee`', 1, function() {
var objects = [{ 'x': 30 }, { 'x': 50 }],
actual = func(objects, { 'x': 40 }, 'x');
strictEqual(actual, 1);
});
test('`_.' + methodName + '` should support arrays larger than `MAX_ARRAY_LENGTH / 2`', 12, function() {
_.each([Math.ceil(MAX_ARRAY_LENGTH / 2), MAX_ARRAY_LENGTH], function(length) {
var array = [],
values = [MAX_ARRAY_LENGTH, NaN, undefined];
array.length = length;
_.each(values, function(value) {
var steps = 0,
actual = func(array, value, function(value) { steps++; return value; });
var expected = (isSortedIndexBy ? !_.isNaN(value) : _.isFinite(value))
? 0
: Math.min(length, MAX_ARRAY_INDEX);
// Avoid false fails in older Firefox.
if (array.length == length) {
ok(steps == 32 || steps == 33);
strictEqual(actual, expected);
}
else {
skipTest(2);
}
});
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.spread');
(function() {
test('should spread arguments to `func`', 1, function() {
var spread = _.spread(add);
strictEqual(spread([4, 2]), 6);
});
test('should throw a TypeError when receiving a non-array `array` argument', 1, function() {
raises(function() { _.spread(4, 2); }, TypeError);
});
test('should provide the correct `func` arguments', 1, function() {
var args;
var spread = _.spread(function() {
args = slice.call(arguments);
});
spread([4, 2], 'ignored');
deepEqual(args, [4, 2]);
});
test('should not set a `this` binding', 1, function() {
var spread = _.spread(function(x, y) {
return this[x] + this[y];
});
var object = { 'spread': spread, 'x': 4, 'y': 2 };
strictEqual(object.spread(['x', 'y']), 6);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.startsWith');
(function() {
var string = 'abc';
test('should return `true` if a string starts with `target`', 1, function() {
strictEqual(_.startsWith(string, 'a'), true);
});
test('should return `false` if a string does not start with `target`', 1, function() {
strictEqual(_.startsWith(string, 'b'), false);
});
test('should work with a `position` argument', 1, function() {
strictEqual(_.startsWith(string, 'b', 1), true);
});
test('should work with `position` >= `string.length`', 4, function() {
_.each([3, 5, MAX_SAFE_INTEGER, Infinity], function(position) {
strictEqual(_.startsWith(string, 'a', position), false);
});
});
test('should treat falsey `position` values as `0`', 1, function() {
var expected = _.map(falsey, _.constant(true));
var actual = _.map(falsey, function(position) {
return _.startsWith(string, 'a', position);
});
deepEqual(actual, expected);
});
test('should treat a negative `position` as `0`', 6, function() {
_.each([-1, -3, -Infinity], function(position) {
strictEqual(_.startsWith(string, 'a', position), true);
strictEqual(_.startsWith(string, 'b', position), false);
});
});
test('should coerce `position` to an integer', 1, function() {
strictEqual(_.startsWith(string, 'bc', 1.2), true);
});
test('should return `true` when `target` is an empty string regardless of `position`', 1, function() {
ok(_.every([-Infinity, NaN, -3, -1, 0, 1, 2, 3, 5, MAX_SAFE_INTEGER, Infinity], function(position) {
return _.startsWith(string, '', position, true);
}));
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.startsWith and lodash.endsWith');
_.each(['startsWith', 'endsWith'], function(methodName) {
var func = _[methodName],
isStartsWith = methodName == 'startsWith';
var string = 'abc',
chr = isStartsWith ? 'a' : 'c';
test('`_.' + methodName + '` should coerce `string` to a string', 2, function() {
strictEqual(func(Object(string), chr), true);
strictEqual(func({ 'toString': _.constant(string) }, chr), true);
});
test('`_.' + methodName + '` should coerce `target` to a string', 2, function() {
strictEqual(func(string, Object(chr)), true);
strictEqual(func(string, { 'toString': _.constant(chr) }), true);
});
test('`_.' + methodName + '` should coerce `position` to a number', 2, function() {
var position = isStartsWith ? 1 : 2;
strictEqual(func(string, 'b', Object(position)), true);
strictEqual(func(string, 'b', { 'toString': _.constant(String(position)) }), true);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.sum');
(function() {
var array = [6, 4, 2];
test('should return the sum of an array of numbers', 1, function() {
strictEqual(_.sum(array), 12);
});
test('should return `0` when passing empty `array` values', 1, function() {
var expected = _.map(empties, _.constant(0));
var actual = _.map(empties, function(value) {
return _.sum(value);
});
deepEqual(actual, expected);
});
test('should coerce values to numbers and `NaN` to `0`', 1, function() {
strictEqual(_.sum(['1', NaN, '2']), 3);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.sumBy');
(function() {
var array = [6, 4, 2],
objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }];
test('should work with an `iteratee` argument', 1, function() {
var actual = _.sumBy(objects, function(object) {
return object.a;
});
deepEqual(actual, 6);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.sumBy(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [6]);
});
test('should work with a "_.property" style `iteratee`', 2, function() {
var arrays = [[2], [3], [1]];
strictEqual(_.sumBy(arrays, 0), 6);
strictEqual(_.sumBy(objects, 'a'), 6);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.tap');
(function() {
test('should intercept and return the given value', 2, function() {
if (!isNpm) {
var intercepted,
array = [1, 2, 3];
var actual = _.tap(array, function(value) {
intercepted = value;
});
strictEqual(actual, array);
strictEqual(intercepted, array);
}
else {
skipTest(2);
}
});
test('should intercept unwrapped values and return wrapped values when chaining', 2, function() {
if (!isNpm) {
var intercepted,
array = [1, 2, 3];
var wrapped = _(array).tap(function(value) {
intercepted = value;
value.pop();
});
ok(wrapped instanceof _);
wrapped.value();
strictEqual(intercepted, array);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.template');
(function() {
test('should escape values in "escape" delimiters', 1, function() {
var strings = ['<p><%- value %></p>', '<p><%-value%></p>', '<p><%-\nvalue\n%></p>'],
expected = _.map(strings, _.constant('<p>&<>"'`\/</p>')),
data = { 'value': '&<>"\'`\/' };
var actual = _.map(strings, function(string) {
return _.template(string)(data);
});
deepEqual(actual, expected);
});
test('should evaluate JavaScript in "evaluate" delimiters', 1, function() {
var compiled = _.template(
'<ul><%\
for (var key in collection) {\
%><li><%= collection[key] %></li><%\
} %></ul>'
);
var data = { 'collection': { 'a': 'A', 'b': 'B' } },
actual = compiled(data);
strictEqual(actual, '<ul><li>A</li><li>B</li></ul>');
});
test('should interpolate data object properties', 1, function() {
var strings = ['<%= a %>BC', '<%=a%>BC', '<%=\na\n%>BC'],
expected = _.map(strings, _.constant('ABC')),
data = { 'a': 'A' };
var actual = _.map(strings, function(string) {
return _.template(string)(data);
});
deepEqual(actual, expected);
});
test('should support escaped values in "interpolation" delimiters', 1, function() {
var compiled = _.template('<%= a ? "a=\\"A\\"" : "" %>'),
data = { 'a': true };
strictEqual(compiled(data), 'a="A"');
});
test('should work with "interpolate" delimiters containing ternary operators', 1, function() {
var compiled = _.template('<%= value ? value : "b" %>'),
data = { 'value': 'a' };
strictEqual(compiled(data), 'a');
});
test('should work with "interpolate" delimiters containing global values', 1, function() {
var compiled = _.template('<%= typeof Math.abs %>');
try {
var actual = compiled();
} catch(e) {}
strictEqual(actual, 'function');
});
test('should work with complex "interpolate" delimiters', 22, function() {
_.each({
'<%= a + b %>': '3',
'<%= b - a %>': '1',
'<%= a = b %>': '2',
'<%= !a %>': 'false',
'<%= ~a %>': '-2',
'<%= a * b %>': '2',
'<%= a / b %>': '0.5',
'<%= a % b %>': '1',
'<%= a >> b %>': '0',
'<%= a << b %>': '4',
'<%= a & b %>': '0',
'<%= a ^ b %>': '3',
'<%= a | b %>': '3',
'<%= {}.toString.call(0) %>': numberTag,
'<%= a.toFixed(2) %>': '1.00',
'<%= obj["a"] %>': '1',
'<%= delete a %>': 'true',
'<%= "a" in obj %>': 'true',
'<%= obj instanceof Object %>': 'true',
'<%= new Boolean %>': 'false',
'<%= typeof a %>': 'number',
'<%= void a %>': ''
},
function(value, key) {
var compiled = _.template(key),
data = { 'a': 1, 'b': 2 };
strictEqual(compiled(data), value, key);
});
});
test('should parse ES6 template delimiters', 2, function() {
var data = { 'value': 2 };
strictEqual(_.template('1${value}3')(data), '123');
strictEqual(_.template('${"{" + value + "\\}"}')(data), '{2}');
});
test('should not reference `_.escape` when "escape" delimiters are not used', 1, function() {
var compiled = _.template('<%= typeof __e %>');
strictEqual(compiled({}), 'undefined');
});
test('should allow referencing variables declared in "evaluate" delimiters from other delimiters', 1, function() {
var compiled = _.template('<% var b = a; %><%= b.value %>'),
data = { 'a': { 'value': 1 } };
strictEqual(compiled(data), '1');
});
test('should support single line comments in "evaluate" delimiters (test production builds)', 1, function() {
var compiled = _.template('<% // A code comment. %><% if (value) { %>yap<% } else { %>nope<% } %>'),
data = { 'value': true };
strictEqual(compiled(data), 'yap');
});
test('should work with custom delimiters', 2, function() {
_.times(2, function(index) {
var settingsClone = _.clone(_.templateSettings);
var settings = _.assign(index ? _.templateSettings : {}, {
'escape': /\{\{-([\s\S]+?)\}\}/g,
'evaluate': /\{\{([\s\S]+?)\}\}/g,
'interpolate': /\{\{=([\s\S]+?)\}\}/g
});
var compiled = _.template('<ul>{{ _.each(collection, function(value, index) {}}<li>{{= index }}: {{- value }}</li>{{}); }}</ul>', index ? null : settings),
expected = '<ul><li>0: a & A</li><li>1: b & B</li></ul>',
data = { 'collection': ['a & A', 'b & B'] };
strictEqual(compiled(data), expected);
_.assign(_.templateSettings, settingsClone);
});
});
test('should work with custom delimiters containing special characters', 2, function() {
_.times(2, function(index) {
var settingsClone = _.clone(_.templateSettings);
var settings = _.assign(index ? _.templateSettings : {}, {
'escape': /<\?-([\s\S]+?)\?>/g,
'evaluate': /<\?([\s\S]+?)\?>/g,
'interpolate': /<\?=([\s\S]+?)\?>/g
});
var compiled = _.template('<ul><? _.each(collection, function(value, index) { ?><li><?= index ?>: <?- value ?></li><? }); ?></ul>', index ? null : settings),
expected = '<ul><li>0: a & A</li><li>1: b & B</li></ul>',
data = { 'collection': ['a & A', 'b & B'] };
strictEqual(compiled(data), expected);
_.assign(_.templateSettings, settingsClone);
});
});
test('should work with strings without delimiters', 1, function() {
var expected = 'abc';
strictEqual(_.template(expected)({}), expected);
});
test('should support the "imports" option', 1, function() {
var compiled = _.template('<%= a %>', { 'imports': { 'a': 1 } });
strictEqual(compiled({}), '1');
});
test('should support the "variable" options', 1, function() {
var compiled = _.template(
'<% _.each( data.a, function( value ) { %>' +
'<%= value.valueOf() %>' +
'<% }) %>', { 'variable': 'data' }
);
var data = { 'a': [1, 2, 3] };
try {
strictEqual(compiled(data), '123');
} catch(e) {
ok(false, e.message);
}
});
test('should support the legacy `options` param signature', 1, function() {
var compiled = _.template('<%= data.a %>', null, { 'variable': 'data' }),
data = { 'a': 1 };
strictEqual(compiled(data), '1');
});
test('should use a `with` statement by default', 1, function() {
var compiled = _.template('<%= index %><%= collection[index] %><% _.each(collection, function(value, index) { %><%= index %><% }); %>'),
actual = compiled({ 'index': 1, 'collection': ['a', 'b', 'c'] });
strictEqual(actual, '1b012');
});
test('should work with `this` references', 2, function() {
var compiled = _.template('a<%= this.String("b") %>c');
strictEqual(compiled(), 'abc');
var object = { 'b': 'B' };
object.compiled = _.template('A<%= this.b %>C', { 'variable': 'obj' });
strictEqual(object.compiled(), 'ABC');
});
test('should work with backslashes', 1, function() {
var compiled = _.template('<%= a %> \\b'),
data = { 'a': 'A' };
strictEqual(compiled(data), 'A \\b');
});
test('should work with escaped characters in string literals', 2, function() {
var compiled = _.template('<% print("\'\\n\\r\\t\\u2028\\u2029\\\\") %>');
strictEqual(compiled(), "'\n\r\t\u2028\u2029\\");
var data = { 'a': 'A' };
compiled = _.template('\'\n\r\t<%= a %>\u2028\u2029\\"');
strictEqual(compiled(data), '\'\n\r\tA\u2028\u2029\\"');
});
test('should handle \\u2028 & \\u2029 characters', 1, function() {
var compiled = _.template('\u2028<%= "\\u2028\\u2029" %>\u2029');
strictEqual(compiled(), '\u2028\u2028\u2029\u2029');
});
test('should work with statements containing quotes', 1, function() {
var compiled = _.template("<%\
if (a == 'A' || a == \"a\") {\
%>'a',\"A\"<%\
} %>"
);
var data = { 'a': 'A' };
strictEqual(compiled(data), "'a',\"A\"");
});
test('should work with templates containing newlines and comments', 1, function() {
var compiled = _.template('<%\n\
// A code comment.\n\
if (value) { value += 3; }\n\
%><p><%= value %></p>'
);
strictEqual(compiled({ 'value': 3 }), '<p>6</p>');
});
test('should not error with IE conditional comments enabled (test with development build)', 1, function() {
var compiled = _.template(''),
pass = true;
/*@cc_on @*/
try {
compiled();
} catch(e) {
pass = false;
}
ok(pass);
});
test('should tokenize delimiters', 1, function() {
var compiled = _.template('<span class="icon-<%= type %>2"></span>'),
data = { 'type': 1 };
strictEqual(compiled(data), '<span class="icon-12"></span>');
});
test('should evaluate delimiters once', 1, function() {
var actual = [],
compiled = _.template('<%= func("a") %><%- func("b") %><% func("c") %>'),
data = { 'func': function(value) { actual.push(value); } };
compiled(data);
deepEqual(actual, ['a', 'b', 'c']);
});
test('should match delimiters before escaping text', 1, function() {
var compiled = _.template('<<\n a \n>>', { 'evaluate': /<<(.*?)>>/g });
strictEqual(compiled(), '<<\n a \n>>');
});
test('should resolve nullish values to an empty string', 3, function() {
var compiled = _.template('<%= a %><%- a %>'),
data = { 'a': null };
strictEqual(compiled(data), '');
data = { 'a': undefined };
strictEqual(compiled(data), '');
data = { 'a': {} };
compiled = _.template('<%= a.b %><%- a.b %>');
strictEqual(compiled(data), '');
});
test('should parse delimiters without newlines', 1, function() {
var expected = '<<\nprint("<p>" + (value ? "yes" : "no") + "</p>")\n>>',
compiled = _.template(expected, { 'evaluate': /<<(.+?)>>/g }),
data = { 'value': true };
strictEqual(compiled(data), expected);
});
test('should support recursive calls', 1, function() {
var compiled = _.template('<%= a %><% a = _.template(c)(obj) %><%= a %>'),
data = { 'a': 'A', 'b': 'B', 'c': '<%= b %>' };
strictEqual(compiled(data), 'AB');
});
test('should coerce `text` argument to a string', 1, function() {
var object = { 'toString': _.constant('<%= a %>') },
data = { 'a': 1 };
strictEqual(_.template(object)(data), '1');
});
test('should not augment the `options` object', 1, function() {
var options = {};
_.template('', options);
deepEqual(options, {});
});
test('should not modify `_.templateSettings` when `options` are provided', 2, function() {
var data = { 'a': 1 };
ok(!('a' in _.templateSettings));
_.template('', {}, data);
ok(!('a' in _.templateSettings));
delete _.templateSettings.a;
});
test('should not error for non-object `data` and `options` values', 2, function() {
var pass = true;
try {
_.template('')(1);
} catch(e) {
pass = false;
}
ok(pass, '`data` value');
pass = true;
try {
_.template('', 1)(1);
} catch(e) {
pass = false;
}
ok(pass, '`options` value');
});
test('should expose the source for compiled templates', 1, function() {
var compiled = _.template('x'),
values = [String(compiled), compiled.source],
expected = _.map(values, _.constant(true));
var actual = _.map(values, function(value) {
return _.includes(value, '__p');
});
deepEqual(actual, expected);
});
test('should expose the source when a SyntaxError occurs', 1, function() {
try {
_.template('<% if x %>');
} catch(e) {
var source = e.source;
}
ok(_.includes(source, '__p'));
});
test('should not include sourceURLs in the source', 1, function() {
var options = { 'sourceURL': '/a/b/c' },
compiled = _.template('x', options),
values = [compiled.source, undefined];
try {
_.template('<% if x %>', options);
} catch(e) {
values[1] = e.source;
}
var expected = _.map(values, _.constant(false));
var actual = _.map(values, function(value) {
return _.includes(value, 'sourceURL');
});
deepEqual(actual, expected);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var array = ['<%= a %>', '<%- b %>', '<% print(c) %>'],
compiles = _.map(array, _.template),
data = { 'a': 'one', 'b': '`two`', 'c': 'three' };
var actual = _.map(compiles, function(compiled) {
return compiled(data);
});
deepEqual(actual, ['one', '`two`', 'three']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.trunc');
(function() {
var string = 'hi-diddly-ho there, neighborino';
test('should truncate to a length of `30` by default', 1, function() {
strictEqual(_.trunc(string), 'hi-diddly-ho there, neighbo...');
});
test('should not truncate if `string` is <= `length`', 2, function() {
strictEqual(_.trunc(string, { 'length': string.length }), string);
strictEqual(_.trunc(string, { 'length': string.length + 2 }), string);
});
test('should truncate string the given length', 1, function() {
strictEqual(_.trunc(string, { 'length': 24 }), 'hi-diddly-ho there, n...');
});
test('should support a `omission` option', 1, function() {
strictEqual(_.trunc(string, { 'omission': ' [...]' }), 'hi-diddly-ho there, neig [...]');
});
test('should support a `length` option', 1, function() {
strictEqual(_.trunc(string, { 'length': 4 }), 'h...');
});
test('should support a `separator` option', 2, function() {
strictEqual(_.trunc(string, { 'length': 24, 'separator': ' ' }), 'hi-diddly-ho there,...');
strictEqual(_.trunc(string, { 'length': 24, 'separator': /,? +/ }), 'hi-diddly-ho there...');
});
test('should treat negative `length` as `0`', 2, function() {
_.each([0, -2], function(length) {
strictEqual(_.trunc(string, { 'length': length }), '...');
});
});
test('should coerce `length` to an integer', 4, function() {
_.each(['', NaN, 4.6, '4'], function(length, index) {
var actual = index > 1 ? 'h...' : '...';
strictEqual(_.trunc(string, { 'length': { 'valueOf': _.constant(length) } }), actual);
});
});
test('should coerce `string` to a string', 2, function() {
strictEqual(_.trunc(Object(string), { 'length': 4 }), 'h...');
strictEqual(_.trunc({ 'toString': _.constant(string) }, { 'length': 5 }), 'hi...');
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var actual = _.map([string, string, string], _.trunc),
truncated = 'hi-diddly-ho there, neighbo...';
deepEqual(actual, [truncated, truncated, truncated]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.throttle');
(function() {
asyncTest('should throttle a function', 2, function() {
if (!(isRhino && isModularize)) {
var callCount = 0,
throttled = _.throttle(function() { callCount++; }, 32);
throttled();
throttled();
throttled();
var lastCount = callCount;
ok(callCount > 0);
setTimeout(function() {
ok(callCount > lastCount);
QUnit.start();
}, 64);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('subsequent calls should return the result of the first call', 5, function() {
if (!(isRhino && isModularize)) {
var throttled = _.throttle(_.identity, 32),
result = [throttled('a'), throttled('b')];
deepEqual(result, ['a', 'a']);
setTimeout(function() {
var result = [throttled('x'), throttled('y')];
notEqual(result[0], 'a');
notStrictEqual(result[0], undefined);
notEqual(result[1], 'y');
notStrictEqual(result[1], undefined);
QUnit.start();
}, 64);
}
else {
skipTest(5);
QUnit.start();
}
});
asyncTest('should clear timeout when `func` is called', 1, function() {
if (!isModularize) {
var callCount = 0,
dateCount = 0;
var getTime = function() {
return ++dateCount == 5 ? Infinity : +new Date;
};
var lodash = _.runInContext(_.assign({}, root, {
'Date': _.assign(function() {
return { 'getTime': getTime };
}, {
'now': Date.now
})
}));
var throttled = lodash.throttle(function() {
callCount++;
}, 32);
throttled();
throttled();
throttled();
setTimeout(function() {
strictEqual(callCount, 2);
QUnit.start();
}, 64);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('should not trigger a trailing call when invoked once', 2, function() {
if (!(isRhino && isModularize)) {
var callCount = 0,
throttled = _.throttle(function() { callCount++; }, 32);
throttled();
strictEqual(callCount, 1);
setTimeout(function() {
strictEqual(callCount, 1);
QUnit.start();
}, 64);
}
else {
skipTest(2);
QUnit.start();
}
});
_.times(2, function(index) {
asyncTest('should trigger a call when invoked repeatedly' + (index ? ' and `leading` is `false`' : ''), 1, function() {
if (!(isRhino && isModularize)) {
var callCount = 0,
limit = (argv || isPhantom) ? 1000 : 320,
options = index ? { 'leading': false } : {};
var throttled = _.throttle(function() {
callCount++;
}, 32, options);
var start = +new Date;
while ((new Date - start) < limit) {
throttled();
}
var actual = callCount > 1;
setTimeout(function() {
ok(actual);
QUnit.start();
}, 1);
}
else {
skipTest();
QUnit.start();
}
});
});
asyncTest('should apply default options', 3, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var throttled = _.throttle(function(value) {
callCount++;
return value;
}, 32, {});
strictEqual(throttled('a'), 'a');
strictEqual(throttled('b'), 'a');
setTimeout(function() {
strictEqual(callCount, 2);
QUnit.start();
}, 128);
}
else {
skipTest(3);
QUnit.start();
}
});
test('should support a `leading` option', 2, function() {
if (!(isRhino && isModularize)) {
var withLeading = _.throttle(_.identity, 32, { 'leading': true });
strictEqual(withLeading('a'), 'a');
var withoutLeading = _.throttle(_.identity, 32, { 'leading': false });
strictEqual(withoutLeading('a'), undefined);
}
else {
skipTest(2);
}
});
asyncTest('should support a `trailing` option', 6, function() {
if (!(isRhino && isModularize)) {
var withCount = 0,
withoutCount = 0;
var withTrailing = _.throttle(function(value) {
withCount++;
return value;
}, 64, { 'trailing': true });
var withoutTrailing = _.throttle(function(value) {
withoutCount++;
return value;
}, 64, { 'trailing': false });
strictEqual(withTrailing('a'), 'a');
strictEqual(withTrailing('b'), 'a');
strictEqual(withoutTrailing('a'), 'a');
strictEqual(withoutTrailing('b'), 'a');
setTimeout(function() {
strictEqual(withCount, 2);
strictEqual(withoutCount, 1);
QUnit.start();
}, 256);
}
else {
skipTest(6);
QUnit.start();
}
});
asyncTest('should not update `lastCalled`, at the end of the timeout, when `trailing` is `false`', 1, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var throttled = _.throttle(function() {
callCount++;
}, 64, { 'trailing': false });
throttled();
throttled();
setTimeout(function() {
throttled();
throttled();
}, 96);
setTimeout(function() {
ok(callCount > 1);
QUnit.start();
}, 192);
}
else {
skipTest();
QUnit.start();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.debounce and lodash.throttle');
_.each(['debounce', 'throttle'], function(methodName) {
var func = _[methodName],
isDebounce = methodName == 'debounce';
test('_.' + methodName + ' should not error for non-object `options` values', 1, function() {
var pass = true;
try {
func(_.noop, 32, 1);
} catch(e) {
pass = false;
}
ok(pass);
});
asyncTest('_.' + methodName + ' should have a default `wait` of `0`', 1, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var funced = func(function() {
callCount++;
});
funced();
setTimeout(function() {
funced();
strictEqual(callCount, isDebounce ? 1 : 2);
QUnit.start();
}, 32);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('_.' + methodName + ' should invoke `func` with the correct `this` binding', 1, function() {
if (!(isRhino && isModularize)) {
var object = {
'funced': func(function() { actual.push(this); }, 32)
};
var actual = [],
expected = _.times(isDebounce ? 1 : 2, _.constant(object));
object.funced();
if (!isDebounce) {
object.funced();
}
setTimeout(function() {
deepEqual(actual, expected);
QUnit.start();
}, 64);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('_.' + methodName + ' supports recursive calls', 2, function() {
if (!(isRhino && isModularize)) {
var actual = [],
args = _.map(['a', 'b', 'c'], function(chr) { return [{}, chr]; }),
expected = args.slice(),
queue = args.slice();
var funced = func(function() {
var current = [this];
push.apply(current, arguments);
actual.push(current);
var next = queue.shift();
if (next) {
funced.call(next[0], next[1]);
}
}, 32);
var next = queue.shift();
funced.call(next[0], next[1]);
deepEqual(actual, expected.slice(0, isDebounce ? 0 : 1));
setTimeout(function() {
deepEqual(actual, expected.slice(0, actual.length));
QUnit.start();
}, 256);
}
else {
skipTest(2);
QUnit.start();
}
});
asyncTest('_.' + methodName + ' should work if the system time is set backwards', 1, function() {
if (!isModularize) {
var callCount = 0,
dateCount = 0;
var getTime = function() {
return ++dateCount === 4 ? +new Date(2012, 3, 23, 23, 27, 18) : +new Date;
};
var lodash = _.runInContext(_.assign({}, root, {
'Date': _.assign(function() {
return { 'getTime': getTime, 'valueOf': getTime };
}, {
'now': Date.now
})
}));
var funced = lodash[methodName](function() {
callCount++;
}, 32);
funced();
setTimeout(function() {
funced();
strictEqual(callCount, isDebounce ? 1 : 2);
QUnit.start();
}, 64);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('_.' + methodName + ' should support cancelling delayed calls', 1, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var funced = func(function() {
callCount++;
}, 32, { 'leading': false });
funced();
funced.cancel();
setTimeout(function() {
strictEqual(callCount, 0);
QUnit.start();
}, 64);
}
else {
skipTest();
QUnit.start();
}
});
asyncTest('_.' + methodName + ' should reset `lastCalled` after cancelling', 3, function() {
if (!(isRhino && isModularize)) {
var callCount = 0;
var funced = func(function() {
return ++callCount;
}, 32, { 'leading': true });
strictEqual(funced(), 1);
funced.cancel();
strictEqual(funced(), 2);
setTimeout(function() {
strictEqual(callCount, 2);
QUnit.start();
}, 64);
}
else {
skipTest(3);
QUnit.start();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.times');
(function() {
test('should coerce non-finite `n` values to `0`', 3, function() {
_.each([-Infinity, NaN, Infinity], function(n) {
deepEqual(_.times(n), []);
});
});
test('should coerce `n` to an integer', 1, function() {
var actual = _.times(2.4, _.indentify);
deepEqual(actual, [0, 1]);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.times(1, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [0]);
});
test('should use `_.identity` when `iteratee` is nullish', 1, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant([0, 1, 2]));
var actual = _.map(values, function(value, index) {
return index ? _.times(3, value) : _.times(3);
});
deepEqual(actual, expected);
});
test('should return an array of the results of each `iteratee` execution', 1, function() {
deepEqual(_.times(3, function(n) { return n * 2; }), [0, 2, 4]);
});
test('should return an empty array for falsey and negative `n` arguments', 1, function() {
var values = falsey.concat(-1, -Infinity),
expected = _.map(values, _.constant([]));
var actual = _.map(values, function(value, index) {
return index ? _.times(value) : _.times();
});
deepEqual(actual, expected);
});
test('should return a wrapped value when chaining', 2, function() {
if (!isNpm) {
var wrapped = _(3).times();
ok(wrapped instanceof _);
deepEqual(wrapped.value(), [0, 1, 2]);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.toArray');
(function() {
test('should return the values of objects', 1, function() {
var array = [1, 2],
object = { 'a': 1, 'b': 2 };
deepEqual(_.toArray(object), array);
});
test('should work with a string for `collection`', 2, function() {
deepEqual(_.toArray('ab'), ['a', 'b']);
deepEqual(_.toArray(Object('ab')), ['a', 'b']);
});
test('should work in a lazy chain sequence', 2, function() {
if (!isNpm) {
var array = _.range(0, LARGE_ARRAY_SIZE + 1),
actual = _(array).slice(1).map(String).toArray().value();
deepEqual(actual, _.map(array.slice(1), String));
var object = _.zipObject(_.times(LARGE_ARRAY_SIZE, function(index) {
return ['key' + index, index];
}));
actual = _(object).toArray().slice(1).map(String).value();
deepEqual(actual, _.map(_.toArray(object).slice(1), String));
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.slice and lodash.toArray');
_.each(['slice', 'toArray'], function(methodName) {
var args = (function() { return arguments; }(1, 2, 3)),
array = [1, 2, 3],
func = _[methodName];
test('should return a dense array', 3, function() {
var sparse = Array(3);
sparse[1] = 2;
var actual = func(sparse);
ok('0' in actual);
ok('2' in actual);
deepEqual(actual, sparse);
});
test('should treat array-like objects like arrays', 2, function() {
var object = { '0': 'a', '1': 'b', '2': 'c', 'length': 3 };
deepEqual(func(object), ['a', 'b', 'c']);
deepEqual(func(args), array);
});
test('should return a shallow clone of arrays', 2, function() {
var actual = func(array);
deepEqual(actual, array);
notStrictEqual(actual, array);
});
test('should work with a node list for `collection`', 1, function() {
if (document) {
try {
var actual = func(document.getElementsByTagName('body'));
} catch(e) {}
deepEqual(actual, [body]);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.toPlainObject');
(function() {
var args = arguments;
test('should flatten inherited properties', 1, function() {
function Foo() { this.b = 2; }
Foo.prototype.c = 3;
var actual = _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 });
});
test('should convert `arguments` objects to plain objects', 1, function() {
var actual = _.toPlainObject(args),
expected = { '0': 1, '1': 2, '2': 3 };
deepEqual(actual, expected);
});
test('should convert arrays to plain objects', 1, function() {
var actual = _.toPlainObject(['a', 'b', 'c']),
expected = { '0': 'a', '1': 'b', '2': 'c' };
deepEqual(actual, expected);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.transform');
(function() {
function Foo() {
this.a = 1;
this.b = 2;
this.c = 3;
}
test('should create an object with the same `[[Prototype]]` as `object` when `accumulator` is nullish', 4, function() {
var accumulators = [, null, undefined],
expected = _.map(accumulators, _.constant(true)),
object = new Foo;
var iteratee = function(result, value, key) {
result[key] = value * value;
};
var mapper = function(accumulator, index) {
return index ? _.transform(object, iteratee, accumulator) : _.transform(object, iteratee);
};
var results = _.map(accumulators, mapper);
var actual = _.map(results, function(result) {
return result instanceof Foo;
});
deepEqual(actual, expected);
expected = _.map(accumulators, _.constant({ 'a': 1, 'b': 4, 'c': 9 }));
actual = _.map(results, _.clone);
deepEqual(actual, expected);
object = { 'a': 1, 'b': 2, 'c': 3 };
actual = _.map(accumulators, mapper);
deepEqual(actual, expected);
object = [1, 2, 3];
expected = _.map(accumulators, _.constant([1, 4, 9]));
actual = _.map(accumulators, mapper);
deepEqual(actual, expected);
});
test('should support an `accumulator` value', 4, function() {
var values = [new Foo, [1, 2, 3], { 'a': 1, 'b': 2, 'c': 3 }],
expected = _.map(values, _.constant([0, 1, 4, 9]));
var actual = _.map(values, function(value) {
return _.transform(value, function(result, value) {
result.push(value * value);
}, [0]);
});
deepEqual(actual, expected);
var object = { '_': 0, 'a': 1, 'b': 4, 'c': 9 };
expected = [object, { '_': 0, '0': 1, '1': 4, '2': 9 }, object];
actual = _.map(values, function(value) {
return _.transform(value, function(result, value, key) {
result[key] = value * value;
}, { '_': 0 });
});
deepEqual(actual, expected);
object = {};
expected = _.map(values, _.constant(object));
actual = _.map(values, function(value) {
return _.transform(value, _.noop, object);
});
deepEqual(actual, expected);
actual = _.map(values, function(value) {
return _.transform(null, null, object);
});
deepEqual(actual, expected);
});
test('should treat sparse arrays as dense', 1, function() {
var actual = _.transform(Array(1), function(result, value, index) {
result[index] = String(value);
});
deepEqual(actual, ['undefined']);
});
test('should work without an `iteratee` argument', 1, function() {
ok(_.transform(new Foo) instanceof Foo);
});
test('should check that `object` is an object before using its `[[Prototype]]`', 2, function() {
var Ctors = [Boolean, Boolean, Number, Number, Number, String, String],
values = [true, false, 0, 1, NaN, '', 'a'],
expected = _.map(values, _.constant({}));
var results = _.map(values, function(value) {
return _.transform(value);
});
deepEqual(results, expected);
expected = _.map(values, _.constant(false));
var actual = _.map(results, function(value, index) {
return value instanceof Ctors[index];
});
deepEqual(actual, expected);
});
test('should create an empty object when provided a falsey `object` argument', 1, function() {
var expected = _.map(falsey, _.constant({}));
var actual = _.map(falsey, function(object, index) {
return index ? _.transform(object) : _.transform();
});
deepEqual(actual, expected);
});
_.each({
'array': [1, 2, 3],
'object': { 'a': 1, 'b': 2, 'c': 3 }
},
function(object, key) {
test('should provide the correct `iteratee` arguments when transforming an ' + key, 2, function() {
var args;
_.transform(object, function() {
args || (args = slice.call(arguments));
});
var first = args[0];
if (key == 'array') {
ok(first !== object && _.isArray(first));
deepEqual(args, [first, 1, 0, object]);
} else {
ok(first !== object && _.isPlainObject(first));
deepEqual(args, [first, 1, 'a', object]);
}
});
});
test('should create an object from the same realm as `object`', 1, function() {
var objects = _.transform(_, function(result, value, key) {
if (_.startsWith(key, '_') && _.isObject(value) && !_.isElement(value)) {
result.push(value);
}
}, []);
var expected = _.times(objects.length, _.constant(true));
var actual = _.map(objects, function(object) {
var Ctor = object.constructor,
result = _.transform(object);
if (result === object) {
return false;
}
if (_.isTypedArray(object)) {
return result instanceof Array;
}
return result instanceof Ctor || !(new Ctor instanceof Ctor);
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('trim methods');
_.each(['trim', 'trimLeft', 'trimRight'], function(methodName, index) {
var func = _[methodName];
var parts = [];
if (index != 2) {
parts.push('leading');
}
if (index != 1) {
parts.push('trailing');
}
parts = parts.join(' and ');
test('`_.' + methodName + '` should remove ' + parts + ' whitespace', 1, function() {
var string = whitespace + 'a b c' + whitespace,
expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');
strictEqual(func(string), expected);
});
test('`_.' + methodName + '` should not remove non-whitespace characters', 1, function() {
// Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace.
var problemChars = '\x85\u200b\ufffe',
string = problemChars + 'a b c' + problemChars;
strictEqual(func(string), string);
});
test('`_.' + methodName + '` should coerce `string` to a string', 1, function() {
var object = { 'toString': _.constant(whitespace + 'a b c' + whitespace) },
expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');
strictEqual(func(object), expected);
});
test('`_.' + methodName + '` should remove ' + parts + ' `chars`', 1, function() {
var string = '-_-a-b-c-_-',
expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : '');
strictEqual(func(string, '_-'), expected);
});
test('`_.' + methodName + '` should coerce `chars` to a string', 1, function() {
var object = { 'toString': _.constant('_-') },
string = '-_-a-b-c-_-',
expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : '');
strictEqual(func(string, object), expected);
});
test('`_.' + methodName + '` should return an empty string for empty values and `chars`', 6, function() {
_.each([null, '_-'], function(chars) {
strictEqual(func(null, chars), '');
strictEqual(func(undefined, chars), '');
strictEqual(func('', chars), '');
});
});
test('`_.' + methodName + '` should work with nullish or empty string values for `chars`', 3, function() {
var string = whitespace + 'a b c' + whitespace,
expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');
strictEqual(func(string, null), expected);
strictEqual(func(string, undefined), expected);
strictEqual(func(string, ''), string);
});
test('`_.' + methodName + '` should work as an iteratee for methods like `_.map`', 1, function() {
var string = Object(whitespace + 'a b c' + whitespace),
trimmed = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : ''),
actual = _.map([string, string, string], func);
deepEqual(actual, [trimmed, trimmed, trimmed]);
});
test('`_.' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
var string = whitespace + 'a b c' + whitespace,
expected = (index == 2 ? whitespace : '') + 'a b c' + (index == 1 ? whitespace : '');
strictEqual(_(string)[methodName](), expected);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
var string = whitespace + 'a b c' + whitespace;
ok(_(string).chain()[methodName]() instanceof _);
}
else {
skipTest();
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.unescape');
(function() {
var escaped = '&<>"'\/',
unescaped = '&<>"\'\/';
escaped += escaped;
unescaped += unescaped;
test('should unescape entities in order', 1, function() {
strictEqual(_.unescape('&lt;'), '<');
});
test('should unescape the proper entities', 1, function() {
strictEqual(_.unescape(escaped), unescaped);
});
test('should not unescape the "/" entity', 1, function() {
strictEqual(_.unescape('/'), '/');
});
test('should handle strings with nothing to unescape', 1, function() {
strictEqual(_.unescape('abc'), 'abc');
});
test('should unescape the same characters escaped by `_.escape`', 1, function() {
strictEqual(_.unescape(_.escape(unescaped)), unescaped);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.union');
(function() {
var args = arguments;
test('should return the union of the given arrays', 1, function() {
var actual = _.union([1, 3, 2], [5, 2, 1, 4], [2, 1]);
deepEqual(actual, [1, 3, 2, 5, 4]);
});
test('should not flatten nested arrays', 1, function() {
var actual = _.union([1, 3, 2], [1, [5]], [2, [4]]);
deepEqual(actual, [1, 3, 2, [5], [4]]);
});
test('should ignore values that are not arrays or `arguments` objects', 3, function() {
var array = [0];
deepEqual(_.union(array, 3, null, { '0': 1 }), array);
deepEqual(_.union(null, array, null, [2, 1]), [0, 2, 1]);
deepEqual(_.union(array, null, args, null), [0, 1, 2, 3]);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.uniq');
(function() {
test('should perform an unsorted uniq when used as an iteratee for methods like `_.map`', 1, function() {
var array = [[2, 1, 2], [1, 2, 1]],
actual = _.map(array, _.uniq);
deepEqual(actual, [[2, 1], [1, 2]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.uniqBy');
(function() {
var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }, { 'a': 2 }, { 'a': 3 }, { 'a': 1 }];
test('should work with an `iteratee` argument', 2, function() {
_.each([objects, _.sortBy(objects, 'a')], function(array, index) {
var isSorted = !!index,
expected = isSorted ? [objects[2], objects[0], objects[1]] : objects.slice(0, 3);
var actual = _.uniqBy(array, isSorted, function(object) {
return object.a;
});
deepEqual(actual, expected);
});
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.uniqBy(objects, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [objects[0]]);
});
test('should work with `iteratee` without specifying `isSorted`', 1, function() {
var actual = _.uniqBy(objects, function(object) {
return object.a;
});
deepEqual(actual, objects.slice(0, 3));
});
test('should work with a "_.property" style `iteratee`', 2, function() {
var actual = _.uniqBy(objects, 'a');
deepEqual(actual, objects.slice(0, 3));
var arrays = [[2], [3], [1], [2], [3], [1]];
actual = _.uniqBy(arrays, 0);
deepEqual(actual, arrays.slice(0, 3));
});
_.each({
'an array': [0, 'a'],
'an object': { '0': 'a' },
'a number': 0,
'a string': '0'
},
function(iteratee, key) {
test('should work with ' + key + ' for `iteratee`', 1, function() {
var actual = _.uniqBy([['a'], ['b'], ['a']], iteratee);
deepEqual(actual, [['a'], ['b']]);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('uniq methods');
_.each(['uniq', 'uniqBy'], function(methodName) {
var func = _[methodName],
objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }, { 'a': 2 }, { 'a': 3 }, { 'a': 1 }];
test('`_.' + methodName + '` should return unique values of an unsorted array', 1, function() {
var array = [2, 3, 1, 2, 3, 1];
deepEqual(func(array), [2, 3, 1]);
});
test('`_.' + methodName + '` should return unique values of a sorted array', 1, function() {
var array = [1, 1, 2, 2, 3];
deepEqual(func(array), [1, 2, 3]);
});
test('`_.' + methodName + '` should treat object instances as unique', 1, function() {
deepEqual(func(objects), objects);
});
test('`_.' + methodName + '` should not treat `NaN` as unique', 1, function() {
deepEqual(func([1, NaN, 3, NaN]), [1, NaN, 3]);
});
test('`_.' + methodName + '` should work with `isSorted`', 3, function() {
var expected = [1, 2, 3];
deepEqual(func([1, 2, 3], true), expected);
deepEqual(func([1, 1, 2, 2, 3], true), expected);
deepEqual(func([1, 2, 3, 3, 3, 3, 3], true), expected);
});
test('`_.' + methodName + '` should work with large arrays', 1, function() {
var largeArray = [],
expected = [0, 'a', {}],
count = Math.ceil(LARGE_ARRAY_SIZE / expected.length);
_.times(count, function() {
push.apply(largeArray, expected);
});
deepEqual(func(largeArray), expected);
});
test('`_.' + methodName + '` should work with large arrays of boolean, `NaN`, and nullish values', 1, function() {
var largeArray = [],
expected = [true, false, NaN, null, undefined],
count = Math.ceil(LARGE_ARRAY_SIZE / expected.length);
_.times(count, function() {
push.apply(largeArray, expected);
});
deepEqual(func(largeArray), expected);
});
test('`_.' + methodName + '` should work with large arrays of symbols', 1, function() {
if (Symbol) {
var largeArray = _.times(LARGE_ARRAY_SIZE, function() {
return Symbol();
});
deepEqual(func(largeArray), largeArray);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should work with large arrays of well-known symbols', 1, function() {
// See http://www.ecma-international.org/ecma-262/6.0/#sec-well-known-symbols.
if (Symbol) {
var expected = [
Symbol.hasInstance, Symbol.isConcatSpreadable, Symbol.iterator,
Symbol.match, Symbol.replace, Symbol.search, Symbol.species,
Symbol.split, Symbol.toPrimitive, Symbol.toStringTag, Symbol.unscopables
];
var largeArray = [],
count = Math.ceil(LARGE_ARRAY_SIZE / expected.length);
expected = _.map(expected, function(symbol) {
return symbol || {};
});
_.times(count, function() {
push.apply(largeArray, expected);
});
deepEqual(func(largeArray), expected);
}
else {
skipTest();
}
});
test('`_.' + methodName + '` should distinguish between numbers and numeric strings', 1, function() {
var array = [],
expected = ['2', 2, Object('2'), Object(2)],
count = Math.ceil(LARGE_ARRAY_SIZE / expected.length);
_.times(count, function() {
push.apply(array, expected);
});
deepEqual(func(array), expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.uniqueId');
(function() {
test('should generate unique ids', 1, function() {
var actual = _.times(1000, function() {
return _.uniqueId();
});
strictEqual(_.uniq(actual).length, actual.length);
});
test('should return a string value when not providing a prefix argument', 1, function() {
strictEqual(typeof _.uniqueId(), 'string');
});
test('should coerce the prefix argument to a string', 1, function() {
var actual = [_.uniqueId(3), _.uniqueId(2), _.uniqueId(1)];
ok(/3\d+,2\d+,1\d+/.test(actual));
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.unzipWith');
(function() {
test('should unzip arrays combining regrouped elements with `iteratee`', 1, function() {
var array = [[1, 4], [2, 5], [3, 6]];
deepEqual(_.unzipWith(array, _.add), [6, 15]);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.unzipWith([[1, 3, 5], [2, 4, 6]], function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [1, 2, 1, [1, 2]]);
});
test('should perform a basic unzip when `iteratee` is nullish', 1, function() {
var array = [[1, 3], [2, 4]],
values = [, null, undefined],
expected = _.map(values, _.constant(_.unzip(array)));
var actual = _.map(values, function(value, index) {
return index ? _.unzipWith(array, value) : _.unzipWith(array);
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.values');
(function() {
test('should get the values of an object', 1, function() {
var object = { 'a': 1, 'b': 2 };
deepEqual(_.values(object), [1, 2]);
});
test('should work with an object that has a `length` property', 1, function() {
var object = { '0': 'a', '1': 'b', 'length': 2 };
deepEqual(_.values(object), ['a', 'b', 2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.without');
(function() {
test('should use strict equality to determine the values to reject', 2, function() {
var object1 = { 'a': 1 },
object2 = { 'b': 2 },
array = [object1, object2];
deepEqual(_.without(array, { 'a': 1 }), array);
deepEqual(_.without(array, object1), [object2]);
});
test('should remove all occurrences of each value from an array', 1, function() {
var array = [1, 2, 3, 1, 2, 3];
deepEqual(_.without(array, 1, 2), [3, 3]);
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.words');
(function() {
test('should treat latin-1 supplementary letters as words', 1, function() {
var expected = _.map(burredLetters, function(letter) {
return [letter];
});
var actual = _.map(burredLetters, function(letter) {
return _.words(letter);
});
deepEqual(actual, expected);
});
test('should not treat mathematical operators as words', 1, function() {
var operators = ['\xd7', '\xf7'],
expected = _.map(operators, _.constant([])),
actual = _.map(operators, _.words);
deepEqual(actual, expected);
});
test('should work as an iteratee for methods like `_.map`', 1, function() {
var strings = _.map(['a', 'b', 'c'], Object),
actual = _.map(strings, _.words);
deepEqual(actual, [['a'], ['b'], ['c']]);
});
test('should work with compound words', 6, function() {
deepEqual(_.words('aeiouAreVowels'), ['aeiou', 'Are', 'Vowels']);
deepEqual(_.words('enable 24h format'), ['enable', '24', 'h', 'format']);
deepEqual(_.words('LETTERSAeiouAreVowels'), ['LETTERS', 'Aeiou', 'Are', 'Vowels']);
deepEqual(_.words('tooLegit2Quit'), ['too', 'Legit', '2', 'Quit']);
deepEqual(_.words('walk500Miles'), ['walk', '500', 'Miles']);
deepEqual(_.words('xhr2Request'), ['xhr', '2', 'Request']);
});
test('should work with compound words containing diacritical marks', 3, function() {
deepEqual(_.words('LETTERSÆiouAreVowels'), ['LETTERS', 'Æiou', 'Are', 'Vowels']);
deepEqual(_.words('æiouAreVowels'), ['æiou', 'Are', 'Vowels']);
deepEqual(_.words('æiou2Consonants'), ['æiou', '2', 'Consonants']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.wrap');
(function() {
test('should create a wrapped function', 1, function() {
var p = _.wrap(_.escape, function(func, text) {
return '<p>' + func(text) + '</p>';
});
strictEqual(p('fred, barney, & pebbles'), '<p>fred, barney, & pebbles</p>');
});
test('should provide the correct `wrapper` arguments', 1, function() {
var args;
var wrapped = _.wrap(_.noop, function() {
args || (args = slice.call(arguments));
});
wrapped(1, 2, 3);
deepEqual(args, [_.noop, 1, 2, 3]);
});
test('should use `_.identity` when `wrapper` is nullish', 1, function() {
var values = [, null, undefined],
expected = _.map(values, _.constant('a'));
var actual = _.map(values, function(value, index) {
var wrapped = index ? _.wrap('a', value) : _.wrap('a');
return wrapped('b', 'c');
});
deepEqual(actual, expected);
});
test('should not set a `this` binding', 1, function() {
var p = _.wrap(_.escape, function(func) {
return '<p>' + func(this.text) + '</p>';
});
var object = { 'p': p, 'text': 'fred, barney, & pebbles' };
strictEqual(object.p(), '<p>fred, barney, & pebbles</p>');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.xor');
(function() {
var args = arguments;
test('should return the symmetric difference of the given arrays', 1, function() {
var actual = _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
deepEqual(actual, [1, 4, 5]);
});
test('should return an array of unique values', 2, function() {
var actual = _.xor([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]);
deepEqual(actual, [1, 4, 5]);
actual = _.xor([1, 1]);
deepEqual(actual, [1]);
});
test('should return a new array when a single array is provided', 1, function() {
var array = [1];
notStrictEqual(_.xor(array), array);
});
test('should ignore individual secondary arguments', 1, function() {
var array = [0];
deepEqual(_.xor(array, 3, null, { '0': 1 }), array);
});
test('should ignore values that are not arrays or `arguments` objects', 3, function() {
var array = [1, 2];
deepEqual(_.xor(array, 3, null, { '0': 1 }), array);
deepEqual(_.xor(null, array, null, [2, 3]), [1, 3]);
deepEqual(_.xor(array, null, args, null), [3]);
});
test('should return a wrapped value when chaining', 2, function() {
if (!isNpm) {
var wrapped = _([1, 2, 3]).xor([5, 2, 1, 4]);
ok(wrapped instanceof _);
deepEqual(wrapped.value(), [3, 5, 4]);
}
else {
skipTest(2);
}
});
test('should work when in a lazy chain sequence before `first` or `last`', 1, function() {
if (!isNpm) {
var array = _.range(0, LARGE_ARRAY_SIZE + 1),
wrapped = _(array).slice(1).xor([LARGE_ARRAY_SIZE, LARGE_ARRAY_SIZE + 1]);
var actual = _.map(['first', 'last'], function(methodName) {
return wrapped[methodName]();
});
deepEqual(actual, [1, LARGE_ARRAY_SIZE + 1]);
}
else {
skipTest();
}
});
}(1, 2, 3));
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.zipObject');
(function() {
var object = { 'barney': 36, 'fred': 40 },
array = [['barney', 36], ['fred', 40]];
test('should skip falsey elements in a given two dimensional array', 1, function() {
var actual = _.zipObject(array.concat(falsey));
deepEqual(actual, object);
});
test('should zip together key/value arrays into an object', 1, function() {
var actual = _.zipObject(['barney', 'fred'], [36, 40]);
deepEqual(actual, object);
});
test('should ignore extra `values`', 1, function() {
deepEqual(_.zipObject(['a'], [1, 2]), { 'a': 1 });
});
test('should accept a two dimensional array', 1, function() {
var actual = _.zipObject(array);
deepEqual(actual, object);
});
test('should not assume `keys` is two dimensional if `values` is not provided', 1, function() {
var actual = _.zipObject(['barney', 'fred']);
deepEqual(actual, { 'barney': undefined, 'fred': undefined });
});
test('should accept a falsey `array` argument', 1, function() {
var expected = _.map(falsey, _.constant({}));
var actual = _.map(falsey, function(array, index) {
try {
return index ? _.zipObject(array) : _.zipObject();
} catch(e) {}
});
deepEqual(actual, expected);
});
test('should support consuming the return value of `_.pairs`', 1, function() {
deepEqual(_.zipObject(_.pairs(object)), object);
});
test('should work in a lazy chain sequence', 1, function() {
if (!isNpm) {
var array = _.times(LARGE_ARRAY_SIZE, function(index) {
return ['key' + index, index];
});
var predicate = function(value) { return value > 2; },
actual = _(array).zipObject().map(square).filter(predicate).take().value();
deepEqual(actual, _.take(_.filter(_.map(_.zipObject(array), square), predicate)));
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.zipWith');
(function() {
test('should zip arrays combining grouped elements with `iteratee`', 2, function() {
var array1 = [1, 2, 3],
array2 = [4, 5, 6];
deepEqual(_.zipWith(array1, array2, _.add), [5, 7, 9]);
deepEqual(_.zipWith(array1, [], _.add), [1, 2, 3]);
});
test('should provide the correct `iteratee` arguments', 1, function() {
var args;
_.zipWith([1, 2], [3, 4], [5, 6], function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [1, 3, 1, [1, 3, 5]]);
});
test('should perform a basic zip when `iteratee` is nullish', 1, function() {
var array1 = [1, 2],
array2 = [3, 4],
values = [, null, undefined],
expected = _.map(values, _.constant(_.zip(array1, array2)));
var actual = _.map(values, function(value, index) {
return index ? _.zipWith(array1, array2, value) : _.zipWith(array1, array2);
});
deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash.unzip and lodash.zip');
_.each(['unzip', 'zip'], function(methodName, index) {
var func = _[methodName];
func = _.bind(index ? func.apply : func.call, func, null);
var object = {
'an empty array': [
[],
[]
],
'0-tuples': [
[[], []],
[]
],
'2-tuples': [
[['barney', 'fred'], [36, 40]],
[['barney', 36], ['fred', 40]]
],
'3-tuples': [
[['barney', 'fred'], [36, 40], [true, false]],
[['barney', 36, true], ['fred', 40, false]]
]
};
_.forOwn(object, function(pair, key) {
test('`_.' + methodName + '` should work with ' + key, 2, function() {
var actual = func(pair[0]);
deepEqual(actual, pair[1]);
deepEqual(func(actual), actual.length ? pair[0] : []);
});
});
test('`_.' + methodName + '` should work with tuples of different lengths', 4, function() {
var pair = [
[['barney', 36], ['fred', 40, false]],
[['barney', 'fred'], [36, 40], [undefined, false]]
];
var actual = func(pair[0]);
ok('0' in actual[2]);
deepEqual(actual, pair[1]);
actual = func(actual);
ok('2' in actual[0]);
deepEqual(actual, [['barney', 36, undefined], ['fred', 40, false]]);
});
test('`_.' + methodName + '` should treat falsey values as empty arrays', 1, function() {
var expected = _.map(falsey, _.constant([]));
var actual = _.map(falsey, function(value) {
return func([value, value, value]);
});
deepEqual(actual, expected);
});
test('`_.' + methodName + '` should ignore values that are not arrays or `arguments` objects', 1, function() {
var array = [[1, 2], [3, 4], null, undefined, { '0': 1 }];
deepEqual(func(array), [[1, 3], [2, 4]]);
});
test('`_.' + methodName + '` should support consuming its return value', 1, function() {
var expected = [['barney', 'fred'], [36, 40]];
deepEqual(func(func(func(func(expected)))), expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).commit');
(function() {
test('should execute the chained sequence and returns the wrapped result', 4, function() {
if (!isNpm) {
var array = [1],
wrapped = _(array).push(2).push(3);
deepEqual(array, [1]);
var otherWrapper = wrapped.commit();
ok(otherWrapper instanceof _);
deepEqual(otherWrapper.value(), [1, 2, 3]);
deepEqual(wrapped.value(), [1, 2, 3, 2, 3]);
}
else {
skipTest(4);
}
});
test('should track the `__chain__` value of a wrapper', 2, function() {
if (!isNpm) {
var wrapped = _([1]).chain().commit().first();
ok(wrapped instanceof _);
strictEqual(wrapped.value(), 1);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).concat');
(function() {
test('should concat arrays and values', 2, function() {
if (!isNpm) {
var array = [1],
wrapped = _(array).concat(2, [3], [[4]]);
deepEqual(wrapped.value(), [1, 2, 3, [4]]);
deepEqual(array, [1]);
}
else {
skipTest(2);
}
});
test('should treat sparse arrays as dense', 3, function() {
if (!isNpm) {
var expected = [],
wrapped = _(Array(1)).concat(Array(1)),
actual = wrapped.value();
expected.push(undefined, undefined);
ok('0'in actual);
ok('1' in actual);
deepEqual(actual, expected);
}
else {
skipTest(3);
}
});
test('should return a new wrapped array', 3, function() {
if (!isNpm) {
var array = [1],
wrapped = _(array).concat([2, 3]),
actual = wrapped.value();
deepEqual(array, [1]);
deepEqual(actual, [1, 2, 3]);
notStrictEqual(actual, array);
}
else {
skipTest(3);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).join');
(function() {
var array = [1, 2, 3];
test('should return join all array elements into a string', 2, function() {
if (!isNpm) {
var wrapped = _(array);
strictEqual(wrapped.join('.'), '1.2.3');
strictEqual(wrapped.value(), array);
}
else {
skipTest(2);
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_(array).chain().join('.') instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).plant');
(function() {
test('should clone the chained sequence planting `value` as the wrapped value', 2, function() {
if (!isNpm) {
var array1 = [5, null, 3, null, 1],
array2 = [10, null, 8, null, 6],
wrapper1 = _(array1).thru(_.compact).map(square).takeRight(2).sort(),
wrapper2 = wrapper1.plant(array2);
deepEqual(wrapper2.value(), [36, 64]);
deepEqual(wrapper1.value(), [1, 9]);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).pop');
(function() {
test('should remove elements from the end of `array`', 5, function() {
if (!isNpm) {
var array = [1, 2],
wrapped = _(array);
strictEqual(wrapped.pop(), 2);
deepEqual(wrapped.value(), [1]);
strictEqual(wrapped.pop(), 1);
var actual = wrapped.value();
deepEqual(actual, []);
strictEqual(actual, array);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).push');
(function() {
test('should append elements to `array`', 2, function() {
if (!isNpm) {
var array = [1],
wrapped = _(array).push(2, 3),
actual = wrapped.value();
strictEqual(actual, array);
deepEqual(actual, [1, 2, 3]);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).replace');
(function() {
test('should replace the matched pattern', 2, function() {
if (!isNpm) {
var wrapped = _('abcdef');
strictEqual(wrapped.replace('def', '123'), 'abc123');
strictEqual(wrapped.replace(/[bdf]/g, '-'), 'a-c-e-');
}
else {
skipTest(2);
}
});
test('should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
ok(_('abc').chain().replace('b', '_') instanceof _);
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).reverse');
(function() {
var largeArray = _.range(0, LARGE_ARRAY_SIZE).concat(null),
smallArray = [0, 1, 2, null];
test('should return the wrapped reversed `array`', 6, function() {
if (!isNpm) {
_.times(2, function(index) {
var array = (index ? largeArray : smallArray).slice(),
clone = array.slice(),
wrapped = _(array).reverse(),
actual = wrapped.value();
ok(wrapped instanceof _);
strictEqual(actual, array);
deepEqual(actual, clone.slice().reverse());
});
}
else {
skipTest(6);
}
});
test('should work in a lazy chain sequence', 4, function() {
if (!isNpm) {
_.times(2, function(index) {
var array = (index ? largeArray : smallArray).slice(),
expected = array.slice(),
actual = _(array).slice(1).reverse().value();
deepEqual(actual, expected.slice(1).reverse());
deepEqual(array, expected);
});
}
else {
skipTest(4);
}
});
test('should be lazy when in a lazy chain sequence', 3, function() {
if (!isNpm) {
var spy = {
'toString': function() {
throw new Error('spy was revealed');
}
};
var array = largeArray.concat(spy),
expected = array.slice();
try {
var wrapped = _(array).slice(1).map(String).reverse(),
actual = wrapped.last();
} catch(e) {}
ok(wrapped instanceof _);
strictEqual(actual, '1');
deepEqual(array, expected);
}
else {
skipTest(3);
}
});
test('should work in a hybrid chain sequence', 8, function() {
if (!isNpm) {
_.times(2, function(index) {
var clone = (index ? largeArray : smallArray).slice();
_.each(['map', 'filter'], function(methodName) {
var array = clone.slice(),
expected = clone.slice(1, -1).reverse(),
actual = _(array)[methodName](_.identity).thru(_.compact).reverse().value();
deepEqual(actual, expected);
array = clone.slice();
actual = _(array).thru(_.compact)[methodName](_.identity).pull(1).push(3).reverse().value();
deepEqual(actual, [3].concat(expected.slice(0, -1)));
});
});
}
else {
skipTest(8);
}
});
test('should track the `__chain__` value of a wrapper', 6, function() {
if (!isNpm) {
_.times(2, function(index) {
var array = (index ? largeArray : smallArray).slice(),
expected = array.slice().reverse(),
wrapped = _(array).chain().reverse().first();
ok(wrapped instanceof _);
strictEqual(wrapped.value(), _.first(expected));
deepEqual(array, expected);
});
}
else {
skipTest(6);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).shift');
(function() {
test('should remove elements from the front of `array`', 5, function() {
if (!isNpm) {
var array = [1, 2],
wrapped = _(array);
strictEqual(wrapped.shift(), 1);
deepEqual(wrapped.value(), [2]);
strictEqual(wrapped.shift(), 2);
var actual = wrapped.value();
deepEqual(actual, []);
strictEqual(actual, array);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).slice');
(function() {
test('should return a slice of `array`', 3, function() {
if (!isNpm) {
var array = [1, 2, 3],
wrapped = _(array).slice(0, 2),
actual = wrapped.value();
deepEqual(array, [1, 2, 3]);
deepEqual(actual, [1, 2]);
notStrictEqual(actual, array);
}
else {
skipTest(3);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).sort');
(function() {
test('should return the wrapped sorted `array`', 2, function() {
if (!isNpm) {
var array = [3, 1, 2],
wrapped = _(array).sort(),
actual = wrapped.value();
strictEqual(actual, array);
deepEqual(actual, [1, 2, 3]);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).splice');
(function() {
test('should support removing and inserting elements', 5, function() {
if (!isNpm) {
var array = [1, 2],
wrapped = _(array);
deepEqual(wrapped.splice(1, 1, 3).value(), [2]);
deepEqual(wrapped.value(), [1, 3]);
deepEqual(wrapped.splice(0, 2).value(), [1, 3]);
var actual = wrapped.value();
deepEqual(actual, []);
strictEqual(actual, array);
}
else {
skipTest(5);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).split');
(function() {
test('should support string split', 2, function() {
if (!isNpm) {
var wrapped = _('abcde');
deepEqual(wrapped.split('c').value(), ['ab', 'de']);
deepEqual(wrapped.split(/[bd]/).value(), ['a', 'c', 'e']);
}
else {
skipTest(2);
}
});
test('should allow mixed string and array prototype methods', 1, function() {
if (!isNpm) {
var wrapped = _('abc');
strictEqual(wrapped.split('b').join(','), 'a,c');
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).unshift');
(function() {
test('should prepend elements to `array`', 2, function() {
if (!isNpm) {
var array = [3],
wrapped = _(array).unshift(1, 2),
actual = wrapped.value();
strictEqual(actual, array);
deepEqual(actual, [1, 2, 3]);
}
else {
skipTest(2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).toString');
(function() {
test('should return the `toString` result of the wrapped value', 1, function() {
if (!isNpm) {
var wrapped = _([1, 2, 3]);
strictEqual(String(wrapped), '1,2,3');
}
else {
skipTest();
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...).value');
(function() {
test('should execute the chained sequence and extract the unwrapped value', 4, function() {
if (!isNpm) {
var array = [1],
wrapped = _(array).push(2).push(3);
deepEqual(array, [1]);
deepEqual(wrapped.value(), [1, 2, 3]);
deepEqual(wrapped.value(), [1, 2, 3, 2, 3]);
deepEqual(array, [1, 2, 3, 2, 3]);
}
else {
skipTest(4);
}
});
test('should return the `valueOf` result of the wrapped value', 1, function() {
if (!isNpm) {
var wrapped = _(123);
strictEqual(Number(wrapped), 123);
}
else {
skipTest();
}
});
test('should stringify the wrapped value when used by `JSON.stringify`', 1, function() {
if (!isNpm && JSON) {
var wrapped = _([1, 2, 3]);
strictEqual(JSON.stringify(wrapped), '[1,2,3]');
}
else {
skipTest();
}
});
test('should be aliased', 3, function() {
if (!isNpm) {
var expected = _.prototype.value;
strictEqual(_.prototype.run, expected);
strictEqual(_.prototype.toJSON, expected);
strictEqual(_.prototype.valueOf, expected);
}
else {
skipTest(3);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...) methods that return the wrapped modified array');
(function() {
var funcs = [
'push',
'reverse',
'sort',
'unshift'
];
_.each(funcs, function(methodName) {
test('`_(...).' + methodName + '` should return a new wrapper', 2, function() {
if (!isNpm) {
var array = [1, 2, 3],
wrapped = _(array),
actual = wrapped[methodName]();
ok(actual instanceof _);
notStrictEqual(actual, wrapped);
}
else {
skipTest(2);
}
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...) methods that return new wrapped values');
(function() {
var funcs = [
'concat',
'slice',
'splice'
];
_.each(funcs, function(methodName) {
test('`_(...).' + methodName + '` should return a new wrapped value', 2, function() {
if (!isNpm) {
var array = [1, 2, 3],
wrapped = _(array),
actual = wrapped[methodName]();
ok(actual instanceof _);
notStrictEqual(actual, wrapped);
}
else {
skipTest(2);
}
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash(...) methods that return unwrapped values');
(function() {
var funcs = [
'clone',
'every',
'find',
'first',
'has',
'hasIn',
'includes',
'isArguments',
'isArray',
'isBoolean',
'isDate',
'isElement',
'isEmpty',
'isEqual',
'isError',
'isFinite',
'isFunction',
'isNaN',
'isNil',
'isNull',
'isNumber',
'isObject',
'isPlainObject',
'isRegExp',
'isString',
'isUndefined',
'join',
'last',
'max',
'maxBy',
'min',
'minBy',
'parseInt',
'pop',
'shift',
'sum',
'random',
'reduce',
'reduceRight',
'some'
];
_.each(funcs, function(methodName) {
test('`_(...).' + methodName + '` should return an unwrapped value when implicitly chaining', 1, function() {
if (!isNpm) {
var array = [1, 2, 3],
actual = _(array)[methodName]();
ok(!(actual instanceof _));
}
else {
skipTest();
}
});
test('`_(...).' + methodName + '` should return a wrapped value when explicitly chaining', 1, function() {
if (!isNpm) {
var array = [1, 2, 3],
actual = _(array).chain()[methodName]();
ok(actual instanceof _);
}
else {
skipTest();
}
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('"Arrays" category methods');
(function() {
var args = arguments,
array = [1, 2, 3, 4, 5, 6];
test('should work with `arguments` objects', 28, function() {
function message(methodName) {
return '`_.' + methodName + '` should work with `arguments` objects';
}
deepEqual(_.difference(args, [null]), [1, [3], 5], message('difference'));
deepEqual(_.difference(array, args), [2, 3, 4, 6], '_.difference should work with `arguments` objects as secondary arguments');
deepEqual(_.union(args, [null, 6]), [1, null, [3], 5, 6], message('union'));
deepEqual(_.union(array, args), array.concat([null, [3]]), '_.union should work with `arguments` objects as secondary arguments');
deepEqual(_.compact(args), [1, [3], 5], message('compact'));
deepEqual(_.drop(args, 3), [null, 5], message('drop'));
deepEqual(_.dropRight(args, 3), [1, null], message('dropRight'));
deepEqual(_.dropRightWhile(args,_.identity), [1, null, [3], null], message('dropRightWhile'));
deepEqual(_.dropWhile(args,_.identity), [ null, [3], null, 5], message('dropWhile'));
deepEqual(_.findIndex(args, _.identity), 0, message('findIndex'));
deepEqual(_.findLastIndex(args, _.identity), 4, message('findLastIndex'));
deepEqual(_.first(args), 1, message('first'));
deepEqual(_.flatten(args), [1, null, 3, null, 5], message('flatten'));
deepEqual(_.indexOf(args, 5), 4, message('indexOf'));
deepEqual(_.initial(args), [1, null, [3], null], message('initial'));
deepEqual(_.intersection(args, [1]), [1], message('intersection'));
deepEqual(_.last(args), 5, message('last'));
deepEqual(_.lastIndexOf(args, 1), 0, message('lastIndexOf'));
deepEqual(_.rest(args, 4), [null, [3], null, 5], message('rest'));
deepEqual(_.sortedIndex(args, 6), 5, message('sortedIndex'));
deepEqual(_.sortedLastIndex(args, 6), 5, message('sortedLastIndex'));
deepEqual(_.take(args, 2), [1, null], message('take'));
deepEqual(_.takeRight(args, 1), [5], message('takeRight'));
deepEqual(_.takeRightWhile(args, _.identity), [5], message('takeRightWhile'));
deepEqual(_.takeWhile(args, _.identity), [1], message('takeWhile'));
deepEqual(_.uniq(args), [1, null, [3], 5], message('uniq'));
deepEqual(_.without(args, null), [1, [3], 5], message('without'));
deepEqual(_.zip(args, args), [[1, 1], [null, null], [[3], [3]], [null, null], [5, 5]], message('zip'));
});
test('should accept falsey primary arguments', 4, function() {
function message(methodName) {
return '`_.' + methodName + '` should accept falsey primary arguments';
}
deepEqual(_.difference(null, array), [], message('difference'));
deepEqual(_.intersection(null, array), [], message('intersection'));
deepEqual(_.union(null, array), array, message('union'));
deepEqual(_.xor(null, array), array, message('xor'));
});
test('should accept falsey secondary arguments', 3, function() {
function message(methodName) {
return '`_.' + methodName + '` should accept falsey secondary arguments';
}
deepEqual(_.difference(array, null), array, message('difference'));
deepEqual(_.intersection(array, null), [], message('intersection'));
deepEqual(_.union(array, null), array, message('union'));
});
}(1, null, [3], null, 5));
/*--------------------------------------------------------------------------*/
QUnit.module('"Strings" category methods');
(function() {
var stringMethods = [
'camelCase',
'capitalize',
'escape',
'kebabCase',
'pad',
'padLeft',
'padRight',
'repeat',
'snakeCase',
'trim',
'trimLeft',
'trimRight',
'trunc',
'unescape'
];
_.each(stringMethods, function(methodName) {
var func = _[methodName];
test('`_.' + methodName + '` should return an empty string for empty values', 3, function() {
strictEqual(func(null), '');
strictEqual(func(undefined), '');
strictEqual(func(''), '');
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('lodash methods');
(function() {
var allMethods = _.reject(_.functions(_).sort(), function(methodName) {
return _.startsWith(methodName, '_');
});
var checkFuncs = [
'after',
'ary',
'before',
'bind',
'curry',
'curryRight',
'debounce',
'defer',
'delay',
'memoize',
'modArgs',
'negate',
'once',
'partial',
'partialRight',
'rearg',
'restParam',
'spread',
'throttle'
];
var rejectFalsey = [
'flow',
'flowRight',
'tap',
'thru'
].concat(checkFuncs);
var returnArrays = [
'at',
'chunk',
'compact',
'difference',
'drop',
'filter',
'flatten',
'functions',
'initial',
'intersection',
'invoke',
'keys',
'map',
'pairs',
'pull',
'pullAt',
'range',
'reject',
'remove',
'rest',
'sample',
'shuffle',
'sortBy',
'sortByOrder',
'take',
'times',
'toArray',
'union',
'uniq',
'values',
'without',
'xor',
'zip'
];
var acceptFalsey = _.difference(allMethods, rejectFalsey);
test('should accept falsey arguments', 224, function() {
var emptyArrays = _.map(falsey, _.constant([]));
_.each(acceptFalsey, function(methodName) {
var expected = emptyArrays,
func = _[methodName],
pass = true;
var actual = _.map(falsey, function(value, index) {
try {
return index ? func(value) : func();
} catch(e) {
pass = false;
}
});
if (methodName == 'noConflict') {
root._ = oldDash;
}
else if (methodName == 'pull') {
expected = falsey;
}
if (_.includes(returnArrays, methodName) && methodName != 'sample') {
deepEqual(actual, expected, '_.' + methodName + ' returns an array');
}
ok(pass, '`_.' + methodName + '` accepts falsey arguments');
});
// Skip tests for missing methods of modularized builds.
_.each(['chain', 'noConflict', 'runInContext'], function(methodName) {
if (!_[methodName]) {
skipTest();
}
});
});
test('should return an array', 66, function() {
var array = [1, 2, 3];
_.each(returnArrays, function(methodName) {
var actual,
func = _[methodName];
switch (methodName) {
case 'invoke':
actual = func(array, 'toFixed');
break;
case 'sample':
actual = func(array, 1);
break;
default:
actual = func(array);
}
ok(_.isArray(actual), '_.' + methodName + ' returns an array');
var isPull = methodName == 'pull';
strictEqual(actual === array, isPull, '_.' + methodName + ' should ' + (isPull ? '' : 'not ') + 'return the provided array');
});
});
test('should throw an error for falsey arguments', 23, function() {
_.each(rejectFalsey, function(methodName) {
var expected = _.map(falsey, _.constant(true)),
func = _[methodName];
var actual = _.map(falsey, function(value, index) {
var pass = !index && /^(?:backflow|compose|flow(Right)?)$/.test(methodName);
try {
index ? func(value) : func();
} catch(e) {
pass = _.includes(checkFuncs, methodName)
? e.message == FUNC_ERROR_TEXT
: !pass;
}
return pass;
});
deepEqual(actual, expected, '`_.' + methodName + '` rejects falsey arguments');
});
});
test('should not contain minified method names (test production builds)', 1, function() {
var shortNames = ['at', 'eq', 'gt', 'lt'];
ok(_.every(_.functions(_), function(methodName) {
return methodName.length > 2 || _.includes(shortNames, methodName);
}));
});
}());
/*--------------------------------------------------------------------------*/
QUnit.config.asyncRetries = 10;
QUnit.config.hidepassed = true;
if (!document) {
QUnit.config.noglobals = true;
QUnit.load();
}
}.call(this));
|
process.title = 'node-dummy';
process.addListener('uncaughtException', function (err, stack) {
console.log('Caught exception: ' + err);
console.log(err.stack.split('\n'));
});
var connect = require('connect');
var assetManager = require('connect-assetmanager');
var assetHandler = require('connect-assetmanager-handlers');
var express = require('express');
var dummyHelper = require('./lib/dummy-helper');
var SocketServer = require('./lib/socket-server');
var fs = require('fs');
var sass = require('sass');
// preManipulate handler for compiling .sass files to .css
var sass_compile = function (file, path, index, isLast, callback) {
if (path.match(/\.sass$/)) {
callback(sass.render(file));
} else {
callback(file);
}
};
var dummyTimestamps = 0;
var assets = assetManager({
'js': {
'route': /\/static\/js\/[0-9]+\/.*\.js/
, 'path': './public/js/'
, 'dataType': 'js'
, 'files': [
'plugins.js'
, 'script.js'
, 'jquery.client.js'
, 'jquery.frontend-development.js'
]
, 'preManipulate': {
'^': [
function (file, path, index, isLast, callback) {
if (path.match(/jquery.client/)) {
callback(file.replace(/'#socketIoPort#'/, port));
} else {
callback(file);
}
}
]
}
, 'postManipulate': {
'^': [
assetHandler.uglifyJsOptimize
, function (file, path, index, isLast, callback) {
callback(file);
dummyTimestamps.content = Date.now();
}
]
}
}, 'css': {
'route': /\/static\/css\/[0-9]+\/.*\.css/
, 'path': './public/css/'
, 'dataType': 'css'
, 'files': [
'boilerplate.css'
, 'styles.sass'
, 'boilerplate_media.css'
, 'frontend-development.css'
]
, 'preManipulate': {
'msie [6-7]': [
sass_compile
, assetHandler.fixVendorPrefixes
, assetHandler.fixGradients
, assetHandler.stripDataUrlsPrefix
]
, '^': [
sass_compile
, assetHandler.fixVendorPrefixes
, assetHandler.fixGradients
, assetHandler.replaceImageRefToBase64(__dirname + '/public')
]
}
, 'postManipulate': {
'^': [
assetHandler.yuiCssOptimize
, function (file, path, index, isLast, callback) {
callback(file);
dummyTimestamps.css = Date.now();
}
]
}
}
});
var port = 3000;
var app = module.exports = express.createServer();
app.configure(function() {
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
});
app.configure(function() {
app.use(connect.bodyParser());
app.use(connect.logger({ format: ':req[x-real-ip]\t:status\t:method\t:url\t' }));
app.use(assets);
app.use(connect.static(__dirname + '/public'));
});
app.dynamicHelpers({
'cacheTimeStamps': function(req, res) {
return assets.cacheTimestamps;
}
});
//setup the errors
app.error(function (err, req, res, next) {
console.log(err.stack.split('\n'));
res.render('500', {locals: {'err': err}});
});
//A route for creating a 500 error (useful to keep around for testing the page)
app.get('/500', function (req, res) {
throw new Error('This is a 500 Error');
});
// Your routes
app.get('/', function(req, res) {
var locals = { 'key': 'value' };
locals = dummyHelper.add_overlay(app, req, locals);
res.render('index', locals);
});
// Keep this just above .listen()
dummyTimestamps = new dummyHelper.DummyHelper(app);
//The 404 route (ALWAYS keep this as the last route)
app.get('/*', function (req, res) {
res.render('404');
});
app.listen(port, null);
//new SocketServer(app);
|
const hammerhead = window.getTestCafeModule('hammerhead');
const browserUtils = hammerhead.utils.browser;
const featureDetection = hammerhead.utils.featureDetection;
const testCafeCore = window.getTestCafeModule('testCafeCore');
const domUtils = testCafeCore.get('./utils/dom');
const textSelection = testCafeCore.get('./utils/text-selection');
const position = testCafeCore.get('./utils/position');
testCafeCore.preventRealEvents();
const testCafeAutomation = window.getTestCafeModule('testCafeAutomation');
const ClickAutomation = testCafeAutomation.Click;
const DblClickAutomation = testCafeAutomation.DblClick;
const SelectTextAutomation = testCafeAutomation.SelectText;
const TypeAutomation = testCafeAutomation.Type;
const PressAutomation = testCafeAutomation.Press;
const DragToOffsetAutomation = testCafeAutomation.DragToOffset;
const ClickOptions = testCafeAutomation.get('../../test-run/commands/options').ClickOptions;
const TypeOptions = testCafeAutomation.get('../../test-run/commands/options').TypeOptions;
const MouseOptions = testCafeAutomation.get('../../test-run/commands/options').MouseOptions;
const parseKeySequence = testCafeCore.get('./utils/parse-key-sequence');
const getOffsetOptions = testCafeAutomation.getOffsetOptions;
$(document).ready(function () {
//consts
const TEST_ELEMENT_CLASS = 'testElement';
//utils
const createTextInput = function () {
return $('<input type="text">').attr('id', 'input').addClass(TEST_ELEMENT_CLASS).appendTo('body');
};
const createTextarea = function () {
return $('<textarea>').attr('id', 'textarea').addClass(TEST_ELEMENT_CLASS).appendTo('body').css('height', 200);
};
$('body').css('height', 1500);
//NOTE: problem with window.top bodyMargin in IE9 if test 'runAll'
//because we can't determine that element is in qunit test iframe
if (browserUtils.isIE9)
$(window.top.document).find('body').css('marginTop', '0px');
const DRAGGABLE_BIND_FLAG = 'tc-dbf-c56a4d91';
const CURSOR_POSITION_PROPERTY = 'tc-cpp-ac4a65d4';
const SCROLL_POSITION_PROPERTY = 'tc-spp-ac4a65d4';
const DRAGGABLE_CLASS = 'draggable';
const DRAG_STARTED_PROPERTY = 'dragStarted';
const initDraggable = function (win, doc, $el) {
const $doc = $(doc);
const $win = $(win);
if (!$doc.data(DRAGGABLE_BIND_FLAG)) {
$doc.data(DRAGGABLE_BIND_FLAG, true);
$doc.data(CURSOR_POSITION_PROPERTY, null);
$doc.bind(featureDetection.isTouchDevice ? 'touchmove' : 'mousemove', function (e) {
const curMousePos = featureDetection.isTouchDevice ? {
x: e.originalEvent.targetTouches[0].pageX || e.originalEvent.touches[0].pageX,
y: e.originalEvent.targetTouches[0].pageY || e.originalEvent.touches[0].pageY
} : {
x: e.clientX,
y: e.clientY
};
$.each($doc.find('.' + DRAGGABLE_CLASS), function () {
const $this = $(this);
if ($(this).data(DRAG_STARTED_PROPERTY)) {
$this.css({
left: Math.round($this.position().left) + curMousePos.x -
$doc.data(CURSOR_POSITION_PROPERTY).x,
top: Math.round($this.position().top) + curMousePos.y -
$doc.data(CURSOR_POSITION_PROPERTY).y
});
return false;
}
return true;
});
$doc.data(CURSOR_POSITION_PROPERTY, curMousePos);
});
}
if (!$win.data(DRAGGABLE_BIND_FLAG)) {
$win.data(DRAGGABLE_BIND_FLAG, true);
$win.data(SCROLL_POSITION_PROPERTY, {
x: 0,
y: 0
});
$win.scroll(function () {
const x = $win.scrollLeft() - $win.data(SCROLL_POSITION_PROPERTY).x;
const y = $win.scrollTop() - $win.data(SCROLL_POSITION_PROPERTY).y;
$win.data(SCROLL_POSITION_PROPERTY).x = $win.scrollLeft();
$win.data(SCROLL_POSITION_PROPERTY).y = $win.scrollTop();
$.each($doc.find('.' + DRAGGABLE_CLASS), function () {
const $this = $(this);
if ($(this).data(DRAG_STARTED_PROPERTY)) {
$this.css({
left: $this.position().left + x,
top: $this.position().top + y
});
return false;
}
return true;
});
});
}
$el.addClass(DRAGGABLE_CLASS);
$el.bind(featureDetection.isTouchDevice ? 'touchstart' : 'mousedown', function (e) {
doc[CURSOR_POSITION_PROPERTY] = featureDetection.isTouchDevice ? {
x: e.originalEvent.targetTouches[0].pageX || e.originalEvent.touches[0].pageX,
y: e.originalEvent.targetTouches[0].pageY || e.originalEvent.touches[0].pageY
} : {
x: e.clientX,
y: e.clientY
};
$doc.data(CURSOR_POSITION_PROPERTY, doc[CURSOR_POSITION_PROPERTY]);
$(this).data(DRAG_STARTED_PROPERTY, true);
});
$el.bind(featureDetection.isTouchDevice ? 'touchend' : 'mouseup', function () {
doc[CURSOR_POSITION_PROPERTY] = null;
$(this).data(DRAG_STARTED_PROPERTY, false);
});
};
const createDraggable = function (currentWindow, currentDocument, x, y) {
currentDocument = currentDocument || document;
currentWindow = currentWindow || window;
const $draggable = $('<div></div>')
.attr('id', 'draggable')
.addClass(TEST_ELEMENT_CLASS)
.css({
width: '60px',
height: '60px',
position: 'absolute',
backgroundColor: 'grey',
left: x ? x + 'px' : '100px',
top: y ? y + 'px' : '850px',
zIndex: 5
})
.appendTo($(currentDocument).find('body'));
initDraggable(currentWindow, currentDocument, $draggable);
return $draggable;
};
const startNext = function (ms) {
if (browserUtils.isIE) {
removeTestElements();
window.setTimeout(start, ms || 30);
}
else
start();
};
const removeTestElements = function () {
$('.' + TEST_ELEMENT_CLASS).remove();
};
const checkEditorSelection = function (element, startSelection, endSelection, selectionInversed) {
const start = textSelection.getSelectionStart(element);
let result = document.activeElement === element && start === startSelection;
if (result && typeof endSelection !== 'undefined')
result = textSelection.getSelectionEnd(element) === endSelection;
if (result && typeof selectionInversed !== 'undefined')
result = textSelection.hasInverseSelection(element) === selectionInversed;
return result;
};
const checkSelection = function (el, start, end, inverse) {
equal(domUtils.getActiveElement(), el, 'selected element is active');
equal(textSelection.getSelectionStart(el), start, 'start selection correct');
equal(textSelection.getSelectionEnd(el), end, 'end selection correct');
if (!window.DIRECTION_ALWAYS_IS_FORWARD)
equal(textSelection.hasInverseSelection(el), inverse, 'selection direction correct');
};
const preventDefault = function (e) {
const ev = e || window.event;
if (ev.preventDefault)
ev.preventDefault();
else
ev.returnValue = false;
};
const runPressAutomation = function (keys, callback) {
const pressAutomation = new PressAutomation(parseKeySequence(keys).combinations, {});
pressAutomation
.run()
.then(callback);
};
const runClickAutomation = function (el, options, callback) {
const offsets = getOffsetOptions(el, options.offsetX, options.offsetY);
const clickOptions = new ClickOptions({
offsetX: offsets.offsetX,
offsetY: offsets.offsetY,
caretPos: options.caretPos,
modifiers: {
ctrl: options.ctrl,
alt: options.ctrl,
shift: options.shift,
meta: options.meta
}
});
const clickAutomation = new ClickAutomation(el, clickOptions);
clickAutomation
.run()
.then(callback);
};
const runTypeAutomation = function (element, text, callback) {
const offsets = getOffsetOptions(element);
const typeOptions = new TypeOptions({
offsetX: offsets.offsetX,
offsetY: offsets.offsetY
});
const typeAutomation = new TypeAutomation(element, text, typeOptions);
typeAutomation
.run()
.then(callback);
};
QUnit.testDone(function () {
if (!browserUtils.isIE)
removeTestElements();
});
//tests
asyncTest('run click playback', function () {
const $input = createTextInput();
let clickCount = 0;
$input.click(function () {
clickCount++;
});
runClickAutomation($input[0], {}, function () {
equal(clickCount, 1);
startNext();
});
});
asyncTest('run dblclick playback', function () {
const $input = createTextInput();
let dblclickCount = 0;
let clickCount = 0;
$input.dblclick(function () {
dblclickCount++;
});
$input.click(function () {
clickCount++;
});
const offsets = getOffsetOptions($input[0]);
const clickOptions = new ClickOptions({
offsetX: offsets.offsetX,
offsetY: offsets.offsetY,
modifiers: {}
});
const dblClickAutomation = new DblClickAutomation($input[0], clickOptions);
dblClickAutomation
.run()
.then(function () {
equal(clickCount, 2);
equal(dblclickCount, 1);
startNext();
});
});
asyncTest('run drag playback', function () {
const $draggable = createDraggable();
const dragOffsetX = 10;
const dragOffsetY = -100;
const center = position.findCenter($draggable[0]);
const pointTo = { x: center.x + dragOffsetX, y: center.y + dragOffsetY };
const dragAutomation = new DragToOffsetAutomation($draggable[0], dragOffsetX, dragOffsetY, new MouseOptions({ offsetX: 0, offsetY: 0 }));
dragAutomation
.run()
.then(function () {
deepEqual(position.findCenter($draggable[0]), pointTo);
startNext();
});
});
asyncTest('run select playback in input', function () {
const $input = createTextInput();
$input[0].value = '123456789qwertyuiop';
const selectTextAutomation = new SelectTextAutomation($input[0], 10, 2, {});
selectTextAutomation
.run()
.then(function () {
checkSelection($input[0], 2, 10, true);
startNext(300);
});
});
asyncTest('run select playback in textarea', function () {
const $textarea = createTextarea();
const value = '123456789\nabcd\nefjtybllsjaLJS';
$textarea[0].value = value;
$textarea[0].textContent = value;
$textarea.text(value);
const selectTextAutomation = new SelectTextAutomation($textarea[0], 2, value.length - 5, {});
selectTextAutomation
.run()
.then(function () {
checkSelection($textarea[0], 2, value.length - 5, false);
startNext();
});
});
asyncTest('run press playback', function () {
const initText = 'init';
const newText = 'ini';
const input = createTextInput()[0];
const keys = 'backspace';
runTypeAutomation(input, initText, function () {
equal(input.value, initText);
runPressAutomation(keys, function () {
equal(input.value, newText);
startNext();
});
});
});
asyncTest('run type playback', function () {
const initText = 'init';
const newText = 'new';
const $input = createTextInput().attr('value', initText);
runTypeAutomation($input[0], newText, function () {
equal($input[0].value, initText + newText);
startNext();
});
});
asyncTest('press down in textarea', function () {
const initText = 'Textarea\rfor test\r123456789';
const $textarea = createTextarea().val(initText);
const keys = 'down';
window.async.series({
'Click on textarea': function (callback) {
runClickAutomation($textarea[0], { caretPos: 5 }, function () {
callback();
});
},
'First press down': function (callback) {
ok(checkEditorSelection($textarea[0], 5));
runPressAutomation(keys, callback);
},
'Second press down': function (callback) {
ok(checkEditorSelection($textarea[0], 14));
runPressAutomation(keys, callback);
},
'Third press down': function (callback) {
ok(checkEditorSelection($textarea[0], 23));
runPressAutomation(keys, callback);
},
'Check selection': function () {
ok(checkEditorSelection($textarea[0], $textarea[0].value.length));
startNext();
}
});
});
asyncTest('press up in textarea', function () {
const initText = 'Textarea\rfor test\r123456789';
const $textarea = createTextarea().val(initText);
const keys = 'up';
window.async.series({
'Click on textarea': function (callback) {
runClickAutomation($textarea[0], { caretPos: 23 }, function () {
callback();
});
},
'First press up': function (callback) {
ok(checkEditorSelection($textarea[0], 23));
runPressAutomation(keys, callback);
},
'Second press up': function (callback) {
ok(checkEditorSelection($textarea[0], 14));
runPressAutomation(keys, callback);
},
'Third press up': function (callback) {
ok(checkEditorSelection($textarea[0], 5));
runPressAutomation(keys, callback);
},
'Check selection': function () {
ok(checkEditorSelection($textarea[0], 0));
startNext();
}
});
});
asyncTest('press home in textarea', function () {
const initText = 'abc\n123\n123456789';
const $textarea = createTextarea().val(initText);
window.async.series({
'Click on textarea': function (callback) {
runClickAutomation($textarea[0], { caretPos: 5 }, function () {
callback();
});
},
'Press home': function (callback) {
ok(checkEditorSelection($textarea[0], 5));
runPressAutomation('home', callback);
},
'Check selection': function () {
ok(checkEditorSelection($textarea[0], 4));
startNext();
}
});
});
asyncTest('press end in textarea', function () {
const initText = 'Textarea\rfor test\r123456789';
const $textarea = createTextarea().val(initText);
window.async.series({
'Click on textarea': function (callback) {
runClickAutomation($textarea[0], { caretPos: 15 }, function () {
callback();
});
},
'Press end': function (callback) {
ok(checkEditorSelection($textarea[0], 15));
runPressAutomation('end', callback);
},
'Check selection': function () {
ok(checkEditorSelection($textarea[0], 17));
startNext();
}
});
});
module('checking the require scrolling');
asyncTest('click element with scroll then click body near to first click does not raise scroll again', function () {
const $input = createTextInput();
let clickCount = 0;
let errorScroll = false;
const $scrollableContainer = $('<div />')
.css({
position: 'absolute',
left: '50px',
top: '1200px',
border: '1px solid black',
overflow: 'scroll'
})
.width(200)
.height(150)
.addClass(TEST_ELEMENT_CLASS)
.appendTo($('body'));
$input.css({ marginTop: '400px' });
$input.appendTo($scrollableContainer);
const scrollHandler = function () {
if (clickCount === 1)
errorScroll = true;
};
const bindScrollHandlers = function () {
$scrollableContainer.bind('scroll', scrollHandler);
$(window).bind('scroll', scrollHandler);
};
const unbindScrollHandlers = function () {
$scrollableContainer.unbind('scroll', scrollHandler);
$(window).unbind('scroll', scrollHandler);
};
$input.click(function () {
clickCount++;
});
$input.bind('mousedown', function () {
unbindScrollHandlers();
});
bindScrollHandlers();
window.async.series({
'First Click': function (callback) {
runClickAutomation($input[0], {}, function () {
callback();
});
},
'Second Click': function (callback) {
equal(clickCount, 1);
bindScrollHandlers();
runClickAutomation($input[0], {}, function () {
callback();
});
},
'Check assertions': function () {
equal(clickCount, 2);
ok(!errorScroll);
startNext();
}
});
});
module('check preventing events');
asyncTest('focus event doesn\'t raised on click if mousedown event prevented', function () {
const input = createTextInput()[0];
let focusRaised = false;
input['onmousedown'] = preventDefault;
input['onfocus'] = function () {
focusRaised = true;
};
runClickAutomation(input, {}, function () {
equal(focusRaised, false);
notEqual(document.activeElement, input);
startNext();
});
});
asyncTest('input text doesn\'t changed on type if keydown event prevented', function () {
const initText = '1';
const newText = '123';
const $input = createTextInput().attr('value', initText);
$input[0]['onkeydown'] = preventDefault;
runTypeAutomation($input[0], newText, function () {
equal($input[0].value, initText);
startNext();
});
});
module('Regression');
asyncTest('T191234 - Press Enter key on a textbox element doesn\'t raise report\'s element updating during test running', function () {
const input = createTextInput()[0];
const keys = 'enter';
let changeCount = 0;
input.addEventListener('change', function () {
changeCount++;
});
runTypeAutomation(input, 'a', function () {
equal(document.activeElement, input);
equal(changeCount, 0);
runPressAutomation(keys, function () {
equal(document.activeElement, input);
equal(changeCount, browserUtils.isIE ? 0 : 1);
runPressAutomation(keys, function () {
equal(document.activeElement, input);
equal(changeCount, browserUtils.isIE ? 0 : 1);
start();
});
});
});
});
});
|
function variants(num, to, fn, from = 0, attribs = []) {
if (num == 1) { from = to; }
for (let i=from; i<=to; i++) {
let newAttribs = attribs.concat();
newAttribs.push(i);
if (num > 1) {
variants(num-1, to-i, fn, from, newAttribs);
} else {
fn(newAttribs);
}
}
}
function getIngredientInfo(ingredientDescription) {
const info = {
capacity: ingredientDescription.match(/capacity (-?[0-9]+)/i)[1],
durability: ingredientDescription.match(/durability (-?[0-9]+)/i)[1],
flavor: ingredientDescription.match(/flavor (-?[0-9]+)/i)[1],
texture: ingredientDescription.match(/texture (-?[0-9]+)/i)[1],
calories: ingredientDescription.match(/calories (-?[0-9]+)/i)[1]
};
return info;
}
export function run(data) {
const lines = data.split(/[\r\n]+/).filter(r => r.length);
let ingredients = [];
let max = 0;
lines.forEach(line => {
ingredients.push(getIngredientInfo(line));
});
variants(ingredients.length, 100, attribs => {
let tmp = {
capacity: 0,
durability: 0,
flavor: 0,
texture: 0,
calories: 0
};
ingredients.forEach((ingredient, i) => {
tmp.capacity += ingredient.capacity * attribs[i];
tmp.durability += ingredient.durability * attribs[i];
tmp.flavor += ingredient.flavor * attribs[i];
tmp.texture += ingredient.texture * attribs[i];
tmp.calories += ingredient.calories * attribs[i];
});
const sum = Math.max(0, tmp.capacity)
* Math.max(0, tmp.durability)
* Math.max(0, tmp.flavor)
* Math.max(0, tmp.texture);
if (sum > max && tmp.calories == 500) {
max = sum;
}
});
return max;
};
|
const express = require('express');
const request = require('request');
const cors = require('cors');
const morgan = require('morgan');
const smtpMail = require('./jason_mail');
import { sendSMS } from './helpers/sms.helper';
const schedule = require('node-schedule');
const apiServerHost = process.argv[2];
const app = express();
const bodyParser = require('body-parser');
require('./helpers/db.helper');
//Setup timezone
process.env.TZ = 'Australia/Sydney';
app.use(cors());
app.use(morgan('dev'));
app.use(bodyParser.json({ limit: '150mb' }));
app.use(bodyParser.urlencoded({
limit: '150mb',
extended: true,
}));
app.use('/api/', function(req, res) {
console.log('routing correctly');
console.log(req.url);
const url = apiServerHost + req.url;
req.pipe(request(url)).pipe(res);
});
require('./routes/index.routes')(app);
console.log('YOUR AWESOME APP STARTED AT: ');
var date = new Date();
console.log('hour', date.getYear());
console.log('month', date.getMonth());
console.log('date', date.getDate());
console.log('hours', date.getHours());
console.log('minutes', date.getMinutes());
console.log('seconds', date.getSeconds());
app.listen(4000); |
import alt from '../../../exseed.core/alt';
import UserActions from '../actions/UserActions';
class UserStore {
constructor() {
this.bindActions(UserActions);
if (process.env.BROWSER) {
// client-side render
this.token = localStorage.getItem('token');
this.user = JSON.parse(localStorage.getItem('user'));
} else {
// server-side render
this.token = '';
this.user = {};
}
}
onRegisterSucc(res) {
console.log('register done');
}
onRegisterFail(res) {
console.log('register fail');
}
onLoginSucc(res) {
this.token = res.data.bearerToken;
this.user = res.data.user;
localStorage.setItem('token', this.token);
localStorage.setItem('user', JSON.stringify(this.user));
}
onLoginFail(res) {
console.log('login fail');
}
onLogoutSucc(res) {
this.token = '';
localStorage.removeItem('token');
localStorage.removeItem('user');
}
onLogoutFail(res) {
console.log('logout fail');
}
}
export default alt.createStore(UserStore, 'UserStore'); |
window.onload = (function() {
var WIDTH = 800,
HEIGHT = 640;
Crafty.init(WIDTH, HEIGHT);
/*
* Create Sprites of size 32 from the PNG file.
* There is only one Sprite in the file. It is mostly transparent
* so the background color will shine through it.
*/
Crafty.sprite(32, "../../img/crate.png", { crate: [0, 0]});
/**
* This is a simple component, a Box, which again gets capabilities from these
* other components:
* - 2D, Canvas: can be drawn on a Canvas
* - Color: has a Background Color
* - Fourway: can be moved with WASD and arrow keys
* - Mouse: reacts on mouse events, like click
* - Tween: simple animation, used here for fading out after mouse click
* - crate: That's the Sprite defined above, not really a JS component
*/
Crafty.c("Box", {
init: function() {
this.addComponent("2D, Canvas, Color, Fourway, Mouse, Tween, crate");
this.w = 32; // width
this.h = 32; // height
this.fourway(10); // initalize 4-way movement
/*
* An 'enterframe' event is created by Crafty for every frame that is
* created. Components should update their status in the phase.
* Here we check if the alpha gradient is < 0.1, in which case the
* entity gets destroyed.
* The alpha value gets changed by the Tween component.
*/
this.bind("EnterFrame", function(e) {
if (this._alpha < 0.1) {
this.destroy();
}
});
/*
* This defines the handler method for mouse clicks.
* Here we tell the entity to gradually change its alpha gradient to 0.0.
* This is done with the Tween component and it takes 50 frames from 1.0 to 0.0.
*/
this.bind("Click", function(e) {
console.log(arguments);
this.tween({alpha: 0.0}, 50);
});
},
/**
* Convenience method which sets the box position and color
*/
makeBox: function(x, y, color) {
this.attr({x: x, y: y}).color(color);
}
});
// create 5 boxes of different colors and place them on the canvas
Crafty.e("Box").makeBox(160, 96, "#F00");
Crafty.e("Box").makeBox(240, 96, "#0F0");
Crafty.e("Box").makeBox(320, 96, "#FF0");
Crafty.e("Box").makeBox(400, 96, "#F0F");
Crafty.e("Box").makeBox(480, 96, "#0FF");
});
|
// Download the Node helper library from twilio.com/docs/node/install
// These consts are your accountSid and authToken from https://www.twilio.com/console
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
const filterOpts = {
messageDateAfter: '2016-07-06',
messageDateBefore: '2016-07-08',
log: '1',
};
client.notifications.each(filterOpts, notification =>
console.log(notification.requestUrl)
);
|
var http = require("http");
var bl = require("bl");
var datas=[];
var index=0;
for(var i=2;i<process.argv.length;i++){
callfunc(i);
}
function callfunc(i) {
var url=process.argv[i];
http.get(url,function(res){
res.pipe(bl(function(err,data){
datas[i]=data.toString();
index++;
if(index==3){
datas.forEach(function(d){
console.log(d);
});
}
}));
});
}
/*
var http = require('http')
var bl = require('bl')
var results = []
var count = 0
function printResults () {
for (var i = 0; i < 3; i++)
console.log(results[i])
}
function httpGet (index) {
http.get(process.argv[2 + index], function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
results[index] = data.toString()
count++
if (count == 3)
printResults()
}))
})
}
for (var i = 0; i < 3; i++)
httpGet(i)
*/
|
const webpack = require('webpack')
// Banner
const bannerTemplate = require('./webpack.banner.js')
const banner = bannerTemplate.replace('<module_format>', 'CommonJS')
// Get externals from package.json dependencies
const dependencies = Object.keys(require('./package.json').dependencies).concat(['angular', 'moment'])
const externals = {}
dependencies.forEach((dep) => { externals[dep] = dep })
// Export config
module.exports = {
entry: './src/index.js',
output: {
path: './lib',
filename: 'index.js',
library: '$moment',
libraryTarget: 'commonjs'
},
plugins: [
new webpack.BannerPlugin({ banner, raw: true, entryOnly: true })
],
target: 'web',
externals,
node: {
process: false,
Buffer: false,
setImmediate: false
}
}
|
import logger from "winston";
import HttpClientPushSensor from "./http/HttpClientPushSensor";
import HttpServerPullSensor from "./http/HttpServerPullSensor";
import UdpClientPushSensor from "./udp/UdpClientPushSensor";
import app from "../server/app";
import storage from "../storage";
import SensorMeta from "./SensorMeta";
let sensors = null;
let sensorMetas = null;
function getSensors()
{
return sensors;
}
async function load()
{
await loadSensorMeta();
await loadSensor();
}
async function loadSensorMeta()
{
logger.info("Loading sensor meta...");
const conn = storage.connection.internalConnection;
sensorMetas = await conn.collection("sensor-meta").find({}).toArray();
logger.info("sensor meta loaded");
let s;
for (let i = 0; i < sensorMetas.length; i++)
{
let sensorMeta;
s = sensorMetas[i];
sensorMeta = new SensorMeta(s);
sensorMetas[s._id] = sensorMeta
}
}
async function loadSensor()
{
logger.info("Loading sensors...");
const conn = storage.connection.internalConnection;
sensors = await conn.collection("sensor-instances").find({}).toArray();
let s = null;
for (let i = 0; i < sensors.length; i++)
{
s = sensors[i];
logger.info(`- [${s.id}] - ${s.name}`);
let sensor = null;
s.meta = sensorMetas[s.meta.oid];
console.log(s);
try
{
if (s.monitor.mode === "http-server-pull")
{
sensor = new HttpServerPullSensor(s);
}
else if (s.monitor.mode === "http-client-push")
{
sensor = new HttpClientPushSensor(s);
}
else if (s.monitor.mode === "udp")
{
sensor = new UdpClientPushSensor(s);
}
else
{
throw new Error(`"${s.monitor.mode}" is not a supported sensor monitor mode. Try "http-server-pull" or "http-client-push".`);
}
// Setup router
app.use("/api/sensor/" + sensor.id, sensor.router);
console.log(sensor.id);
// Re-map indices for sensor.
sensors[i] = sensor;
if (s.id)
{
sensors[s.id] = sensor;
}
}
catch (err)
{
logger.error(err);
throw new Error(`Error ocurs when create sensor "${s.name}".`);
}
const sensorStorage = new storage.SensorStorage(storage.connection);
try
{
await sensorStorage.bind(sensor);
}
catch (err)
{
logger.error(err);
throw new Error(`Error ocurs when binding SensorStorage to sensor "${s.name}".`);
}
if (sensor.startMonitor) //若为服务器拉模式,需要
{
sensor.startMonitor();
}
}
}
export default {
load,
getSensors
};
|
/*
* Name: LineChartImpl.js
* Module: DataModel
* Location: Norris/Main/DataModel
* Date: 2015-04-12
* Version: v1.00
*
* History:
*
* ================================================================================
* Version Date Programmer Changes
* ================================================================================
* v1.00 2015-06-15 Carlon Chiara Approved
* ================================================================================
* v0.08 2015-06-02 Pavanello Fabio Matteo Verify
* ================================================================================
* v0.07 2015-05-30 Bigarella Chiara Edit
* ================================================================================
* v0.06 2015-05-24 Carlon Chiara Verify
* ================================================================================
* v0.05 2015-05-21 Pavanello Fabio Matteo Edit
* ================================================================================
* v0.04 2015-04-27 Bigarella Chiara Verify
* ================================================================================
* v0.03 2015-04-25 Bucco Riccardo Edit
* ================================================================================
* v0.02 2015-04-14 Pavanello Fabio Matteo Verify
* ================================================================================
* v0.01 2015-04-12 Moretto Alessandro Creation
* ================================================================================
*/
var ChartImpl = require('./ChartImpl.js');
var LineChartInPlaceUpdater = require('./LineChartInPlaceUpdater.js');
var LineChartStreamUpdater = require('./LineChartStreamUpdater.js');
module.exports = LineChartImpl;
var defaults = {
description : 'This is a line chart.',
xLabel : '',
yLabel : '',
legendPosition : 'right',
maxItems : 10,
style : {
pointDotSize : 0 , // Number - Size of each point dot in pixels
bezierCurve : true, // Boolean - Whether the line is curved between points
showGrid : false,
animationDuration : 1000,
maxValue: null,
minValue: null
}
};
/**
* Creates a new line chart.
* @constructor
* @param {String} id - the line chart's id.
*/
function LineChartImpl (id) {
if (!(this instanceof LineChartImpl)) return new LineChartImpl(id);
ChartImpl.call(this, 'linechart', id);
for(var key in defaults) {
this.settings[key] = defaults[key];
}
}
LineChartImpl.prototype.__proto__ = ChartImpl.prototype;
/* LineChartFactory ------------------------------------------------------- */
/**
* Creates a new line chart factory.
* @constructor
*/
function LineChartFactory() {
if(!(this instanceof LineChartFactory)) return new LineChartFactory();
}
LineChartFactory.prototype.instance=new LineChartFactory(); // static
/**
* Gets the LineChartFactory's instance.
* @returns {LineChartFactory} the factory's instance.
*/
LineChartFactory.getInstance = function() { // static
return LineChartFactory.prototype.instance;
};
/**
* Creates a new line chart.
* @param {String} id - the line chart's id;
* @returns {LineChartImpl} - the created line chart.
*/
LineChartFactory.prototype.createChart = function (id) {
return new LineChartImpl(id);
};
// Dependency injection:
ChartImpl.registerFactory('linechart' , LineChartFactory.getInstance());
ChartImpl.registerUpdater('linechart:inplace', LineChartInPlaceUpdater.getInstance() );
ChartImpl.registerUpdater('linechart:stream', LineChartStreamUpdater.getInstance() );
|
'use strict';
const Node = require('../Node');
class TableAlias extends Node
{
constructor(ident)
{
super();
this.name = ident.name;
}
childNodes()
{
return [];
}
}
module.exports = TableAlias;
|
search_result['1919']=["topic_00000000000004AA.html","BlobDirectory.CompanyProfile Property",""]; |
/*========================================================
console battlefield against the computer.
-you have 3 ships you can add. 2 destoyers (sized 1x4) and
1 battleship (sized 1x5)
-input is to be added in a 2 value format: [A-J][0-9].
-details regarding battlefield map:
0 - Empty / 1 - Occupied(Ship) / 2 - Hit
-once you hit an enemy ship, you get another shot.
-type 'quit' at any moment to quit the game
========================================================*/
import {Battlefield} from './battlefield.js';
import {Battleship, Destroyer } from './ships.js';
import {EnemyAI} from './enemyAI.js';
import {Converter} from './utils.js';
var consolePrompter = require('./consolePrompter.js');
class Manager {
constructor() {
this.Init();
}
async Init() {
this.InitEnemy(); //add enemy
await this.InitPlayer(); //add for user
this.StartGame();
}
InitEnemy() {
console.log('start loading enemy..');
//init array
this.enemyBattlefield = new Battlefield();
//adding computer ships
console.log('');
var addedShips = 0;
while (addedShips < 3) {
var randX = Math.floor((Math.random() * this.enemyBattlefield.sizeX) + 1);
var randY = Math.floor((Math.random() * this.enemyBattlefield.sizeY) + 1);
var ship = null;
if (addedShips === 0) {
ship = new Battleship(randX, randY);
} else {
ship = new Destroyer(randX, randY);
}
var shipWasAdded = this.enemyBattlefield.AddShip(ship, false);
if (shipWasAdded) {
addedShips++;
console.log('enemy ship added!');
} else {
// console.log('problem adding ship, will try again with new coords');
}
}
}
async InitPlayer() {
console.log('\nstart loading player..');
//init array
this.playerBattlefield = new Battlefield();
var addedShipsNr = 0;
while (addedShipsNr < 3) {
console.log('');
if (addedShipsNr < 2) {
console.log('adding destroyer (size 1x4)');
} else {
console.log('adding battleship (size 1x5)');
}
var point = null;
try {
point = await consolePrompter.promptAddPositionAsync();
} catch (error) {
console.log('ERROR: ' + error);
}
var ship = null;
if (point) {
if (addedShipsNr < 2) {
ship = new Destroyer(point.x, point.y);
} else {
ship = new Battleship(point.x, point.y);
}
var hasAddedShip = this.playerBattlefield.AddShip(ship, true);
if (hasAddedShip) {
addedShipsNr++;
console.log('SHIP ADDED; YOUR BATTLEFIELD: ');
console.log('');
this.playerBattlefield.Print(true);
}
} else {
console.log('data added is not correct; try again');
}
}
console.log('');
}
async PlayerStrike() {
console.log('==>>>> your turn =========>>>>>>');
var point = null;
do {
try {
point = await consolePrompter.promptAddPositionAsync();
} catch (error) {
console.log('ERROR: ' + error);
}
if (point === null) {
console.log('point not correct; please try again')
} else if (this.enemyBattlefield.AlreadyHit(point)) {
console.log('destination was already hit by you; retry');
point = null;
}
} while (point === null);
var shipHitted = this.enemyBattlefield.Hit(point);
if (shipHitted) {
console.log('!!!! your hit the enemy\'s ship at point:' + Converter.ToDisplayCoord(point));
if (this.enemyBattlefield.CheckIfShipsLeft() === false) {
console.log('!!!!!!!!!!!!!!!!!!!! You\'ve won!!! ');
this.GameStarted = false;
}
return true;
} else {
console.log('you\'ve missed!! :' + Converter.ToDisplayCoord(point));
return false;
}
}
async StartGame() {
console.log('loading game..');
this.GameStarted = true;
while (this.GameStarted) {
var repeatStrike = false;
//enemy attack
do {
repeatStrike = EnemyAI.EnemyStrike(this.playerBattlefield);
if (repeatStrike === null) {
this.GameStarted = false;
}
} while (repeatStrike === true);
if (this.GameStarted) {
do {
repeatStrike = await this.PlayerStrike();
} while (repeatStrike === true && this.GameStarted === true);
}
console.log('Your battlefield:');
this.playerBattlefield.Print(true);
console.log('\nenemy\'s battlefield:');
this.enemyBattlefield.Print();
}
}
}
export {Manager} |
// 1. start the dev server
var server = require('../../build/dev-server.js')
// 2. run the nightwatch test suite against it
// to run in additional browsers:
// 1. add an entry in test/e2e/nightwatch.conf.json under "test_settings"
// 2. add it to the --env flag below
// For more information on Nightwatch's config file, see
// http://nightwatchjs.org/guide#settings-file
var runner = require('child_process').spawn(
'./node_modules/.bin/nightwatch',
[
'--config', 'test/e2e/nightwatch.conf.json',
'--env', 'chrome,firefox'
],
{
stdio: 'inherit'
}
)
runner.on('exit', function (code) {
server.close()
process.exit(code)
})
runner.on('error', function (err) {
server.close()
throw err
})
|
'use strict';
require("./phone-item.component.scss");
var PhoneItemComponent = require("./phone-item.component");
angular.module('phoneItem', [])
.component('phoneItem', PhoneItemComponent);
|
angular.module('super').controller('view_celda.controller', ['$scope','$http','$routeParams',
function($scope, $http, $routeParams){
$scope.reverse = false;
$scope.field = 'fecha';
$scope.onFiltro = function(field){
$scope.reverse = !$scope.reverse;
$scope.field = field;
}
$scope.today = new Date();
var meses = [
'Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre'
]
$scope.sucursal = $routeParams.sucursal;
$scope.categoria = $routeParams.categoria;
$('#loadLogo').show();
$http({
method: 'GET',
url: '/api/detallesOfCelda/'+$routeParams.anio+'/'+$routeParams.mes+'/'+$routeParams.sucursal+'/'+$routeParams.categoria
}).then(function(response){
$('#loadLogo').hide();
$scope.detalles = response.data;
$scope.total = 0;
for(var i in $scope.detalles){
//Obtener Total
$scope.total = Number($scope.total) + Number($scope.detalles[i].valor);
}
}, function(errorResponse){
$('#loadLogo').hide();
mostrarNotificacion(errorResponse.data.message);
})
$scope.back = function(){
window.history.back();
}
$scope.printDiv = function(IdDiv){
var divToPrint = jQuery(IdDiv).html();
var newWin = window.open('', 'my div','left=0,top=0,width=5000,height=5000,toolbar=1,resizable=0');
var fecha = new Date();
var mes = Number(fecha.getMonth()) + 1;
var fechaTitle = fecha.getDate()+'-'+mes+'-'+fecha.getFullYear();
newWin.document.write('<html><head><title>Reporte '+fechaTitle+'</title>');
newWin.document.write('<link href="/css/bootstrap.min.css" rel="stylesheet">');
newWin.document.write('<link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet">');
newWin.document.write('<link href="/css/print.css" rel="stylesheet">');
newWin.document.write('</head><body>');
newWin.document.write(divToPrint);
newWin.document.write('</body>');
newWin.document.write('<script type="text/javascript">');
newWin.document.write('window.print();');
newWin.document.write('window.close();');
newWin.document.write('</script>');
newWin.document.write('</html>');
};
$scope.getDate = function(){
return meses[$routeParams.mes-1] + '/' + $routeParams.anio;
}
$scope.getSucursal = function(){
if($routeParams.sucursal != 'Todas'){
return $routeParams.sucursal+' - '
}
return '';
}
$scope.getCategoria = function(){
if($routeParams.categoria != 'Todas'){
return $routeParams.categoria+' - '
}
return '';
}
//---Modal Detalle
$scope.getDetalle = function(detalle){
$scope.detalle = detalle;
}
}
])
|
import * as React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import InstrumentPage from "../utils/instrument-page"
const CompilationHashPage = () => (
<Layout>
<h1>Hi from Compilation Hash page</h1>
<p>Used by integration/compilation-hash.js test</p>
<p>
<Link to="/deep-link-page/" data-testid="deep-link-page">
To deeply linked page
</Link>
</p>
</Layout>
)
export default InstrumentPage(CompilationHashPage)
|
export default [
{
path: '/index/',
component: require('./pages/index.vue')
},
{
path: '/teamManage/',
component: require('./pages/teamManage.vue')
},
{
path: '/businessServices/',
component: require('./pages/businessServices.vue')
},
{
path: '/companyList/',
component: require('./pages/companyList.vue')
},
{
path: '/companyDetail/',
component: require('./pages/companyDetail.vue')
},
{
path: '/newsList/',
component: require('./pages/newsList.vue')
},
{
path: '/newsDetail/',
component: require('./pages/newsDetail.vue')
},
{
path: '/safety/',
component: require('./pages/my/safety.vue')
},
{
path: '/faq/',
component: require('./pages/my/faq.vue')
},
{
path: '/meetingRoom/',
component: require('./pages/service/meetingRoom.vue')
},
{
path: '/atOnceorder/',
component: require('./pages/service/atOnceorder.vue')
},
{
path: '/myTeam/',
component: require('./pages/teamManage/myTeam.vue')
},
{
path: '/honor/',
component: require('./pages/teamManage/honor.vue')
},
{
path: '/addHonor/',
component: require('./pages/teamManage/addHonor.vue')
},
{
path: '/allMember/',
component: require('./pages/teamManage/allMember.vue')
},
{
path: '/addMember/',
component: require('./pages/teamManage/addMember.vue')
},
{
path: '/myService/',
component: require('./pages/service/myService.vue')//我的服务
},
{
path: '/addService/',
component: require('./pages/service/addService.vue')//添加服务
},
{
path: '/addInteract/',
component: require('./pages/interact/addInteract.vue')//添加服务
},
// {
// path: '/personalCenter/',
// component: require('./pages/personalCenter.vue')
// },
// {
// path: '/dynamic-route/blog/:blogId/post/:postId/',
// component: require('./pages/dynamic-route.vue')
// }
] |
export default {
read: false,
static: true
};
|
/**
* parse cli-options and exec placeholder.
*
* @type {exports}
*/
var nopt = require("nopt");
exports.cli = function() {
var path = require("path");
// var knownOpts = {};
// var shortHands = {};
var knownOpts = {
"config" : path,
"version" : Boolean
};
var shortHands = {
"c" : ["--config"],
"v" : ["--version"]
};
var parsed = nopt(knownOpts, shortHands, process.argv, 2);
console.log( "-- cli options parsed." );
return parsed;
}; |
test('.prototype.times()', 8, function () {
// integer
equal((new MathLib.Integer('+10000000')).times(new MathLib.Integer('+10')).toString(), '100000000');
equal((new MathLib.Integer('+10000000')).times(new MathLib.Integer('-10')).toString(), '-100000000');
equal((new MathLib.Integer('-10000000')).times(new MathLib.Integer('+10')).toString(), '-100000000');
equal((new MathLib.Integer('-10000000')).times(new MathLib.Integer('-10')).toString(), '100000000');
// number
equal((new MathLib.Integer('+100')).times(10), 1000);
equal((new MathLib.Integer('+100')).times(-10), -1000);
equal((new MathLib.Integer('-100')).times(10), -1000);
equal((new MathLib.Integer('-100')).times(-10), 1000);
}); |
var yo = require('yo-yo')
var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager
var Terminal = require('./terminal')
var styles = require('./styles/editor-panel-styles')
var cssTabs = styles.cssTabs
var css = styles.css
class EditorPanel {
constructor (opts = {}) {
var self = this
self._api = opts.api
self.event = new EventManager()
self.data = {
_FILE_SCROLL_DELTA: 200,
_layout: {
top: {
offset: self._api.config.get('terminal-top-offset') || 500,
show: true
}
}
}
self._view = {}
self._components = {
editor: opts.api.editor, // @TODO: instantiate in eventpanel instead of passing via `opts`
terminal: new Terminal({
api: {
getPosition (event) {
var limitUp = 36
var limitDown = 20
var height = window.innerHeight
var newpos = (event.pageY < limitUp) ? limitUp : event.pageY
newpos = (newpos < height - limitDown) ? newpos : height - limitDown
return newpos
},
web3 () {
return self._api.web3()
},
context () {
return self._api.context()
}
}
})
}
self._components.terminal.event.register('filterChanged', (type, value) => {
this.event.trigger('terminalFilterChanged', [type, value])
})
self._components.terminal.event.register('resize', delta => self._adjustLayout('top', delta))
if (self._api.txListener) {
self._components.terminal.event.register('listenOnNetWork', (listenOnNetWork) => {
self._api.txListener.setListenOnNetwork(listenOnNetWork)
})
}
if (document && document.head) {
document.head.appendChild(cssTabs)
}
}
_adjustLayout (direction, delta) {
var limitUp = 0
var limitDown = 32
var containerHeight = window.innerHeight - limitUp // - menu bar containerHeight
var self = this
var layout = self.data._layout[direction]
if (layout) {
if (delta === undefined) {
layout.show = !layout.show
if (layout.show) delta = layout.offset
else delta = containerHeight
} else {
layout.show = true
self._api.config.set(`terminal-${direction}-offset`, delta)
layout.offset = delta
}
}
var tmp = delta - limitDown
delta = tmp > 0 ? tmp : 0
if (direction === 'top') {
var height = containerHeight - delta
height = height < 0 ? 0 : height
self._view.editor.style.height = `${delta}px`
self._view.terminal.style.height = `${height}px` // - menu bar height
self._components.editor.resize((document.querySelector('#editorWrap') || {}).checked)
self._components.terminal.scroll2bottom()
}
}
refresh () {
var self = this
self._view.tabs.onmouseenter()
}
log (data = {}) {
var self = this
var command = self._components.terminal.commands[data.type]
if (typeof command === 'function') command(data.value)
}
render () {
var self = this
if (self._view.el) return self._view.el
self._view.editor = self._components.editor.render()
self._view.terminal = self._components.terminal.render()
self._view.content = yo`
<div class=${css.content}>
${self._renderTabsbar()}
<div class=${css.contextviewcontainer}>
${self._api.contextview.render()}
</div>
${self._view.editor}
${self._view.terminal}
</div>
`
self._view.el = yo`
<div class=${css.editorpanel}>
${self._view.content}
</div>
`
// INIT
self._adjustLayout('top', self.data._layout.top.offset)
return self._view.el
}
registerCommand (name, command, opts) {
var self = this
return self._components.terminal.registerCommand(name, command, opts)
}
updateTerminalFilter (filter) {
this._components.terminal.updateJournal(filter)
}
_renderTabsbar () {
var self = this
if (self._view.tabsbar) return self._view.tabsbar
self._view.filetabs = yo`<ul id="files" class="${css.files} nav nav-tabs"></ul>`
self._view.tabs = yo`
<div class=${css.tabs} onmouseenter=${toggleScrollers} onmouseleave=${toggleScrollers}>
<div onclick=${scrollLeft} class="${css.scroller} ${css.hide} ${css.scrollerleft}">
<i class="fa fa-chevron-left "></i>
</div>
${self._view.filetabs}
<div onclick=${scrollRight} class="${css.scroller} ${css.hide} ${css.scrollerright}">
<i class="fa fa-chevron-right "></i>
</div>
</div>
`
self._view.tabsbar = yo`
<div class=${css.tabsbar}>
<div class=${css.buttons}>
<span class=${css.toggleLHP} onclick=${toggleLHP} title="Toggle left hand panel">
<i class="fa fa-angle-double-left"></i>
</span>
<span class=${css.changeeditorfontsize} >
<i class="increditorsize fa fa-plus" onclick=${increase} aria-hidden="true" title="increase editor font size"></i>
<i class="decreditorsize fa fa-minus" onclick=${decrease} aria-hidden="true" title="decrease editor font size"></i>
</span>
</div>
${self._view.tabs}
<span class="${css.toggleRHP}" onclick=${toggleRHP} title="Toggle right hand panel">
<i class="fa fa-angle-double-right"></i>
</span>
</div>
`
return self._view.tabsbar
function toggleScrollers (event = {}) {
if (event.type) self.data._focus = event.type
var isMouseEnter = self.data._focus === 'mouseenter'
var leftArrow = this.children[0]
var rightArrow = this.children[2]
if (isMouseEnter && this.children[1].offsetWidth > this.offsetWidth) {
var hiddenLength = self._view.filetabs.offsetWidth - self._view.tabs.offsetWidth
var currentLeft = self._view.filetabs.offsetLeft || 0
var hiddenRight = hiddenLength + currentLeft
if (currentLeft < 0) {
leftArrow.classList.add(css.show)
leftArrow.classList.remove(css.hide)
}
if (hiddenRight > 0) {
rightArrow.classList.add(css.show)
rightArrow.classList.remove(css.hide)
}
} else {
leftArrow.classList.remove(css.show)
leftArrow.classList.add(css.hide)
rightArrow.classList.remove(css.show)
rightArrow.classList.add(css.hide)
}
}
function toggleLHP (event) {
this.children[0].classList.toggle('fa-angle-double-right')
this.children[0].classList.toggle('fa-angle-double-left')
self.event.trigger('resize', ['left'])
}
function toggleRHP (event) {
this.children[0].classList.toggle('fa-angle-double-right')
this.children[0].classList.toggle('fa-angle-double-left')
self.event.trigger('resize', ['right'])
}
function increase () { self._components.editor.editorFontSize(1) }
function decrease () { self._components.editor.editorFontSize(-1) }
function scrollLeft (event) {
var leftArrow = this
var rightArrow = this.nextElementSibling.nextElementSibling
var currentLeft = self._view.filetabs.offsetLeft || 0
if (currentLeft < 0) {
rightArrow.classList.add(css.show)
rightArrow.classList.remove(css.hide)
if (currentLeft < -self.data._FILE_SCROLL_DELTA) {
self._view.filetabs.style.left = `${currentLeft + self.data._FILE_SCROLL_DELTA}px`
} else {
self._view.filetabs.style.left = `${currentLeft - currentLeft}px`
leftArrow.classList.remove(css.show)
leftArrow.classList.add(css.hide)
}
}
}
function scrollRight (event) {
var rightArrow = this
var leftArrow = this.previousElementSibling.previousElementSibling
var hiddenLength = self._view.filetabs.offsetWidth - self._view.tabs.offsetWidth
var currentLeft = self._view.filetabs.offsetLeft || 0
var hiddenRight = hiddenLength + currentLeft
if (hiddenRight > 0) {
leftArrow.classList.add(css.show)
leftArrow.classList.remove(css.hide)
if (hiddenRight > self.data._FILE_SCROLL_DELTA) {
self._view.filetabs.style.left = `${currentLeft - self.data._FILE_SCROLL_DELTA}px`
} else {
self._view.filetabs.style.left = `${currentLeft - hiddenRight}px`
rightArrow.classList.remove(css.show)
rightArrow.classList.add(css.hide)
}
}
}
}
}
module.exports = EditorPanel
|
/*
* File: TableTools.js
* Version: 2.1.4
* Description: Tools and buttons for DataTables
* Author: Allan Jardine (www.sprymedia.co.uk)
* Language: Javascript
* License: GPL v2 or BSD 3 point style
* Project: DataTables
*
* Copyright 2009-2012 Allan Jardine, all rights reserved.
*
* This source file is free software, under either the GPL v2 license or a
* BSD style license, available at:
* http://datatables.net/license_gpl2
* http://datatables.net/license_bsd
*/
/* Global scope for TableTools */
var TableTools;
(function ($, window, document) {
/**
* TableTools provides flexible buttons and other tools for a DataTables enhanced table
* @class TableTools
* @constructor
* @param {Object} oDT DataTables instance
* @param {Object} oOpts TableTools options
* @param {String} oOpts.sSwfPath ZeroClipboard SWF path
* @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi'
* @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection
* @param {Function} oOpts.fnRowSelected Callback function just after row selection
* @param {Function} oOpts.fnRowDeselected Callback function when row is deselected
* @param {Array} oOpts.aButtons List of buttons to be used
*/
TableTools = function (oDT, oOpts) {
/* Santiy check that we are a new instance */
if (!this instanceof TableTools) {
alert("Warning: TableTools must be initialised with the keyword 'new'");
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @namespace Settings object which contains customisable information for TableTools instance
*/
this.s = {
/**
* Store 'this' so the instance can be retrieved from the settings object
* @property that
* @type object
* @default this
*/
"that": this,
/**
* DataTables settings objects
* @property dt
* @type object
* @default <i>From the oDT init option</i>
*/
"dt": oDT.fnSettings(),
/**
* @namespace Print specific information
*/
"print": {
/**
* DataTables draw 'start' point before the printing display was shown
* @property saveStart
* @type int
* @default -1
*/
"saveStart": -1,
/**
* DataTables draw 'length' point before the printing display was shown
* @property saveLength
* @type int
* @default -1
*/
"saveLength": -1,
/**
* Page scrolling point before the printing display was shown so it can be restored
* @property saveScroll
* @type int
* @default -1
*/
"saveScroll": -1,
/**
* Wrapped function to end the print display (to maintain scope)
* @property funcEnd
* @type Function
* @default function () {}
*/
"funcEnd": function () {
}
},
/**
* A unique ID is assigned to each button in each instance
* @property buttonCounter
* @type int
* @default 0
*/
"buttonCounter": 0,
/**
* @namespace Select rows specific information
*/
"select": {
/**
* Select type - can be 'none', 'single' or 'multi'
* @property type
* @type string
* @default ""
*/
"type": "",
/**
* Array of nodes which are currently selected
* @property selected
* @type array
* @default []
*/
"selected": [],
/**
* Function to run before the selection can take place. Will cancel the select if the
* function returns false
* @property preRowSelect
* @type Function
* @default null
*/
"preRowSelect": null,
/**
* Function to run when a row is selected
* @property postSelected
* @type Function
* @default null
*/
"postSelected": null,
/**
* Function to run when a row is deselected
* @property postDeselected
* @type Function
* @default null
*/
"postDeselected": null,
/**
* Indicate if all rows are selected (needed for server-side processing)
* @property all
* @type boolean
* @default false
*/
"all": false,
/**
* Class name to add to selected TR nodes
* @property selectedClass
* @type String
* @default ""
*/
"selectedClass": ""
},
/**
* Store of the user input customisation object
* @property custom
* @type object
* @default {}
*/
"custom": {},
/**
* SWF movie path
* @property swfPath
* @type string
* @default ""
*/
"swfPath": "",
/**
* Default button set
* @property buttonSet
* @type array
* @default []
*/
"buttonSet": [],
/**
* When there is more than one TableTools instance for a DataTable, there must be a
* master which controls events (row selection etc)
* @property master
* @type boolean
* @default false
*/
"master": false,
/**
* Tag names that are used for creating collections and buttons
* @namesapce
*/
"tags": {}
};
/**
* @namespace Common and useful DOM elements for the class instance
*/
this.dom = {
/**
* DIV element that is create and all TableTools buttons (and their children) put into
* @property container
* @type node
* @default null
*/
"container": null,
/**
* The table node to which TableTools will be applied
* @property table
* @type node
* @default null
*/
"table": null,
/**
* @namespace Nodes used for the print display
*/
"print": {
/**
* Nodes which have been removed from the display by setting them to display none
* @property hidden
* @type array
* @default []
*/
"hidden": [],
/**
* The information display saying telling the user about the print display
* @property message
* @type node
* @default null
*/
"message": null
},
/**
* @namespace Nodes used for a collection display. This contains the currently used collection
*/
"collection": {
/**
* The div wrapper containing the buttons in the collection (i.e. the menu)
* @property collection
* @type node
* @default null
*/
"collection": null,
/**
* Background display to provide focus and capture events
* @property background
* @type node
* @default null
*/
"background": null
}
};
/**
* @namespace Name space for the classes that this TableTools instance will use
* @extends TableTools.classes
*/
this.classes = $.extend(true, {}, TableTools.classes);
if (this.s.dt.bJUI) {
$.extend(true, this.classes, TableTools.classes_themeroller);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @method fnSettings
* @returns {object} TableTools settings object
*/
this.fnSettings = function () {
return this.s;
};
/* Constructor logic */
if (typeof oOpts == 'undefined') {
oOpts = {};
}
this._fnConstruct(oOpts);
return this;
};
TableTools.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @returns {array} List of TR nodes which are currently selected
* @param {boolean} [filtered=false] Get only selected rows which are
* available given the filtering applied to the table. By default
* this is false - i.e. all rows, regardless of filtering are
selected.
*/
"fnGetSelected": function (filtered) {
var
out = [],
data = this.s.dt.aoData,
displayed = this.s.dt.aiDisplay,
i, iLen;
if (filtered) {
// Only consider filtered rows
for (i = 0, iLen = displayed.length; i < iLen; i++) {
if (data[displayed[i]]._DTTT_selected) {
out.push(data[displayed[i]].nTr);
}
}
}
else {
// Use all rows
for (i = 0, iLen = data.length; i < iLen; i++) {
if (data[i]._DTTT_selected) {
out.push(data[i].nTr);
}
}
}
return out;
},
/**
* Get the data source objects/arrays from DataTables for the selected rows (same as
* fnGetSelected followed by fnGetData on each row from the table)
* @returns {array} Data from the TR nodes which are currently selected
*/
"fnGetSelectedData": function () {
var out = [];
var data = this.s.dt.aoData;
var i, iLen;
for (i = 0, iLen = data.length; i < iLen; i++) {
if (data[i]._DTTT_selected) {
out.push(this.s.dt.oInstance.fnGetData(i));
}
}
return out;
},
/**
* Check to see if a current row is selected or not
* @param {Node} n TR node to check if it is currently selected or not
* @returns {Boolean} true if select, false otherwise
*/
"fnIsSelected": function (n) {
var pos = this.s.dt.oInstance.fnGetPosition(n);
return (this.s.dt.aoData[pos]._DTTT_selected === true) ? true : false;
},
/**
* Select all rows in the table
* @param {boolean} [filtered=false] Select only rows which are available
* given the filtering applied to the table. By default this is false -
* i.e. all rows, regardless of filtering are selected.
*/
"fnSelectAll": function (filtered) {
var s = this._fnGetMasterSettings();
this._fnRowSelect((filtered === true) ?
s.dt.aiDisplay :
s.dt.aoData
);
},
/**
* Deselect all rows in the table
* @param {boolean} [filtered=false] Deselect only rows which are available
* given the filtering applied to the table. By default this is false -
* i.e. all rows, regardless of filtering are deselected.
*/
"fnSelectNone": function (filtered) {
var s = this._fnGetMasterSettings();
this._fnRowDeselect(this.fnGetSelected(filtered));
},
/**
* Select row(s)
* @param {node|object|array} n The row(s) to select. Can be a single DOM
* TR node, an array of TR nodes or a jQuery object.
*/
"fnSelect": function (n) {
if (this.s.select.type == "single") {
this.fnSelectNone();
this._fnRowSelect(n);
}
else if (this.s.select.type == "multi") {
this._fnRowSelect(n);
}
},
/**
* Deselect row(s)
* @param {node|object|array} n The row(s) to deselect. Can be a single DOM
* TR node, an array of TR nodes or a jQuery object.
*/
"fnDeselect": function (n) {
this._fnRowDeselect(n);
},
/**
* Get the title of the document - useful for file names. The title is retrieved from either
* the configuration object's 'title' parameter, or the HTML document title
* @param {Object} oConfig Button configuration object
* @returns {String} Button title
*/
"fnGetTitle": function (oConfig) {
var sTitle = "";
if (typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "") {
sTitle = oConfig.sTitle;
} else {
var anTitle = document.getElementsByTagName('title');
if (anTitle.length > 0) {
sTitle = anTitle[0].innerHTML;
}
}
/* Strip characters which the OS will object to - checking for UTF8 support in the scripting
* engine
*/
if ("\u00A1".toString().length < 4) {
return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, "");
} else {
return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, "");
}
},
/**
* Calculate a unity array with the column width by proportion for a set of columns to be
* included for a button. This is particularly useful for PDF creation, where we can use the
* column widths calculated by the browser to size the columns in the PDF.
* @param {Object} oConfig Button configuration object
* @returns {Array} Unity array of column ratios
*/
"fnCalcColRatios": function (oConfig) {
var
aoCols = this.s.dt.aoColumns,
aColumnsInc = this._fnColumnTargets(oConfig.mColumns),
aColWidths = [],
iWidth = 0, iTotal = 0, i, iLen;
for (i = 0, iLen = aColumnsInc.length; i < iLen; i++) {
if (aColumnsInc[i]) {
iWidth = aoCols[i].nTh.offsetWidth;
iTotal += iWidth;
aColWidths.push(iWidth);
}
}
for (i = 0, iLen = aColWidths.length; i < iLen; i++) {
aColWidths[i] = aColWidths[i] / iTotal;
}
return aColWidths.join('\t');
},
/**
* Get the information contained in a table as a string
* @param {Object} oConfig Button configuration object
* @returns {String} Table data as a string
*/
"fnGetTableData": function (oConfig) {
/* In future this could be used to get data from a plain HTML source as well as DataTables */
if (this.s.dt) {
return this._fnGetDataTablesData(oConfig);
}
},
/**
* Pass text to a flash button instance, which will be used on the button's click handler
* @param {Object} clip Flash button object
* @param {String} text Text to set
*/
"fnSetText": function (clip, text) {
this._fnFlashSetText(clip, text);
},
/**
* Resize the flash elements of the buttons attached to this TableTools instance - this is
* useful for when initialising TableTools when it is hidden (display:none) since sizes can't
* be calculated at that time.
*/
"fnResizeButtons": function () {
for (var cli in ZeroClipboard_TableTools.clients) {
if (cli) {
var client = ZeroClipboard_TableTools.clients[cli];
if (typeof client.domElement != 'undefined' &&
client.domElement.parentNode) {
client.positionElement();
}
}
}
},
/**
* Check to see if any of the ZeroClipboard client's attached need to be resized
*/
"fnResizeRequired": function () {
for (var cli in ZeroClipboard_TableTools.clients) {
if (cli) {
var client = ZeroClipboard_TableTools.clients[cli];
if (typeof client.domElement != 'undefined' &&
client.domElement.parentNode == this.dom.container &&
client.sized === false) {
return true;
}
}
}
return false;
},
/**
* Programmatically enable or disable the print view
* @param {boolean} [bView=true] Show the print view if true or not given. If false, then
* terminate the print view and return to normal.
* @param {object} [oConfig={}] Configuration for the print view
* @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true
* @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the
* user to let them know what the print view is.
* @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will
* be included in the printed document.
*/
"fnPrint": function (bView, oConfig) {
if (oConfig === undefined) {
oConfig = {};
}
if (bView === undefined || bView) {
this._fnPrintStart(oConfig);
}
else {
this._fnPrintEnd();
}
},
/**
* Show a message to the end user which is nicely styled
* @param {string} message The HTML string to show to the user
* @param {int} time The duration the message is to be shown on screen for (mS)
*/
"fnInfo": function (message, time) {
var nInfo = document.createElement("div");
nInfo.className = this.classes.print.info;
nInfo.innerHTML = message;
document.body.appendChild(nInfo);
setTimeout(function () {
$(nInfo).fadeOut("normal", function () {
document.body.removeChild(nInfo);
});
}, time);
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods (they are of course public in JS, but recommended as private)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Constructor logic
* @method _fnConstruct
* @param {Object} oOpts Same as TableTools constructor
* @returns void
* @private
*/
"_fnConstruct": function (oOpts) {
var that = this;
this._fnCustomiseSettings(oOpts);
/* Container element */
this.dom.container = document.createElement(this.s.tags.container);
this.dom.container.className = this.classes.container;
/* Row selection config */
if (this.s.select.type != 'none') {
this._fnRowSelectConfig();
}
/* Buttons */
this._fnButtonDefinations(this.s.buttonSet, this.dom.container);
/* Destructor - need to wipe the DOM for IE's garbage collector */
this.s.dt.aoDestroyCallback.push({
"sName": "TableTools",
"fn": function () {
that.dom.container.innerHTML = "";
}
});
},
/**
* Take the user defined settings and the default settings and combine them.
* @method _fnCustomiseSettings
* @param {Object} oOpts Same as TableTools constructor
* @returns void
* @private
*/
"_fnCustomiseSettings": function (oOpts) {
/* Is this the master control instance or not? */
if (typeof this.s.dt._TableToolsInit == 'undefined') {
this.s.master = true;
this.s.dt._TableToolsInit = true;
}
/* We can use the table node from comparisons to group controls */
this.dom.table = this.s.dt.nTable;
/* Clone the defaults and then the user options */
this.s.custom = $.extend({}, TableTools.DEFAULTS, oOpts);
/* Flash file location */
this.s.swfPath = this.s.custom.sSwfPath;
if (typeof ZeroClipboard_TableTools != 'undefined') {
ZeroClipboard_TableTools.moviePath = this.s.swfPath;
}
/* Table row selecting */
this.s.select.type = this.s.custom.sRowSelect;
this.s.select.preRowSelect = this.s.custom.fnPreRowSelect;
this.s.select.postSelected = this.s.custom.fnRowSelected;
this.s.select.postDeselected = this.s.custom.fnRowDeselected;
// Backwards compatibility - allow the user to specify a custom class in the initialiser
if (this.s.custom.sSelectedClass) {
this.classes.select.row = this.s.custom.sSelectedClass;
}
this.s.tags = this.s.custom.oTags;
/* Button set */
this.s.buttonSet = this.s.custom.aButtons;
},
/**
* Take the user input arrays and expand them to be fully defined, and then add them to a given
* DOM element
* @method _fnButtonDefinations
* @param {array} buttonSet Set of user defined buttons
* @param {node} wrapper Node to add the created buttons to
* @returns void
* @private
*/
"_fnButtonDefinations": function (buttonSet, wrapper) {
var buttonDef;
for (var i = 0, iLen = buttonSet.length; i < iLen; i++) {
if (typeof buttonSet[i] == "string") {
if (typeof TableTools.BUTTONS[buttonSet[i]] == 'undefined') {
alert("TableTools: Warning - unknown button type: " + buttonSet[i]);
continue;
}
buttonDef = $.extend({}, TableTools.BUTTONS[buttonSet[i]], true);
}
else {
if (typeof TableTools.BUTTONS[buttonSet[i].sExtends] == 'undefined') {
alert("TableTools: Warning - unknown button type: " + buttonSet[i].sExtends);
continue;
}
var o = $.extend({}, TableTools.BUTTONS[buttonSet[i].sExtends], true);
buttonDef = $.extend(o, buttonSet[i], true);
}
wrapper.appendChild(this._fnCreateButton(
buttonDef,
$(wrapper).hasClass(this.classes.collection.container)
));
}
},
/**
* Create and configure a TableTools button
* @method _fnCreateButton
* @param {Object} oConfig Button configuration object
* @returns {Node} Button element
* @private
*/
"_fnCreateButton": function (oConfig, bCollectionButton) {
var nButton = this._fnButtonBase(oConfig, bCollectionButton);
if (oConfig.sAction.match(/flash/)) {
this._fnFlashConfig(nButton, oConfig);
}
else if (oConfig.sAction == "text") {
this._fnTextConfig(nButton, oConfig);
}
else if (oConfig.sAction == "div") {
this._fnTextConfig(nButton, oConfig);
}
else if (oConfig.sAction == "collection") {
this._fnTextConfig(nButton, oConfig);
this._fnCollectionConfig(nButton, oConfig);
}
return nButton;
},
/**
* Create the DOM needed for the button and apply some base properties. All buttons start here
* @method _fnButtonBase
* @param {o} oConfig Button configuration object
* @returns {Node} DIV element for the button
* @private
*/
"_fnButtonBase": function (o, bCollectionButton) {
var sTag, sLiner, sClass;
if (bCollectionButton) {
sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button;
sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner;
sClass = this.classes.collection.buttons.normal;
}
else {
sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button;
sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner;
sClass = this.classes.buttons.normal;
}
var
nButton = document.createElement(sTag),
nSpan = document.createElement(sLiner),
masterS = this._fnGetMasterSettings();
nButton.className = sClass + " " + o.sButtonClass;
nButton.setAttribute('id', "ToolTables_" + this.s.dt.sInstance + "_" + masterS.buttonCounter);
nButton.appendChild(nSpan);
nSpan.innerHTML = o.sButtonText;
masterS.buttonCounter++;
return nButton;
},
/**
* Get the settings object for the master instance. When more than one TableTools instance is
* assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such,
* we will typically want to interact with that master for global properties.
* @method _fnGetMasterSettings
* @returns {Object} TableTools settings object
* @private
*/
"_fnGetMasterSettings": function () {
if (this.s.master) {
return this.s;
}
else {
/* Look for the master which has the same DT as this one */
var instances = TableTools._aInstances;
for (var i = 0, iLen = instances.length; i < iLen; i++) {
if (this.dom.table == instances[i].s.dt.nTable) {
return instances[i].s;
}
}
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Button collection functions
*/
/**
* Create a collection button, when activated will present a drop down list of other buttons
* @param {Node} nButton Button to use for the collection activation
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionConfig": function (nButton, oConfig) {
var nHidden = document.createElement(this.s.tags.collection.container);
nHidden.style.display = "none";
nHidden.className = this.classes.collection.container;
oConfig._collection = nHidden;
document.body.appendChild(nHidden);
this._fnButtonDefinations(oConfig.aButtons, nHidden);
},
/**
* Show a button collection
* @param {Node} nButton Button to use for the collection
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionShow": function (nButton, oConfig) {
var
that = this,
oPos = $(nButton).offset(),
nHidden = oConfig._collection,
iDivX = oPos.left,
iDivY = oPos.top + $(nButton).outerHeight(),
iWinHeight = $(window).height(), iDocHeight = $(document).height(),
iWinWidth = $(window).width(), iDocWidth = $(document).width();
nHidden.style.position = "absolute";
nHidden.style.left = iDivX + "px";
nHidden.style.top = iDivY + "px";
nHidden.style.display = "block";
$(nHidden).css('opacity', 0);
var nBackground = document.createElement('div');
nBackground.style.position = "absolute";
nBackground.style.left = "0px";
nBackground.style.top = "0px";
nBackground.style.height = ((iWinHeight > iDocHeight) ? iWinHeight : iDocHeight) + "px";
nBackground.style.width = ((iWinWidth > iDocWidth) ? iWinWidth : iDocWidth) + "px";
nBackground.className = this.classes.collection.background;
$(nBackground).css('opacity', 0);
document.body.appendChild(nBackground);
document.body.appendChild(nHidden);
/* Visual corrections to try and keep the collection visible */
var iDivWidth = $(nHidden).outerWidth();
var iDivHeight = $(nHidden).outerHeight();
if (iDivX + iDivWidth > iDocWidth) {
nHidden.style.left = (iDocWidth - iDivWidth) + "px";
}
if (iDivY + iDivHeight > iDocHeight) {
nHidden.style.top = (iDivY - iDivHeight - $(nButton).outerHeight()) + "px";
}
this.dom.collection.collection = nHidden;
this.dom.collection.background = nBackground;
/* This results in a very small delay for the end user but it allows the animation to be
* much smoother. If you don't want the animation, then the setTimeout can be removed
*/
setTimeout(function () {
$(nHidden).animate({"opacity": 1}, 500);
$(nBackground).animate({"opacity": 0.25}, 500);
}, 10);
/* Resize the buttons to the Flash contents fit */
this.fnResizeButtons();
/* Event handler to remove the collection display */
$(nBackground).click(function () {
that._fnCollectionHide.call(that, null, null);
});
},
/**
* Hide a button collection
* @param {Node} nButton Button to use for the collection
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionHide": function (nButton, oConfig) {
if (oConfig !== null && oConfig.sExtends == 'collection') {
return;
}
if (this.dom.collection.collection !== null) {
$(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) {
this.style.display = "none";
});
$(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) {
this.parentNode.removeChild(this);
});
this.dom.collection.collection = null;
this.dom.collection.background = null;
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Row selection functions
*/
/**
* Add event handlers to a table to allow for row selection
* @method _fnRowSelectConfig
* @returns void
* @private
*/
"_fnRowSelectConfig": function () {
if (this.s.master) {
var
that = this,
i, iLen,
dt = this.s.dt,
aoOpenRows = this.s.dt.aoOpenRows;
$(dt.nTable).addClass(this.classes.select.table);
$('tr', dt.nTBody).live('click', function (e) {
/* Sub-table must be ignored (odd that the selector won't do this with >) */
if (this.parentNode != dt.nTBody) {
return;
}
/* Check that we are actually working with a DataTables controlled row */
if (dt.oInstance.fnGetData(this) === null) {
return;
}
if (that.fnIsSelected(this)) {
that._fnRowDeselect(this, e);
}
else if (that.s.select.type == "single") {
that.fnSelectNone();
that._fnRowSelect(this, e);
}
else if (that.s.select.type == "multi") {
that._fnRowSelect(this, e);
}
});
// Bind a listener to the DataTable for when new rows are created.
// This allows rows to be visually selected when they should be and
// deferred rendering is used.
dt.oApi._fnCallbackReg(dt, 'aoRowCreatedCallback', function (tr, data, index) {
if (dt.aoData[index]._DTTT_selected) {
$(tr).addClass(that.classes.select.row);
}
}, 'TableTools-SelectAll');
}
},
/**
* Select rows
* @param {*} src Rows to select - see _fnSelectData for a description of valid inputs
* @private
*/
"_fnRowSelect": function (src, e) {
var
that = this,
data = this._fnSelectData(src),
firstTr = data.length === 0 ? null : data[0].nTr,
anSelected = [],
i, len;
// Get all the rows that will be selected
for (i = 0, len = data.length; i < len; i++) {
if (data[i].nTr) {
anSelected.push(data[i].nTr);
}
}
// User defined pre-selection function
if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true)) {
return;
}
// Mark them as selected
for (i = 0, len = data.length; i < len; i++) {
data[i]._DTTT_selected = true;
if (data[i].nTr) {
$(data[i].nTr).addClass(that.classes.select.row);
}
}
// Post-selection function
if (this.s.select.postSelected !== null) {
this.s.select.postSelected.call(this, anSelected);
}
TableTools._fnEventDispatch(this, 'select', anSelected, true);
},
/**
* Deselect rows
* @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs
* @private
*/
"_fnRowDeselect": function (src, e) {
var
that = this,
data = this._fnSelectData(src),
firstTr = data.length === 0 ? null : data[0].nTr,
anDeselectedTrs = [],
i, len;
// Get all the rows that will be deselected
for (i = 0, len = data.length; i < len; i++) {
if (data[i].nTr) {
anDeselectedTrs.push(data[i].nTr);
}
}
// User defined pre-selection function
if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false)) {
return;
}
// Mark them as deselected
for (i = 0, len = data.length; i < len; i++) {
data[i]._DTTT_selected = false;
if (data[i].nTr) {
$(data[i].nTr).removeClass(that.classes.select.row);
}
}
// Post-deselection function
if (this.s.select.postDeselected !== null) {
this.s.select.postDeselected.call(this, anDeselectedTrs);
}
TableTools._fnEventDispatch(this, 'select', anDeselectedTrs, false);
},
/**
* Take a data source for row selection and convert it into aoData points for the DT
* @param {*} src Can be a single DOM TR node, an array of TR nodes (including a
* a jQuery object), a single aoData point from DataTables, an array of aoData
* points or an array of aoData indexes
* @returns {array} An array of aoData points
*/
"_fnSelectData": function (src) {
var out = [], pos, i, iLen;
if (src.nodeName) {
// Single node
pos = this.s.dt.oInstance.fnGetPosition(src);
out.push(this.s.dt.aoData[pos]);
}
else if (typeof src.length !== 'undefined') {
// jQuery object or an array of nodes, or aoData points
for (i = 0, iLen = src.length; i < iLen; i++) {
if (src[i].nodeName) {
pos = this.s.dt.oInstance.fnGetPosition(src[i]);
out.push(this.s.dt.aoData[pos]);
}
else if (typeof src[i] === 'number') {
out.push(this.s.dt.aoData[src[i]]);
}
else {
out.push(src[i]);
}
}
return out;
}
else {
// A single aoData point
out.push(src);
}
return out;
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Text button functions
*/
/**
* Configure a text based button for interaction events
* @method _fnTextConfig
* @param {Node} nButton Button element which is being considered
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnTextConfig": function (nButton, oConfig) {
var that = this;
if (oConfig.fnInit !== null) {
oConfig.fnInit.call(this, nButton, oConfig);
}
if (oConfig.sToolTip !== "") {
nButton.title = oConfig.sToolTip;
}
$(nButton).hover(function () {
if (oConfig.fnMouseover !== null) {
oConfig.fnMouseover.call(this, nButton, oConfig, null);
}
}, function () {
if (oConfig.fnMouseout !== null) {
oConfig.fnMouseout.call(this, nButton, oConfig, null);
}
});
if (oConfig.fnSelect !== null) {
TableTools._fnEventListen(this, 'select', function (n) {
oConfig.fnSelect.call(that, nButton, oConfig, n);
});
}
$(nButton).click(function (e) {
//e.preventDefault();
if (oConfig.fnClick !== null) {
oConfig.fnClick.call(that, nButton, oConfig, null);
}
/* Provide a complete function to match the behaviour of the flash elements */
if (oConfig.fnComplete !== null) {
oConfig.fnComplete.call(that, nButton, oConfig, null, null);
}
that._fnCollectionHide(nButton, oConfig);
});
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Flash button functions
*/
/**
* Configure a flash based button for interaction events
* @method _fnFlashConfig
* @param {Node} nButton Button element which is being considered
* @param {o} oConfig Button configuration object
* @returns void
* @private
*/
"_fnFlashConfig": function (nButton, oConfig) {
var that = this;
var flash = new ZeroClipboard_TableTools.Client();
if (oConfig.fnInit !== null) {
oConfig.fnInit.call(this, nButton, oConfig);
}
flash.setHandCursor(true);
if (oConfig.sAction == "flash_save") {
flash.setAction('save');
flash.setCharSet((oConfig.sCharSet == "utf16le") ? 'UTF16LE' : 'UTF8');
flash.setBomInc(oConfig.bBomInc);
flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)));
}
else if (oConfig.sAction == "flash_pdf") {
flash.setAction('pdf');
flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)));
}
else {
flash.setAction('copy');
}
flash.addEventListener('mouseOver', function (client) {
if (oConfig.fnMouseover !== null) {
oConfig.fnMouseover.call(that, nButton, oConfig, flash);
}
});
flash.addEventListener('mouseOut', function (client) {
if (oConfig.fnMouseout !== null) {
oConfig.fnMouseout.call(that, nButton, oConfig, flash);
}
});
flash.addEventListener('mouseDown', function (client) {
if (oConfig.fnClick !== null) {
oConfig.fnClick.call(that, nButton, oConfig, flash);
}
});
flash.addEventListener('complete', function (client, text) {
if (oConfig.fnComplete !== null) {
oConfig.fnComplete.call(that, nButton, oConfig, flash, text);
}
that._fnCollectionHide(nButton, oConfig);
});
this._fnFlashGlue(flash, nButton, oConfig.sToolTip);
},
/**
* Wait until the id is in the DOM before we "glue" the swf. Note that this function will call
* itself (using setTimeout) until it completes successfully
* @method _fnFlashGlue
* @param {Object} clip Zero clipboard object
* @param {Node} node node to glue swf to
* @param {String} text title of the flash movie
* @returns void
* @private
*/
"_fnFlashGlue": function (flash, node, text) {
var that = this;
var id = node.getAttribute('id');
if (document.getElementById(id)) {
flash.glue(node, text);
}
else {
setTimeout(function () {
that._fnFlashGlue(flash, node, text);
}, 100);
}
},
/**
* Set the text for the flash clip to deal with
*
* This function is required for large information sets. There is a limit on the
* amount of data that can be transferred between Javascript and Flash in a single call, so
* we use this method to build up the text in Flash by sending over chunks. It is estimated
* that the data limit is around 64k, although it is undocumented, and appears to be different
* between different flash versions. We chunk at 8KiB.
* @method _fnFlashSetText
* @param {Object} clip the ZeroClipboard object
* @param {String} sData the data to be set
* @returns void
* @private
*/
"_fnFlashSetText": function (clip, sData) {
var asData = this._fnChunkData(sData, 8192);
clip.clearText();
for (var i = 0, iLen = asData.length; i < iLen; i++) {
clip.appendText(asData[i]);
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Data retrieval functions
*/
/**
* Convert the mixed columns variable into a boolean array the same size as the columns, which
* indicates which columns we want to include
* @method _fnColumnTargets
* @param {String|Array} mColumns The columns to be included in data retrieval. If a string
* then it can take the value of "visible" or "hidden" (to include all visible or
* hidden columns respectively). Or an array of column indexes
* @returns {Array} A boolean array the length of the columns of the table, which each value
* indicating if the column is to be included or not
* @private
*/
"_fnColumnTargets": function (mColumns) {
var aColumns = [];
var dt = this.s.dt;
if (typeof mColumns == "object") {
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
aColumns.push(false);
}
for (i = 0, iLen = mColumns.length; i < iLen; i++) {
aColumns[mColumns[i]] = true;
}
}
else if (mColumns == "visible") {
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
aColumns.push(dt.aoColumns[i].bVisible ? true : false);
}
}
else if (mColumns == "hidden") {
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
aColumns.push(dt.aoColumns[i].bVisible ? false : true);
}
}
else if (mColumns == "sortable") {
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
aColumns.push(dt.aoColumns[i].bSortable ? true : false);
}
}
else /* all */
{
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
aColumns.push(true);
}
}
return aColumns;
},
/**
* New line character(s) depend on the platforms
* @method method
* @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine
* @returns {String} Newline character
*/
"_fnNewline": function (oConfig) {
if (oConfig.sNewLine == "auto") {
return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n";
}
else {
return oConfig.sNewLine;
}
},
/**
* Get data from DataTables' internals and format it for output
* @method _fnGetDataTablesData
* @param {Object} oConfig Button configuration object
* @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string
* @param {String} oConfig.sFieldSeperator Field separator for the data cells
* @param {String} oConfig.sNewline New line options
* @param {Mixed} oConfig.mColumns Which columns should be included in the output
* @param {Boolean} oConfig.bHeader Include the header
* @param {Boolean} oConfig.bFooter Include the footer
* @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output
* @returns {String} Concatenated string of data
* @private
*/
"_fnGetDataTablesData": function (oConfig) {
var i, iLen, j, jLen;
var aRow, aData = [], sLoopData = '', arr;
var dt = this.s.dt, tr, child;
var regex = new RegExp(oConfig.sFieldBoundary, "g");
/* Do it here for speed */
var aColumnsInc = this._fnColumnTargets(oConfig.mColumns);
var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false;
/*
* Header
*/
if (oConfig.bHeader) {
aRow = [];
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
if (aColumnsInc[i]) {
sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g, " ").replace(/<.*?>/g, "").replace(/^\s+|\s+$/g, "");
sLoopData = this._fnHtmlDecode(sLoopData);
aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
}
}
aData.push(aRow.join(oConfig.sFieldSeperator));
}
/*
* Body
*/
var aDataIndex = dt.aiDisplay;
var aSelected = this.fnGetSelected();
if (this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0) {
aDataIndex = [];
for (i = 0, iLen = aSelected.length; i < iLen; i++) {
aDataIndex.push(dt.oInstance.fnGetPosition(aSelected[i]));
}
}
for (j = 0, jLen = aDataIndex.length; j < jLen; j++) {
tr = dt.aoData[aDataIndex[j]].nTr;
aRow = [];
/* Columns */
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
if (aColumnsInc[i]) {
/* Convert to strings (with small optimisation) */
var mTypeData = dt.oApi._fnGetCellData(dt, aDataIndex[j], i, 'display');
if (oConfig.fnCellRender) {
sLoopData = oConfig.fnCellRender(mTypeData, i, tr, aDataIndex[j]) + "";
}
else if (typeof mTypeData == "string") {
/* Strip newlines, replace img tags with alt attr. and finally strip html... */
sLoopData = mTypeData.replace(/\n/g, " ");
sLoopData =
sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi,
'$1$2$3');
sLoopData = sLoopData.replace(/<.*?>/g, "");
}
else {
sLoopData = mTypeData + "";
}
/* Trim and clean the data */
sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, '');
sLoopData = this._fnHtmlDecode(sLoopData);
/* Bound it and add it to the total data */
aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
}
}
aData.push(aRow.join(oConfig.sFieldSeperator));
/* Details rows from fnOpen */
if (oConfig.bOpenRows) {
arr = $.grep(dt.aoOpenRows, function (o) {
return o.nParent === tr;
});
if (arr.length === 1) {
sLoopData = this._fnBoundData($('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex);
aData.push(sLoopData);
}
}
}
/*
* Footer
*/
if (oConfig.bFooter && dt.nTFoot !== null) {
aRow = [];
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
if (aColumnsInc[i] && dt.aoColumns[i].nTf !== null) {
sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g, " ").replace(/<.*?>/g, "");
sLoopData = this._fnHtmlDecode(sLoopData);
aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
}
}
aData.push(aRow.join(oConfig.sFieldSeperator));
}
_sLastData = aData.join(this._fnNewline(oConfig));
return _sLastData;
},
/**
* Wrap data up with a boundary string
* @method _fnBoundData
* @param {String} sData data to bound
* @param {String} sBoundary bounding char(s)
* @param {RegExp} regex search for the bounding chars - constructed outside for efficiency
* in the loop
* @returns {String} bound data
* @private
*/
"_fnBoundData": function (sData, sBoundary, regex) {
if (sBoundary === "") {
return sData;
}
else {
return sBoundary + sData.replace(regex, sBoundary + sBoundary) + sBoundary;
}
},
/**
* Break a string up into an array of smaller strings
* @method _fnChunkData
* @param {String} sData data to be broken up
* @param {Int} iSize chunk size
* @returns {Array} String array of broken up text
* @private
*/
"_fnChunkData": function (sData, iSize) {
var asReturn = [];
var iStrlen = sData.length;
for (var i = 0; i < iStrlen; i += iSize) {
if (i + iSize < iStrlen) {
asReturn.push(sData.substring(i, i + iSize));
}
else {
asReturn.push(sData.substring(i, iStrlen));
}
}
return asReturn;
},
/**
* Decode HTML entities
* @method _fnHtmlDecode
* @param {String} sData encoded string
* @returns {String} decoded string
* @private
*/
"_fnHtmlDecode": function (sData) {
if (sData.indexOf('&') === -1) {
return sData;
}
var n = document.createElement('div');
return sData.replace(/&([^\s]*);/g, function (match, match2) {
if (match.substr(1, 1) === '#') {
return String.fromCharCode(Number(match2.substr(1)));
}
else {
n.innerHTML = match;
return n.childNodes[0].nodeValue;
}
});
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Printing functions
*/
/**
* Show print display
* @method _fnPrintStart
* @param {Event} e Event object
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnPrintStart": function (oConfig) {
var that = this;
var oSetDT = this.s.dt;
/* Parse through the DOM hiding everything that isn't needed for the table */
this._fnPrintHideNodes(oSetDT.nTable);
/* Show the whole table */
this.s.print.saveStart = oSetDT._iDisplayStart;
this.s.print.saveLength = oSetDT._iDisplayLength;
if (oConfig.bShowAll) {
oSetDT._iDisplayStart = 0;
oSetDT._iDisplayLength = -1;
oSetDT.oApi._fnCalculateEnd(oSetDT);
oSetDT.oApi._fnDraw(oSetDT);
}
/* Adjust the display for scrolling which might be done by DataTables */
if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") {
this._fnPrintScrollStart(oSetDT);
// If the table redraws while in print view, the DataTables scrolling
// setup would hide the header, so we need to readd it on draw
$(this.s.dt.nTable).bind('draw.DTTT_Print', function () {
that._fnPrintScrollStart(oSetDT);
});
}
/* Remove the other DataTables feature nodes - but leave the table! and info div */
var anFeature = oSetDT.aanFeatures;
for (var cFeature in anFeature) {
if (cFeature != 'i' && cFeature != 't' && cFeature.length == 1) {
for (var i = 0, iLen = anFeature[cFeature].length; i < iLen; i++) {
this.dom.print.hidden.push({
"node": anFeature[cFeature][i],
"display": "block"
});
anFeature[cFeature][i].style.display = "none";
}
}
}
/* Print class can be used for styling */
$(document.body).addClass(this.classes.print.body);
/* Show information message to let the user know what is happening */
if (oConfig.sInfo !== "") {
this.fnInfo(oConfig.sInfo, 3000);
}
/* Add a message at the top of the page */
if (oConfig.sMessage) {
this.dom.print.message = document.createElement("div");
this.dom.print.message.className = this.classes.print.message;
this.dom.print.message.innerHTML = oConfig.sMessage;
document.body.insertBefore(this.dom.print.message, document.body.childNodes[0]);
}
/* Cache the scrolling and the jump to the top of the page */
this.s.print.saveScroll = $(window).scrollTop();
window.scrollTo(0, 0);
/* Bind a key event listener to the document for the escape key -
* it is removed in the callback
*/
$(document).bind("keydown.DTTT", function (e) {
/* Only interested in the escape key */
if (e.keyCode == 27) {
e.preventDefault();
that._fnPrintEnd.call(that, e);
}
});
},
/**
* Printing is finished, resume normal display
* @method _fnPrintEnd
* @param {Event} e Event object
* @returns void
* @private
*/
"_fnPrintEnd": function (e) {
var that = this;
var oSetDT = this.s.dt;
var oSetPrint = this.s.print;
var oDomPrint = this.dom.print;
/* Show all hidden nodes */
this._fnPrintShowNodes();
/* Restore DataTables' scrolling */
if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") {
$(this.s.dt.nTable).unbind('draw.DTTT_Print');
this._fnPrintScrollEnd();
}
/* Restore the scroll */
window.scrollTo(0, oSetPrint.saveScroll);
/* Drop the print message */
if (oDomPrint.message !== null) {
document.body.removeChild(oDomPrint.message);
oDomPrint.message = null;
}
/* Styling class */
$(document.body).removeClass('DTTT_Print');
/* Restore the table length */
oSetDT._iDisplayStart = oSetPrint.saveStart;
oSetDT._iDisplayLength = oSetPrint.saveLength;
oSetDT.oApi._fnCalculateEnd(oSetDT);
oSetDT.oApi._fnDraw(oSetDT);
$(document).unbind("keydown.DTTT");
},
/**
* Take account of scrolling in DataTables by showing the full table
* @returns void
* @private
*/
"_fnPrintScrollStart": function () {
var
oSetDT = this.s.dt,
nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0],
nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0],
nScrollBody = oSetDT.nTable.parentNode;
/* Copy the header in the thead in the body table, this way we show one single table when
* in print view. Note that this section of code is more or less verbatim from DT 1.7.0
*/
var nTheadSize = oSetDT.nTable.getElementsByTagName('thead');
if (nTheadSize.length > 0) {
oSetDT.nTable.removeChild(nTheadSize[0]);
}
if (oSetDT.nTFoot !== null) {
var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot');
if (nTfootSize.length > 0) {
oSetDT.nTable.removeChild(nTfootSize[0]);
}
}
nTheadSize = oSetDT.nTHead.cloneNode(true);
oSetDT.nTable.insertBefore(nTheadSize, oSetDT.nTable.childNodes[0]);
if (oSetDT.nTFoot !== null) {
nTfootSize = oSetDT.nTFoot.cloneNode(true);
oSetDT.nTable.insertBefore(nTfootSize, oSetDT.nTable.childNodes[1]);
}
/* Now adjust the table's viewport so we can actually see it */
if (oSetDT.oScroll.sX !== "") {
oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth() + "px";
nScrollBody.style.width = $(oSetDT.nTable).outerWidth() + "px";
nScrollBody.style.overflow = "visible";
}
if (oSetDT.oScroll.sY !== "") {
nScrollBody.style.height = $(oSetDT.nTable).outerHeight() + "px";
nScrollBody.style.overflow = "visible";
}
},
/**
* Take account of scrolling in DataTables by showing the full table. Note that the redraw of
* the DataTable that we do will actually deal with the majority of the hard work here
* @returns void
* @private
*/
"_fnPrintScrollEnd": function () {
var
oSetDT = this.s.dt,
nScrollBody = oSetDT.nTable.parentNode;
if (oSetDT.oScroll.sX !== "") {
nScrollBody.style.width = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sX);
nScrollBody.style.overflow = "auto";
}
if (oSetDT.oScroll.sY !== "") {
nScrollBody.style.height = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sY);
nScrollBody.style.overflow = "auto";
}
},
/**
* Resume the display of all TableTools hidden nodes
* @method _fnPrintShowNodes
* @returns void
* @private
*/
"_fnPrintShowNodes": function () {
var anHidden = this.dom.print.hidden;
for (var i = 0, iLen = anHidden.length; i < iLen; i++) {
anHidden[i].node.style.display = anHidden[i].display;
}
anHidden.splice(0, anHidden.length);
},
/**
* Hide nodes which are not needed in order to display the table. Note that this function is
* recursive
* @method _fnPrintHideNodes
* @param {Node} nNode Element which should be showing in a 'print' display
* @returns void
* @private
*/
"_fnPrintHideNodes": function (nNode) {
var anHidden = this.dom.print.hidden;
var nParent = nNode.parentNode;
var nChildren = nParent.childNodes;
for (var i = 0, iLen = nChildren.length; i < iLen; i++) {
if (nChildren[i] != nNode && nChildren[i].nodeType == 1) {
/* If our node is shown (don't want to show nodes which were previously hidden) */
var sDisplay = $(nChildren[i]).css("display");
if (sDisplay != "none") {
/* Cache the node and it's previous state so we can restore it */
anHidden.push({
"node": nChildren[i],
"display": sDisplay
});
nChildren[i].style.display = "none";
}
}
}
if (nParent.nodeName != "BODY") {
this._fnPrintHideNodes(nParent);
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Store of all instances that have been created of TableTools, so one can look up other (when
* there is need of a master)
* @property _aInstances
* @type Array
* @default []
* @private
*/
TableTools._aInstances = [];
/**
* Store of all listeners and their callback functions
* @property _aListeners
* @type Array
* @default []
*/
TableTools._aListeners = [];
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Get an array of all the master instances
* @method fnGetMasters
* @returns {Array} List of master TableTools instances
* @static
*/
TableTools.fnGetMasters = function () {
var a = [];
for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) {
if (TableTools._aInstances[i].s.master) {
a.push(TableTools._aInstances[i]);
}
}
return a;
};
/**
* Get the master instance for a table node (or id if a string is given)
* @method fnGetInstance
* @returns {Object} ID of table OR table node, for which we want the TableTools instance
* @static
*/
TableTools.fnGetInstance = function (node) {
if (typeof node != 'object') {
node = document.getElementById(node);
}
for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) {
if (TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node) {
return TableTools._aInstances[i];
}
}
return null;
};
/**
* Add a listener for a specific event
* @method _fnEventListen
* @param {Object} that Scope of the listening function (i.e. 'this' in the caller)
* @param {String} type Event type
* @param {Function} fn Function
* @returns void
* @private
* @static
*/
TableTools._fnEventListen = function (that, type, fn) {
TableTools._aListeners.push({
"that": that,
"type": type,
"fn": fn
});
};
/**
* An event has occurred - look up every listener and fire it off. We check that the event we are
* going to fire is attached to the same table (using the table node as reference) before firing
* @method _fnEventDispatch
* @param {Object} that Scope of the listening function (i.e. 'this' in the caller)
* @param {String} type Event type
* @param {Node} node Element that the event occurred on (may be null)
* @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false)
* @returns void
* @private
* @static
*/
TableTools._fnEventDispatch = function (that, type, node, selected) {
var listeners = TableTools._aListeners;
for (var i = 0, iLen = listeners.length; i < iLen; i++) {
if (that.dom.table == listeners[i].that.dom.table && listeners[i].type == type) {
listeners[i].fn(node, selected);
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constants
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
TableTools.buttonBase = {
// Button base
"sAction": "text",
"sTag": "default",
"sLinerTag": "default",
"sButtonClass": "DTTT_button_text",
"sButtonText": "Button text",
"sTitle": "",
"sToolTip": "",
// Common button specific options
"sCharSet": "utf8",
"bBomInc": false,
"sFileName": "*.csv",
"sFieldBoundary": "",
"sFieldSeperator": "\t",
"sNewLine": "auto",
"mColumns": "all", /* "all", "visible", "hidden" or array of column integers */
"bHeader": true,
"bFooter": true,
"bOpenRows": false,
"bSelectedOnly": false,
// Callbacks
"fnMouseover": null,
"fnMouseout": null,
"fnClick": null,
"fnSelect": null,
"fnComplete": null,
"fnInit": null,
"fnCellRender": null
};
/**
* @namespace Default button configurations
*/
TableTools.BUTTONS = {
"csv": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_save",
"sButtonClass": "DTTT_button_csv",
"sButtonText": "CSV",
"sFieldBoundary": '"',
"sFieldSeperator": ",",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash, this.fnGetTableData(oConfig));
}
}),
"xls": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_save",
"sCharSet": "utf16le",
"bBomInc": true,
"sButtonClass": "DTTT_button_xls",
"sButtonText": "Excel",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash, this.fnGetTableData(oConfig));
}
}),
"copy": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_copy",
"sButtonClass": "DTTT_button_copy",
"sButtonText": "Copy",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash, this.fnGetTableData(oConfig));
},
"fnComplete": function (nButton, oConfig, flash, text) {
var
lines = text.split('\n').length,
len = this.s.dt.nTFoot === null ? lines - 1 : lines - 2,
plural = (len == 1) ? "" : "s";
this.fnInfo('<h6>Table copied</h6>' +
'<p>Copied ' + len + ' row' + plural + ' to the clipboard.</p>',
1500
);
}
}),
"pdf": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_pdf",
"sNewLine": "\n",
"sFileName": "*.pdf",
"sButtonClass": "DTTT_button_pdf",
"sButtonText": "PDF",
"sPdfOrientation": "portrait",
"sPdfSize": "A4",
"sPdfMessage": "",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash,
"title:" + this.fnGetTitle(oConfig) + "\n" +
"message:" + oConfig.sPdfMessage + "\n" +
"colWidth:" + this.fnCalcColRatios(oConfig) + "\n" +
"orientation:" + oConfig.sPdfOrientation + "\n" +
"size:" + oConfig.sPdfSize + "\n" +
"--/TableToolsOpts--\n" +
this.fnGetTableData(oConfig)
);
}
}),
"print": $.extend({}, TableTools.buttonBase, {
"sInfo": "<h6>Print view</h6><p>Please use your browser's print function to " +
"print this table. Press escape when finished.",
"sMessage": null,
"bShowAll": true,
"sToolTip": "View print view",
"sButtonClass": "DTTT_button_print",
"sButtonText": "Print",
"fnClick": function (nButton, oConfig) {
this.fnPrint(true, oConfig);
}
}),
"text": $.extend({}, TableTools.buttonBase),
"select": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Select button",
"fnSelect": function (nButton, oConfig) {
if (this.fnGetSelected().length !== 0) {
$(nButton).removeClass(this.classes.buttons.disabled);
} else {
$(nButton).addClass(this.classes.buttons.disabled);
}
},
"fnInit": function (nButton, oConfig) {
$(nButton).addClass(this.classes.buttons.disabled);
}
}),
"select_single": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Select button",
"fnSelect": function (nButton, oConfig) {
var iSelected = this.fnGetSelected().length;
if (iSelected == 1) {
$(nButton).removeClass(this.classes.buttons.disabled);
} else {
$(nButton).addClass(this.classes.buttons.disabled);
}
},
"fnInit": function (nButton, oConfig) {
$(nButton).addClass(this.classes.buttons.disabled);
}
}),
"select_all": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Select all",
"fnClick": function (nButton, oConfig) {
this.fnSelectAll();
},
"fnSelect": function (nButton, oConfig) {
if (this.fnGetSelected().length == this.s.dt.fnRecordsDisplay()) {
$(nButton).addClass(this.classes.buttons.disabled);
} else {
$(nButton).removeClass(this.classes.buttons.disabled);
}
}
}),
"select_none": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Deselect all",
"fnClick": function (nButton, oConfig) {
this.fnSelectNone();
},
"fnSelect": function (nButton, oConfig) {
if (this.fnGetSelected().length !== 0) {
$(nButton).removeClass(this.classes.buttons.disabled);
} else {
$(nButton).addClass(this.classes.buttons.disabled);
}
},
"fnInit": function (nButton, oConfig) {
$(nButton).addClass(this.classes.buttons.disabled);
}
}),
"ajax": $.extend({}, TableTools.buttonBase, {
"sAjaxUrl": "/xhr.php",
"sButtonText": "Ajax button",
"fnClick": function (nButton, oConfig) {
var sData = this.fnGetTableData(oConfig);
$.ajax({
"url": oConfig.sAjaxUrl,
"data": [
{"name": "tableData", "value": sData}
],
"success": oConfig.fnAjaxComplete,
"dataType": "json",
"type": "POST",
"cache": false,
"error": function () {
alert("Error detected when sending table data to server");
}
});
},
"fnAjaxComplete": function (json) {
alert('Ajax complete');
}
}),
"div": $.extend({}, TableTools.buttonBase, {
"sAction": "div",
"sTag": "div",
"sButtonClass": "DTTT_nonbutton",
"sButtonText": "Text button"
}),
"collection": $.extend({}, TableTools.buttonBase, {
"sAction": "collection",
"sButtonClass": "DTTT_button_collection",
"sButtonText": "Collection",
"fnClick": function (nButton, oConfig) {
this._fnCollectionShow(nButton, oConfig);
}
})
};
/*
* on* callback parameters:
* 1. node - button element
* 2. object - configuration object for this button
* 3. object - ZeroClipboard reference (flash button only)
* 4. string - Returned string from Flash (flash button only - and only on 'complete')
*/
/**
* @namespace Classes used by TableTools - allows the styles to be override easily.
* Note that when TableTools initialises it will take a copy of the classes object
* and will use its internal copy for the remainder of its run time.
*/
TableTools.classes = {
"container": "DTTT_container",
"buttons": {
"normal": "DTTT_button",
"disabled": "DTTT_disabled"
},
"collection": {
"container": "DTTT_collection",
"background": "DTTT_collection_background",
"buttons": {
"normal": "DTTT_button",
"disabled": "DTTT_disabled"
}
},
"select": {
"table": "DTTT_selectable",
"row": "DTTT_selected"
},
"print": {
"body": "DTTT_Print",
"info": "DTTT_print_info",
"message": "DTTT_PrintMessage"
}
};
/**
* @namespace ThemeRoller classes - built in for compatibility with DataTables'
* bJQueryUI option.
*/
TableTools.classes_themeroller = {
"container": "DTTT_container ui-buttonset ui-buttonset-multi",
"buttons": {
"normal": "DTTT_button ui-button ui-state-default"
},
"collection": {
"container": "DTTT_collection ui-buttonset ui-buttonset-multi"
}
};
/**
* @namespace TableTools default settings for initialisation
*/
TableTools.DEFAULTS = {
"sSwfPath": "/assets/plugins/datatable/swf/copy_csv_xls_pdf.swf",
"sRowSelect": "none",
"sSelectedClass": null,
"fnPreRowSelect": null,
"fnRowSelected": null,
"fnRowDeselected": null,
"aButtons": ["copy", "csv", "xls", "pdf", "print"],
"oTags": {
"container": "div",
"button": "a", // We really want to use buttons here, but Firefox and IE ignore the
// click on the Flash element in the button (but not mouse[in|out]).
"liner": "span",
"collection": {
"container": "div",
"button": "a",
"liner": "span"
}
}
};
/**
* Name of this class
* @constant CLASS
* @type String
* @default TableTools
*/
TableTools.prototype.CLASS = "TableTools";
/**
* TableTools version
* @constant VERSION
* @type String
* @default See code
*/
TableTools.VERSION = "2.1.4";
TableTools.prototype.VERSION = TableTools.VERSION;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Initialisation
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Register a new feature with DataTables
*/
if (typeof $.fn.dataTable == "function" &&
typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
$.fn.dataTableExt.fnVersionCheck('1.9.0')) {
$.fn.dataTableExt.aoFeatures.push({
"fnInit": function (oDTSettings) {
var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ?
oDTSettings.oInit.oTableTools : {};
var oTT = new TableTools(oDTSettings.oInstance, oOpts);
TableTools._aInstances.push(oTT);
return oTT.dom.container;
},
"cFeature": "T",
"sFeature": "TableTools"
});
}
else {
alert("Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download");
}
$.fn.DataTable.TableTools = TableTools;
})(jQuery, window, document);
|
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var getData = require('./services.js');
var port = process.env.port || 3000;
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', function(socket) {
// Send a chat message to everyone in the specified room
socket.on('get data', function(dataInfo) {
console.log("I got: ");
console.log(dataInfo.s1);
console.log(dataInfo.s2);
processData(dataInfo.s1, dataInfo.s2);
});
function processData(s1, s2) {
console.log("Gathering data... ")
getData(s1, s2, giveData);
};
function giveData(processedData, absMax) {
console.log("made it")
socket.emit('give data', {data: processedData, max: absMax});
};
});
server.listen(port, function() {
console.log("Server started on port " + port);
}); |
const Util = require('util');
const AbstractIterator = require('abstract-leveldown').AbstractIterator;
const fastFuture = require('fast-future');
function Iterator(db, options) {
AbstractIterator.call(this, db);
this.binding = db.binding.iterator(options);
this.cache = null;
this.finished = false;
this.fastFuture = fastFuture();
}
Util.inherits(Iterator, AbstractIterator);
Iterator.prototype.seek = function(key) {
if (typeof key !== 'string')
throw new Error('seek requires a string key');
this.cache = null;
this.binding.seek(key);
};
Iterator.prototype._next = function(callback) {
var that = this;
var key, value;
if (this.cache && this.cache.length) {
key = this.cache.pop();
value = this.cache.pop();
this.fastFuture(function() {
callback(null, key, value);
});
} else if (this.finished) {
this.fastFuture(function() {
callback();
});
} else {
this.binding.next(function(err, array, finished) {
if (err) return callback(err);
that.cache = array;
that.finished = finished;
that._next(callback);
});
}
return this;
};
Iterator.prototype._end = function(callback) {
delete this.cache;
this.binding.end(callback);
};
module.exports = Iterator;
|
import ensureArray from 'ensure-array';
import * as parser from 'gcode-parser';
import _ from 'lodash';
import SerialConnection from '../../lib/SerialConnection';
import EventTrigger from '../../lib/EventTrigger';
import Feeder from '../../lib/Feeder';
import Sender, { SP_TYPE_CHAR_COUNTING } from '../../lib/Sender';
import Workflow, {
WORKFLOW_STATE_IDLE,
WORKFLOW_STATE_PAUSED,
WORKFLOW_STATE_RUNNING
} from '../../lib/Workflow';
import delay from '../../lib/delay';
import ensurePositiveNumber from '../../lib/ensure-positive-number';
import evaluateAssignmentExpression from '../../lib/evaluate-assignment-expression';
import logger from '../../lib/logger';
import translateExpression from '../../lib/translate-expression';
import config from '../../services/configstore';
import monitor from '../../services/monitor';
import taskRunner from '../../services/taskrunner';
import store from '../../store';
import {
GLOBAL_OBJECTS as globalObjects,
WRITE_SOURCE_CLIENT,
WRITE_SOURCE_FEEDER
} from '../constants';
import SmoothieRunner from './SmoothieRunner';
import {
SMOOTHIE,
SMOOTHIE_ACTIVE_STATE_HOLD,
SMOOTHIE_REALTIME_COMMANDS
} from './constants';
// % commands
const WAIT = '%wait';
const log = logger('controller:Smoothie');
const noop = _.noop;
class SmoothieController {
type = SMOOTHIE;
// CNCEngine
engine = null;
// Sockets
sockets = {};
// Connection
connection = null;
connectionEventListener = {
data: (data) => {
log.silly(`< ${data}`);
this.runner.parse('' + data);
},
close: (err) => {
this.ready = false;
if (err) {
log.warn(`Disconnected from serial port "${this.options.port}":`, err);
}
this.close(err => {
// Remove controller from store
const port = this.options.port;
store.unset(`controllers[${JSON.stringify(port)}]`);
// Destroy controller
this.destroy();
});
},
error: (err) => {
this.ready = false;
if (err) {
log.error(`Unexpected error while reading/writing serial port "${this.options.port}":`, err);
}
}
};
// Smoothie
controller = null;
ready = false;
state = {};
settings = {};
queryTimer = null;
actionMask = {
queryParserState: {
state: false, // wait for a message containing the current G-code parser modal state
reply: false // wait for an `ok` or `error` response
},
queryStatusReport: false,
// Respond to user input
replyParserState: false, // $G
replyStatusReport: false // ?
};
actionTime = {
queryParserState: 0,
queryStatusReport: 0,
senderFinishTime: 0
};
feedOverride = 100;
spindleOverride = 100;
// Event Trigger
event = null;
// Feeder
feeder = null;
// Sender
sender = null;
// Shared context
sharedContext = {};
// Workflow
workflow = null;
constructor(engine, options) {
if (!engine) {
throw new Error('engine must be specified');
}
this.engine = engine;
const { port, baudrate, rtscts } = { ...options };
this.options = {
...this.options,
port: port,
baudrate: baudrate,
rtscts: rtscts
};
// Connection
this.connection = new SerialConnection({
path: port,
baudRate: baudrate,
rtscts: rtscts,
writeFilter: (data) => {
return data;
}
});
// Event Trigger
this.event = new EventTrigger((event, trigger, commands) => {
log.debug(`EventTrigger: event="${event}", trigger="${trigger}", commands="${commands}"`);
if (trigger === 'system') {
taskRunner.run(commands);
} else {
this.command('gcode', commands);
}
});
// Feeder
this.feeder = new Feeder({
dataFilter: (line, context) => {
// Remove comments that start with a semicolon `;`
line = line.replace(/\s*;.*/g, '').trim();
context = this.populateContext(context);
if (line[0] === '%') {
// %wait
if (line === WAIT) {
log.debug('Wait for the planner to empty');
return 'G4 P0.5'; // dwell
}
// Expression
// %_x=posx,_y=posy,_z=posz
evaluateAssignmentExpression(line.slice(1), context);
return '';
}
// line="G0 X[posx - 8] Y[ymax]"
// > "G0 X2 Y50"
line = translateExpression(line, context);
const data = parser.parseLine(line, { flatten: true });
const words = ensureArray(data.words);
{ // Program Mode: M0, M1
const programMode = _.intersection(words, ['M0', 'M1'])[0];
if (programMode === 'M0') {
log.debug('M0 Program Pause');
this.feeder.hold({ data: 'M0' }); // Hold reason
} else if (programMode === 'M1') {
log.debug('M1 Program Pause');
this.feeder.hold({ data: 'M1' }); // Hold reason
}
}
// M6 Tool Change
if (_.includes(words, 'M6')) {
log.debug('M6 Tool Change');
this.feeder.hold({ data: 'M6' }); // Hold reason
}
return line;
}
});
this.feeder.on('data', (line = '', context = {}) => {
if (this.isClose()) {
log.error(`Serial port "${this.options.port}" is not accessible`);
return;
}
if (this.runner.isAlarm()) {
this.feeder.reset();
log.warn('Stopped sending G-code commands in Alarm mode');
return;
}
line = String(line).trim();
if (line.length === 0) {
return;
}
this.emit('serialport:write', line + '\n', {
...context,
source: WRITE_SOURCE_FEEDER
});
this.connection.write(line + '\n');
log.silly(`> ${line}`);
});
this.feeder.on('hold', noop);
this.feeder.on('unhold', noop);
// Sender
this.sender = new Sender(SP_TYPE_CHAR_COUNTING, {
// Deduct the buffer size to prevent from buffer overrun
bufferSize: (128 - 8), // The default buffer size is 128 bytes
dataFilter: (line, context) => {
// Remove comments that start with a semicolon `;`
line = line.replace(/\s*;.*/g, '').trim();
context = this.populateContext(context);
const { sent, received } = this.sender.state;
if (line[0] === '%') {
// %wait
if (line === WAIT) {
log.debug(`Wait for the planner to empty: line=${sent + 1}, sent=${sent}, received=${received}`);
this.sender.hold({ data: WAIT }); // Hold reason
return 'G4 P0.5'; // dwell
}
// Expression
// %_x=posx,_y=posy,_z=posz
evaluateAssignmentExpression(line.slice(1), context);
return '';
}
// line="G0 X[posx - 8] Y[ymax]"
// > "G0 X2 Y50"
line = translateExpression(line, context);
const data = parser.parseLine(line, { flatten: true });
const words = ensureArray(data.words);
{ // Program Mode: M0, M1
const programMode = _.intersection(words, ['M0', 'M1'])[0];
if (programMode === 'M0') {
log.debug(`M0 Program Pause: line=${sent + 1}, sent=${sent}, received=${received}`);
this.workflow.pause({ data: 'M0' });
} else if (programMode === 'M1') {
log.debug(`M1 Program Pause: line=${sent + 1}, sent=${sent}, received=${received}`);
this.workflow.pause({ data: 'M1' });
}
}
// M6 Tool Change
if (_.includes(words, 'M6')) {
log.debug(`M6 Tool Change: line=${sent + 1}, sent=${sent}, received=${received}`);
this.workflow.pause({ data: 'M6' });
}
return line;
}
});
this.sender.on('data', (line = '', context = {}) => {
if (this.isClose()) {
log.error(`Serial port "${this.options.port}" is not accessible`);
return;
}
if (this.workflow.state === WORKFLOW_STATE_IDLE) {
log.error(`Unexpected workflow state: ${this.workflow.state}`);
return;
}
line = String(line).trim();
if (line.length === 0) {
log.warn(`Expected non-empty line: N=${this.sender.state.sent}`);
return;
}
this.connection.write(line + '\n');
log.silly(`> ${line}`);
});
this.sender.on('hold', noop);
this.sender.on('unhold', noop);
this.sender.on('start', (startTime) => {
this.actionTime.senderFinishTime = 0;
});
this.sender.on('end', (finishTime) => {
this.actionTime.senderFinishTime = finishTime;
});
// Workflow
this.workflow = new Workflow();
this.workflow.on('start', (...args) => {
this.emit('workflow:state', this.workflow.state);
this.sender.rewind();
});
this.workflow.on('stop', (...args) => {
this.emit('workflow:state', this.workflow.state);
this.sender.rewind();
});
this.workflow.on('pause', (...args) => {
this.emit('workflow:state', this.workflow.state);
if (args.length > 0) {
const reason = { ...args[0] };
this.sender.hold(reason); // Hold reason
} else {
this.sender.hold();
}
});
this.workflow.on('resume', (...args) => {
this.emit('workflow:state', this.workflow.state);
// Reset feeder prior to resume program execution
this.feeder.reset();
// Resume program execution
this.sender.unhold();
this.sender.next();
});
// Smoothie
this.runner = new SmoothieRunner();
this.runner.on('raw', noop);
this.runner.on('status', (res) => {
this.actionMask.queryStatusReport = false;
if (this.actionMask.replyStatusReport) {
this.actionMask.replyStatusReport = false;
this.emit('serialport:read', res.raw);
}
// Check if the receive buffer is available in the status report (#115)
// @see https://github.com/cncjs/cncjs/issues/115
// @see https://github.com/cncjs/cncjs/issues/133
const rx = Number(_.get(res, 'buf.rx', 0)) || 0;
if (rx > 0) {
// Do not modify the buffer size when running a G-code program
if (this.workflow.state !== WORKFLOW_STATE_IDLE) {
return;
}
// Check if the streaming protocol is character-counting streaming protocol
if (this.sender.sp.type !== SP_TYPE_CHAR_COUNTING) {
return;
}
// Check if the queue is empty
if (this.sender.sp.dataLength !== 0) {
return;
}
// Deduct the receive buffer length to prevent from buffer overrun
const bufferSize = (rx - 8); // TODO
if (bufferSize > this.sender.sp.bufferSize) {
this.sender.sp.bufferSize = bufferSize;
}
}
});
this.runner.on('ok', (res) => {
if (this.actionMask.queryParserState.reply) {
if (this.actionMask.replyParserState) {
this.actionMask.replyParserState = false;
this.emit('serialport:read', res.raw);
}
this.actionMask.queryParserState.reply = false;
return;
}
const { hold, sent, received } = this.sender.state;
if (this.workflow.state === WORKFLOW_STATE_RUNNING) {
if (hold && (received + 1 >= sent)) {
log.debug(`Continue sending G-code: hold=${hold}, sent=${sent}, received=${received + 1}`);
this.sender.unhold();
}
this.sender.ack();
this.sender.next();
return;
}
if ((this.workflow.state === WORKFLOW_STATE_PAUSED) && (received < sent)) {
if (!hold) {
log.error('The sender does not hold off during the paused state');
}
if (received + 1 >= sent) {
log.debug(`Stop sending G-code: hold=${hold}, sent=${sent}, received=${received + 1}`);
}
this.sender.ack();
this.sender.next();
return;
}
this.emit('serialport:read', res.raw);
// Feeder
this.feeder.next();
});
this.runner.on('error', (res) => {
if (this.workflow.state === WORKFLOW_STATE_RUNNING) {
const ignoreErrors = config.get('state.controller.exception.ignoreErrors');
const pauseError = !ignoreErrors;
const { lines, received } = this.sender.state;
const line = lines[received] || '';
this.emit('serialport:read', `> ${line.trim()} (line=${received + 1})`);
this.emit('serialport:read', res.raw);
if (pauseError) {
this.workflow.pause({ err: res.raw });
}
this.sender.ack();
this.sender.next();
return;
}
this.emit('serialport:read', res.raw);
// Feeder
this.feeder.next();
});
this.runner.on('alarm', (res) => {
this.emit('serialport:read', res.raw);
});
this.runner.on('parserstate', (res) => {
this.actionMask.queryParserState.state = false;
this.actionMask.queryParserState.reply = true;
if (this.actionMask.replyParserState) {
this.emit('serialport:read', res.raw);
}
});
this.runner.on('parameters', (res) => {
this.emit('serialport:read', res.raw);
});
this.runner.on('version', (res) => {
this.emit('serialport:read', res.raw);
});
this.runner.on('others', (res) => {
this.emit('serialport:read', res.raw);
});
const queryStatusReport = () => {
// Check the ready flag
if (!(this.ready)) {
return;
}
const now = new Date().getTime();
// The status report query (?) is a realtime command, it does not consume the receive buffer.
const lastQueryTime = this.actionTime.queryStatusReport;
if (lastQueryTime > 0) {
const timespan = Math.abs(now - lastQueryTime);
const toleranceTime = 5000; // 5 seconds
// Check if it has not been updated for a long time
if (timespan >= toleranceTime) {
log.debug(`Continue status report query: timespan=${timespan}ms`);
this.actionMask.queryStatusReport = false;
}
}
if (this.actionMask.queryStatusReport) {
return;
}
if (this.isOpen()) {
this.actionMask.queryStatusReport = true;
this.actionTime.queryStatusReport = now;
this.connection.write('?');
}
};
// The throttle function is executed on the trailing edge of the timeout,
// the function might be executed even if the query timer has been destroyed.
const queryParserState = _.throttle(() => {
// Check the ready flag
if (!(this.ready)) {
return;
}
const now = new Date().getTime();
// Do not force query parser state ($G) when running a G-code program,
// it will consume 3 bytes from the receive buffer in each time period.
// @see https://github.com/cncjs/cncjs/issues/176
// @see https://github.com/cncjs/cncjs/issues/186
if ((this.workflow.state === WORKFLOW_STATE_IDLE) && this.runner.isIdle()) {
const lastQueryTime = this.actionTime.queryParserState;
if (lastQueryTime > 0) {
const timespan = Math.abs(now - lastQueryTime);
const toleranceTime = 10000; // 10 seconds
// Check if it has not been updated for a long time
if (timespan >= toleranceTime) {
log.debug(`Continue parser state query: timespan=${timespan}ms`);
this.actionMask.queryParserState.state = false;
this.actionMask.queryParserState.reply = false;
}
}
}
if (this.actionMask.queryParserState.state || this.actionMask.queryParserState.reply) {
return;
}
if (this.isOpen()) {
this.actionMask.queryParserState.state = true;
this.actionMask.queryParserState.reply = false;
this.actionTime.queryParserState = now;
this.connection.write('$G\n');
}
}, 500);
this.queryTimer = setInterval(() => {
if (this.isClose()) {
// Serial port is closed
return;
}
// Feeder
if (this.feeder.peek()) {
this.emit('feeder:status', this.feeder.toJSON());
}
// Sender
if (this.sender.peek()) {
this.emit('sender:status', this.sender.toJSON());
}
const zeroOffset = _.isEqual(
this.runner.getWorkPosition(this.state),
this.runner.getWorkPosition(this.runner.state)
);
// Smoothie settings
if (this.settings !== this.runner.settings) {
this.settings = this.runner.settings;
this.emit('controller:settings', SMOOTHIE, this.settings);
this.emit('Smoothie:settings', this.settings); // Backward compatibility
}
// Smoothie state
if (this.state !== this.runner.state) {
this.state = this.runner.state;
this.emit('controller:state', SMOOTHIE, this.state);
this.emit('Smoothie:state', this.state); // Backward compatibility
}
// Check the ready flag
if (!(this.ready)) {
return;
}
// ? - Status Report
queryStatusReport();
// $G - Parser State
queryParserState();
// Check if the machine has stopped movement after completion
if (this.actionTime.senderFinishTime > 0) {
const machineIdle = zeroOffset && this.runner.isIdle();
const now = new Date().getTime();
const timespan = Math.abs(now - this.actionTime.senderFinishTime);
const toleranceTime = 500; // in milliseconds
if (!machineIdle) {
// Extend the sender finish time
this.actionTime.senderFinishTime = now;
} else if (timespan > toleranceTime) {
log.silly(`Finished sending G-code: timespan=${timespan}`);
this.actionTime.senderFinishTime = 0;
// Stop workflow
this.command('gcode:stop');
}
}
}, 250);
}
populateContext(context) {
// Machine position
const {
x: mposx,
y: mposy,
z: mposz,
a: mposa,
b: mposb,
c: mposc
} = this.runner.getMachinePosition();
// Work position
const {
x: posx,
y: posy,
z: posz,
a: posa,
b: posb,
c: posc
} = this.runner.getWorkPosition();
// Modal group
const modal = this.runner.getModalGroup();
// Tool
const tool = this.runner.getTool();
return Object.assign(context || {}, {
// User-defined global variables
global: this.sharedContext,
// Bounding box
xmin: Number(context.xmin) || 0,
xmax: Number(context.xmax) || 0,
ymin: Number(context.ymin) || 0,
ymax: Number(context.ymax) || 0,
zmin: Number(context.zmin) || 0,
zmax: Number(context.zmax) || 0,
// Machine position
mposx: Number(mposx) || 0,
mposy: Number(mposy) || 0,
mposz: Number(mposz) || 0,
mposa: Number(mposa) || 0,
mposb: Number(mposb) || 0,
mposc: Number(mposc) || 0,
// Work position
posx: Number(posx) || 0,
posy: Number(posy) || 0,
posz: Number(posz) || 0,
posa: Number(posa) || 0,
posb: Number(posb) || 0,
posc: Number(posc) || 0,
// Modal group
modal: {
motion: modal.motion,
wcs: modal.wcs,
plane: modal.plane,
units: modal.units,
distance: modal.distance,
feedrate: modal.feedrate,
program: modal.program,
spindle: modal.spindle,
// M7 and M8 may be active at the same time, but a modal group violation might occur when issuing M7 and M8 together on the same line. Using the new line character (\n) to separate lines can avoid this issue.
coolant: ensureArray(modal.coolant).join('\n'),
},
// Tool
tool: Number(tool) || 0,
// Global objects
...globalObjects,
});
}
clearActionValues() {
this.actionMask.queryParserState.state = false;
this.actionMask.queryParserState.reply = false;
this.actionMask.queryStatusReport = false;
this.actionMask.replyParserState = false;
this.actionMask.replyStatusReport = false;
this.actionTime.queryParserState = 0;
this.actionTime.queryStatusReport = 0;
this.actionTime.senderFinishTime = 0;
}
destroy() {
if (this.queryTimer) {
clearInterval(this.queryTimer);
this.queryTimer = null;
}
if (this.runner) {
this.runner.removeAllListeners();
this.runner = null;
}
this.sockets = {};
if (this.connection) {
this.connection = null;
}
if (this.event) {
this.event = null;
}
if (this.feeder) {
this.feeder = null;
}
if (this.sender) {
this.sender = null;
}
if (this.workflow) {
this.workflow = null;
}
}
async initController() {
// Check if it is Smoothieware
this.command('gcode', 'version');
await delay(50);
this.event.trigger('controller:ready');
}
get status() {
return {
port: this.options.port,
baudrate: this.options.baudrate,
rtscts: this.options.rtscts,
sockets: Object.keys(this.sockets),
ready: this.ready,
controller: {
type: this.type,
settings: this.settings,
state: this.state
},
feeder: this.feeder.toJSON(),
sender: this.sender.toJSON(),
workflow: {
state: this.workflow.state
}
};
}
open(callback = noop) {
const { port, baudrate } = this.options;
// Assertion check
if (this.isOpen()) {
log.error(`Cannot open serial port "${port}"`);
return;
}
this.connection.on('data', this.connectionEventListener.data);
this.connection.on('close', this.connectionEventListener.close);
this.connection.on('error', this.connectionEventListener.error);
this.connection.open(async (err) => {
if (err) {
log.error(`Error opening serial port "${port}":`, err);
this.emit('serialport:error', { err: err, port: port });
callback(err); // notify error
return;
}
this.emit('serialport:open', {
port: port,
baudrate: baudrate,
controllerType: this.type,
inuse: true
});
// Emit a change event to all connected sockets
if (this.engine.io) {
this.engine.io.emit('serialport:change', {
port: port,
inuse: true
});
}
callback(); // register controller
log.debug(`Connected to serial port "${port}"`);
this.workflow.stop();
// Clear action values
this.clearActionValues();
if (this.sender.state.gcode) {
// Unload G-code
this.command('unload');
}
// Wait for the bootloader to complete before sending commands
await delay(1000);
// Set ready flag to true
this.ready = true;
// Initialize controller
this.initController();
});
}
close(callback) {
const { port } = this.options;
// Assertion check
if (!this.connection) {
const err = `Serial port "${port}" is not available`;
callback(new Error(err));
return;
}
// Stop status query
this.ready = false;
this.emit('serialport:close', {
port: port,
inuse: false
});
// Emit a change event to all connected sockets
if (this.engine.io) {
this.engine.io.emit('serialport:change', {
port: port,
inuse: false
});
}
if (this.isClose()) {
callback(null);
return;
}
this.connection.removeAllListeners();
this.connection.close(callback);
}
isOpen() {
return this.connection && this.connection.isOpen;
}
isClose() {
return !(this.isOpen());
}
addConnection(socket) {
if (!socket) {
log.error('The socket parameter is not specified');
return;
}
log.debug(`Add socket connection: id=${socket.id}`);
this.sockets[socket.id] = socket;
//
// Send data to newly connected client
//
if (this.isOpen()) {
socket.emit('serialport:open', {
port: this.options.port,
baudrate: this.options.baudrate,
controllerType: this.type,
inuse: true
});
}
if (!_.isEmpty(this.settings)) {
// controller settings
socket.emit('controller:settings', SMOOTHIE, this.settings);
socket.emit('Smoothie:settings', this.settings); // Backward compatibility
}
if (!_.isEmpty(this.state)) {
// controller state
socket.emit('controller:state', SMOOTHIE, this.state);
socket.emit('Smoothie:state', this.state); // Backward compatibility
}
if (this.feeder) {
// feeder status
socket.emit('feeder:status', this.feeder.toJSON());
}
if (this.sender) {
// sender status
socket.emit('sender:status', this.sender.toJSON());
const { name, gcode, context } = this.sender.state;
if (gcode) {
socket.emit('gcode:load', name, gcode, context);
}
}
if (this.workflow) {
// workflow state
socket.emit('workflow:state', this.workflow.state);
}
}
removeConnection(socket) {
if (!socket) {
log.error('The socket parameter is not specified');
return;
}
log.debug(`Remove socket connection: id=${socket.id}`);
this.sockets[socket.id] = undefined;
delete this.sockets[socket.id];
}
emit(eventName, ...args) {
Object.keys(this.sockets).forEach(id => {
const socket = this.sockets[id];
socket.emit(eventName, ...args);
});
}
command(cmd, ...args) {
const handler = {
'gcode:load': () => {
let [name, gcode, context = {}, callback = noop] = args;
if (typeof context === 'function') {
callback = context;
context = {};
}
// G4 P0 or P with a very small value will empty the planner queue and then
// respond with an ok when the dwell is complete. At that instant, there will
// be no queued motions, as long as no more commands were sent after the G4.
// This is the fastest way to do it without having to check the status reports.
const dwell = '%wait ; Wait for the planner to empty';
const ok = this.sender.load(name, gcode + '\n' + dwell, context);
if (!ok) {
callback(new Error(`Invalid G-code: name=${name}`));
return;
}
this.emit('gcode:load', name, gcode, context);
this.event.trigger('gcode:load');
log.debug(`Load G-code: name="${this.sender.state.name}", size=${this.sender.state.gcode.length}, total=${this.sender.state.total}`);
this.workflow.stop();
callback(null, this.sender.toJSON());
},
'gcode:unload': () => {
this.workflow.stop();
// Sender
this.sender.unload();
this.emit('gcode:unload');
this.event.trigger('gcode:unload');
},
'start': () => {
log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`);
this.command('gcode:start');
},
'gcode:start': () => {
this.event.trigger('gcode:start');
this.workflow.start();
// Feeder
this.feeder.reset();
// Sender
this.sender.next();
},
'stop': () => {
log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`);
this.command('gcode:stop', ...args);
},
// @param {object} options The options object.
// @param {boolean} [options.force] Whether to force stop a G-code program. Defaults to false.
'gcode:stop': () => {
this.event.trigger('gcode:stop');
this.workflow.stop();
const activeState = _.get(this.state, 'status.activeState', '');
if (activeState === SMOOTHIE_ACTIVE_STATE_HOLD) {
this.write('~'); // resume
}
},
'pause': () => {
log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`);
this.command('gcode:pause');
},
'gcode:pause': () => {
this.event.trigger('gcode:pause');
this.workflow.pause();
this.write('!');
},
'resume': () => {
log.warn(`Warning: The "${cmd}" command is deprecated and will be removed in a future release.`);
this.command('gcode:resume');
},
'gcode:resume': () => {
this.event.trigger('gcode:resume');
this.write('~');
this.workflow.resume();
},
'feeder:feed': () => {
const [commands, context = {}] = args;
this.command('gcode', commands, context);
},
'feeder:start': () => {
if (this.workflow.state === WORKFLOW_STATE_RUNNING) {
return;
}
this.write('~');
this.feeder.unhold();
this.feeder.next();
},
'feeder:stop': () => {
this.feeder.reset();
},
'feedhold': () => {
this.event.trigger('feedhold');
this.write('!');
},
'cyclestart': () => {
this.event.trigger('cyclestart');
this.write('~');
},
'statusreport': () => {
this.write('?');
},
'homing': () => {
this.event.trigger('homing');
this.writeln('$H');
},
'sleep': () => {
this.event.trigger('sleep');
// Not supported
},
'unlock': () => {
this.writeln('$X');
},
'reset': () => {
this.workflow.stop();
this.feeder.reset();
this.write('\x18'); // ^x
},
// Feed Overrides
// @param {number} value A percentage value between 10 and 200. A value of zero will reset to 100%.
'feedOverride': () => {
const [value] = args;
let feedOverride = this.runner.state.status.ovF;
if (value === 0) {
feedOverride = 100;
} else if ((feedOverride + value) > 200) {
feedOverride = 200;
} else if ((feedOverride + value) < 10) {
feedOverride = 10;
} else {
feedOverride += value;
}
this.command('gcode', 'M220S' + feedOverride);
// enforce state change
this.runner.state = {
...this.runner.state,
status: {
...this.runner.state.status,
ovF: feedOverride
}
};
},
// Spindle Speed Overrides
// @param {number} value A percentage value between 10 and 200. A value of zero will reset to 100%.
'spindleOverride': () => {
const [value] = args;
let spindleOverride = this.runner.state.status.ovS;
if (value === 0) {
spindleOverride = 100;
} else if ((spindleOverride + value) > 200) {
spindleOverride = 200;
} else if ((spindleOverride + value) < 10) {
spindleOverride = 10;
} else {
spindleOverride += value;
}
this.command('gcode', 'M221S' + spindleOverride);
// enforce state change
this.runner.state = {
...this.runner.state,
status: {
...this.runner.state.status,
ovS: spindleOverride
}
};
},
// Rapid Overrides
'rapidOverride': () => {
// Not supported
},
'lasertest:on': () => {
const [power = 0, duration = 0] = args;
this.writeln('M3');
// Firing laser at <power>% power and entering manual mode
this.writeln('fire ' + ensurePositiveNumber(power));
if (duration > 0) {
// http://smoothieware.org/g4
// Dwell S<seconds> or P<milliseconds>
// Note that if `grbl_mode` is set to `true`, then the `P` parameter
// is the duration to wait in seconds, not milliseconds, as a float value.
// This is to confirm to G-code standards.
this.writeln('G4P' + ensurePositiveNumber(duration / 1000));
// Turning laser off and returning to auto mode
this.writeln('fire off');
this.writeln('M5');
}
},
'lasertest:off': () => {
// Turning laser off and returning to auto mode
this.writeln('fire off');
this.writeln('M5');
},
'gcode': () => {
const [commands, context] = args;
const data = ensureArray(commands)
.join('\n')
.split(/\r?\n/)
.filter(line => {
if (typeof line !== 'string') {
return false;
}
return line.trim().length > 0;
});
this.feeder.feed(data, context);
if (!this.feeder.isPending()) {
this.feeder.next();
}
},
'macro:run': () => {
let [id, context = {}, callback = noop] = args;
if (typeof context === 'function') {
callback = context;
context = {};
}
const macros = config.get('macros');
const macro = _.find(macros, { id: id });
if (!macro) {
log.error(`Cannot find the macro: id=${id}`);
return;
}
this.event.trigger('macro:run');
this.command('gcode', macro.content, context);
callback(null);
},
'macro:load': () => {
let [id, context = {}, callback = noop] = args;
if (typeof context === 'function') {
callback = context;
context = {};
}
const macros = config.get('macros');
const macro = _.find(macros, { id: id });
if (!macro) {
log.error(`Cannot find the macro: id=${id}`);
return;
}
this.event.trigger('macro:load');
this.command('gcode:load', macro.name, macro.content, context, callback);
},
'watchdir:load': () => {
const [file, callback = noop] = args;
const context = {}; // empty context
monitor.readFile(file, (err, data) => {
if (err) {
callback(err);
return;
}
this.command('gcode:load', file, data, context, callback);
});
}
}[cmd];
if (!handler) {
log.error(`Unknown command: ${cmd}`);
return;
}
handler();
}
write(data, context) {
// Assertion check
if (this.isClose()) {
log.error(`Serial port "${this.options.port}" is not accessible`);
return;
}
const cmd = data.trim();
this.actionMask.replyStatusReport = (cmd === '?') || this.actionMask.replyStatusReport;
this.actionMask.replyParserState = (cmd === '$G') || this.actionMask.replyParserState;
this.emit('serialport:write', data, {
...context,
source: WRITE_SOURCE_CLIENT
});
this.connection.write(data);
log.silly(`> ${data}`);
}
writeln(data, context) {
if (_.includes(SMOOTHIE_REALTIME_COMMANDS, data)) {
this.write(data, context);
} else {
this.write(data + '\n', context);
}
}
}
export default SmoothieController;
|
var app = angular.module('testangular', []);
|
var app = new Vue({
el:'#app',
data:{
indexUpdate: -1,
isActive: false,
newTipoDespesa:{
id:'',
descricao:''
},
tiposDespesa:[]
},
mounted:function(){
this.findAll();
},
methods: {
findAll: function () {
this.$http.get("http://localhost:8080/tipoDespesa/private/")
.then(function (res) {
this.tiposDespesa = res.body;
}, function (res) {
console.log(res);
});
},
updateTipoDespesa: function () {
this.$http.put("http://localhost:8080/tipoDespesa/private/edit", this.newTipoDespesa)
.then(function(res) {
this.findAll();
}, function (res){
window.alert(res.body.mensagem);
});
},
save:function(){
if(this.newTipoDespesa.remoteId==""){
this.add();
}else {
this.updateTipoDespesa();
}
this.clear();
},
add: function () {
this.$http.post("http://localhost:8080/tipoDespesa/private/savenofile", this.newTipoDespesa)
.then(function(res) {
this.findAll();
}, function (res){
window.alert(res.body.mensagem);
});
},
deleteTipoDespesa: function (i) {
this.$http.delete("http://localhost:8080/tipoDespesa/private/" + (i))
.then(function (res) {
this.findAll();
}, function (res) {
console.log(res);
});
},
prepareUpdate :function(i){
this.newTipoDespesa= Vue.util.extend({},this.tiposDespesa[i]);
},
clear: function () {
this.newTipoDespesa = {
id:'',
descricao:''
}
}
}
}) |
#!/usr/bin/env node
'use strict';
var infix = require('..');
var exp = infix.generateExpression(require('./random_expression')(10, 1));
function explicitlyCompile(iterations) {
var f = infix.compile(exp, infix.nativeNumberProvider);
var x = 0;
for (var i = 0; i < iterations; i++) {
x += f(i);
}
return x;
}
function memoizingCompiler(iterations) {
var compile = infix.memoizing.compilerFor(infix.nativeNumberProvider);
var x = 0;
for (var i = 0; i < iterations; i++) {
x += compile(exp)(i);
}
return x;
}
function memoizingEvaluator(iterations) {
var evaluate = infix.memoizing.evaluatorFor(infix.nativeNumberProvider);
var x = 0;
for (var i = 0; i < iterations; i++) {
x += evaluate(exp, i);
}
return x;
}
function nonMemoizing(iterations) {
var evaluate = infix.evaluatorFor(infix.nativeNumberProvider);
var x = 0;
for (var i = 0; i < iterations; i++) {
x += evaluate(exp, i);
}
return x;
}
function time(inner, iterations) {
var start = Date.now();
inner(iterations);
return Date.now() - start;
}
function trial(inner, iterations) {
process.stdout.write("Measuring " + inner.name);
var times = [];
for (var i = 0; i < 10; ++i) {
times.push(time(inner, iterations));
}
times.sort();
var avg = times.slice(2, -2).reduce(function (a, b) { return a+b; }) / 6 / iterations;
console.log(" => " + (avg * 1000000).toFixed(2) + "ns per iteration");
return avg;
}
var a = trial(explicitlyCompile, 10000);
var b = trial(memoizingCompiler, 2000);
var c = trial(memoizingEvaluator, 1000);
var d = trial(nonMemoizing, 100);
console.log(`explicitlyCompile is ${(b/a).toFixed(2)} times as fast as memoizingCompiler`);
console.log(`memoizingCompiler is ${(c/b).toFixed(2)} times as fast as memoizingEvaluator`);
console.log(`memoizingCompiler is ${(d/b).toFixed(2)} times as fast as nonMemoizing`);
|
search_result['516']=["topic_00000000000000FB_props--.html","ApplicantController Properties",""]; |
(function (window, document, Math) {
var rAF = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) { window.setTimeout(callback, 1000 / 60); };
var utils = (function () {
var me = {};
var _elementStyle = document.createElement('div').style;
var _vendor = (function () {
var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
transform,
i = 0,
l = vendors.length;
for ( ; i < l; i++ ) {
transform = vendors[i] + 'ransform';
if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1);
}
return false;
})();
function _prefixStyle (style) {
if ( _vendor === false ) return false;
if ( _vendor === '' ) return style;
return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
}
me.getTime = Date.now || function getTime () { return new Date().getTime(); };
me.extend = function (target, obj) {
for ( var i in obj ) {
target[i] = obj[i];
}
};
me.addEvent = function (el, type, fn, capture) {
el.addEventListener(type, fn, !!capture);
};
me.removeEvent = function (el, type, fn, capture) {
el.removeEventListener(type, fn, !!capture);
};
me.prefixPointerEvent = function (pointerEvent) {
return window.MSPointerEvent ?
'MSPointer' + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10):
pointerEvent;
};
me.momentum = function (current, start, time, lowerMargin, wrapperSize, deceleration) {
var distance = current - start,
speed = Math.abs(distance) / time,
destination,
duration;
deceleration = deceleration === undefined ? 0.0006 : deceleration;
destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 );
duration = speed / deceleration;
if ( destination < lowerMargin ) {
destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
distance = Math.abs(destination - current);
duration = distance / speed;
} else if ( destination > 0 ) {
destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
distance = Math.abs(current) + destination;
duration = distance / speed;
}
return {
destination: Math.round(destination),
duration: duration
};
};
var _transform = _prefixStyle('transform');
me.extend(me, {
hasTransform: _transform !== false,
hasPerspective: _prefixStyle('perspective') in _elementStyle,
hasTouch: 'ontouchstart' in window,
hasPointer: window.PointerEvent || window.MSPointerEvent, // IE10 is prefixed
hasTransition: _prefixStyle('transition') in _elementStyle
});
// This should find all Android browsers lower than build 535.19 (both stock browser and webview)
me.isBadAndroid = /Android /.test(window.navigator.appVersion) && !(/Chrome\/\d/.test(window.navigator.appVersion));
me.extend(me.style = {}, {
transform: _transform,
transitionTimingFunction: _prefixStyle('transitionTimingFunction'),
transitionDuration: _prefixStyle('transitionDuration'),
transitionDelay: _prefixStyle('transitionDelay'),
transformOrigin: _prefixStyle('transformOrigin')
});
me.hasClass = function (e, c) {
var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
return re.test(e.className);
};
me.addClass = function (e, c) {
if ( me.hasClass(e, c) ) {
return;
}
var newclass = e.className.split(' ');
newclass.push(c);
e.className = newclass.join(' ');
};
me.removeClass = function (e, c) {
if ( !me.hasClass(e, c) ) {
return;
}
var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
e.className = e.className.replace(re, ' ');
};
me.offset = function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
// jshint -W084
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
// jshint +W084
return {
left: left,
top: top
};
};
me.preventDefaultException = function (el, exceptions) {
for ( var i in exceptions ) {
if ( exceptions[i].test(el[i]) ) {
return true;
}
}
return false;
};
me.extend(me.eventType = {}, {
touchstart: 1,
touchmove: 1,
touchend: 1,
mousedown: 2,
mousemove: 2,
mouseup: 2,
pointerdown: 3,
pointermove: 3,
pointerup: 3,
MSPointerDown: 3,
MSPointerMove: 3,
MSPointerUp: 3
});
me.extend(me.ease = {}, {
quadratic: {
style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
fn: function (k) {
return k * ( 2 - k );
}
},
circular: {
style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
fn: function (k) {
return Math.sqrt( 1 - ( --k * k ) );
}
},
back: {
style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
fn: function (k) {
var b = 4;
return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1;
}
},
bounce: {
style: '',
fn: function (k) {
if ( ( k /= 1 ) < ( 1 / 2.75 ) ) {
return 7.5625 * k * k;
} else if ( k < ( 2 / 2.75 ) ) {
return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
} else if ( k < ( 2.5 / 2.75 ) ) {
return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
} else {
return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
}
}
},
elastic: {
style: '',
fn: function (k) {
var f = 0.22,
e = 0.4;
if ( k === 0 ) { return 0; }
if ( k == 1 ) { return 1; }
return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 );
}
}
});
me.tap = function (e, eventName) {
var ev = document.createEvent('Event');
ev.initEvent(eventName, true, true);
ev.pageX = e.pageX;
ev.pageY = e.pageY;
e.target.dispatchEvent(ev);
};
me.click = function (e) {
var target = e.target,
ev;
if ( !(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName) ) {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
target.screenX, target.screenY, target.clientX, target.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._constructed = true;
target.dispatchEvent(ev);
}
};
return me;
})();
function IScroll (el, options) {
this.wrapper = typeof el == 'string' ? document.querySelector(el) : el;
this.scroller = this.wrapper.children[0];
this.scrollerStyle = this.scroller.style; // cache style for better performance
this.options = {
resizeScrollbars: true,
mouseWheelSpeed: 20,
snapThreshold: 0.334,
// INSERT POINT: OPTIONS
startX: 0,
startY: 0,
scrollY: true,
directionLockThreshold: 5,
momentum: true,
bounce: true,
bounceTime: 600,
bounceEasing: '',
preventDefault: true,
preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ },
HWCompositing: true,
useTransition: true,
useTransform: true
};
for ( var i in options ) {
this.options[i] = options[i];
}
// Normalize options
this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : '';
this.options.useTransition = utils.hasTransition && this.options.useTransition;
this.options.useTransform = utils.hasTransform && this.options.useTransform;
this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough;
this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;
// If you want eventPassthrough I have to lock one of the axes
this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY;
this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX;
// With eventPassthrough we also need lockDirection mechanism
this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;
this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;
this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;
if ( this.options.tap === true ) {
this.options.tap = 'tap';
}
if ( this.options.shrinkScrollbars == 'scale' ) {
this.options.useTransition = false;
}
this.options.invertWheelDirection = this.options.invertWheelDirection ? -1 : 1;
if ( this.options.probeType == 3 ) {
this.options.useTransition = false; }
// INSERT POINT: NORMALIZATION
// Some defaults
this.x = 0;
this.y = 0;
this.directionX = 0;
this.directionY = 0;
this._events = {};
// INSERT POINT: DEFAULTS
this._init();
this.refresh();
this.scrollTo(this.options.startX, this.options.startY);
this.enable();
}
IScroll.prototype = {
version: '5.1.2',
_init: function () {
this._initEvents();
if ( this.options.scrollbars || this.options.indicators ) {
this._initIndicators();
}
if ( this.options.mouseWheel ) {
this._initWheel();
}
if ( this.options.snap ) {
this._initSnap();
}
if ( this.options.keyBindings ) {
this._initKeys();
}
// INSERT POINT: _init
},
destroy: function () {
this._initEvents(true);
this._execEvent('destroy');
},
_transitionEnd: function (e) {
if ( e.target != this.scroller || !this.isInTransition ) {
return;
}
this._transitionTime();
if ( !this.resetPosition(this.options.bounceTime) ) {
this.isInTransition = false;
this._execEvent('scrollEnd');
}
},
_start: function (e) {
// React to left mouse button only
if ( utils.eventType[e.type] != 1 ) {
if ( e.button !== 0 ) {
return;
}
}
if ( !this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated) ) {
return;
}
if ( this.options.preventDefault && !utils.isBadAndroid && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
e.preventDefault();
}
var point = e.touches ? e.touches[0] : e,
pos;
this.initiated = utils.eventType[e.type];
this.moved = false;
this.distX = 0;
this.distY = 0;
this.directionX = 0;
this.directionY = 0;
this.directionLocked = 0;
this._transitionTime();
this.startTime = utils.getTime();
if ( this.options.useTransition && this.isInTransition ) {
this.isInTransition = false;
pos = this.getComputedPosition();
this._translate(Math.round(pos.x), Math.round(pos.y));
this._execEvent('scrollEnd');
} else if ( !this.options.useTransition && this.isAnimating ) {
this.isAnimating = false;
this._execEvent('scrollEnd');
}
this.startX = this.x;
this.startY = this.y;
this.absStartX = this.x;
this.absStartY = this.y;
this.pointX = point.pageX;
this.pointY = point.pageY;
this._execEvent('beforeScrollStart');
},
_move: function (e) {
if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
return;
}
if ( this.options.preventDefault ) { // increases performance on Android? TODO: check!
e.preventDefault();
}
var point = e.touches ? e.touches[0] : e,
deltaX = point.pageX - this.pointX,
deltaY = point.pageY - this.pointY,
timestamp = utils.getTime(),
newX, newY,
absDistX, absDistY;
this.pointX = point.pageX;
this.pointY = point.pageY;
this.distX += deltaX;
this.distY += deltaY;
absDistX = Math.abs(this.distX);
absDistY = Math.abs(this.distY);
// We need to move at least 10 pixels for the scrolling to initiate
if ( timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10) ) {
return;
}
// If you are scrolling in one direction lock the other
if ( !this.directionLocked && !this.options.freeScroll ) {
if ( absDistX > absDistY + this.options.directionLockThreshold ) {
this.directionLocked = 'h'; // lock horizontally
} else if ( absDistY >= absDistX + this.options.directionLockThreshold ) {
this.directionLocked = 'v'; // lock vertically
} else {
this.directionLocked = 'n'; // no lock
}
}
if ( this.directionLocked == 'h' ) {
if ( this.options.eventPassthrough == 'vertical' ) {
e.preventDefault();
} else if ( this.options.eventPassthrough == 'horizontal' ) {
this.initiated = false;
return;
}
deltaY = 0;
} else if ( this.directionLocked == 'v' ) {
if ( this.options.eventPassthrough == 'horizontal' ) {
e.preventDefault();
} else if ( this.options.eventPassthrough == 'vertical' ) {
this.initiated = false;
return;
}
deltaX = 0;
}
deltaX = this.hasHorizontalScroll ? deltaX : 0;
deltaY = this.hasVerticalScroll ? deltaY : 0;
newX = this.x + deltaX;
newY = this.y + deltaY;
// Slow down if outside of the boundaries
if ( newX > 0 || newX < this.maxScrollX ) {
newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
}
if ( newY > 0 || newY < this.maxScrollY ) {
newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
}
this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if ( !this.moved ) {
this._execEvent('scrollStart');
}
this.moved = true;
this._translate(newX, newY);
/* REPLACE START: _move */
if ( timestamp - this.startTime > 300 ) {
this.startTime = timestamp;
this.startX = this.x;
this.startY = this.y;
if ( this.options.probeType == 1 ) {
this._execEvent('scroll');
}
}
if ( this.options.probeType > 1 ) {
this._execEvent('scroll');
}
/* REPLACE END: _move */
},
_end: function (e) {
if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
return;
}
if ( this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
e.preventDefault();
}
var point = e.changedTouches ? e.changedTouches[0] : e,
momentumX,
momentumY,
duration = utils.getTime() - this.startTime,
newX = Math.round(this.x),
newY = Math.round(this.y),
distanceX = Math.abs(newX - this.startX),
distanceY = Math.abs(newY - this.startY),
time = 0,
easing = '';
this.isInTransition = 0;
this.initiated = 0;
this.endTime = utils.getTime();
// reset if we are outside of the boundaries
if ( this.resetPosition(this.options.bounceTime) ) {
return;
}
this.scrollTo(newX, newY); // ensures that the last position is rounded
// we scrolled less than 10 pixels
if ( !this.moved ) {
if ( this.options.tap ) {
utils.tap(e, this.options.tap);
}
if ( this.options.click ) {
utils.click(e);
}
this._execEvent('scrollCancel');
return;
}
if ( this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100 ) {
this._execEvent('flick');
return;
}
// start momentum animation if needed
if ( this.options.momentum && duration < 300 ) {
momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options.deceleration) : { destination: newX, duration: 0 };
momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options.deceleration) : { destination: newY, duration: 0 };
newX = momentumX.destination;
newY = momentumY.destination;
time = Math.max(momentumX.duration, momentumY.duration);
this.isInTransition = 1;
}
if ( this.options.snap ) {
var snap = this._nearestSnap(newX, newY);
this.currentPage = snap;
time = this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(newX - snap.x), 1000),
Math.min(Math.abs(newY - snap.y), 1000)
), 300);
newX = snap.x;
newY = snap.y;
this.directionX = 0;
this.directionY = 0;
easing = this.options.bounceEasing;
}
// INSERT POINT: _end
if ( newX != this.x || newY != this.y ) {
// change easing function when scroller goes out of the boundaries
if ( newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY ) {
easing = utils.ease.quadratic;
}
this.scrollTo(newX, newY, time, easing);
return;
}
this._execEvent('scrollEnd');
},
_resize: function () {
var that = this;
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(function () {
that.refresh();
}, this.options.resizePolling);
},
resetPosition: function (time) {
var x = this.x,
y = this.y;
time = time || 0;
if ( !this.hasHorizontalScroll || this.x > 0 ) {
x = 0;
} else if ( this.x < this.maxScrollX ) {
x = this.maxScrollX;
}
if ( !this.hasVerticalScroll || this.y > 0 ) {
y = 0;
} else if ( this.y < this.maxScrollY ) {
y = this.maxScrollY;
}
if ( x == this.x && y == this.y ) {
return false;
}
this.scrollTo(x, y, time, this.options.bounceEasing);
return true;
},
disable: function () {
this.enabled = false;
},
enable: function () {
this.enabled = true;
},
refresh: function () {
var rf = this.wrapper.offsetHeight; // Force reflow
this.wrapperWidth = this.wrapper.clientWidth;
this.wrapperHeight = this.wrapper.clientHeight;
/* REPLACE START: refresh */
this.scrollerWidth = this.scroller.offsetWidth;
this.scrollerHeight = this.scroller.offsetHeight;
this.maxScrollX = this.wrapperWidth - this.scrollerWidth;
this.maxScrollY = this.wrapperHeight - this.scrollerHeight;
/* REPLACE END: refresh */
this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0;
this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0;
if ( !this.hasHorizontalScroll ) {
this.maxScrollX = 0;
this.scrollerWidth = this.wrapperWidth;
}
if ( !this.hasVerticalScroll ) {
this.maxScrollY = 0;
this.scrollerHeight = this.wrapperHeight;
}
this.endTime = 0;
this.directionX = 0;
this.directionY = 0;
this.wrapperOffset = utils.offset(this.wrapper);
this._execEvent('refresh');
this.resetPosition();
// INSERT POINT: _refresh
},
on: function (type, fn) {
if ( !this._events[type] ) {
this._events[type] = [];
}
this._events[type].push(fn);
},
off: function (type, fn) {
if ( !this._events[type] ) {
return;
}
var index = this._events[type].indexOf(fn);
if ( index > -1 ) {
this._events[type].splice(index, 1);
}
},
_execEvent: function (type) {
if ( !this._events[type] ) {
return;
}
var i = 0,
l = this._events[type].length;
if ( !l ) {
return;
}
for ( ; i < l; i++ ) {
this._events[type][i].apply(this, [].slice.call(arguments, 1));
}
},
scrollBy: function (x, y, time, easing) {
x = this.x + x;
y = this.y + y;
time = time || 0;
this.scrollTo(x, y, time, easing);
},
scrollTo: function (x, y, time, easing) {
easing = easing || utils.ease.circular;
this.isInTransition = this.options.useTransition && time > 0;
if ( !time || (this.options.useTransition && easing.style) ) {
this._transitionTimingFunction(easing.style);
this._transitionTime(time);
this._translate(x, y);
} else {
this._animate(x, y, time, easing.fn);
}
},
scrollToElement: function (el, time, offsetX, offsetY, easing) {
el = el.nodeType ? el : this.scroller.querySelector(el);
if ( !el ) {
return;
}
var pos = utils.offset(el);
pos.left -= this.wrapperOffset.left;
pos.top -= this.wrapperOffset.top;
// if offsetX/Y are true we center the element to the screen
if ( offsetX === true ) {
offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2);
}
if ( offsetY === true ) {
offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2);
}
pos.left -= offsetX || 0;
pos.top -= offsetY || 0;
pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top;
time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x-pos.left), Math.abs(this.y-pos.top)) : time;
this.scrollTo(pos.left, pos.top, time, easing);
},
_transitionTime: function (time) {
time = time || 0;
this.scrollerStyle[utils.style.transitionDuration] = time + 'ms';
if ( !time && utils.isBadAndroid ) {
this.scrollerStyle[utils.style.transitionDuration] = '0.001s';
}
if ( this.indicators ) {
for ( var i = this.indicators.length; i--; ) {
this.indicators[i].transitionTime(time);
}
}
// INSERT POINT: _transitionTime
},
_transitionTimingFunction: function (easing) {
this.scrollerStyle[utils.style.transitionTimingFunction] = easing;
if ( this.indicators ) {
for ( var i = this.indicators.length; i--; ) {
this.indicators[i].transitionTimingFunction(easing);
}
}
// INSERT POINT: _transitionTimingFunction
},
_translate: function (x, y) {
if ( this.options.useTransform ) {
/* REPLACE START: _translate */
this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ;
/* REPLACE END: _translate */
} else {
x = Math.round(x);
y = Math.round(y);
this.scrollerStyle.left = x + 'px';
this.scrollerStyle.top = y + 'px';
}
this.x = x;
this.y = y;
if ( this.indicators ) {
for ( var i = this.indicators.length; i--; ) {
this.indicators[i].updatePosition();
}
}
// INSERT POINT: _translate
},
_initEvents: function (remove) {
var eventType = remove ? utils.removeEvent : utils.addEvent,
target = this.options.bindToWrapper ? this.wrapper : window;
eventType(window, 'orientationchange', this);
eventType(window, 'resize', this);
if ( this.options.click ) {
eventType(this.wrapper, 'click', this, true);
}
if ( !this.options.disableMouse ) {
eventType(this.wrapper, 'mousedown', this);
eventType(target, 'mousemove', this);
eventType(target, 'mousecancel', this);
eventType(target, 'mouseup', this);
}
if ( utils.hasPointer && !this.options.disablePointer ) {
eventType(this.wrapper, utils.prefixPointerEvent('pointerdown'), this);
eventType(target, utils.prefixPointerEvent('pointermove'), this);
eventType(target, utils.prefixPointerEvent('pointercancel'), this);
eventType(target, utils.prefixPointerEvent('pointerup'), this);
}
if ( utils.hasTouch && !this.options.disableTouch ) {
eventType(this.wrapper, 'touchstart', this);
eventType(target, 'touchmove', this);
eventType(target, 'touchcancel', this);
eventType(target, 'touchend', this);
}
eventType(this.scroller, 'transitionend', this);
eventType(this.scroller, 'webkitTransitionEnd', this);
eventType(this.scroller, 'oTransitionEnd', this);
eventType(this.scroller, 'MSTransitionEnd', this);
},
getComputedPosition: function () {
var matrix = window.getComputedStyle(this.scroller, null),
x, y;
if ( this.options.useTransform ) {
matrix = matrix[utils.style.transform].split(')')[0].split(', ');
x = +(matrix[12] || matrix[4]);
y = +(matrix[13] || matrix[5]);
} else {
x = +matrix.left.replace(/[^-\d.]/g, '');
y = +matrix.top.replace(/[^-\d.]/g, '');
}
return { x: x, y: y };
},
_initIndicators: function () {
var interactive = this.options.interactiveScrollbars,
customStyle = typeof this.options.scrollbars != 'string',
indicators = [],
indicator;
var that = this;
this.indicators = [];
if ( this.options.scrollbars ) {
// Vertical scrollbar
if ( this.options.scrollY ) {
indicator = {
el: createDefaultScrollbar('v', interactive, this.options.scrollbars),
interactive: interactive,
defaultScrollbars: true,
customStyle: customStyle,
resize: this.options.resizeScrollbars,
shrink: this.options.shrinkScrollbars,
fade: this.options.fadeScrollbars,
listenX: false
};
this.wrapper.appendChild(indicator.el);
indicators.push(indicator);
}
// Horizontal scrollbar
if ( this.options.scrollX ) {
indicator = {
el: createDefaultScrollbar('h', interactive, this.options.scrollbars),
interactive: interactive,
defaultScrollbars: true,
customStyle: customStyle,
resize: this.options.resizeScrollbars,
shrink: this.options.shrinkScrollbars,
fade: this.options.fadeScrollbars,
listenY: false
};
this.wrapper.appendChild(indicator.el);
indicators.push(indicator);
}
}
if ( this.options.indicators ) {
// TODO: check concat compatibility
indicators = indicators.concat(this.options.indicators);
}
for ( var i = indicators.length; i--; ) {
this.indicators.push( new Indicator(this, indicators[i]) );
}
// TODO: check if we can use array.map (wide compatibility and performance issues)
function _indicatorsMap (fn) {
for ( var i = that.indicators.length; i--; ) {
fn.call(that.indicators[i]);
}
}
if ( this.options.fadeScrollbars ) {
this.on('scrollEnd', function () {
_indicatorsMap(function () {
this.fade();
});
});
this.on('scrollCancel', function () {
_indicatorsMap(function () {
this.fade();
});
});
this.on('scrollStart', function () {
_indicatorsMap(function () {
this.fade(1);
});
});
this.on('beforeScrollStart', function () {
_indicatorsMap(function () {
this.fade(1, true);
});
});
}
this.on('refresh', function () {
_indicatorsMap(function () {
this.refresh();
});
});
this.on('destroy', function () {
_indicatorsMap(function () {
this.destroy();
});
delete this.indicators;
});
},
_initWheel: function () {
utils.addEvent(this.wrapper, 'wheel', this);
utils.addEvent(this.wrapper, 'mousewheel', this);
utils.addEvent(this.wrapper, 'DOMMouseScroll', this);
this.on('destroy', function () {
utils.removeEvent(this.wrapper, 'wheel', this);
utils.removeEvent(this.wrapper, 'mousewheel', this);
utils.removeEvent(this.wrapper, 'DOMMouseScroll', this);
});
},
_wheel: function (e) {
if ( !this.enabled ) {
return;
}
e.preventDefault();
e.stopPropagation();
var wheelDeltaX, wheelDeltaY,
newX, newY,
that = this;
if ( this.wheelTimeout === undefined ) {
that._execEvent('scrollStart');
}
// Execute the scrollEnd event after 400ms the wheel stopped scrolling
clearTimeout(this.wheelTimeout);
this.wheelTimeout = setTimeout(function () {
that._execEvent('scrollEnd');
that.wheelTimeout = undefined;
}, 400);
if ( 'deltaX' in e ) {
wheelDeltaX = -e.deltaX;
wheelDeltaY = -e.deltaY;
} else if ( 'wheelDeltaX' in e ) {
wheelDeltaX = e.wheelDeltaX / 120 * this.options.mouseWheelSpeed;
wheelDeltaY = e.wheelDeltaY / 120 * this.options.mouseWheelSpeed;
} else if ( 'wheelDelta' in e ) {
wheelDeltaX = wheelDeltaY = e.wheelDelta / 120 * this.options.mouseWheelSpeed;
} else if ( 'detail' in e ) {
wheelDeltaX = wheelDeltaY = -e.detail / 3 * this.options.mouseWheelSpeed;
} else {
return;
}
wheelDeltaX *= this.options.invertWheelDirection;
wheelDeltaY *= this.options.invertWheelDirection;
if ( !this.hasVerticalScroll ) {
wheelDeltaX = wheelDeltaY;
wheelDeltaY = 0;
}
if ( this.options.snap ) {
newX = this.currentPage.pageX;
newY = this.currentPage.pageY;
if ( wheelDeltaX > 0 ) {
newX--;
} else if ( wheelDeltaX < 0 ) {
newX++;
}
if ( wheelDeltaY > 0 ) {
newY--;
} else if ( wheelDeltaY < 0 ) {
newY++;
}
this.goToPage(newX, newY);
return;
}
newX = this.x + Math.round(this.hasHorizontalScroll ? wheelDeltaX : 0);
newY = this.y + Math.round(this.hasVerticalScroll ? wheelDeltaY : 0);
if ( newX > 0 ) {
newX = 0;
} else if ( newX < this.maxScrollX ) {
newX = this.maxScrollX;
}
if ( newY > 0 ) {
newY = 0;
} else if ( newY < this.maxScrollY ) {
newY = this.maxScrollY;
}
this.scrollTo(newX, newY, 0);
if ( this.options.probeType > 1 ) {
this._execEvent('scroll');
}
// INSERT POINT: _wheel
},
_initSnap: function () {
this.currentPage = {};
if ( typeof this.options.snap == 'string' ) {
this.options.snap = this.scroller.querySelectorAll(this.options.snap);
}
this.on('refresh', function () {
var i = 0, l,
m = 0, n,
cx, cy,
x = 0, y,
stepX = this.options.snapStepX || this.wrapperWidth,
stepY = this.options.snapStepY || this.wrapperHeight,
el;
this.pages = [];
if ( !this.wrapperWidth || !this.wrapperHeight || !this.scrollerWidth || !this.scrollerHeight ) {
return;
}
if ( this.options.snap === true ) {
cx = Math.round( stepX / 2 );
cy = Math.round( stepY / 2 );
while ( x > -this.scrollerWidth ) {
this.pages[i] = [];
l = 0;
y = 0;
while ( y > -this.scrollerHeight ) {
this.pages[i][l] = {
x: Math.max(x, this.maxScrollX),
y: Math.max(y, this.maxScrollY),
width: stepX,
height: stepY,
cx: x - cx,
cy: y - cy
};
y -= stepY;
l++;
}
x -= stepX;
i++;
}
} else {
el = this.options.snap;
l = el.length;
n = -1;
for ( ; i < l; i++ ) {
if ( i === 0 || el[i].offsetLeft <= el[i-1].offsetLeft ) {
m = 0;
n++;
}
if ( !this.pages[m] ) {
this.pages[m] = [];
}
x = Math.max(-el[i].offsetLeft, this.maxScrollX);
y = Math.max(-el[i].offsetTop, this.maxScrollY);
cx = x - Math.round(el[i].offsetWidth / 2);
cy = y - Math.round(el[i].offsetHeight / 2);
this.pages[m][n] = {
x: x,
y: y,
width: el[i].offsetWidth,
height: el[i].offsetHeight,
cx: cx,
cy: cy
};
if ( x > this.maxScrollX ) {
m++;
}
}
}
this.goToPage(this.currentPage.pageX || 0, this.currentPage.pageY || 0, 0);
// Update snap threshold if needed
if ( this.options.snapThreshold % 1 === 0 ) {
this.snapThresholdX = this.options.snapThreshold;
this.snapThresholdY = this.options.snapThreshold;
} else {
this.snapThresholdX = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].width * this.options.snapThreshold);
this.snapThresholdY = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].height * this.options.snapThreshold);
}
});
this.on('flick', function () {
var time = this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(this.x - this.startX), 1000),
Math.min(Math.abs(this.y - this.startY), 1000)
), 300);
this.goToPage(
this.currentPage.pageX + this.directionX,
this.currentPage.pageY + this.directionY,
time
);
});
},
_nearestSnap: function (x, y) {
if ( !this.pages.length ) {
return { x: 0, y: 0, pageX: 0, pageY: 0 };
}
var i = 0,
l = this.pages.length,
m = 0;
// Check if we exceeded the snap threshold
if ( Math.abs(x - this.absStartX) < this.snapThresholdX &&
Math.abs(y - this.absStartY) < this.snapThresholdY ) {
return this.currentPage;
}
if ( x > 0 ) {
x = 0;
} else if ( x < this.maxScrollX ) {
x = this.maxScrollX;
}
if ( y > 0 ) {
y = 0;
} else if ( y < this.maxScrollY ) {
y = this.maxScrollY;
}
for ( ; i < l; i++ ) {
if ( x >= this.pages[i][0].cx ) {
x = this.pages[i][0].x;
break;
}
}
l = this.pages[i].length;
for ( ; m < l; m++ ) {
if ( y >= this.pages[0][m].cy ) {
y = this.pages[0][m].y;
break;
}
}
if ( i == this.currentPage.pageX ) {
i += this.directionX;
if ( i < 0 ) {
i = 0;
} else if ( i >= this.pages.length ) {
i = this.pages.length - 1;
}
x = this.pages[i][0].x;
}
if ( m == this.currentPage.pageY ) {
m += this.directionY;
if ( m < 0 ) {
m = 0;
} else if ( m >= this.pages[0].length ) {
m = this.pages[0].length - 1;
}
y = this.pages[0][m].y;
}
return {
x: x,
y: y,
pageX: i,
pageY: m
};
},
goToPage: function (x, y, time, easing) {
easing = easing || this.options.bounceEasing;
if ( x >= this.pages.length ) {
x = this.pages.length - 1;
} else if ( x < 0 ) {
x = 0;
}
if ( y >= this.pages[x].length ) {
y = this.pages[x].length - 1;
} else if ( y < 0 ) {
y = 0;
}
var posX = this.pages[x][y].x,
posY = this.pages[x][y].y;
time = time === undefined ? this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(posX - this.x), 1000),
Math.min(Math.abs(posY - this.y), 1000)
), 300) : time;
this.currentPage = {
x: posX,
y: posY,
pageX: x,
pageY: y
};
this.scrollTo(posX, posY, time, easing);
},
next: function (time, easing) {
var x = this.currentPage.pageX,
y = this.currentPage.pageY;
x++;
if ( x >= this.pages.length && this.hasVerticalScroll ) {
x = 0;
y++;
}
this.goToPage(x, y, time, easing);
},
prev: function (time, easing) {
var x = this.currentPage.pageX,
y = this.currentPage.pageY;
x--;
if ( x < 0 && this.hasVerticalScroll ) {
x = 0;
y--;
}
this.goToPage(x, y, time, easing);
},
_initKeys: function (e) {
// default key bindings
var keys = {
pageUp: 33,
pageDown: 34,
end: 35,
home: 36,
left: 37,
up: 38,
right: 39,
down: 40
};
var i;
// if you give me characters I give you keycode
if ( typeof this.options.keyBindings == 'object' ) {
for ( i in this.options.keyBindings ) {
if ( typeof this.options.keyBindings[i] == 'string' ) {
this.options.keyBindings[i] = this.options.keyBindings[i].toUpperCase().charCodeAt(0);
}
}
} else {
this.options.keyBindings = {};
}
for ( i in keys ) {
this.options.keyBindings[i] = this.options.keyBindings[i] || keys[i];
}
utils.addEvent(window, 'keydown', this);
this.on('destroy', function () {
utils.removeEvent(window, 'keydown', this);
});
},
_key: function (e) {
if ( !this.enabled ) {
return;
}
var snap = this.options.snap, // we are using this alot, better to cache it
newX = snap ? this.currentPage.pageX : this.x,
newY = snap ? this.currentPage.pageY : this.y,
now = utils.getTime(),
prevTime = this.keyTime || 0,
acceleration = 0.250,
pos;
if ( this.options.useTransition && this.isInTransition ) {
pos = this.getComputedPosition();
this._translate(Math.round(pos.x), Math.round(pos.y));
this.isInTransition = false;
}
this.keyAcceleration = now - prevTime < 200 ? Math.min(this.keyAcceleration + acceleration, 50) : 0;
switch ( e.keyCode ) {
case this.options.keyBindings.pageUp:
if ( this.hasHorizontalScroll && !this.hasVerticalScroll ) {
newX += snap ? 1 : this.wrapperWidth;
} else {
newY += snap ? 1 : this.wrapperHeight;
}
break;
case this.options.keyBindings.pageDown:
if ( this.hasHorizontalScroll && !this.hasVerticalScroll ) {
newX -= snap ? 1 : this.wrapperWidth;
} else {
newY -= snap ? 1 : this.wrapperHeight;
}
break;
case this.options.keyBindings.end:
newX = snap ? this.pages.length-1 : this.maxScrollX;
newY = snap ? this.pages[0].length-1 : this.maxScrollY;
break;
case this.options.keyBindings.home:
newX = 0;
newY = 0;
break;
case this.options.keyBindings.left:
newX += snap ? -1 : 5 + this.keyAcceleration>>0;
break;
case this.options.keyBindings.up:
newY += snap ? 1 : 5 + this.keyAcceleration>>0;
break;
case this.options.keyBindings.right:
newX -= snap ? -1 : 5 + this.keyAcceleration>>0;
break;
case this.options.keyBindings.down:
newY -= snap ? 1 : 5 + this.keyAcceleration>>0;
break;
default:
return;
}
if ( snap ) {
this.goToPage(newX, newY);
return;
}
if ( newX > 0 ) {
newX = 0;
this.keyAcceleration = 0;
} else if ( newX < this.maxScrollX ) {
newX = this.maxScrollX;
this.keyAcceleration = 0;
}
if ( newY > 0 ) {
newY = 0;
this.keyAcceleration = 0;
} else if ( newY < this.maxScrollY ) {
newY = this.maxScrollY;
this.keyAcceleration = 0;
}
this.scrollTo(newX, newY, 0);
this.keyTime = now;
},
_animate: function (destX, destY, duration, easingFn) {
var that = this,
startX = this.x,
startY = this.y,
startTime = utils.getTime(),
destTime = startTime + duration;
function step () {
var now = utils.getTime(),
newX, newY,
easing;
if ( now >= destTime ) {
that.isAnimating = false;
that._translate(destX, destY);
if ( !that.resetPosition(that.options.bounceTime) ) {
that._execEvent('scrollEnd');
}
return;
}
now = ( now - startTime ) / duration;
easing = easingFn(now);
newX = ( destX - startX ) * easing + startX;
newY = ( destY - startY ) * easing + startY;
that._translate(newX, newY);
if ( that.isAnimating ) {
rAF(step);
}
if ( that.options.probeType == 3 ) {
that._execEvent('scroll');
}
}
this.isAnimating = true;
step();
},
handleEvent: function (e) {
switch ( e.type ) {
case 'touchstart':
case 'pointerdown':
case 'MSPointerDown':
case 'mousedown':
this._start(e);
break;
case 'touchmove':
case 'pointermove':
case 'MSPointerMove':
case 'mousemove':
this._move(e);
break;
case 'touchend':
case 'pointerup':
case 'MSPointerUp':
case 'mouseup':
case 'touchcancel':
case 'pointercancel':
case 'MSPointerCancel':
case 'mousecancel':
this._end(e);
break;
case 'orientationchange':
case 'resize':
this._resize();
break;
case 'transitionend':
case 'webkitTransitionEnd':
case 'oTransitionEnd':
case 'MSTransitionEnd':
this._transitionEnd(e);
break;
case 'wheel':
case 'DOMMouseScroll':
case 'mousewheel':
this._wheel(e);
break;
case 'keydown':
this._key(e);
break;
case 'click':
if ( !e._constructed ) {
e.preventDefault();
e.stopPropagation();
}
break;
}
}
};
function createDefaultScrollbar (direction, interactive, type) {
var scrollbar = document.createElement('div'),
indicator = document.createElement('div');
if ( type === true ) {
scrollbar.style.cssText = 'position:absolute;z-index:9999';
indicator.style.cssText = '-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);border-radius:3px';
}
indicator.className = 'iScrollIndicator';
if ( direction == 'h' ) {
if ( type === true ) {
scrollbar.style.cssText += ';height:7px;left:2px;right:2px;bottom:0';
indicator.style.height = '100%';
}
scrollbar.className = 'iScrollHorizontalScrollbar';
} else {
if ( type === true ) {
scrollbar.style.cssText += ';width:7px;bottom:2px;top:2px;right:1px';
indicator.style.width = '100%';
}
scrollbar.className = 'iScrollVerticalScrollbar';
}
scrollbar.style.cssText += ';overflow:hidden';
if ( !interactive ) {
scrollbar.style.pointerEvents = 'none';
}
scrollbar.appendChild(indicator);
return scrollbar;
}
function Indicator (scroller, options) {
this.wrapper = typeof options.el == 'string' ? document.querySelector(options.el) : options.el;
this.wrapperStyle = this.wrapper.style;
this.indicator = this.wrapper.children[0];
this.indicatorStyle = this.indicator.style;
this.scroller = scroller;
this.options = {
listenX: true,
listenY: true,
interactive: false,
resize: true,
defaultScrollbars: false,
shrink: false,
fade: false,
speedRatioX: 0,
speedRatioY: 0
};
for ( var i in options ) {
this.options[i] = options[i];
}
this.sizeRatioX = 1;
this.sizeRatioY = 1;
this.maxPosX = 0;
this.maxPosY = 0;
if ( this.options.interactive ) {
if ( !this.options.disableTouch ) {
utils.addEvent(this.indicator, 'touchstart', this);
utils.addEvent(window, 'touchend', this);
}
if ( !this.options.disablePointer ) {
utils.addEvent(this.indicator, utils.prefixPointerEvent('pointerdown'), this);
utils.addEvent(window, utils.prefixPointerEvent('pointerup'), this);
}
if ( !this.options.disableMouse ) {
utils.addEvent(this.indicator, 'mousedown', this);
utils.addEvent(window, 'mouseup', this);
}
}
if ( this.options.fade ) {
this.wrapperStyle[utils.style.transform] = this.scroller.translateZ;
this.wrapperStyle[utils.style.transitionDuration] = utils.isBadAndroid ? '0.001s' : '0ms';
this.wrapperStyle.opacity = '0';
}
}
Indicator.prototype = {
handleEvent: function (e) {
switch ( e.type ) {
case 'touchstart':
case 'pointerdown':
case 'MSPointerDown':
case 'mousedown':
this._start(e);
break;
case 'touchmove':
case 'pointermove':
case 'MSPointerMove':
case 'mousemove':
this._move(e);
break;
case 'touchend':
case 'pointerup':
case 'MSPointerUp':
case 'mouseup':
case 'touchcancel':
case 'pointercancel':
case 'MSPointerCancel':
case 'mousecancel':
this._end(e);
break;
}
},
destroy: function () {
if ( this.options.interactive ) {
utils.removeEvent(this.indicator, 'touchstart', this);
utils.removeEvent(this.indicator, utils.prefixPointerEvent('pointerdown'), this);
utils.removeEvent(this.indicator, 'mousedown', this);
utils.removeEvent(window, 'touchmove', this);
utils.removeEvent(window, utils.prefixPointerEvent('pointermove'), this);
utils.removeEvent(window, 'mousemove', this);
utils.removeEvent(window, 'touchend', this);
utils.removeEvent(window, utils.prefixPointerEvent('pointerup'), this);
utils.removeEvent(window, 'mouseup', this);
}
if ( this.options.defaultScrollbars ) {
this.wrapper.parentNode.removeChild(this.wrapper);
}
},
_start: function (e) {
var point = e.touches ? e.touches[0] : e;
e.preventDefault();
e.stopPropagation();
this.transitionTime();
this.initiated = true;
this.moved = false;
this.lastPointX = point.pageX;
this.lastPointY = point.pageY;
this.startTime = utils.getTime();
if ( !this.options.disableTouch ) {
utils.addEvent(window, 'touchmove', this);
}
if ( !this.options.disablePointer ) {
utils.addEvent(window, utils.prefixPointerEvent('pointermove'), this);
}
if ( !this.options.disableMouse ) {
utils.addEvent(window, 'mousemove', this);
}
this.scroller._execEvent('beforeScrollStart');
},
_move: function (e) {
var point = e.touches ? e.touches[0] : e,
deltaX, deltaY,
newX, newY,
timestamp = utils.getTime();
if ( !this.moved ) {
this.scroller._execEvent('scrollStart');
}
this.moved = true;
deltaX = point.pageX - this.lastPointX;
this.lastPointX = point.pageX;
deltaY = point.pageY - this.lastPointY;
this.lastPointY = point.pageY;
newX = this.x + deltaX;
newY = this.y + deltaY;
this._pos(newX, newY);
if ( this.scroller.options.probeType == 1 && timestamp - this.startTime > 300 ) {
this.startTime = timestamp;
this.scroller._execEvent('scroll');
} else if ( this.scroller.options.probeType > 1 ) {
this.scroller._execEvent('scroll');
}
// INSERT POINT: indicator._move
e.preventDefault();
e.stopPropagation();
},
_end: function (e) {
if ( !this.initiated ) {
return;
}
this.initiated = false;
e.preventDefault();
e.stopPropagation();
utils.removeEvent(window, 'touchmove', this);
utils.removeEvent(window, utils.prefixPointerEvent('pointermove'), this);
utils.removeEvent(window, 'mousemove', this);
if ( this.scroller.options.snap ) {
var snap = this.scroller._nearestSnap(this.scroller.x, this.scroller.y);
var time = this.options.snapSpeed || Math.max(
Math.max(
Math.min(Math.abs(this.scroller.x - snap.x), 1000),
Math.min(Math.abs(this.scroller.y - snap.y), 1000)
), 300);
if ( this.scroller.x != snap.x || this.scroller.y != snap.y ) {
this.scroller.directionX = 0;
this.scroller.directionY = 0;
this.scroller.currentPage = snap;
this.scroller.scrollTo(snap.x, snap.y, time, this.scroller.options.bounceEasing);
}
}
if ( this.moved ) {
this.scroller._execEvent('scrollEnd');
}
},
transitionTime: function (time) {
time = time || 0;
this.indicatorStyle[utils.style.transitionDuration] = time + 'ms';
if ( !time && utils.isBadAndroid ) {
this.indicatorStyle[utils.style.transitionDuration] = '0.001s';
}
},
transitionTimingFunction: function (easing) {
this.indicatorStyle[utils.style.transitionTimingFunction] = easing;
},
refresh: function () {
this.transitionTime();
if ( this.options.listenX && !this.options.listenY ) {
this.indicatorStyle.display = this.scroller.hasHorizontalScroll ? 'block' : 'none';
} else if ( this.options.listenY && !this.options.listenX ) {
this.indicatorStyle.display = this.scroller.hasVerticalScroll ? 'block' : 'none';
} else {
this.indicatorStyle.display = this.scroller.hasHorizontalScroll || this.scroller.hasVerticalScroll ? 'block' : 'none';
}
if ( this.scroller.hasHorizontalScroll && this.scroller.hasVerticalScroll ) {
utils.addClass(this.wrapper, 'iScrollBothScrollbars');
utils.removeClass(this.wrapper, 'iScrollLoneScrollbar');
if ( this.options.defaultScrollbars && this.options.customStyle ) {
if ( this.options.listenX ) {
this.wrapper.style.right = '8px';
} else {
this.wrapper.style.bottom = '8px';
}
}
} else {
utils.removeClass(this.wrapper, 'iScrollBothScrollbars');
utils.addClass(this.wrapper, 'iScrollLoneScrollbar');
if ( this.options.defaultScrollbars && this.options.customStyle ) {
if ( this.options.listenX ) {
this.wrapper.style.right = '2px';
} else {
this.wrapper.style.bottom = '2px';
}
}
}
var r = this.wrapper.offsetHeight; // force refresh
if ( this.options.listenX ) {
this.wrapperWidth = this.wrapper.clientWidth;
if ( this.options.resize ) {
this.indicatorWidth = Math.max(Math.round(this.wrapperWidth * this.wrapperWidth / (this.scroller.scrollerWidth || this.wrapperWidth || 1)), 8);
this.indicatorStyle.width = this.indicatorWidth + 'px';
} else {
this.indicatorWidth = this.indicator.clientWidth;
}
this.maxPosX = this.wrapperWidth - this.indicatorWidth;
if ( this.options.shrink == 'clip' ) {
this.minBoundaryX = -this.indicatorWidth + 8;
this.maxBoundaryX = this.wrapperWidth - 8;
} else {
this.minBoundaryX = 0;
this.maxBoundaryX = this.maxPosX;
}
this.sizeRatioX = this.options.speedRatioX || (this.scroller.maxScrollX && (this.maxPosX / this.scroller.maxScrollX));
}
if ( this.options.listenY ) {
this.wrapperHeight = this.wrapper.clientHeight;
if ( this.options.resize ) {
this.indicatorHeight = Math.max(Math.round(this.wrapperHeight * this.wrapperHeight / (this.scroller.scrollerHeight || this.wrapperHeight || 1)), 8);
this.indicatorStyle.height = this.indicatorHeight + 'px';
} else {
this.indicatorHeight = this.indicator.clientHeight;
}
this.maxPosY = this.wrapperHeight - this.indicatorHeight;
if ( this.options.shrink == 'clip' ) {
this.minBoundaryY = -this.indicatorHeight + 8;
this.maxBoundaryY = this.wrapperHeight - 8;
} else {
this.minBoundaryY = 0;
this.maxBoundaryY = this.maxPosY;
}
this.maxPosY = this.wrapperHeight - this.indicatorHeight;
this.sizeRatioY = this.options.speedRatioY || (this.scroller.maxScrollY && (this.maxPosY / this.scroller.maxScrollY));
}
this.updatePosition();
},
updatePosition: function () {
var x = this.options.listenX && Math.round(this.sizeRatioX * this.scroller.x) || 0,
y = this.options.listenY && Math.round(this.sizeRatioY * this.scroller.y) || 0;
if ( !this.options.ignoreBoundaries ) {
if ( x < this.minBoundaryX ) {
if ( this.options.shrink == 'scale' ) {
this.width = Math.max(this.indicatorWidth + x, 8);
this.indicatorStyle.width = this.width + 'px';
}
x = this.minBoundaryX;
} else if ( x > this.maxBoundaryX ) {
if ( this.options.shrink == 'scale' ) {
this.width = Math.max(this.indicatorWidth - (x - this.maxPosX), 8);
this.indicatorStyle.width = this.width + 'px';
x = this.maxPosX + this.indicatorWidth - this.width;
} else {
x = this.maxBoundaryX;
}
} else if ( this.options.shrink == 'scale' && this.width != this.indicatorWidth ) {
this.width = this.indicatorWidth;
this.indicatorStyle.width = this.width + 'px';
}
if ( y < this.minBoundaryY ) {
if ( this.options.shrink == 'scale' ) {
this.height = Math.max(this.indicatorHeight + y * 3, 8);
this.indicatorStyle.height = this.height + 'px';
}
y = this.minBoundaryY;
} else if ( y > this.maxBoundaryY ) {
if ( this.options.shrink == 'scale' ) {
this.height = Math.max(this.indicatorHeight - (y - this.maxPosY) * 3, 8);
this.indicatorStyle.height = this.height + 'px';
y = this.maxPosY + this.indicatorHeight - this.height;
} else {
y = this.maxBoundaryY;
}
} else if ( this.options.shrink == 'scale' && this.height != this.indicatorHeight ) {
this.height = this.indicatorHeight;
this.indicatorStyle.height = this.height + 'px';
}
}
this.x = x;
this.y = y;
if ( this.scroller.options.useTransform ) {
this.indicatorStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.scroller.translateZ;
} else {
this.indicatorStyle.left = x + 'px';
this.indicatorStyle.top = y + 'px';
}
},
_pos: function (x, y) {
if ( x < 0 ) {
x = 0;
} else if ( x > this.maxPosX ) {
x = this.maxPosX;
}
if ( y < 0 ) {
y = 0;
} else if ( y > this.maxPosY ) {
y = this.maxPosY;
}
x = this.options.listenX ? Math.round(x / this.sizeRatioX) : this.scroller.x;
y = this.options.listenY ? Math.round(y / this.sizeRatioY) : this.scroller.y;
this.scroller.scrollTo(x, y);
},
fade: function (val, hold) {
if ( hold && !this.visible ) {
return;
}
clearTimeout(this.fadeTimeout);
this.fadeTimeout = null;
var time = val ? 250 : 500,
delay = val ? 0 : 300;
val = val ? '1' : '0';
this.wrapperStyle[utils.style.transitionDuration] = time + 'ms';
this.fadeTimeout = setTimeout((function (val) {
this.wrapperStyle.opacity = val;
this.visible = +val;
}).bind(this, val), delay);
}
};
IScroll.utils = utils;
if ( typeof module != 'undefined' && module.exports ) {
module.exports = IScroll;
} else {
window.IScroll = IScroll;
}
})(window, document, Math); |
define(['Child'],
function(Child) {
//an "superclass" for any object that can occupy a space
function SpaceOccupant(space) {
Child.call(this, space);
}
SpaceOccupant.prototype = Object.create(Child.prototype);
SpaceOccupant.prototype.constructor = SpaceOccupant;
SpaceOccupant.prototype.setSpace = function(space) {
this.setParent(space);
return this;
};
SpaceOccupant.prototype.getSpace = function() {
return this.getParent();
};
return SpaceOccupant;
}
);
|
/**
* Swiper 7.0.0-alpha.26
* Most modern mobile touch slider and framework with hardware accelerated transitions
* https://swiperjs.com
*
* Copyright 2014-2021 Vladimir Kharlampidi
*
* Released under the MIT License
*
* Released on: August 12, 2021
*/
import Swiper from './core/core.js';
export { default as Swiper, default } from './core/core.js';
import Virtual from './modules/virtual/virtual.js';
import Keyboard from './modules/keyboard/keyboard.js';
import Mousewheel from './modules/mousewheel/mousewheel.js';
import Navigation from './modules/navigation/navigation.js';
import Pagination from './modules/pagination/pagination.js';
import Scrollbar from './modules/scrollbar/scrollbar.js';
import Parallax from './modules/parallax/parallax.js';
import Zoom from './modules/zoom/zoom.js';
import Lazy from './modules/lazy/lazy.js';
import Controller from './modules/controller/controller.js';
import A11y from './modules/a11y/a11y.js';
import History from './modules/history/history.js';
import HashNavigation from './modules/hash-navigation/hash-navigation.js';
import Autoplay from './modules/autoplay/autoplay.js';
import Thumbs from './modules/thumbs/thumbs.js';
import FreeMode from './modules/free-mode/free-mode.js';
import Grid from './modules/grid/grid.js';
import Manipulation from './modules/manipulation/manipulation.js';
import EffectFade from './modules/effect-fade/effect-fade.js';
import EffectCube from './modules/effect-cube/effect-cube.js';
import EffectFlip from './modules/effect-flip/effect-flip.js';
import EffectCoverflow from './modules/effect-coverflow/effect-coverflow.js';
import EffectCreative from './modules/effect-creative/effect-creative.js';
import EffectCards from './modules/effect-cards/effect-cards.js';
// Swiper Class
const modules = [Virtual, Keyboard, Mousewheel, Navigation, Pagination, Scrollbar, Parallax, Zoom, Lazy, Controller, A11y, History, HashNavigation, Autoplay, Thumbs, FreeMode, Grid, Manipulation, EffectFade, EffectCube, EffectFlip, EffectCoverflow, EffectCreative, EffectCards];
Swiper.use(modules);
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['3453',"Tlece.WebApp.Controllers Namespace","topic_0000000000000013.html"],['3458',"ErrorController Class","topic_000000000000001A.html"],['3459',"ErrorController Constructor","topic_000000000000001B.html"]]; |
export const messages = {
code: {
empty: 'Secret code is required.',
unverified: 'Invalid code. You can try {codeAttemptsRemainingCount} more time(s).',
maxAttempts: 'You have exceeded the maximum allowable secret code attempts.',
alreadyApplied: 'Your code has already been validated. Please use the forward button on your browser and do not navigate back to this page.'
},
correlationId: {
'null': 'Something went wrong. Please restart the registration process.'
}
}
export default values => {
const errors = { }
if (!values.code) errors.code = messages.code.empty
return errors
}
|
module.exports = {
base_dir : __dirname,
name : 'components_test_app',
preload_components : [ 'log_router', 'outside_components/preload' ],
components : {
web_sockets : false,
http : true,
log_router : {
routes : {
console : {
levels : [ 'warning', 'error', 'info', 'trace' ]
}
}
},
user_component : {
param : 42
},
nested_user_component : {
param : 43
},
'outside_components/sample' : true,
'outside_components/preload' : true
}
} |
// run as: "babel-node --stage 0 loadClients.js"
import mongobless, {ObjectId} from 'mongobless';
import {Company, Person, Mission, Note} from '../../src/server/models';
import async from 'async';
import _ from 'lodash';
import params from '../../params';
mongobless.connect(params.db, (err) => {
if(err) throw err;
async.parallel({ notes, company, mission, person }, (err, data) => {
if(err){
mongobless.close();
throw err;
}
updateNotes(data, (err) => {
console.log("Done.");
mongobless.close();
});
});
});
function updateNotes({notes, ...types}, cb){
async.map(notes, updateNote.bind(null, types), cb);
}
function updateNote(types, note, cb){
const type = _.reduce(_.toPairs(types), (type, [name, h]) => h[note.entityId] && name || type, null )
Note.collection.update({_id: note._id}, {$set: {entityType: type}}, cb);
}
function notes(cb){
Note.findAll({}, cb);
}
function company(cb){
Company.findAll({}, (err, companies) => cb(err, _.reduce(companies, (res, x) => { res[x._id] = x; return res}, {})));
}
function person(cb){
Person.findAll({}, (err, people) => cb(err, _.reduce(people, (res, x) => { res[x._id] = x; return res}, {})));
}
function mission(cb){
Mission.findAll({}, (err, missions) => cb(err, _.reduce(missions, (res, x) => { res[x._id] = x; return res}, {})));
}
|
/*!
* Native JavaScript for Bootstrap Carousel v3.0.14 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2020 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Carousel = factory());
}(this, (function () { 'use strict';
var mouseHoverEvents = ('onmouseleave' in document) ? [ 'mouseenter', 'mouseleave'] : [ 'mouseover', 'mouseout' ];
var supportPassive = (function () {
var result = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
result = true;
}
});
document.addEventListener('DOMContentLoaded', function wrap(){
document.removeEventListener('DOMContentLoaded', wrap, opts);
}, opts);
} catch (e) {}
return result;
})();
var passiveHandler = supportPassive ? { passive: true } : false;
var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
var computedStyle = getComputedStyle(element),
property = computedStyle[transitionProperty],
duration = supportTransition && property && property !== 'none'
? parseFloat(computedStyle[transitionDuration]) : 0;
return !isNaN(duration) ? duration * 1000 : 0;
}
var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
function emulateTransitionEnd(element,handler){
var called = 0, duration = getElementTransitionDuration(element);
duration ? element.addEventListener( transitionEndEvent, function transitionEndWrapper(e){
!called && handler(e), called = 1;
element.removeEventListener( transitionEndEvent, transitionEndWrapper);
})
: setTimeout(function() { !called && handler(), called = 1; }, 17);
}
function isElementInScrollRange(element) {
var bcr = element.getBoundingClientRect(),
viewportHeight = window.innerHeight || document.documentElement.clientHeight;
return bcr.top <= viewportHeight && bcr.bottom >= 0;
}
function queryElement(selector, parent) {
var lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function bootstrapCustomEvent(eventName, componentName, eventProperties) {
var OriginalCustomEvent = new CustomEvent( eventName + '.bs.' + componentName, {cancelable: true});
if (typeof eventProperties !== 'undefined') {
Object.keys(eventProperties).forEach(function (key) {
Object.defineProperty(OriginalCustomEvent, key, {
value: eventProperties[key]
});
});
}
return OriginalCustomEvent;
}
function dispatchCustomEvent(customEvent){
this && this.dispatchEvent(customEvent);
}
function Carousel (element,options) {
options = options || {};
var self = this,
vars, ops,
slideCustomEvent, slidCustomEvent,
slides, leftArrow, rightArrow, indicator, indicators;
function pauseHandler() {
if ( ops.interval !==false && !element.classList.contains('paused') ) {
element.classList.add('paused');
!vars.isSliding && ( clearInterval(vars.timer), vars.timer = null );
}
}
function resumeHandler() {
if ( ops.interval !== false && element.classList.contains('paused') ) {
element.classList.remove('paused');
!vars.isSliding && ( clearInterval(vars.timer), vars.timer = null );
!vars.isSliding && self.cycle();
}
}
function indicatorHandler(e) {
e.preventDefault();
if (vars.isSliding) { return; }
var eventTarget = e.target;
if ( eventTarget && !eventTarget.classList.contains('active') && eventTarget.getAttribute('data-slide-to') ) {
vars.index = parseInt( eventTarget.getAttribute('data-slide-to'));
} else { return false; }
self.slideTo( vars.index );
}
function controlsHandler(e) {
e.preventDefault();
if (vars.isSliding) { return; }
var eventTarget = e.currentTarget || e.srcElement;
if ( eventTarget === rightArrow ) {
vars.index++;
} else if ( eventTarget === leftArrow ) {
vars.index--;
}
self.slideTo( vars.index );
}
function keyHandler(ref) {
var which = ref.which;
if (vars.isSliding) { return; }
switch (which) {
case 39:
vars.index++;
break;
case 37:
vars.index--;
break;
default: return;
}
self.slideTo( vars.index );
}
function toggleEvents(action) {
action = action ? 'addEventListener' : 'removeEventListener';
if ( ops.pause && ops.interval ) {
element[action]( mouseHoverEvents[0], pauseHandler, false );
element[action]( mouseHoverEvents[1], resumeHandler, false );
element[action]( 'touchstart', pauseHandler, passiveHandler );
element[action]( 'touchend', resumeHandler, passiveHandler );
}
ops.touch && slides.length > 1 && element[action]( 'touchstart', touchDownHandler, passiveHandler );
rightArrow && rightArrow[action]( 'click', controlsHandler,false );
leftArrow && leftArrow[action]( 'click', controlsHandler,false );
indicator && indicator[action]( 'click', indicatorHandler,false );
ops.keyboard && window[action]( 'keydown', keyHandler,false );
}
function toggleTouchEvents(action) {
action = action ? 'addEventListener' : 'removeEventListener';
element[action]( 'touchmove', touchMoveHandler, passiveHandler );
element[action]( 'touchend', touchEndHandler, passiveHandler );
}
function touchDownHandler(e) {
if ( vars.isTouch ) { return; }
vars.touchPosition.startX = e.changedTouches[0].pageX;
if ( element.contains(e.target) ) {
vars.isTouch = true;
toggleTouchEvents(1);
}
}
function touchMoveHandler(e) {
if ( !vars.isTouch ) { e.preventDefault(); return; }
vars.touchPosition.currentX = e.changedTouches[0].pageX;
if ( e.type === 'touchmove' && e.changedTouches.length > 1 ) {
e.preventDefault();
return false;
}
}
function touchEndHandler (e) {
if ( !vars.isTouch || vars.isSliding ) { return }
vars.touchPosition.endX = vars.touchPosition.currentX || e.changedTouches[0].pageX;
if ( vars.isTouch ) {
if ( (!element.contains(e.target) || !element.contains(e.relatedTarget) )
&& Math.abs(vars.touchPosition.startX - vars.touchPosition.endX) < 75 ) {
return false;
} else {
if ( vars.touchPosition.currentX < vars.touchPosition.startX ) {
vars.index++;
} else if ( vars.touchPosition.currentX > vars.touchPosition.startX ) {
vars.index--;
}
vars.isTouch = false;
self.slideTo(vars.index);
}
toggleTouchEvents();
}
}
function setActivePage(pageIndex) {
Array.from(indicators).map(function (x){x.classList.remove('active');});
indicators[pageIndex] && indicators[pageIndex].classList.add('active');
}
function transitionEndHandler(e){
if (vars.touchPosition){
var next = vars.index,
timeout = e && e.target !== slides[next] ? e.elapsedTime*1000+100 : 20,
activeItem = self.getActiveIndex(),
orientation = vars.direction === 'left' ? 'next' : 'prev';
vars.isSliding && setTimeout(function () {
if (vars.touchPosition){
vars.isSliding = false;
slides[next].classList.add('active');
slides[activeItem].classList.remove('active');
slides[next].classList.remove(("carousel-item-" + orientation));
slides[next].classList.remove(("carousel-item-" + (vars.direction)));
slides[activeItem].classList.remove(("carousel-item-" + (vars.direction)));
dispatchCustomEvent.call(element, slidCustomEvent);
if ( !document.hidden && ops.interval && !element.classList.contains('paused') ) {
self.cycle();
}
}
}, timeout);
}
}
self.cycle = function () {
if (vars.timer) {
clearInterval(vars.timer);
vars.timer = null;
}
vars.timer = setInterval(function () {
var idx = vars.index || self.getActiveIndex();
isElementInScrollRange(element) && (idx++, self.slideTo( idx ) );
}, ops.interval);
};
self.slideTo = function (next) {
if (vars.isSliding) { return; }
var activeItem = self.getActiveIndex(), orientation, eventProperties;
if ( activeItem === next ) {
return;
} else if ( (activeItem < next ) || (activeItem === 0 && next === slides.length -1 ) ) {
vars.direction = 'left';
} else if ( (activeItem > next) || (activeItem === slides.length - 1 && next === 0 ) ) {
vars.direction = 'right';
}
if ( next < 0 ) { next = slides.length - 1; }
else if ( next >= slides.length ){ next = 0; }
orientation = vars.direction === 'left' ? 'next' : 'prev';
eventProperties = { relatedTarget: slides[next], direction: vars.direction, from: activeItem, to: next };
slideCustomEvent = bootstrapCustomEvent('slide', 'carousel', eventProperties);
slidCustomEvent = bootstrapCustomEvent('slid', 'carousel', eventProperties);
dispatchCustomEvent.call(element, slideCustomEvent);
if (slideCustomEvent.defaultPrevented) { return; }
vars.index = next;
vars.isSliding = true;
clearInterval(vars.timer);
vars.timer = null;
setActivePage( next );
if ( getElementTransitionDuration(slides[next]) && element.classList.contains('slide') ) {
slides[next].classList.add(("carousel-item-" + orientation));
slides[next].offsetWidth;
slides[next].classList.add(("carousel-item-" + (vars.direction)));
slides[activeItem].classList.add(("carousel-item-" + (vars.direction)));
emulateTransitionEnd(slides[next], transitionEndHandler);
} else {
slides[next].classList.add('active');
slides[next].offsetWidth;
slides[activeItem].classList.remove('active');
setTimeout(function () {
vars.isSliding = false;
if ( ops.interval && element && !element.classList.contains('paused') ) {
self.cycle();
}
dispatchCustomEvent.call(element, slidCustomEvent);
}, 100 );
}
};
self.getActiveIndex = function () { return Array.from(slides).indexOf(element.getElementsByClassName('carousel-item active')[0]) || 0; };
self.dispose = function () {
var itemClasses = ['left','right','prev','next'];
Array.from(slides).map(function (slide,idx) {
slide.classList.contains('active') && setActivePage( idx );
itemClasses.map(function (cls) { return slide.classList.remove(("carousel-item-" + cls)); });
});
clearInterval(vars.timer);
toggleEvents();
vars = {};
ops = {};
delete element.Carousel;
};
element = queryElement( element );
element.Carousel && element.Carousel.dispose();
slides = element.getElementsByClassName('carousel-item');
leftArrow = element.getElementsByClassName('carousel-control-prev')[0];
rightArrow = element.getElementsByClassName('carousel-control-next')[0];
indicator = element.getElementsByClassName('carousel-indicators')[0];
indicators = indicator && indicator.getElementsByTagName( "LI" ) || [];
if (slides.length < 2) { return }
var
intervalAttribute = element.getAttribute('data-interval'),
intervalData = intervalAttribute === 'false' ? 0 : parseInt(intervalAttribute),
touchData = element.getAttribute('data-touch') === 'false' ? 0 : 1,
pauseData = element.getAttribute('data-pause') === 'hover' || false,
keyboardData = element.getAttribute('data-keyboard') === 'true' || false,
intervalOption = options.interval,
touchOption = options.touch;
ops = {};
ops.keyboard = options.keyboard === true || keyboardData;
ops.pause = (options.pause === 'hover' || pauseData) ? 'hover' : false;
ops.touch = touchOption || touchData;
ops.interval = typeof intervalOption === 'number' ? intervalOption
: intervalOption === false || intervalData === 0 || intervalData === false ? 0
: isNaN(intervalData) ? 5000
: intervalData;
if (self.getActiveIndex()<0) {
slides.length && slides[0].classList.add('active');
indicators.length && setActivePage(0);
}
vars = {};
vars.direction = 'left';
vars.index = 0;
vars.timer = null;
vars.isSliding = false;
vars.isTouch = false;
vars.touchPosition = {
startX : 0,
currentX : 0,
endX : 0
};
toggleEvents(1);
if ( ops.interval ){ self.cycle(); }
element.Carousel = self;
}
return Carousel;
})));
|
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _utils = require("@material-ui/utils");
var _unstyled = require("@material-ui/unstyled");
var _colorManipulator = require("../styles/colorManipulator");
var _capitalize = _interopRequireDefault(require("../utils/capitalize"));
var _SwitchBase = _interopRequireDefault(require("../internal/SwitchBase"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled"));
var _switchClasses = _interopRequireWildcard(require("./switchClasses"));
var _jsxRuntime = require("react/jsx-runtime");
// @inheritedComponent IconButton
const useUtilityClasses = styleProps => {
const {
classes,
edge,
size,
color,
checked,
disabled
} = styleProps;
const slots = {
root: ['root', edge && `edge${(0, _capitalize.default)(edge)}`, `size${(0, _capitalize.default)(size)}`],
switchBase: ['switchBase', `color${(0, _capitalize.default)(color)}`, checked && 'checked', disabled && 'disabled'],
thumb: ['thumb'],
track: ['track'],
input: ['input']
};
const composedClasses = (0, _unstyled.unstable_composeClasses)(slots, _switchClasses.getSwitchUtilityClass, classes);
return (0, _extends2.default)({}, classes, composedClasses);
};
const SwitchRoot = (0, _experimentalStyled.default)('span', {}, {
name: 'MuiSwitch',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return (0, _extends2.default)({}, styles.root, styleProps.edge && styles[`edge${(0, _capitalize.default)(styleProps.edge)}`], styles[`size${(0, _capitalize.default)(styleProps.size)}`]);
}
})(({
styleProps
}) => (0, _extends2.default)({
/* Styles applied to the root element. */
display: 'inline-flex',
width: 34 + 12 * 2,
height: 14 + 12 * 2,
overflow: 'hidden',
padding: 12,
boxSizing: 'border-box',
position: 'relative',
flexShrink: 0,
zIndex: 0,
// Reset the stacking context.
verticalAlign: 'middle',
// For correct alignment with the text.
'@media print': {
colorAdjust: 'exact'
}
}, styleProps.edge === 'start' && {
marginLeft: -8
}, styleProps.edge === 'end' && {
marginRight: -8
}, styleProps.size === 'small' && {
width: 40,
height: 24,
padding: 7,
[`& .${_switchClasses.default.thumb}`]: {
width: 16,
height: 16
},
[`& .${_switchClasses.default.switchBase}`]: {
padding: 4,
[`&.${_switchClasses.default.checked}`]: {
transform: 'translateX(16px)'
}
}
}));
const SwitchSwitchBase = (0, _experimentalStyled.default)(_SwitchBase.default, {}, {
name: 'MuiSwitch',
slot: 'SwitchBase',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return (0, _extends2.default)({}, styles.switchBase, styles.input, styleProps.color !== 'default' && styles[`color${(0, _capitalize.default)(styleProps.color)}`]);
}
})(({
theme
}) => ({
/* Styles applied to the internal `SwitchBase` component's `root` class. */
position: 'absolute',
top: 0,
left: 0,
zIndex: 1,
// Render above the focus ripple.
color: theme.palette.mode === 'light' ? theme.palette.common.white : theme.palette.grey[300],
transition: theme.transitions.create(['left', 'transform'], {
duration: theme.transitions.duration.shortest
}),
[`&.${_switchClasses.default.checked}`]: {
transform: 'translateX(20px)'
},
[`&.${_switchClasses.default.disabled}`]: {
color: theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[600]
},
[`&.${_switchClasses.default.checked} + .${_switchClasses.default.track}`]: {
opacity: 0.5
},
[`&.${_switchClasses.default.disabled} + .${_switchClasses.default.track}`]: {
opacity: theme.palette.mode === 'light' ? 0.12 : 0.2
},
[`& .${_switchClasses.default.input}`]: {
/* Styles applied to the internal SwitchBase component's input element. */
left: '-100%',
width: '300%'
}
}), ({
theme,
styleProps
}) => (0, _extends2.default)({}, styleProps.color !== 'default' && {
[`&.${_switchClasses.default.checked}`]: {
color: theme.palette[styleProps.color].main,
'&:hover': {
backgroundColor: (0, _colorManipulator.alpha)(theme.palette[styleProps.color].main, theme.palette.action.hoverOpacity),
'@media (hover: none)': {
backgroundColor: 'transparent'
}
},
[`&.${_switchClasses.default.disabled}`]: {
color: theme.palette.mode === 'light' ? (0, _colorManipulator.lighten)(theme.palette[styleProps.color].main, 0.62) : (0, _colorManipulator.darken)(theme.palette[styleProps.color].main, 0.55)
}
},
[`&.${_switchClasses.default.checked} + .${_switchClasses.default.track}`]: {
backgroundColor: theme.palette[styleProps.color].main
}
}));
const SwitchTrack = (0, _experimentalStyled.default)('span', {}, {
name: 'MuiSwitch',
slot: 'Track',
overridesResolver: (props, styles) => styles.track
})(({
theme
}) => ({
/* Styles applied to the track element. */
height: '100%',
width: '100%',
borderRadius: 14 / 2,
zIndex: -1,
transition: theme.transitions.create(['opacity', 'background-color'], {
duration: theme.transitions.duration.shortest
}),
backgroundColor: theme.palette.mode === 'light' ? theme.palette.common.black : theme.palette.common.white,
opacity: theme.palette.mode === 'light' ? 0.38 : 0.3
}));
const SwitchThumb = (0, _experimentalStyled.default)('span', {}, {
name: 'MuiSwitch',
slot: 'Thumb',
overridesResolver: (props, styles) => styles.thumb
})(({
theme
}) => ({
/* Styles used to create the thumb passed to the internal `SwitchBase` component `icon` prop. */
boxShadow: theme.shadows[1],
backgroundColor: 'currentColor',
width: 20,
height: 20,
borderRadius: '50%'
}));
const Switch = /*#__PURE__*/React.forwardRef(function Switch(inProps, ref) {
const props = (0, _useThemeProps.default)({
props: inProps,
name: 'MuiSwitch'
});
const {
className,
color = 'primary',
edge = false,
size = 'medium',
sx
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["className", "color", "edge", "size", "sx"]);
const styleProps = (0, _extends2.default)({}, props, {
color,
edge,
size
});
const classes = useUtilityClasses(styleProps);
const icon = /*#__PURE__*/(0, _jsxRuntime.jsx)(SwitchThumb, {
className: classes.thumb,
styleProps: styleProps
});
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(SwitchRoot, {
className: (0, _clsx.default)(classes.root, className),
sx: sx,
styleProps: styleProps,
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SwitchSwitchBase, (0, _extends2.default)({
type: "checkbox",
icon: icon,
checkedIcon: icon,
ref: ref,
styleProps: styleProps
}, other, {
classes: (0, _extends2.default)({}, classes, {
root: classes.switchBase
})
})), /*#__PURE__*/(0, _jsxRuntime.jsx)(SwitchTrack, {
className: classes.track,
styleProps: styleProps
})]
});
});
process.env.NODE_ENV !== "production" ? Switch.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the component is checked.
*/
checked: _propTypes.default.bool,
/**
* The icon to display when the component is checked.
*/
checkedIcon: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'primary'
*/
color: _propTypes.default
/* @typescript-to-proptypes-ignore */
.oneOfType([_propTypes.default.oneOf(['default', 'primary', 'secondary']), _propTypes.default.string]),
/**
* The default checked state. Use when the component is not controlled.
*/
defaultChecked: _propTypes.default.bool,
/**
* If `true`, the component is disabled.
*/
disabled: _propTypes.default.bool,
/**
* If `true`, the ripple effect is disabled.
*/
disableRipple: _propTypes.default.bool,
/**
* If given, uses a negative margin to counteract the padding on one
* side (this is often helpful for aligning the left or right
* side of the icon with content above or below, without ruining the border
* size and shape).
* @default false
*/
edge: _propTypes.default.oneOf(['end', 'start', false]),
/**
* The icon to display when the component is unchecked.
*/
icon: _propTypes.default.node,
/**
* The id of the `input` element.
*/
id: _propTypes.default.string,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: _propTypes.default.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: _utils.refType,
/**
* Callback fired when the state is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange: _propTypes.default.func,
/**
* If `true`, the `input` element is required.
*/
required: _propTypes.default.bool,
/**
* The size of the component.
* `small` is equivalent to the dense switch styling.
* @default 'medium'
*/
size: _propTypes.default
/* @typescript-to-proptypes-ignore */
.oneOfType([_propTypes.default.oneOf(['medium', 'small']), _propTypes.default.string]),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object,
/**
* The value of the component. The DOM API casts this to a string.
* The browser uses "on" as the default value.
*/
value: _propTypes.default.any
} : void 0;
var _default = Switch;
exports.default = _default; |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
(global = global || self, factory(global.ReactBigCalendar = {}, global.React, global.ReactDOM));
}(this, function (exports, React, ReactDOM) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
var ReactDOM__default = 'default' in ReactDOM ? ReactDOM['default'] : ReactDOM;
function NoopWrapper(props) {
return props.children;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var reactIs_production_min = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:!0});
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.memo"):
60115,r=b?Symbol.for("react.lazy"):60116;function t(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case h:return a;default:return u}}case r:case q:case d:return u}}}function v(a){return t(a)===m}exports.typeOf=t;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;
exports.Fragment=e;exports.Lazy=r;exports.Memo=q;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||"object"===typeof a&&null!==a&&(a.$$typeof===r||a.$$typeof===q||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n)};exports.isAsyncMode=function(a){return v(a)||t(a)===l};exports.isConcurrentMode=v;exports.isContextConsumer=function(a){return t(a)===k};
exports.isContextProvider=function(a){return t(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return t(a)===n};exports.isFragment=function(a){return t(a)===e};exports.isLazy=function(a){return t(a)===r};exports.isMemo=function(a){return t(a)===q};exports.isPortal=function(a){return t(a)===d};exports.isProfiler=function(a){return t(a)===g};exports.isStrictMode=function(a){return t(a)===f};
exports.isSuspense=function(a){return t(a)===p};
});
unwrapExports(reactIs_production_min);
var reactIs_production_min_1 = reactIs_production_min.typeOf;
var reactIs_production_min_2 = reactIs_production_min.AsyncMode;
var reactIs_production_min_3 = reactIs_production_min.ConcurrentMode;
var reactIs_production_min_4 = reactIs_production_min.ContextConsumer;
var reactIs_production_min_5 = reactIs_production_min.ContextProvider;
var reactIs_production_min_6 = reactIs_production_min.Element;
var reactIs_production_min_7 = reactIs_production_min.ForwardRef;
var reactIs_production_min_8 = reactIs_production_min.Fragment;
var reactIs_production_min_9 = reactIs_production_min.Lazy;
var reactIs_production_min_10 = reactIs_production_min.Memo;
var reactIs_production_min_11 = reactIs_production_min.Portal;
var reactIs_production_min_12 = reactIs_production_min.Profiler;
var reactIs_production_min_13 = reactIs_production_min.StrictMode;
var reactIs_production_min_14 = reactIs_production_min.Suspense;
var reactIs_production_min_15 = reactIs_production_min.isValidElementType;
var reactIs_production_min_16 = reactIs_production_min.isAsyncMode;
var reactIs_production_min_17 = reactIs_production_min.isConcurrentMode;
var reactIs_production_min_18 = reactIs_production_min.isContextConsumer;
var reactIs_production_min_19 = reactIs_production_min.isContextProvider;
var reactIs_production_min_20 = reactIs_production_min.isElement;
var reactIs_production_min_21 = reactIs_production_min.isForwardRef;
var reactIs_production_min_22 = reactIs_production_min.isFragment;
var reactIs_production_min_23 = reactIs_production_min.isLazy;
var reactIs_production_min_24 = reactIs_production_min.isMemo;
var reactIs_production_min_25 = reactIs_production_min.isPortal;
var reactIs_production_min_26 = reactIs_production_min.isProfiler;
var reactIs_production_min_27 = reactIs_production_min.isStrictMode;
var reactIs_production_min_28 = reactIs_production_min.isSuspense;
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' ||
// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
// AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
// AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
})();
}
});
unwrapExports(reactIs_development);
var reactIs_development_1 = reactIs_development.typeOf;
var reactIs_development_2 = reactIs_development.AsyncMode;
var reactIs_development_3 = reactIs_development.ConcurrentMode;
var reactIs_development_4 = reactIs_development.ContextConsumer;
var reactIs_development_5 = reactIs_development.ContextProvider;
var reactIs_development_6 = reactIs_development.Element;
var reactIs_development_7 = reactIs_development.ForwardRef;
var reactIs_development_8 = reactIs_development.Fragment;
var reactIs_development_9 = reactIs_development.Lazy;
var reactIs_development_10 = reactIs_development.Memo;
var reactIs_development_11 = reactIs_development.Portal;
var reactIs_development_12 = reactIs_development.Profiler;
var reactIs_development_13 = reactIs_development.StrictMode;
var reactIs_development_14 = reactIs_development.Suspense;
var reactIs_development_15 = reactIs_development.isValidElementType;
var reactIs_development_16 = reactIs_development.isAsyncMode;
var reactIs_development_17 = reactIs_development.isConcurrentMode;
var reactIs_development_18 = reactIs_development.isContextConsumer;
var reactIs_development_19 = reactIs_development.isContextProvider;
var reactIs_development_20 = reactIs_development.isElement;
var reactIs_development_21 = reactIs_development.isForwardRef;
var reactIs_development_22 = reactIs_development.isFragment;
var reactIs_development_23 = reactIs_development.isLazy;
var reactIs_development_24 = reactIs_development.isMemo;
var reactIs_development_25 = reactIs_development.isPortal;
var reactIs_development_26 = reactIs_development.isProfiler;
var reactIs_development_27 = reactIs_development.isStrictMode;
var reactIs_development_28 = reactIs_development.isSuspense;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var printWarning = function() {};
{
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
var has = Function.call.bind(Object.prototype.hasOwnProperty);
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
{
loggedTypeFailures = {};
}
};
var checkPropTypes_1 = checkPropTypes;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning$1 = function() {};
{
printWarning$1 = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} else if (typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning$1(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!reactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
{
if (arguments.length > 1) {
printWarning$1(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning$1('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has$1(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning$1(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var ReactIs = reactIs;
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}
});
function _extends$1() {
_extends$1 = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends$1.apply(this, arguments);
}
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1 = invariant;
var noop = function noop() {};
function readOnlyPropType(handler, name) {
return function (props, propName) {
if (props[propName] !== undefined) {
if (!props[handler]) {
return new Error("You have provided a `" + propName + "` prop to `" + name + "` " + ("without an `" + handler + "` handler prop. This will render a read-only field. ") + ("If the field should be mutable use `" + defaultKey(propName) + "`. ") + ("Otherwise, set `" + handler + "`."));
}
}
};
}
function uncontrolledPropTypes(controlledValues, displayName) {
var propTypes = {};
Object.keys(controlledValues).forEach(function (prop) {
// add default propTypes for folks that use runtime checks
propTypes[defaultKey(prop)] = noop;
{
var handler = controlledValues[prop];
!(typeof handler === 'string' && handler.trim().length) ? invariant_1(false, 'Uncontrollable - [%s]: the prop `%s` needs a valid handler key name in order to make it uncontrollable', displayName, prop) : void 0;
propTypes[prop] = readOnlyPropType(handler, displayName);
}
});
return propTypes;
}
function isProp(props, prop) {
return props[prop] !== undefined;
}
function defaultKey(key) {
return 'default' + key.charAt(0).toUpperCase() + key.substr(1);
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function canAcceptRef(component) {
return !!component && (typeof component !== 'function' || component.prototype && component.prototype.isReactComponent);
}
function _inheritsLoose$1(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function uncontrollable(Component, controlledValues, methods) {
if (methods === void 0) {
methods = [];
}
var displayName = Component.displayName || Component.name || 'Component';
var canAcceptRef$1 = canAcceptRef(Component);
var controlledProps = Object.keys(controlledValues);
var PROPS_TO_OMIT = controlledProps.map(defaultKey);
!(canAcceptRef$1 || !methods.length) ? invariant_1(false, '[uncontrollable] stateless function components cannot pass through methods ' + 'because they have no associated instances. Check component: ' + displayName + ', ' + 'attempting to pass through methods: ' + methods.join(', ')) : void 0;
var UncontrolledComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose$1(UncontrolledComponent, _React$Component);
function UncontrolledComponent() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handlers = Object.create(null);
controlledProps.forEach(function (propName) {
var handlerName = controlledValues[propName];
var handleChange = function handleChange(value) {
if (_this.props[handlerName]) {
var _this$props;
_this._notifying = true;
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
(_this$props = _this.props)[handlerName].apply(_this$props, [value].concat(args));
_this._notifying = false;
}
_this._values[propName] = value;
if (!_this.unmounted) _this.forceUpdate();
};
_this.handlers[handlerName] = handleChange;
});
if (methods.length) _this.attachRef = function (ref) {
_this.inner = ref;
};
return _this;
}
var _proto = UncontrolledComponent.prototype;
_proto.shouldComponentUpdate = function shouldComponentUpdate() {
//let the forceUpdate trigger the update
return !this._notifying;
};
_proto.componentWillMount = function componentWillMount() {
var _this2 = this;
var props = this.props;
this._values = Object.create(null);
controlledProps.forEach(function (key) {
_this2._values[key] = props[defaultKey(key)];
});
};
_proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this3 = this;
var props = this.props;
controlledProps.forEach(function (key) {
/**
* If a prop switches from controlled to Uncontrolled
* reset its value to the defaultValue
*/
if (!isProp(nextProps, key) && isProp(props, key)) {
_this3._values[key] = nextProps[defaultKey(key)];
}
});
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.unmounted = true;
};
_proto.render = function render() {
var _this4 = this;
var _this$props2 = this.props,
innerRef = _this$props2.innerRef,
props = _objectWithoutPropertiesLoose$1(_this$props2, ["innerRef"]);
PROPS_TO_OMIT.forEach(function (prop) {
delete props[prop];
});
var newProps = {};
controlledProps.forEach(function (propName) {
var propValue = _this4.props[propName];
newProps[propName] = propValue !== undefined ? propValue : _this4._values[propName];
});
return React__default.createElement(Component, _extends$1({}, props, newProps, this.handlers, {
ref: innerRef || this.attachRef
}));
};
return UncontrolledComponent;
}(React__default.Component);
UncontrolledComponent.displayName = "Uncontrolled(" + displayName + ")";
UncontrolledComponent.propTypes = _extends$1({
innerRef: function innerRef() {}
}, uncontrolledPropTypes(controlledValues, displayName));
methods.forEach(function (method) {
UncontrolledComponent.prototype[method] = function $proxiedMethod() {
var _this$inner;
return (_this$inner = this.inner)[method].apply(_this$inner, arguments);
};
});
var WrappedComponent = UncontrolledComponent;
if (React__default.forwardRef) {
WrappedComponent = React__default.forwardRef(function (props, ref) {
return React__default.createElement(UncontrolledComponent, _extends$1({}, props, {
innerRef: ref
}));
});
WrappedComponent.propTypes = UncontrolledComponent.propTypes;
}
WrappedComponent.ControlledComponent = Component;
/**
* useful when wrapping a Component and you want to control
* everything
*/
WrappedComponent.deferControlTo = function (newComponent, additions, nextMethods) {
if (additions === void 0) {
additions = {};
}
return uncontrollable(newComponent, _extends$1({}, controlledValues, additions), nextMethods);
};
return WrappedComponent;
}
function toVal(mix) {
var k, y, str='';
if (mix) {
if (typeof mix === 'object') {
if (!!mix.push) {
for (k=0; k < mix.length; k++) {
if (mix[k] && (y = toVal(mix[k]))) {
str && (str += ' ');
str += y;
}
}
} else {
for (k in mix) {
if (mix[k] && (y = toVal(k))) {
str && (str += ' ');
str += y;
}
}
}
} else if (typeof mix !== 'boolean' && !mix.call) {
str && (str += ' ');
str += mix;
}
}
return str;
}
function clsx () {
var i=0, x, str='';
while (i < arguments.length) {
if (x = toVal(arguments[i++])) {
str && (str += ' ');
str += x;
}
}
return str;
}
var navigate = {
PREVIOUS: 'PREV',
NEXT: 'NEXT',
TODAY: 'TODAY',
DATE: 'DATE'
};
var views = {
MONTH: 'month',
WEEK: 'week',
WORK_WEEK: 'work_week',
DAY: 'day',
AGENDA: 'agenda'
};
var viewNames = Object.keys(views).map(function (k) {
return views[k];
});
var accessor = propTypes.oneOfType([propTypes.string, propTypes.func]);
var dateFormat = propTypes.any;
var dateRangeFormat = propTypes.func;
/**
* accepts either an array of builtin view names:
*
* ```
* views={['month', 'day', 'agenda']}
* ```
*
* or an object hash of the view name and the component (or boolean for builtin)
*
* ```
* views={{
* month: true,
* week: false,
* workweek: WorkWeekViewComponent,
* }}
* ```
*/
var views$1 = propTypes.oneOfType([propTypes.arrayOf(propTypes.oneOf(viewNames)), propTypes.objectOf(function (prop, key) {
var isBuiltinView = viewNames.indexOf(key) !== -1 && typeof prop[key] === 'boolean';
if (isBuiltinView) {
return null;
} else {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
return propTypes.elementType.apply(propTypes, [prop, key].concat(args));
}
})]);
var DayLayoutAlgorithmPropType = propTypes.oneOfType([propTypes.oneOf(['overlap', 'no-overlap']), propTypes.func]);
function notify(handler, args) {
handler && handler.apply(null, [].concat(args));
}
var localePropType = propTypes.oneOfType([propTypes.string, propTypes.func]);
function _format(localizer, formatter, value, format, culture) {
var result = typeof format === 'function' ? format(value, culture, localizer) : formatter.call(localizer, value, format, culture);
!(result == null || typeof result === 'string') ? invariant_1(false, '`localizer format(..)` must return a string, null, or undefined') : void 0;
return result;
}
var DateLocalizer = function DateLocalizer(spec) {
var _this = this;
!(typeof spec.format === 'function') ? invariant_1(false, 'date localizer `format(..)` must be a function') : void 0;
!(typeof spec.firstOfWeek === 'function') ? invariant_1(false, 'date localizer `firstOfWeek(..)` must be a function') : void 0;
this.propType = spec.propType || localePropType;
this.startOfWeek = spec.firstOfWeek;
this.formats = spec.formats;
this.format = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _format.apply(void 0, [_this, spec.format].concat(args));
};
};
function mergeWithDefaults(localizer, culture, formatOverrides, messages) {
var formats = _extends({}, localizer.formats, formatOverrides);
return _extends({}, localizer, {
messages: messages,
startOfWeek: function startOfWeek() {
return localizer.startOfWeek(culture);
},
format: function format(value, _format2) {
return localizer.format(value, formats[_format2] || _format2, culture);
}
});
}
var defaultMessages = {
date: 'Date',
time: 'Time',
event: 'Event',
allDay: 'All Day',
week: 'Week',
work_week: 'Work Week',
day: 'Day',
month: 'Month',
previous: 'Back',
next: 'Next',
yesterday: 'Yesterday',
tomorrow: 'Tomorrow',
today: 'Today',
agenda: 'Agenda',
noEventsInRange: 'There are no events in this range.',
showMore: function showMore(total) {
return "+" + total + " more";
}
};
function messages(msgs) {
return _extends({}, defaultMessages, msgs);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var MILI = 'milliseconds'
, SECONDS = 'seconds'
, MINUTES = 'minutes'
, HOURS = 'hours'
, DAY = 'day'
, WEEK = 'week'
, MONTH = 'month'
, YEAR = 'year'
, DECADE = 'decade'
, CENTURY = 'century';
var multiplierMilli = {
'milliseconds': 1,
'seconds': 1000,
'minutes': 60 * 1000,
'hours': 60 * 60 * 1000,
'day': 24 * 60 * 60 * 1000,
'week': 7 * 24 * 60 * 60 * 1000
};
var multiplierMonth = {
'month': 1,
'year': 12,
'decade': 10 * 12,
'century': 100 * 12
};
function daysOf(year) {
return [31, daysInFeb(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
}
function daysInFeb(year) {
return (
year % 4 === 0
&& year % 100 !== 0
) || year % 400 === 0
? 29
: 28
}
function add(d, num, unit) {
d = new Date(d);
switch (unit){
case MILI:
case SECONDS:
case MINUTES:
case HOURS:
case DAY:
case WEEK:
return addMillis(d, num * multiplierMilli[unit])
case MONTH:
case YEAR:
case DECADE:
case CENTURY:
return addMonths(d, num * multiplierMonth[unit])
}
throw new TypeError('Invalid units: "' + unit + '"')
}
function addMillis(d, num) {
var nextDate = new Date(+(d) + num);
return solveDST(d, nextDate)
}
function addMonths(d, num) {
var year = d.getFullYear()
, month = d.getMonth()
, day = d.getDate()
, totalMonths = year * 12 + month + num
, nextYear = Math.trunc(totalMonths / 12)
, nextMonth = totalMonths % 12
, nextDay = Math.min(day, daysOf(nextYear)[nextMonth]);
var nextDate = new Date(d);
nextDate.setFullYear(nextYear);
// To avoid a bug when sets the Feb month
// with a date > 28 or date > 29 (leap year)
nextDate.setDate(1);
nextDate.setMonth(nextMonth);
nextDate.setDate(nextDay);
return nextDate
}
function solveDST(currentDate, nextDate) {
var currentOffset = currentDate.getTimezoneOffset()
, nextOffset = nextDate.getTimezoneOffset();
// if is DST, add the difference in minutes
// else the difference is zero
var diffMinutes = (nextOffset - currentOffset);
return new Date(+(nextDate) + diffMinutes * multiplierMilli['minutes'])
}
function subtract(d, num, unit) {
return add(d, -num, unit)
}
function startOf(d, unit, firstOfWeek) {
d = new Date(d);
switch (unit) {
case CENTURY:
case DECADE:
case YEAR:
d = month(d, 0);
case MONTH:
d = date(d, 1);
case WEEK:
case DAY:
d = hours(d, 0);
case HOURS:
d = minutes(d, 0);
case MINUTES:
d = seconds(d, 0);
case SECONDS:
d = milliseconds(d, 0);
}
if (unit === DECADE)
d = subtract(d, year(d) % 10, 'year');
if (unit === CENTURY)
d = subtract(d, year(d) % 100, 'year');
if (unit === WEEK)
d = weekday(d, 0, firstOfWeek);
return d
}
function endOf(d, unit, firstOfWeek){
d = new Date(d);
d = startOf(d, unit, firstOfWeek);
switch (unit) {
case CENTURY:
case DECADE:
case YEAR:
case MONTH:
case WEEK:
d = add(d, 1, unit);
d = subtract(d, 1, DAY);
d.setHours(23, 59, 59, 999);
break;
case DAY:
d.setHours(23, 59, 59, 999);
break;
case HOURS:
case MINUTES:
case SECONDS:
d = add(d, 1, unit);
d = subtract(d, 1, MILI);
}
return d
}
var eq = createComparer(function(a, b){ return a === b });
var gt = createComparer(function(a, b){ return a > b });
var gte = createComparer(function(a, b){ return a >= b });
var lt = createComparer(function(a, b){ return a < b });
var lte = createComparer(function(a, b){ return a <= b });
function min(){
return new Date(Math.min.apply(Math, arguments))
}
function max(){
return new Date(Math.max.apply(Math, arguments))
}
function inRange(day, min, max, unit){
unit = unit || 'day';
return (!min || gte(day, min, unit))
&& (!max || lte(day, max, unit))
}
var milliseconds = createAccessor('Milliseconds');
var seconds = createAccessor('Seconds');
var minutes = createAccessor('Minutes');
var hours = createAccessor('Hours');
var day = createAccessor('Day');
var date = createAccessor('Date');
var month = createAccessor('Month');
var year = createAccessor('FullYear');
function weekday(d, val, firstDay) {
var w = (day(d) + 7 - (firstDay || 0) ) % 7;
return val === undefined
? w
: add(d, val - w, DAY);
}
function createAccessor(method){
var hourLength = (function(method) {
switch(method) {
case 'Milliseconds':
return 3600000;
case 'Seconds':
return 3600;
case 'Minutes':
return 60;
case 'Hours':
return 1;
default:
return null;
}
})(method);
return function(d, val){
if (val === undefined)
return d['get' + method]()
var dateOut = new Date(d);
dateOut['set' + method](val);
if(hourLength && dateOut['get'+method]() != val && (method === 'Hours' || val >=hourLength && (dateOut.getHours()-d.getHours()<Math.floor(val/hourLength))) ){
//Skip DST hour, if it occurs
dateOut['set'+method](val+hourLength);
}
return dateOut
}
}
function createComparer(operator) {
return function (a, b, unit) {
return operator(+startOf(a, unit), +startOf(b, unit))
};
}
/* eslint no-fallthrough: off */
var MILLI = {
seconds: 1000,
minutes: 1000 * 60,
hours: 1000 * 60 * 60,
day: 1000 * 60 * 60 * 24
};
function firstVisibleDay(date, localizer) {
var firstOfMonth = startOf(date, 'month');
return startOf(firstOfMonth, 'week', localizer.startOfWeek());
}
function lastVisibleDay(date, localizer) {
var endOfMonth = endOf(date, 'month');
return endOf(endOfMonth, 'week', localizer.startOfWeek());
}
function visibleDays(date, localizer) {
var current = firstVisibleDay(date, localizer),
last = lastVisibleDay(date, localizer),
days = [];
while (lte(current, last, 'day')) {
days.push(current);
current = add(current, 1, 'day');
}
return days;
}
function ceil(date, unit) {
var floor = startOf(date, unit);
return eq(floor, date) ? floor : add(floor, 1, unit);
}
function range(start, end, unit) {
if (unit === void 0) {
unit = 'day';
}
var current = start,
days = [];
while (lte(current, end, unit)) {
days.push(current);
current = add(current, 1, unit);
}
return days;
}
function merge(date, time) {
if (time == null && date == null) return null;
if (time == null) time = new Date();
if (date == null) date = new Date();
date = startOf(date, 'day');
date = hours(date, hours(time));
date = minutes(date, minutes(time));
date = seconds(date, seconds(time));
return milliseconds(date, milliseconds(time));
}
function isJustDate(date) {
return hours(date) === 0 && minutes(date) === 0 && seconds(date) === 0 && milliseconds(date) === 0;
}
function diff(dateA, dateB, unit) {
if (!unit || unit === 'milliseconds') return Math.abs(+dateA - +dateB); // the .round() handles an edge case
// with DST where the total won't be exact
// since one day in the range may be shorter/longer by an hour
return Math.round(Math.abs(+startOf(dateA, unit) / MILLI[unit] - +startOf(dateB, unit) / MILLI[unit]));
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq$1(value, other) {
return value === other || (value !== value && other !== other);
}
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Built-in value references. */
var Symbol$1 = root.Symbol;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty$1.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$1.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString$1.call(value);
}
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag$1 && symToStringTag$1 in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER$1 : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq$1(object[index], value);
}
return false;
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeMax = Math.max;
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}
function _extends$2() {
_extends$2 = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends$2.apply(this, arguments);
}
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
function ownerWindow(node) {
var doc = ownerDocument(node);
return doc && doc.defaultView || window;
}
function getComputedStyle(node, psuedoElement) {
return ownerWindow(node).getComputedStyle(node, psuedoElement);
}
var rUpper = /([A-Z])/g;
function hyphenate(string) {
return string.replace(rUpper, '-$1').toLowerCase();
}
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js
*/
var msPattern = /^ms-/;
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i;
function isTransform(value) {
return !!(value && supportedTransforms.test(value));
}
function style(node, property) {
var css = '';
var transforms = '';
if (typeof property === 'string') {
return node.style.getPropertyValue(hyphenateStyleName(property)) || getComputedStyle(node).getPropertyValue(hyphenateStyleName(property));
}
Object.keys(property).forEach(function (key) {
var value = property[key];
if (!value && value !== 0) {
node.style.removeProperty(hyphenateStyleName(key));
} else if (isTransform(key)) {
transforms += key + "(" + value + ") ";
} else {
css += hyphenateStyleName(key) + ": " + value + ";";
}
});
if (transforms) {
css += "transform: " + transforms + ";";
}
node.style.cssText += ";" + css;
}
/* eslint-disable no-bitwise, no-cond-assign */
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
function contains(context, node) {
if (context.contains) return context.contains(node);
if (context.compareDocumentPosition) return context === node || !!(context.compareDocumentPosition(node) & 16);
}
function isDocument(element) {
return 'nodeType' in element && element.nodeType === document.DOCUMENT_NODE;
}
function isWindow(node) {
if ('window' in node && node.window === node) return node;
if (isDocument(node)) return node.defaultView || false;
return false;
}
function getscrollAccessor(offset) {
var prop = offset === 'pageXOffset' ? 'scrollLeft' : 'scrollTop';
function scrollAccessor(node, val) {
var win = isWindow(node);
if (val === undefined) {
return win ? win[offset] : node[prop];
}
if (win) {
win.scrollTo(val, win[offset]);
} else {
node[prop] = val;
}
}
return scrollAccessor;
}
var getScrollLeft = getscrollAccessor('pageXOffset');
var getScrollTop = getscrollAccessor('pageYOffset');
function offset(node) {
var doc = ownerDocument(node);
var box = {
top: 0,
left: 0,
height: 0,
width: 0
};
var docElem = doc && doc.documentElement; // Make sure it's not a disconnected DOM node
if (!docElem || !contains(docElem, node)) return box;
if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect();
box = {
top: box.top + getScrollTop(node) - (docElem.clientTop || 0),
left: box.left + getScrollLeft(node) - (docElem.clientLeft || 0),
width: box.width,
height: box.height
};
return box;
}
var isHTMLElement = function isHTMLElement(e) {
return !!e && 'offsetParent' in e;
};
function offsetParent(node) {
var doc = ownerDocument(node);
var parent = node && node.offsetParent;
while (isHTMLElement(parent) && parent.nodeName !== 'HTML' && style(parent, 'position') === 'static') {
parent = parent.offsetParent;
}
return parent || doc.documentElement;
}
var nodeName = function nodeName(node) {
return node.nodeName && node.nodeName.toLowerCase();
};
function position(node, offsetParent$1) {
var parentOffset = {
top: 0,
left: 0
};
var offset$1; // Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if (style(node, 'position') === 'fixed') {
offset$1 = node.getBoundingClientRect();
} else {
var parent = offsetParent$1 || offsetParent(node);
offset$1 = offset(node);
if (nodeName(parent) !== 'html') parentOffset = offset(parent);
var borderTop = String(style(parent, 'borderTopWidth') || 0);
parentOffset.top += parseInt(borderTop, 10) - getScrollTop(parent) || 0;
var borderLeft = String(style(parent, 'borderLeftWidth') || 0);
parentOffset.left += parseInt(borderLeft, 10) - getScrollLeft(parent) || 0;
}
var marginTop = String(style(node, 'marginTop') || 0);
var marginLeft = String(style(node, 'marginLeft') || 0); // Subtract parent offsets and node margins
return _extends$2({}, offset$1, {
top: offset$1.top - parentOffset.top - (parseInt(marginTop, 10) || 0),
left: offset$1.left - parentOffset.left - (parseInt(marginLeft, 10) || 0)
});
}
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/* https://github.com/component/raf */
var prev = new Date().getTime();
function fallback(fn) {
var curr = new Date().getTime();
var ms = Math.max(0, 16 - (curr - prev));
var handle = setTimeout(fn, ms);
prev = curr;
return handle;
}
var vendors = ['', 'webkit', 'moz', 'o', 'ms'];
var cancelMethod = 'clearTimeout';
var rafImpl = fallback; // eslint-disable-next-line import/no-mutable-exports
var getKey = function getKey(vendor, k) {
return vendor + (!vendor ? k : k[0].toUpperCase() + k.substr(1)) + "AnimationFrame";
};
if (canUseDOM) {
vendors.some(function (vendor) {
var rafMethod = getKey(vendor, 'request');
if (rafMethod in window) {
cancelMethod = getKey(vendor, 'cancel'); // @ts-ignore
rafImpl = function rafImpl(cb) {
return window[rafMethod](cb);
};
}
return !!rafImpl;
});
}
var cancel = function cancel(id) {
// @ts-ignore
if (typeof window[cancelMethod] === 'function') window[cancelMethod](id);
};
var request = rafImpl;
var EventCell =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(EventCell, _React$Component);
function EventCell() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = EventCell.prototype;
_proto.render = function render() {
var _this$props = this.props,
style = _this$props.style,
className = _this$props.className,
event = _this$props.event,
selected = _this$props.selected,
isAllDay = _this$props.isAllDay,
onSelect = _this$props.onSelect,
_onDoubleClick = _this$props.onDoubleClick,
_onKeyPress = _this$props.onKeyPress,
localizer = _this$props.localizer,
continuesPrior = _this$props.continuesPrior,
continuesAfter = _this$props.continuesAfter,
accessors = _this$props.accessors,
getters = _this$props.getters,
children = _this$props.children,
_this$props$component = _this$props.components,
Event = _this$props$component.event,
EventWrapper = _this$props$component.eventWrapper,
slotStart = _this$props.slotStart,
slotEnd = _this$props.slotEnd,
props = _objectWithoutPropertiesLoose(_this$props, ["style", "className", "event", "selected", "isAllDay", "onSelect", "onDoubleClick", "onKeyPress", "localizer", "continuesPrior", "continuesAfter", "accessors", "getters", "children", "components", "slotStart", "slotEnd"]);
delete props.resizable;
var title = accessors.title(event);
var tooltip = accessors.tooltip(event);
var end = accessors.end(event);
var start = accessors.start(event);
var allDay = accessors.allDay(event);
var showAsAllDay = isAllDay || allDay || diff(start, ceil(end, 'day'), 'day') > 1;
var userProps = getters.eventProp(event, start, end, selected);
var content = React__default.createElement("div", {
className: "rbc-event-content",
title: tooltip || undefined
}, Event ? React__default.createElement(Event, {
event: event,
continuesPrior: continuesPrior,
continuesAfter: continuesAfter,
title: title,
isAllDay: allDay,
localizer: localizer,
slotStart: slotStart,
slotEnd: slotEnd
}) : title);
return React__default.createElement(EventWrapper, _extends({}, this.props, {
type: "date"
}), React__default.createElement("div", _extends({}, props, {
tabIndex: 0,
style: _extends({}, userProps.style, style),
className: clsx('rbc-event', className, userProps.className, {
'rbc-selected': selected,
'rbc-event-allday': showAsAllDay,
'rbc-event-continues-prior': continuesPrior,
'rbc-event-continues-after': continuesAfter
}),
onClick: function onClick(e) {
return onSelect && onSelect(event, e);
},
onDoubleClick: function onDoubleClick(e) {
return _onDoubleClick && _onDoubleClick(event, e);
},
onKeyPress: function onKeyPress(e) {
return _onKeyPress && _onKeyPress(event, e);
}
}), typeof children === 'function' ? children(content) : content));
};
return EventCell;
}(React__default.Component);
EventCell.propTypes = {
event: propTypes.object.isRequired,
slotStart: propTypes.instanceOf(Date),
slotEnd: propTypes.instanceOf(Date),
resizable: propTypes.bool,
selected: propTypes.bool,
isAllDay: propTypes.bool,
continuesPrior: propTypes.bool,
continuesAfter: propTypes.bool,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object,
onSelect: propTypes.func,
onDoubleClick: propTypes.func,
onKeyPress: propTypes.func
};
function isSelected(event, selected) {
if (!event || selected == null) return false;
return [].concat(selected).indexOf(event) !== -1;
}
function slotWidth(rowBox, slots) {
var rowWidth = rowBox.right - rowBox.left;
var cellWidth = rowWidth / slots;
return cellWidth;
}
function getSlotAtX(rowBox, x, rtl, slots) {
var cellWidth = slotWidth(rowBox, slots);
return rtl ? slots - 1 - Math.floor((x - rowBox.left) / cellWidth) : Math.floor((x - rowBox.left) / cellWidth);
}
function pointInBox(box, _ref) {
var x = _ref.x,
y = _ref.y;
return y >= box.top && y <= box.bottom && x >= box.left && x <= box.right;
}
function dateCellSelection(start, rowBox, box, slots, rtl) {
var startIdx = -1;
var endIdx = -1;
var lastSlotIdx = slots - 1;
var cellWidth = slotWidth(rowBox, slots); // cell under the mouse
var currentSlot = getSlotAtX(rowBox, box.x, rtl, slots); // Identify row as either the initial row
// or the row under the current mouse point
var isCurrentRow = rowBox.top < box.y && rowBox.bottom > box.y;
var isStartRow = rowBox.top < start.y && rowBox.bottom > start.y; // this row's position relative to the start point
var isAboveStart = start.y > rowBox.bottom;
var isBelowStart = rowBox.top > start.y;
var isBetween = box.top < rowBox.top && box.bottom > rowBox.bottom; // this row is between the current and start rows, so entirely selected
if (isBetween) {
startIdx = 0;
endIdx = lastSlotIdx;
}
if (isCurrentRow) {
if (isBelowStart) {
startIdx = 0;
endIdx = currentSlot;
} else if (isAboveStart) {
startIdx = currentSlot;
endIdx = lastSlotIdx;
}
}
if (isStartRow) {
// select the cell under the initial point
startIdx = endIdx = rtl ? lastSlotIdx - Math.floor((start.x - rowBox.left) / cellWidth) : Math.floor((start.x - rowBox.left) / cellWidth);
if (isCurrentRow) {
if (currentSlot < startIdx) startIdx = currentSlot;else endIdx = currentSlot; //select current range
} else if (start.y < box.y) {
// the current row is below start row
// select cells to the right of the start cell
endIdx = lastSlotIdx;
} else {
// select cells to the left of the start cell
startIdx = 0;
}
}
return {
startIdx: startIdx,
endIdx: endIdx
};
}
var Popup =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Popup, _React$Component);
function Popup() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Popup.prototype;
_proto.componentDidMount = function componentDidMount() {
var _this$props = this.props,
_this$props$popupOffs = _this$props.popupOffset,
popupOffset = _this$props$popupOffs === void 0 ? 5 : _this$props$popupOffs,
popperRef = _this$props.popperRef,
_getOffset = offset(popperRef.current),
top = _getOffset.top,
left = _getOffset.left,
width = _getOffset.width,
height = _getOffset.height,
viewBottom = window.innerHeight + getScrollTop(window),
viewRight = window.innerWidth + getScrollLeft(window),
bottom = top + height,
right = left + width;
if (bottom > viewBottom || right > viewRight) {
var topOffset, leftOffset;
if (bottom > viewBottom) topOffset = bottom - viewBottom + (popupOffset.y || +popupOffset || 0);
if (right > viewRight) leftOffset = right - viewRight + (popupOffset.x || +popupOffset || 0);
this.setState({
topOffset: topOffset,
leftOffset: leftOffset
}); //eslint-disable-line
}
};
_proto.render = function render() {
var _this = this;
var _this$props2 = this.props,
events = _this$props2.events,
selected = _this$props2.selected,
getters = _this$props2.getters,
accessors = _this$props2.accessors,
components = _this$props2.components,
onSelect = _this$props2.onSelect,
onDoubleClick = _this$props2.onDoubleClick,
onKeyPress = _this$props2.onKeyPress,
slotStart = _this$props2.slotStart,
slotEnd = _this$props2.slotEnd,
localizer = _this$props2.localizer,
popperRef = _this$props2.popperRef;
var width = this.props.position.width,
topOffset = (this.state || {}).topOffset || 0,
leftOffset = (this.state || {}).leftOffset || 0;
var style = {
top: -topOffset,
left: -leftOffset,
minWidth: width + width / 2
};
return React__default.createElement("div", {
style: _extends({}, this.props.style, style),
className: "rbc-overlay",
ref: popperRef
}, React__default.createElement("div", {
className: "rbc-overlay-header"
}, localizer.format(slotStart, 'dayHeaderFormat')), events.map(function (event, idx) {
return React__default.createElement(EventCell, {
key: idx,
type: "popup",
event: event,
getters: getters,
onSelect: onSelect,
accessors: accessors,
components: components,
onDoubleClick: onDoubleClick,
onKeyPress: onKeyPress,
continuesPrior: lt(accessors.end(event), slotStart, 'day'),
continuesAfter: gte(accessors.start(event), slotEnd, 'day'),
slotStart: slotStart,
slotEnd: slotEnd,
selected: isSelected(event, selected),
draggable: true,
onDragStart: function onDragStart() {
return _this.props.handleDragStart(event);
},
onDragEnd: function onDragEnd() {
return _this.props.show();
}
});
}));
};
return Popup;
}(React__default.Component);
Popup.propTypes = {
position: propTypes.object,
popupOffset: propTypes.oneOfType([propTypes.number, propTypes.shape({
x: propTypes.number,
y: propTypes.number
})]),
events: propTypes.array,
selected: propTypes.object,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object.isRequired,
onSelect: propTypes.func,
onDoubleClick: propTypes.func,
onKeyPress: propTypes.func,
handleDragStart: propTypes.func,
show: propTypes.func,
slotStart: propTypes.instanceOf(Date),
slotEnd: propTypes.number,
popperRef: propTypes.oneOfType([propTypes.func, propTypes.shape({
current: propTypes.Element
})])
/**
* The Overlay component, of react-overlays, creates a ref that is passed to the Popup, and
* requires proper ref forwarding to be used without error
*/
};
var Popup$1 = React__default.forwardRef(function (props, ref) {
return React__default.createElement(Popup, _extends({
popperRef: ref
}, props));
});
function _extends$3() {
_extends$3 = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends$3.apply(this, arguments);
}
function _objectWithoutPropertiesLoose$2(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
/**
* A convenience hook around `useState` designed to be paired with
* the component [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) api.
* Callback refs are useful over `useRef()` when you need to respond to the ref being set
* instead of lazily accessing it in an effect.
*
* ```ts
* const [element, attachRef] = useCallbackRef<HTMLDivElement>()
*
* useEffect(() => {
* if (!element) return
*
* const calendar = new FullCalendar.Calendar(element)
*
* return () => {
* calendar.destroy()
* }
* }, [element])
*
* return <div ref={attachRef} />
* ```
*
* @category refs
*/
function useCallbackRef() {
return React.useState(null);
}
var toFnRef = function toFnRef(ref) {
return !ref || typeof ref === 'function' ? ref : function (value) {
ref.current = value;
};
};
function mergeRefs(refA, refB) {
var a = toFnRef(refA);
var b = toFnRef(refB);
return function (value) {
if (a) a(value);
if (b) b(value);
};
}
/**
* Create and returns a single callback ref composed from two other Refs.
*
* ```tsx
* const Button = React.forwardRef((props, ref) => {
* const [element, attachRef] = useCallbackRef<HTMLButtonElement>();
* const mergedRef = useMergedRefs(ref, attachRef);
*
* return <button ref={mergedRef} {...props}/>
* })
* ```
*
* @param refA A Callback or mutable Ref
* @param refB A Callback or mutable Ref
* @category refs
*/
function useMergedRefs(refA, refB) {
return React.useMemo(function () {
return mergeRefs(refA, refB);
}, [refA, refB]);
}
var top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var auto = 'auto';
var basePlacements = [top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM
var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers
var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
function getBasePlacement(placement) {
return placement.split('-')[0];
}
// Returns the layout rect of an element relative to its offsetParent. Layout
// means it doesn't take into account transforms.
function getLayoutRect(element) {
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
function getWindow(node) {
if (node.toString() !== '[object Window]') {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
/*:: declare function isElement(node: mixed): boolean %checks(node instanceof
Element); */
function isElement(node) {
var OwnElement = getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
/*:: declare function isHTMLElement(node: mixed): boolean %checks(node instanceof
HTMLElement); */
function isHTMLElement$1(node) {
var OwnElement = getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
/*:: declare function isShadowRoot(node: mixed): boolean %checks(node instanceof
ShadowRoot); */
function isShadowRoot(node) {
var OwnElement = getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
function contains$1(parent, child) {
var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
if (parent.contains(child)) {
return true;
} // then fallback to custom implementation with Shadow DOM support
else if (rootNode && isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
} // $FlowFixMe[prop-missing]: need a better way to handle this...
next = next.parentNode || next.host;
} while (next);
} // Give up, the result is false
return false;
}
function getNodeName(element) {
return element ? (element.nodeName || '').toLowerCase() : null;
}
function getComputedStyle$1(element) {
return getWindow(element).getComputedStyle(element);
}
function isTableElement(element) {
return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;
}
function getDocumentElement(element) {
// $FlowFixMe[incompatible-return]: assume body is always available
return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
element.document) || window.document).documentElement;
}
function getParentNode(element) {
if (getNodeName(element) === 'html') {
return element;
}
return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
// $FlowFixMe[incompatible-return]
// $FlowFixMe[prop-missing]
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || // DOM Element detected
// $FlowFixMe[incompatible-return]: need a better way to handle this...
element.host || // ShadowRoot detected
// $FlowFixMe[incompatible-call]: HTMLElement is a Node
getDocumentElement(element) // fallback
);
}
function getTrueOffsetParent(element) {
if (!isHTMLElement$1(element) || // https://github.com/popperjs/popper-core/issues/837
getComputedStyle$1(element).position === 'fixed') {
return null;
}
var offsetParent = element.offsetParent;
if (offsetParent) {
var html = getDocumentElement(offsetParent);
if (getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static' && getComputedStyle$1(html).position !== 'static') {
return html;
}
}
return offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getContainingBlock(element) {
var currentNode = getParentNode(element);
while (isHTMLElement$1(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {
var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
if (css.transform !== 'none' || css.perspective !== 'none' || css.willChange && css.willChange !== 'auto') {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
function getOffsetParent(element) {
var window = getWindow(element);
var offsetParent = getTrueOffsetParent(element);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (offsetParent && getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static') {
return window;
}
return offsetParent || getContainingBlock(element) || window;
}
function getMainAxisFromPlacement(placement) {
return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}
function within(min, value, max) {
return Math.max(min, Math.min(value, max));
}
function getFreshSideObject() {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
}
function mergePaddingObject(paddingObject) {
return Object.assign(Object.assign({}, getFreshSideObject()), paddingObject);
}
function expandToHashMap(value, keys) {
return keys.reduce(function (hashMap, key) {
hashMap[key] = value;
return hashMap;
}, {});
}
function arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state,
name = _ref.name;
var arrowElement = state.elements.arrow;
var popperOffsets = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? 'height' : 'width';
if (!arrowElement || !popperOffsets) {
return;
}
var paddingObject = state.modifiersData[name + "#persistent"].padding;
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === 'y' ? top : left;
var maxProp = axis === 'y' ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
var startDiff = popperOffsets[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
var min = paddingObject[minProp];
var max = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset = within(min, center, max); // Prevents breaking syntax highlighting...
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function effect(_ref2) {
var state = _ref2.state,
options = _ref2.options,
name = _ref2.name;
var _options$element = options.element,
arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element,
_options$padding = options.padding,
padding = _options$padding === void 0 ? 0 : _options$padding;
if (arrowElement == null) {
return;
} // CSS selector
if (typeof arrowElement === 'string') {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
{
if (!isHTMLElement$1(arrowElement)) {
console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', 'the arrow.'].join(' '));
}
}
if (!contains$1(state.elements.popper, arrowElement)) {
{
console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', 'element.'].join(' '));
}
return;
}
state.elements.arrow = arrowElement;
state.modifiersData[name + "#persistent"] = {
padding: mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements))
};
} // eslint-disable-next-line import/no-unused-modules
var arrow$1 = {
name: 'arrow',
enabled: true,
phase: 'main',
fn: arrow,
effect: effect,
requires: ['popperOffsets'],
requiresIfExists: ['preventOverflow']
};
var unsetSides = {
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsetsByDPR(_ref) {
var x = _ref.x,
y = _ref.y;
var win = window;
var dpr = win.devicePixelRatio || 1;
return {
x: Math.round(x * dpr) / dpr || 0,
y: Math.round(y * dpr) / dpr || 0
};
}
function mapToStyles(_ref2) {
var _Object$assign2;
var popper = _ref2.popper,
popperRect = _ref2.popperRect,
placement = _ref2.placement,
offsets = _ref2.offsets,
position = _ref2.position,
gpuAcceleration = _ref2.gpuAcceleration,
adaptive = _ref2.adaptive,
roundOffsets = _ref2.roundOffsets;
var _ref3 = roundOffsets ? roundOffsetsByDPR(offsets) : offsets,
_ref3$x = _ref3.x,
x = _ref3$x === void 0 ? 0 : _ref3$x,
_ref3$y = _ref3.y,
y = _ref3$y === void 0 ? 0 : _ref3$y;
var hasX = offsets.hasOwnProperty('x');
var hasY = offsets.hasOwnProperty('y');
var sideX = left;
var sideY = top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent(popper);
if (offsetParent === getWindow(popper)) {
offsetParent = getDocumentElement(popper);
} // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
/*:: offsetParent = (offsetParent: Element); */
if (placement === top) {
sideY = bottom;
y -= offsetParent.clientHeight - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left) {
sideX = right;
x -= offsetParent.clientWidth - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position: position
}, adaptive && unsetSides);
if (gpuAcceleration) {
var _Object$assign;
return Object.assign(Object.assign({}, commonStyles), {}, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign(Object.assign({}, commonStyles), {}, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref4) {
var state = _ref4.state,
options = _ref4.options;
var _options$gpuAccelerat = options.gpuAcceleration,
gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
_options$adaptive = options.adaptive,
adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
_options$roundOffsets = options.roundOffsets,
roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
{
var transitionProperty = getComputedStyle$1(state.elements.popper).transitionProperty || '';
if (adaptive && ['transform', 'top', 'right', 'bottom', 'left'].some(function (property) {
return transitionProperty.indexOf(property) >= 0;
})) {
console.warn(['Popper: Detected CSS transitions on at least one of the following', 'CSS properties: "transform", "top", "right", "bottom", "left".', '\n\n', 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', 'for smooth transitions, or remove these properties from the CSS', 'transition declaration on the popper element if only transitioning', 'opacity or background-color for example.', '\n\n', 'We recommend using the popper element as a wrapper around an inner', 'element that can have any CSS property transitioned for animations.'].join(' '));
}
}
var commonStyles = {
placement: getBasePlacement(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration: gpuAcceleration
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign(Object.assign({}, state.styles.popper), mapToStyles(Object.assign(Object.assign({}, commonStyles), {}, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive: adaptive,
roundOffsets: roundOffsets
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign(Object.assign({}, state.styles.arrow), mapToStyles(Object.assign(Object.assign({}, commonStyles), {}, {
offsets: state.modifiersData.arrow,
position: 'absolute',
adaptive: false,
roundOffsets: roundOffsets
})));
}
state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {}, {
'data-popper-placement': state.placement
});
} // eslint-disable-next-line import/no-unused-modules
var computeStyles$1 = {
name: 'computeStyles',
enabled: true,
phase: 'beforeWrite',
fn: computeStyles,
data: {}
};
var passive = {
passive: true
};
function effect$1(_ref) {
var state = _ref.state,
instance = _ref.instance,
options = _ref.options;
var _options$scroll = options.scroll,
scroll = _options$scroll === void 0 ? true : _options$scroll,
_options$resize = options.resize,
resize = _options$resize === void 0 ? true : _options$resize;
var window = getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.addEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.addEventListener('resize', instance.update, passive);
}
return function () {
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.removeEventListener('resize', instance.update, passive);
}
};
} // eslint-disable-next-line import/no-unused-modules
var eventListeners = {
name: 'eventListeners',
enabled: true,
phase: 'write',
fn: function fn() {},
effect: effect$1,
data: {}
};
var hash = {
left: 'right',
right: 'left',
bottom: 'top',
top: 'bottom'
};
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
var hash$1 = {
start: 'end',
end: 'start'
};
function getOppositeVariationPlacement(placement) {
return placement.replace(/start|end/g, function (matched) {
return hash$1[matched];
});
}
function getBoundingClientRect(element) {
var rect = element.getBoundingClientRect();
return {
width: rect.width,
height: rect.height,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
x: rect.left,
y: rect.top
};
}
function getWindowScroll(node) {
var win = getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}
function getWindowScrollBarX(element) {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
function getViewportRect(element) {
var win = getWindow(element);
var html = getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper
// can be obscured underneath it.
// Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even
// if it isn't open, so if this isn't available, the popper will be detected
// to overflow the bottom of the screen too early.
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently)
// In Chrome, it returns a value very close to 0 (+/-) but contains rounding
// errors due to floating point numbers, so we need to check precision.
// Safari returns a number <= 0, usually < -1 when pinch-zoomed
// Feature detection fails in mobile emulation mode in Chrome.
// Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <
// 0.001
// Fallback here: "Not Safari" userAgent
if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width: width,
height: height,
x: x + getWindowScrollBarX(element),
y: y
};
}
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
function getDocumentRect(element) {
var html = getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = element.ownerDocument.body;
var width = Math.max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = Math.max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle$1(body || html).direction === 'rtl') {
x += Math.max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width: width,
height: height,
x: x,
y: y
};
}
function isScrollParent(element) {
// Firefox wants us to check `-x` and `-y` variations as well
var _getComputedStyle = getComputedStyle$1(element),
overflow = _getComputedStyle.overflow,
overflowX = _getComputedStyle.overflowX,
overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
function getScrollParent(node) {
if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {
// $FlowFixMe[incompatible-return]: assume body is always available
return node.ownerDocument.body;
}
if (isHTMLElement$1(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/
function listScrollParents(element, list) {
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = getNodeName(scrollParent) === 'body';
var win = getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)));
}
function rectToClientRect(rect) {
return Object.assign(Object.assign({}, rect), {}, {
left: rect.x,
top: rect.y,
right: rect.x + rect.width,
bottom: rect.y + rect.height
});
}
function getInnerBoundingClientRect(element) {
var rect = getBoundingClientRect(element);
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent) {
return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement$1(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element) {
var clippingParents = listScrollParents(getParentNode(element));
var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0;
var clipperElement = canEscapeClipping && isHTMLElement$1(element) ? getOffsetParent(element) : element;
if (!isElement(clipperElement)) {
return [];
} // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(function (clippingParent) {
return isElement(clippingParent) && contains$1(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';
});
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents
function getClippingRect(element, boundary, rootBoundary) {
var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents[0];
var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent);
accRect.top = Math.max(rect.top, accRect.top);
accRect.right = Math.min(rect.right, accRect.right);
accRect.bottom = Math.min(rect.bottom, accRect.bottom);
accRect.left = Math.max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}
function getVariation(placement) {
return placement.split('-')[1];
}
function computeOffsets(_ref) {
var reference = _ref.reference,
element = _ref.element,
placement = _ref.placement;
var basePlacement = placement ? getBasePlacement(placement) : null;
var variation = placement ? getVariation(placement) : null;
var commonX = reference.x + reference.width / 2 - element.width / 2;
var commonY = reference.y + reference.height / 2 - element.height / 2;
var offsets;
switch (basePlacement) {
case top:
offsets = {
x: commonX,
y: reference.y - element.height
};
break;
case bottom:
offsets = {
x: commonX,
y: reference.y + reference.height
};
break;
case right:
offsets = {
x: reference.x + reference.width,
y: commonY
};
break;
case left:
offsets = {
x: reference.x - element.width,
y: commonY
};
break;
default:
offsets = {
x: reference.x,
y: reference.y
};
}
var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
if (mainAxis != null) {
var len = mainAxis === 'y' ? 'height' : 'width';
switch (variation) {
case start:
offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
break;
case end:
offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
break;
default:
}
}
return offsets;
}
function detectOverflow(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
_options$placement = _options.placement,
placement = _options$placement === void 0 ? state.placement : _options$placement,
_options$boundary = _options.boundary,
boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
_options$rootBoundary = _options.rootBoundary,
rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
_options$elementConte = _options.elementContext,
elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
_options$altBoundary = _options.altBoundary,
altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
_options$padding = _options.padding,
padding = _options$padding === void 0 ? 0 : _options$padding;
var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
var altContext = elementContext === popper ? reference : popper;
var referenceElement = state.elements.reference;
var popperRect = state.rects.popper;
var element = state.elements[altBoundary ? altContext : elementContext];
var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
var referenceClientRect = getBoundingClientRect(referenceElement);
var popperOffsets = computeOffsets({
reference: referenceClientRect,
element: popperRect,
strategy: 'absolute',
placement: placement
});
var popperClientRect = rectToClientRect(Object.assign(Object.assign({}, popperRect), popperOffsets));
var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
// 0 or negative = within the clipping rect
var overflowOffsets = {
top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
right: elementClientRect.right - clippingClientRect.right + paddingObject.right
};
var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
if (elementContext === popper && offsetData) {
var offset = offsetData[placement];
Object.keys(overflowOffsets).forEach(function (key) {
var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
overflowOffsets[key] += offset[axis] * multiply;
});
}
return overflowOffsets;
}
/*:: type OverflowsMap = { [ComputedPlacement]: number }; */
/*;; type OverflowsMap = { [key in ComputedPlacement]: number }; */
function computeAutoPlacement(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
placement = _options.placement,
boundary = _options.boundary,
rootBoundary = _options.rootBoundary,
padding = _options.padding,
flipVariations = _options.flipVariations,
_options$allowedAutoP = _options.allowedAutoPlacements,
allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
var variation = getVariation(placement);
var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
return getVariation(placement) === variation;
}) : basePlacements;
var allowedPlacements = placements$1.filter(function (placement) {
return allowedAutoPlacements.indexOf(placement) >= 0;
});
if (allowedPlacements.length === 0) {
allowedPlacements = placements$1;
{
console.error(['Popper: The `allowedAutoPlacements` option did not allow any', 'placements. Ensure the `placement` option matches the variation', 'of the allowed placements.', 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(' '));
}
} // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
var overflows = allowedPlacements.reduce(function (acc, placement) {
acc[placement] = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding
})[getBasePlacement(placement)];
return acc;
}, {});
return Object.keys(overflows).sort(function (a, b) {
return overflows[a] - overflows[b];
});
}
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === auto) {
return [];
}
var oppositePlacement = getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
specifiedFallbackPlacements = options.fallbackPlacements,
padding = options.padding,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
_options$flipVariatio = options.flipVariations,
flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
flipVariations: flipVariations,
allowedAutoPlacements: allowedAutoPlacements
}) : placement);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements[0];
for (var i = 0; i < placements.length; i++) {
var placement = placements[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? 'width' : 'height';
var overflow = detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
altBoundary: altBoundary,
padding: padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function (check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
// `2` may be desired in some cases – research later
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop(_i) {
var fittingPlacement = placements.find(function (placement) {
var checks = checksMap.get(placement);
if (checks) {
return checks.slice(0, _i).every(function (check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break") break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
} // eslint-disable-next-line import/no-unused-modules
var flip$1 = {
name: 'flip',
enabled: true,
phase: 'main',
fn: flip,
requiresIfExists: ['offset'],
data: {
_skip: false
}
};
function getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function isAnySideFullyClipped(overflow) {
return [top, right, bottom, left].some(function (side) {
return overflow[side] >= 0;
});
}
function hide(_ref) {
var state = _ref.state,
name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow(state, {
elementContext: 'reference'
});
var popperAltOverflow = detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets: referenceClippingOffsets,
popperEscapeOffsets: popperEscapeOffsets,
isReferenceHidden: isReferenceHidden,
hasPopperEscaped: hasPopperEscaped
};
state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {}, {
'data-popper-reference-hidden': isReferenceHidden,
'data-popper-escaped': hasPopperEscaped
});
} // eslint-disable-next-line import/no-unused-modules
var hide$1 = {
name: 'hide',
enabled: true,
phase: 'main',
requiresIfExists: ['preventOverflow'],
fn: hide
};
function distanceAndSkiddingToXY(placement, rects, offset) {
var basePlacement = getBasePlacement(placement);
var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
var _ref = typeof offset === 'function' ? offset(Object.assign(Object.assign({}, rects), {}, {
placement: placement
})) : offset,
skidding = _ref[0],
distance = _ref[1];
skidding = skidding || 0;
distance = (distance || 0) * invertDistance;
return [left, right].indexOf(basePlacement) >= 0 ? {
x: distance,
y: skidding
} : {
x: skidding,
y: distance
};
}
function offset$1(_ref2) {
var state = _ref2.state,
options = _ref2.options,
name = _ref2.name;
var _options$offset = options.offset,
offset = _options$offset === void 0 ? [0, 0] : _options$offset;
var data = placements.reduce(function (acc, placement) {
acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
return acc;
}, {});
var _data$state$placement = data[state.placement],
x = _data$state$placement.x,
y = _data$state$placement.y;
if (state.modifiersData.popperOffsets != null) {
state.modifiersData.popperOffsets.x += x;
state.modifiersData.popperOffsets.y += y;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
var offset$2 = {
name: 'offset',
enabled: true,
phase: 'main',
requires: ['popperOffsets'],
fn: offset$1
};
function popperOffsets(_ref) {
var state = _ref.state,
name = _ref.name;
// Offsets are the actual position the popper needs to have to be
// properly positioned near its reference element
// This is the most basic placement, and will be adjusted by
// the modifiers in the next step
state.modifiersData[name] = computeOffsets({
reference: state.rects.reference,
element: state.rects.popper,
strategy: 'absolute',
placement: state.placement
});
} // eslint-disable-next-line import/no-unused-modules
var popperOffsets$1 = {
name: 'popperOffsets',
enabled: true,
phase: 'read',
fn: popperOffsets,
data: {}
};
function getAltAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
function preventOverflow(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
padding = options.padding,
_options$tether = options.tether,
tether = _options$tether === void 0 ? true : _options$tether,
_options$tetherOffset = options.tetherOffset,
tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
var overflow = detectOverflow(state, {
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
altBoundary: altBoundary
});
var basePlacement = getBasePlacement(state.placement);
var variation = getVariation(state.placement);
var isBasePlacement = !variation;
var mainAxis = getMainAxisFromPlacement(basePlacement);
var altAxis = getAltAxis(mainAxis);
var popperOffsets = state.modifiersData.popperOffsets;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign(Object.assign({}, state.rects), {}, {
placement: state.placement
})) : tetherOffset;
var data = {
x: 0,
y: 0
};
if (!popperOffsets) {
return;
}
if (checkMainAxis) {
var mainSide = mainAxis === 'y' ? top : left;
var altSide = mainAxis === 'y' ? bottom : right;
var len = mainAxis === 'y' ? 'height' : 'width';
var offset = popperOffsets[mainAxis];
var min = popperOffsets[mainAxis] + overflow[mainSide];
var max = popperOffsets[mainAxis] - overflow[altSide];
var additive = tether ? -popperRect[len] / 2 : 0;
var minLen = variation === start ? referenceRect[len] : popperRect[len];
var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
// outside the reference bounds
var arrowElement = state.elements.arrow;
var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
width: 0,
height: 0
};
var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
var arrowPaddingMin = arrowPaddingObject[mainSide];
var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
// to include its full size in the calculation. If the reference is small
// and near the edge of a boundary, the popper can overflow even if the
// reference is not overflowing as well (e.g. virtual elements with no
// width or height)
var arrowLen = within(0, referenceRect[len], arrowRect[len]);
var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue;
var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue;
var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0;
var tetherMin = popperOffsets[mainAxis] + minOffset - offsetModifierValue - clientOffset;
var tetherMax = popperOffsets[mainAxis] + maxOffset - offsetModifierValue;
var preventedOffset = within(tether ? Math.min(min, tetherMin) : min, offset, tether ? Math.max(max, tetherMax) : max);
popperOffsets[mainAxis] = preventedOffset;
data[mainAxis] = preventedOffset - offset;
}
if (checkAltAxis) {
var _mainSide = mainAxis === 'x' ? top : left;
var _altSide = mainAxis === 'x' ? bottom : right;
var _offset = popperOffsets[altAxis];
var _min = _offset + overflow[_mainSide];
var _max = _offset - overflow[_altSide];
var _preventedOffset = within(_min, _offset, _max);
popperOffsets[altAxis] = _preventedOffset;
data[altAxis] = _preventedOffset - _offset;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
var preventOverflow$1 = {
name: 'preventOverflow',
enabled: true,
phase: 'main',
fn: preventOverflow,
requiresIfExists: ['offset']
};
function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
function getNodeScroll(node) {
if (node === getWindow(node) || !isHTMLElement$1(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}
// Composite means it takes into account transforms as well as layout.
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var documentElement = getDocumentElement(offsetParent);
var rect = getBoundingClientRect(elementOrVirtualElement);
var isOffsetParentAnElement = isHTMLElement$1(offsetParent);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement$1(offsetParent)) {
offsets = getBoundingClientRect(offsetParent);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
function order(modifiers) {
var map = new Map();
var visited = new Set();
var result = [];
modifiers.forEach(function (modifier) {
map.set(modifier.name, modifier);
}); // On visiting object, check for its dependencies and visit them recursively
function sort(modifier) {
visited.add(modifier.name);
var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
requires.forEach(function (dep) {
if (!visited.has(dep)) {
var depModifier = map.get(dep);
if (depModifier) {
sort(depModifier);
}
}
});
result.push(modifier);
}
modifiers.forEach(function (modifier) {
if (!visited.has(modifier.name)) {
// check for visited object
sort(modifier);
}
});
return result;
}
function orderModifiers(modifiers) {
// order based on dependencies
var orderedModifiers = order(modifiers); // order based on phase
return modifierPhases.reduce(function (acc, phase) {
return acc.concat(orderedModifiers.filter(function (modifier) {
return modifier.phase === phase;
}));
}, []);
}
function debounce(fn) {
var pending;
return function () {
if (!pending) {
pending = new Promise(function (resolve) {
Promise.resolve().then(function () {
pending = undefined;
resolve(fn());
});
});
}
return pending;
};
}
function format(str) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return [].concat(args).reduce(function (p, c) {
return p.replace(/%s/, c);
}, str);
}
var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
var VALID_PROPERTIES = ['name', 'enabled', 'phase', 'fn', 'effect', 'requires', 'options'];
function validateModifiers(modifiers) {
modifiers.forEach(function (modifier) {
Object.keys(modifier).forEach(function (key) {
switch (key) {
case 'name':
if (typeof modifier.name !== 'string') {
console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', "\"" + String(modifier.name) + "\""));
}
break;
case 'enabled':
if (typeof modifier.enabled !== 'boolean') {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', "\"" + String(modifier.enabled) + "\""));
}
case 'phase':
if (modifierPhases.indexOf(modifier.phase) < 0) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(', '), "\"" + String(modifier.phase) + "\""));
}
break;
case 'fn':
if (typeof modifier.fn !== 'function') {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', "\"" + String(modifier.fn) + "\""));
}
break;
case 'effect':
if (typeof modifier.effect !== 'function') {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', "\"" + String(modifier.fn) + "\""));
}
break;
case 'requires':
if (!Array.isArray(modifier.requires)) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', "\"" + String(modifier.requires) + "\""));
}
break;
case 'requiresIfExists':
if (!Array.isArray(modifier.requiresIfExists)) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', "\"" + String(modifier.requiresIfExists) + "\""));
}
break;
case 'options':
case 'data':
break;
default:
console.error("PopperJS: an invalid property has been provided to the \"" + modifier.name + "\" modifier, valid properties are " + VALID_PROPERTIES.map(function (s) {
return "\"" + s + "\"";
}).join(', ') + "; but \"" + key + "\" was provided.");
}
modifier.requires && modifier.requires.forEach(function (requirement) {
if (modifiers.find(function (mod) {
return mod.name === requirement;
}) == null) {
console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
}
});
});
});
}
function uniqueBy(arr, fn) {
var identifiers = new Set();
return arr.filter(function (item) {
var identifier = fn(item);
if (!identifiers.has(identifier)) {
identifiers.add(identifier);
return true;
}
});
}
function mergeByName(modifiers) {
var merged = modifiers.reduce(function (merged, current) {
var existing = merged[current.name];
merged[current.name] = existing ? Object.assign(Object.assign(Object.assign({}, existing), current), {}, {
options: Object.assign(Object.assign({}, existing.options), current.options),
data: Object.assign(Object.assign({}, existing.data), current.data)
}) : current;
return merged;
}, {}); // IE11 does not support Object.values
return Object.keys(merged).map(function (key) {
return merged[key];
});
}
var INVALID_ELEMENT_ERROR = 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';
var INFINITE_LOOP_ERROR = 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';
var DEFAULT_OPTIONS = {
placement: 'bottom',
modifiers: [],
strategy: 'absolute'
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function (element) {
return !(element && typeof element.getBoundingClientRect === 'function');
});
}
function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions,
_generatorOptions$def = _generatorOptions.defaultModifiers,
defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
_generatorOptions$def2 = _generatorOptions.defaultOptions,
defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper(reference, popper, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: 'bottom',
orderedModifiers: [],
options: Object.assign(Object.assign({}, DEFAULT_OPTIONS), defaultOptions),
modifiersData: {},
elements: {
reference: reference,
popper: popper
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state: state,
setOptions: function setOptions(options) {
cleanupModifierEffects();
state.options = Object.assign(Object.assign(Object.assign({}, defaultOptions), state.options), options);
state.scrollParents = {
reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
popper: listScrollParents(popper)
}; // Orders the modifiers based on their dependencies and `phase`
// properties
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
state.orderedModifiers = orderedModifiers.filter(function (m) {
return m.enabled;
}); // Validate the provided modifiers so that the consumer will get warned
// if one of the modifiers is invalid for any reason
{
var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) {
var name = _ref.name;
return name;
});
validateModifiers(modifiers);
if (getBasePlacement(state.options.placement) === auto) {
var flipModifier = state.orderedModifiers.find(function (_ref2) {
var name = _ref2.name;
return name === 'flip';
});
if (!flipModifier) {
console.error(['Popper: "auto" placements require the "flip" modifier be', 'present and enabled to work.'].join(' '));
}
}
var _getComputedStyle = getComputedStyle$1(popper),
marginTop = _getComputedStyle.marginTop,
marginRight = _getComputedStyle.marginRight,
marginBottom = _getComputedStyle.marginBottom,
marginLeft = _getComputedStyle.marginLeft; // We no longer take into account `margins` on the popper, and it can
// cause bugs with positioning, so we'll warn the consumer
if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) {
return parseFloat(margin);
})) {
console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', 'between the popper and its reference element or boundary.', 'To replicate margin, use the `offset` modifier, as well as', 'the `padding` option in the `preventOverflow` and `flip`', 'modifiers.'].join(' '));
}
}
runModifierEffects();
return instance.update();
},
// Sync update – it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements,
reference = _state$elements.reference,
popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
// anymore
if (!areValidElements(reference, popper)) {
{
console.error(INVALID_ELEMENT_ERROR);
}
return;
} // Store the reference and popper rects to be read by modifiers
state.rects = {
reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),
popper: getLayoutRect(popper)
}; // Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset = false;
state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(function (modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
var __debug_loops__ = 0;
for (var index = 0; index < state.orderedModifiers.length; index++) {
{
__debug_loops__ += 1;
if (__debug_loops__ > 100) {
console.error(INFINITE_LOOP_ERROR);
break;
}
}
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index],
fn = _state$orderedModifie.fn,
_state$orderedModifie2 = _state$orderedModifie.options,
_options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
name = _state$orderedModifie.name;
if (typeof fn === 'function') {
state = fn({
state: state,
options: _options,
name: name,
instance: instance
}) || state;
}
}
},
// Async and optimistically optimized update – it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce(function () {
return new Promise(function (resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference, popper)) {
{
console.error(INVALID_ELEMENT_ERROR);
}
return instance;
}
instance.setOptions(options).then(function (state) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state);
}
}); // Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects() {
state.orderedModifiers.forEach(function (_ref3) {
var name = _ref3.name,
_ref3$options = _ref3.options,
options = _ref3$options === void 0 ? {} : _ref3$options,
effect = _ref3.effect;
if (typeof effect === 'function') {
var cleanupFn = effect({
state: state,
name: name,
instance: instance,
options: options
});
var noopFn = function noopFn() {};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function (fn) {
return fn();
});
effectCleanupFns = [];
}
return instance;
};
}
// This is b/c the Popper lib is all esm files, and would break in a common js only environment
var createPopper = popperGenerator({
defaultModifiers: [hide$1, popperOffsets$1, computeStyles$1, eventListeners, offset$2, flip$1, preventOverflow$1, arrow$1]
});
/**
* Track whether a component is current mounted. Generally less preferable than
* properlly canceling effects so they don't run after a component is unmounted,
* but helpful in cases where that isn't feasible, such as a `Promise` resolution.
*
* @returns a function that returns the current isMounted state of the component
*
* ```ts
* const [data, setData] = useState(null)
* const isMounted = useMounted()
*
* useEffect(() => {
* fetchdata().then((newData) => {
* if (isMounted()) {
* setData(newData);
* }
* })
* })
* ```
*/
function useMounted() {
var mounted = React.useRef(true);
var isMounted = React.useRef(function () {
return mounted.current;
});
React.useEffect(function () {
return function () {
mounted.current = false;
};
}, []);
return isMounted.current;
}
function useSafeState(state) {
var isMounted = useMounted();
return [state[0], React.useCallback(function (nextState) {
if (!isMounted()) return;
return state[1](nextState);
}, [isMounted, state[1]])];
}
var initialPopperStyles = function initialPopperStyles(position) {
return {
position: position,
top: '0',
left: '0',
opacity: '0',
pointerEvents: 'none'
};
};
var disabledApplyStylesModifier = {
name: 'applyStyles',
enabled: false
}; // until docjs supports type exports...
var ariaDescribedByModifier = {
name: 'ariaDescribedBy',
enabled: true,
phase: 'afterWrite',
effect: function effect(_ref) {
var state = _ref.state;
return function () {
var _state$elements = state.elements,
reference = _state$elements.reference,
popper = _state$elements.popper;
if ('removeAttribute' in reference) {
var ids = (reference.getAttribute('aria-describedby') || '').split(',').filter(function (id) {
return id.trim() !== popper.id;
});
if (!ids.length) reference.removeAttribute('aria-describedby');else reference.setAttribute('aria-describedby', ids.join(','));
}
};
},
fn: function fn(_ref2) {
var _popper$getAttribute;
var state = _ref2.state;
var _state$elements2 = state.elements,
popper = _state$elements2.popper,
reference = _state$elements2.reference;
var role = (_popper$getAttribute = popper.getAttribute('role')) == null ? void 0 : _popper$getAttribute.toLowerCase();
if (popper.id && role === 'tooltip' && 'setAttribute' in reference) {
var ids = reference.getAttribute('aria-describedby');
if (ids && ids.split(',').indexOf(popper.id) !== -1) {
return;
}
reference.setAttribute('aria-describedby', ids ? ids + "," + popper.id : popper.id);
}
}
};
var EMPTY_MODIFIERS = [];
/**
* Position an element relative some reference element using Popper.js
*
* @param referenceElement
* @param popperElement
* @param {object} options
* @param {object=} options.modifiers Popper.js modifiers
* @param {boolean=} options.enabled toggle the popper functionality on/off
* @param {string=} options.placement The popper element placement relative to the reference element
* @param {string=} options.strategy the positioning strategy
* @param {boolean=} options.eventsEnabled have Popper listen on window resize events to reposition the element
* @param {function=} options.onCreate called when the popper is created
* @param {function=} options.onUpdate called when the popper is updated
*
* @returns {UsePopperState} The popper state
*/
function usePopper(referenceElement, popperElement, _temp) {
var _ref3 = _temp === void 0 ? {} : _temp,
_ref3$enabled = _ref3.enabled,
enabled = _ref3$enabled === void 0 ? true : _ref3$enabled,
_ref3$placement = _ref3.placement,
placement = _ref3$placement === void 0 ? 'bottom' : _ref3$placement,
_ref3$strategy = _ref3.strategy,
strategy = _ref3$strategy === void 0 ? 'absolute' : _ref3$strategy,
_ref3$modifiers = _ref3.modifiers,
modifiers = _ref3$modifiers === void 0 ? EMPTY_MODIFIERS : _ref3$modifiers,
config = _objectWithoutPropertiesLoose$2(_ref3, ["enabled", "placement", "strategy", "modifiers"]);
var popperInstanceRef = React.useRef();
var update = React.useCallback(function () {
var _popperInstanceRef$cu;
(_popperInstanceRef$cu = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu.update();
}, []);
var forceUpdate = React.useCallback(function () {
var _popperInstanceRef$cu2;
(_popperInstanceRef$cu2 = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu2.forceUpdate();
}, []);
var _useSafeState = useSafeState(React.useState({
placement: placement,
update: update,
forceUpdate: forceUpdate,
attributes: {},
styles: {
popper: initialPopperStyles(strategy),
arrow: {}
}
})),
popperState = _useSafeState[0],
setState = _useSafeState[1];
var updateModifier = React.useMemo(function () {
return {
name: 'updateStateModifier',
enabled: true,
phase: 'write',
requires: ['computeStyles'],
fn: function fn(_ref4) {
var state = _ref4.state;
var styles = {};
var attributes = {};
Object.keys(state.elements).forEach(function (element) {
styles[element] = state.styles[element];
attributes[element] = state.attributes[element];
});
setState({
state: state,
styles: styles,
attributes: attributes,
update: update,
forceUpdate: forceUpdate,
placement: state.placement
});
}
};
}, [update, forceUpdate, setState]);
React.useEffect(function () {
if (!popperInstanceRef.current || !enabled) return;
popperInstanceRef.current.setOptions({
placement: placement,
strategy: strategy,
modifiers: [].concat(modifiers, [updateModifier, disabledApplyStylesModifier])
}); // intentionally NOT re-running on new modifiers
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [strategy, placement, updateModifier, enabled]);
React.useEffect(function () {
if (!enabled || referenceElement == null || popperElement == null) {
return undefined;
}
popperInstanceRef.current = createPopper(referenceElement, popperElement, _extends$3({}, config, {
placement: placement,
strategy: strategy,
modifiers: [].concat(modifiers, [ariaDescribedByModifier, updateModifier])
}));
return function () {
if (popperInstanceRef.current != null) {
popperInstanceRef.current.destroy();
popperInstanceRef.current = undefined;
setState(function (s) {
return _extends$3({}, s, {
attributes: {},
styles: {
popper: initialPopperStyles(strategy)
}
});
});
}
}; // This is only run once to _create_ the popper
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, referenceElement, popperElement]);
return popperState;
}
/* eslint-disable no-bitwise, no-cond-assign */
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
function contains$2(context, node) {
if (context.contains) return context.contains(node);
if (context.compareDocumentPosition) return context === node || !!(context.compareDocumentPosition(node) & 16);
}
var canUseDOM$1 = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/* eslint-disable no-return-assign */
var optionsSupported = false;
var onceSupported = false;
try {
var options = {
get passive() {
return optionsSupported = true;
},
get once() {
// eslint-disable-next-line no-multi-assign
return onceSupported = optionsSupported = true;
}
};
if (canUseDOM$1) {
window.addEventListener('test', options, options);
window.removeEventListener('test', options, true);
}
} catch (e) {
/* */
}
/**
* An `addEventListener` ponyfill, supports the `once` option
*/
function addEventListener(node, eventName, handler, options) {
if (options && typeof options !== 'boolean' && !onceSupported) {
var once = options.once,
capture = options.capture;
var wrappedHandler = handler;
if (!onceSupported && once) {
wrappedHandler = handler.__once || function onceHandler(event) {
this.removeEventListener(eventName, onceHandler, capture);
handler.call(this, event);
};
handler.__once = wrappedHandler;
}
node.addEventListener(eventName, wrappedHandler, optionsSupported ? options : capture);
}
node.addEventListener(eventName, handler, options);
}
function removeEventListener(node, eventName, handler, options) {
var capture = options && typeof options !== 'boolean' ? options.capture : options;
node.removeEventListener(eventName, handler, capture);
if (handler.__once) {
node.removeEventListener(eventName, handler.__once, capture);
}
}
function listen(node, eventName, handler, options) {
addEventListener(node, eventName, handler, options);
return function () {
removeEventListener(node, eventName, handler, options);
};
}
/**
* Creates a `Ref` whose value is updated in an effect, ensuring the most recent
* value is the one rendered with. Generally only required for Concurrent mode usage
* where previous work in `render()` may be discarded befor being used.
*
* This is safe to access in an event handler.
*
* @param value The `Ref` value
*/
function useCommittedRef(value) {
var ref = React.useRef(value);
React.useEffect(function () {
ref.current = value;
}, [value]);
return ref;
}
function useEventCallback(fn) {
var ref = useCommittedRef(fn);
return React.useCallback(function () {
return ref.current && ref.current.apply(ref, arguments);
}, [ref]);
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var warning = function() {};
{
var printWarning$2 = function printWarning(format, args) {
var len = arguments.length;
args = new Array(len > 1 ? len - 1 : 0);
for (var key = 1; key < len; key++) {
args[key - 1] = arguments[key];
}
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
printWarning$2.apply(null, [format].concat(args));
}
};
}
var warning_1 = warning;
function ownerDocument$1(node) {
return node && node.ownerDocument || document;
}
function safeFindDOMNode(componentOrElement) {
if (componentOrElement && 'setState' in componentOrElement) {
return ReactDOM__default.findDOMNode(componentOrElement);
}
return componentOrElement != null ? componentOrElement : null;
}
var ownerDocument$2 = (function (componentOrElement) {
return ownerDocument$1(safeFindDOMNode(componentOrElement));
});
var escapeKeyCode = 27;
var noop$1 = function noop() {};
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
var getRefTarget = function getRefTarget(ref) {
return ref && ('current' in ref ? ref.current : ref);
};
/**
* The `useRootClose` hook registers your callback on the document
* when rendered. Powers the `<Overlay/>` component. This is used achieve modal
* style behavior where your callback is triggered when the user tries to
* interact with the rest of the document or hits the `esc` key.
*
* @param {Ref<HTMLElement>| HTMLElement} ref The element boundary
* @param {function} onRootClose
* @param {object=} options
* @param {boolean=} options.disabled
* @param {string=} options.clickTrigger The DOM event name (click, mousedown, etc) to attach listeners on
*/
function useRootClose(ref, onRootClose, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
disabled = _ref.disabled,
_ref$clickTrigger = _ref.clickTrigger,
clickTrigger = _ref$clickTrigger === void 0 ? 'click' : _ref$clickTrigger;
var preventMouseRootCloseRef = React.useRef(false);
var onClose = onRootClose || noop$1;
var handleMouseCapture = React.useCallback(function (e) {
var currentTarget = getRefTarget(ref);
warning_1(!!currentTarget, 'RootClose captured a close event but does not have a ref to compare it to. ' + 'useRootClose(), should be passed a ref that resolves to a DOM node');
preventMouseRootCloseRef.current = !currentTarget || isModifiedEvent(e) || !isLeftClickEvent(e) || !!contains$2(currentTarget, e.target);
}, [ref]);
var handleMouse = useEventCallback(function (e) {
if (!preventMouseRootCloseRef.current) {
onClose(e);
}
});
var handleKeyUp = useEventCallback(function (e) {
if (e.keyCode === escapeKeyCode) {
onClose(e);
}
});
React.useEffect(function () {
if (disabled || ref == null) return undefined; // Store the current event to avoid triggering handlers immediately
// https://github.com/facebook/react/issues/20074
var currentEvent = window.event;
var doc = ownerDocument$2(getRefTarget(ref)); // Use capture for this listener so it fires before React's listener, to
// avoid false positives in the contains() check below if the target DOM
// element is removed in the React mouse callback.
var removeMouseCaptureListener = listen(doc, clickTrigger, handleMouseCapture, true);
var removeMouseListener = listen(doc, clickTrigger, function (e) {
// skip if this event is the same as the one running when we added the handlers
if (e === currentEvent) {
currentEvent = undefined;
return;
}
handleMouse(e);
});
var removeKeyupListener = listen(doc, 'keyup', function (e) {
// skip if this event is the same as the one running when we added the handlers
if (e === currentEvent) {
currentEvent = undefined;
return;
}
handleKeyUp(e);
});
var mobileSafariHackListeners = [];
if ('ontouchstart' in doc.documentElement) {
mobileSafariHackListeners = [].slice.call(doc.body.children).map(function (el) {
return listen(el, 'mousemove', noop$1);
});
}
return function () {
removeMouseCaptureListener();
removeMouseListener();
removeKeyupListener();
mobileSafariHackListeners.forEach(function (remove) {
return remove();
});
};
}, [ref, disabled, clickTrigger, handleMouseCapture, handleMouse, handleKeyUp]);
}
var resolveContainerRef = function resolveContainerRef(ref) {
var _ref;
if (typeof document === 'undefined') return null;
if (ref == null) return ownerDocument$1().body;
if (typeof ref === 'function') ref = ref();
if (ref && 'current' in ref) ref = ref.current;
if ((_ref = ref) == null ? void 0 : _ref.nodeType) return ref || null;
return null;
};
function useWaitForDOMRef(ref, onResolved) {
var _useState = React.useState(function () {
return resolveContainerRef(ref);
}),
resolvedRef = _useState[0],
setRef = _useState[1];
if (!resolvedRef) {
var earlyRef = resolveContainerRef(ref);
if (earlyRef) setRef(earlyRef);
}
React.useEffect(function () {
if (onResolved && resolvedRef) {
onResolved(resolvedRef);
}
}, [onResolved, resolvedRef]);
React.useEffect(function () {
var nextRef = resolveContainerRef(ref);
if (nextRef !== resolvedRef) {
setRef(nextRef);
}
}, [ref, resolvedRef]);
return resolvedRef;
}
function toModifierMap(modifiers) {
var result = {};
if (!Array.isArray(modifiers)) {
return modifiers || result;
} // eslint-disable-next-line no-unused-expressions
modifiers == null ? void 0 : modifiers.forEach(function (m) {
result[m.name] = m;
});
return result;
}
function toModifierArray(map) {
if (map === void 0) {
map = {};
}
if (Array.isArray(map)) return map;
return Object.keys(map).map(function (k) {
map[k].name = k;
return map[k];
});
}
function mergeOptionsWithPopperConfig(_ref) {
var _modifiers$preventOve, _modifiers$preventOve2, _modifiers$offset, _modifiers$arrow;
var enabled = _ref.enabled,
enableEvents = _ref.enableEvents,
placement = _ref.placement,
flip = _ref.flip,
offset = _ref.offset,
containerPadding = _ref.containerPadding,
arrowElement = _ref.arrowElement,
_ref$popperConfig = _ref.popperConfig,
popperConfig = _ref$popperConfig === void 0 ? {} : _ref$popperConfig;
var modifiers = toModifierMap(popperConfig.modifiers);
return _extends$3({}, popperConfig, {
placement: placement,
enabled: enabled,
modifiers: toModifierArray(_extends$3({}, modifiers, {
eventListeners: {
enabled: enableEvents
},
preventOverflow: _extends$3({}, modifiers.preventOverflow, {
options: containerPadding ? _extends$3({
padding: containerPadding
}, (_modifiers$preventOve = modifiers.preventOverflow) == null ? void 0 : _modifiers$preventOve.options) : (_modifiers$preventOve2 = modifiers.preventOverflow) == null ? void 0 : _modifiers$preventOve2.options
}),
offset: {
options: _extends$3({
offset: offset
}, (_modifiers$offset = modifiers.offset) == null ? void 0 : _modifiers$offset.options)
},
arrow: _extends$3({}, modifiers.arrow, {
enabled: !!arrowElement,
options: _extends$3({}, (_modifiers$arrow = modifiers.arrow) == null ? void 0 : _modifiers$arrow.options, {
element: arrowElement
})
}),
flip: _extends$3({
enabled: !!flip
}, modifiers.flip)
}))
});
}
/**
* Built on top of `Popper.js`, the overlay component is
* great for custom tooltip overlays.
*/
var Overlay = /*#__PURE__*/React__default.forwardRef(function (props, outerRef) {
var flip = props.flip,
offset = props.offset,
placement = props.placement,
_props$containerPaddi = props.containerPadding,
containerPadding = _props$containerPaddi === void 0 ? 5 : _props$containerPaddi,
_props$popperConfig = props.popperConfig,
popperConfig = _props$popperConfig === void 0 ? {} : _props$popperConfig,
Transition = props.transition;
var _useCallbackRef = useCallbackRef(),
rootElement = _useCallbackRef[0],
attachRef = _useCallbackRef[1];
var _useCallbackRef2 = useCallbackRef(),
arrowElement = _useCallbackRef2[0],
attachArrowRef = _useCallbackRef2[1];
var mergedRef = useMergedRefs(attachRef, outerRef);
var container = useWaitForDOMRef(props.container);
var target = useWaitForDOMRef(props.target);
var _useState = React.useState(!props.show),
exited = _useState[0],
setExited = _useState[1];
var _usePopper = usePopper(target, rootElement, mergeOptionsWithPopperConfig({
placement: placement,
enableEvents: !!props.show,
containerPadding: containerPadding || 5,
flip: flip,
offset: offset,
arrowElement: arrowElement,
popperConfig: popperConfig
})),
styles = _usePopper.styles,
attributes = _usePopper.attributes,
popper = _objectWithoutPropertiesLoose$2(_usePopper, ["styles", "attributes"]);
if (props.show) {
if (exited) setExited(false);
} else if (!props.transition && !exited) {
setExited(true);
}
var handleHidden = function handleHidden() {
setExited(true);
if (props.onExited) {
props.onExited.apply(props, arguments);
}
}; // Don't un-render the overlay while it's transitioning out.
var mountOverlay = props.show || Transition && !exited;
useRootClose(rootElement, props.onHide, {
disabled: !props.rootClose || props.rootCloseDisabled,
clickTrigger: props.rootCloseEvent
});
if (!mountOverlay) {
// Don't bother showing anything if we don't have to.
return null;
}
var child = props.children(_extends$3({}, popper, {
show: !!props.show,
props: _extends$3({}, attributes.popper, {
style: styles.popper,
ref: mergedRef
}),
arrowProps: _extends$3({}, attributes.arrow, {
style: styles.arrow,
ref: attachArrowRef
})
}));
if (Transition) {
var onExit = props.onExit,
onExiting = props.onExiting,
onEnter = props.onEnter,
onEntering = props.onEntering,
onEntered = props.onEntered;
child = /*#__PURE__*/React__default.createElement(Transition, {
"in": props.show,
appear: true,
onExit: onExit,
onExiting: onExiting,
onExited: handleHidden,
onEnter: onEnter,
onEntering: onEntering,
onEntered: onEntered
}, child);
}
return container ? /*#__PURE__*/ReactDOM__default.createPortal(child, container) : null;
});
Overlay.displayName = 'Overlay';
Overlay.propTypes = {
/**
* Set the visibility of the Overlay
*/
show: propTypes.bool,
/** Specify where the overlay element is positioned in relation to the target element */
placement: propTypes.oneOf(placements),
/**
* A DOM Element, Ref to an element, or function that returns either. The `target` element is where
* the overlay is positioned relative to.
*/
target: propTypes.any,
/**
* A DOM Element, Ref to an element, or function that returns either. The `container` will have the Portal children
* appended to it.
*/
container: propTypes.any,
/**
* Enables the Popper.js `flip` modifier, allowing the Overlay to
* automatically adjust it's placement in case of overlap with the viewport or toggle.
* Refer to the [flip docs](https://popper.js.org/popper-documentation.html#modifiers..flip.enabled) for more info
*/
flip: propTypes.bool,
/**
* A render prop that returns an element to overlay and position. See
* the [react-popper documentation](https://github.com/FezVrasta/react-popper#children) for more info.
*
* @type {Function ({
* show: boolean,
* placement: Placement,
* update: () => void,
* forceUpdate: () => void,
* props: {
* ref: (?HTMLElement) => void,
* style: { [string]: string | number },
* aria-labelledby: ?string
* [string]: string | number,
* },
* arrowProps: {
* ref: (?HTMLElement) => void,
* style: { [string]: string | number },
* [string]: string | number,
* },
* }) => React.Element}
*/
children: propTypes.func.isRequired,
/**
* Control how much space there is between the edge of the boundary element and overlay.
* A convenience shortcut to setting `popperConfig.modfiers.preventOverflow.padding`
*/
containerPadding: propTypes.number,
/**
* A set of popper options and props passed directly to react-popper's Popper component.
*/
popperConfig: propTypes.object,
/**
* Specify whether the overlay should trigger `onHide` when the user clicks outside the overlay
*/
rootClose: propTypes.bool,
/**
* Specify event for toggling overlay
*/
rootCloseEvent: propTypes.oneOf(['click', 'mousedown']),
/**
* Specify disabled for disable RootCloseWrapper
*/
rootCloseDisabled: propTypes.bool,
/**
* A Callback fired by the Overlay when it wishes to be hidden.
*
* __required__ when `rootClose` is `true`.
*
* @type func
*/
onHide: function onHide(props) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (props.rootClose) {
var _PropTypes$func;
return (_PropTypes$func = propTypes.func).isRequired.apply(_PropTypes$func, [props].concat(args));
}
return propTypes.func.apply(propTypes, [props].concat(args));
},
/**
* A `react-transition-group@2.0.0` `<Transition/>` component
* used to animate the overlay as it changes visibility.
*/
// @ts-ignore
transition: propTypes.elementType,
/**
* Callback fired before the Overlay transitions in
*/
onEnter: propTypes.func,
/**
* Callback fired as the Overlay begins to transition in
*/
onEntering: propTypes.func,
/**
* Callback fired after the Overlay finishes transitioning in
*/
onEntered: propTypes.func,
/**
* Callback fired right before the Overlay transitions out
*/
onExit: propTypes.func,
/**
* Callback fired as the Overlay begins to transition out
*/
onExiting: propTypes.func,
/**
* Callback fired after the Overlay finishes transitioning out
*/
onExited: propTypes.func
};
function height(node, client) {
var win = isWindow(node);
return win ? win.innerHeight : client ? node.clientHeight : offset(node).height;
}
var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice);
function qsa(element, selector) {
return toArray(element.querySelectorAll(selector));
}
var matchesImpl;
function matches(node, selector) {
if (!matchesImpl) {
var body = document.body;
var nativeMatch = body.matches || body.matchesSelector || body.webkitMatchesSelector || body.mozMatchesSelector || body.msMatchesSelector;
matchesImpl = function matchesImpl(n, s) {
return nativeMatch.call(n, s);
};
}
return matchesImpl(node, selector);
}
function closest(node, selector, stopAt) {
if (node.closest && !stopAt) node.closest(selector);
var nextNode = node;
do {
if (matches(nextNode, selector)) return nextNode;
nextNode = nextNode.parentElement;
} while (nextNode && nextNode !== stopAt && nextNode.nodeType === document.ELEMENT_NODE);
return null;
}
/* eslint-disable no-return-assign */
var optionsSupported$1 = false;
var onceSupported$1 = false;
try {
var options$1 = {
get passive() {
return optionsSupported$1 = true;
},
get once() {
// eslint-disable-next-line no-multi-assign
return onceSupported$1 = optionsSupported$1 = true;
}
};
if (canUseDOM) {
window.addEventListener('test', options$1, options$1);
window.removeEventListener('test', options$1, true);
}
} catch (e) {
/* */
}
/**
* An `addEventListener` ponyfill, supports the `once` option
*/
function addEventListener$1(node, eventName, handler, options) {
if (options && typeof options !== 'boolean' && !onceSupported$1) {
var once = options.once,
capture = options.capture;
var wrappedHandler = handler;
if (!onceSupported$1 && once) {
wrappedHandler = handler.__once || function onceHandler(event) {
this.removeEventListener(eventName, onceHandler, capture);
handler.call(this, event);
};
handler.__once = wrappedHandler;
}
node.addEventListener(eventName, wrappedHandler, optionsSupported$1 ? options : capture);
}
node.addEventListener(eventName, handler, options);
}
function removeEventListener$1(node, eventName, handler, options) {
var capture = options && typeof options !== 'boolean' ? options.capture : options;
node.removeEventListener(eventName, handler, capture);
if (handler.__once) {
node.removeEventListener(eventName, handler.__once, capture);
}
}
function listen$1(node, eventName, handler, options) {
addEventListener$1(node, eventName, handler, options);
return function () {
removeEventListener$1(node, eventName, handler, options);
};
}
function addEventListener$2(type, handler, target) {
if (target === void 0) {
target = document;
}
return listen$1(target, type, handler, {
passive: false
});
}
function isOverContainer(container, x, y) {
return !container || contains(container, document.elementFromPoint(x, y));
}
function getEventNodeFromPoint(node, _ref) {
var clientX = _ref.clientX,
clientY = _ref.clientY;
var target = document.elementFromPoint(clientX, clientY);
return closest(target, '.rbc-event', node);
}
function isEvent(node, bounds) {
return !!getEventNodeFromPoint(node, bounds);
}
function getEventCoordinates(e) {
var target = e;
if (e.touches && e.touches.length) {
target = e.touches[0];
}
return {
clientX: target.clientX,
clientY: target.clientY,
pageX: target.pageX,
pageY: target.pageY
};
}
var clickTolerance = 5;
var clickInterval = 250;
var Selection =
/*#__PURE__*/
function () {
function Selection(node, _temp) {
var _ref2 = _temp === void 0 ? {} : _temp,
_ref2$global = _ref2.global,
global = _ref2$global === void 0 ? false : _ref2$global,
_ref2$longPressThresh = _ref2.longPressThreshold,
longPressThreshold = _ref2$longPressThresh === void 0 ? 250 : _ref2$longPressThresh;
this.isDetached = false;
this.container = node;
this.globalMouse = !node || global;
this.longPressThreshold = longPressThreshold;
this._listeners = Object.create(null);
this._handleInitialEvent = this._handleInitialEvent.bind(this);
this._handleMoveEvent = this._handleMoveEvent.bind(this);
this._handleTerminatingEvent = this._handleTerminatingEvent.bind(this);
this._keyListener = this._keyListener.bind(this);
this._dropFromOutsideListener = this._dropFromOutsideListener.bind(this);
this._dragOverFromOutsideListener = this._dragOverFromOutsideListener.bind(this); // Fixes an iOS 10 bug where scrolling could not be prevented on the window.
// https://github.com/metafizzy/flickity/issues/457#issuecomment-254501356
this._removeTouchMoveWindowListener = addEventListener$2('touchmove', function () {}, window);
this._removeKeyDownListener = addEventListener$2('keydown', this._keyListener);
this._removeKeyUpListener = addEventListener$2('keyup', this._keyListener);
this._removeDropFromOutsideListener = addEventListener$2('drop', this._dropFromOutsideListener);
this._removeDragOverFromOutsideListener = addEventListener$2('dragover', this._dragOverFromOutsideListener);
this._addInitialEventListener();
}
var _proto = Selection.prototype;
_proto.on = function on(type, handler) {
var handlers = this._listeners[type] || (this._listeners[type] = []);
handlers.push(handler);
return {
remove: function remove() {
var idx = handlers.indexOf(handler);
if (idx !== -1) handlers.splice(idx, 1);
}
};
};
_proto.emit = function emit(type) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var result;
var handlers = this._listeners[type] || [];
handlers.forEach(function (fn) {
if (result === undefined) result = fn.apply(void 0, args);
});
return result;
};
_proto.teardown = function teardown() {
this.isDetached = true;
this.listeners = Object.create(null);
this._removeTouchMoveWindowListener && this._removeTouchMoveWindowListener();
this._removeInitialEventListener && this._removeInitialEventListener();
this._removeEndListener && this._removeEndListener();
this._onEscListener && this._onEscListener();
this._removeMoveListener && this._removeMoveListener();
this._removeKeyUpListener && this._removeKeyUpListener();
this._removeKeyDownListener && this._removeKeyDownListener();
this._removeDropFromOutsideListener && this._removeDropFromOutsideListener();
this._removeDragOverFromOutsideListener && this._removeDragOverFromOutsideListener();
};
_proto.isSelected = function isSelected(node) {
var box = this._selectRect;
if (!box || !this.selecting) return false;
return objectsCollide(box, getBoundsForNode(node));
};
_proto.filter = function filter(items) {
var box = this._selectRect; //not selecting
if (!box || !this.selecting) return [];
return items.filter(this.isSelected, this);
} // Adds a listener that will call the handler only after the user has pressed on the screen
// without moving their finger for 250ms.
;
_proto._addLongPressListener = function _addLongPressListener(handler, initialEvent) {
var _this = this;
var timer = null;
var removeTouchMoveListener = null;
var removeTouchEndListener = null;
var handleTouchStart = function handleTouchStart(initialEvent) {
timer = setTimeout(function () {
cleanup();
handler(initialEvent);
}, _this.longPressThreshold);
removeTouchMoveListener = addEventListener$2('touchmove', function () {
return cleanup();
});
removeTouchEndListener = addEventListener$2('touchend', function () {
return cleanup();
});
};
var removeTouchStartListener = addEventListener$2('touchstart', handleTouchStart);
var cleanup = function cleanup() {
if (timer) {
clearTimeout(timer);
}
if (removeTouchMoveListener) {
removeTouchMoveListener();
}
if (removeTouchEndListener) {
removeTouchEndListener();
}
timer = null;
removeTouchMoveListener = null;
removeTouchEndListener = null;
};
if (initialEvent) {
handleTouchStart(initialEvent);
}
return function () {
cleanup();
removeTouchStartListener();
};
} // Listen for mousedown and touchstart events. When one is received, disable the other and setup
// future event handling based on the type of event.
;
_proto._addInitialEventListener = function _addInitialEventListener() {
var _this2 = this;
var removeMouseDownListener = addEventListener$2('mousedown', function (e) {
_this2._removeInitialEventListener();
_this2._handleInitialEvent(e);
_this2._removeInitialEventListener = addEventListener$2('mousedown', _this2._handleInitialEvent);
});
var removeTouchStartListener = addEventListener$2('touchstart', function (e) {
_this2._removeInitialEventListener();
_this2._removeInitialEventListener = _this2._addLongPressListener(_this2._handleInitialEvent, e);
});
this._removeInitialEventListener = function () {
removeMouseDownListener();
removeTouchStartListener();
};
};
_proto._dropFromOutsideListener = function _dropFromOutsideListener(e) {
var _getEventCoordinates = getEventCoordinates(e),
pageX = _getEventCoordinates.pageX,
pageY = _getEventCoordinates.pageY,
clientX = _getEventCoordinates.clientX,
clientY = _getEventCoordinates.clientY;
this.emit('dropFromOutside', {
x: pageX,
y: pageY,
clientX: clientX,
clientY: clientY
});
e.preventDefault();
};
_proto._dragOverFromOutsideListener = function _dragOverFromOutsideListener(e) {
var _getEventCoordinates2 = getEventCoordinates(e),
pageX = _getEventCoordinates2.pageX,
pageY = _getEventCoordinates2.pageY,
clientX = _getEventCoordinates2.clientX,
clientY = _getEventCoordinates2.clientY;
this.emit('dragOverFromOutside', {
x: pageX,
y: pageY,
clientX: clientX,
clientY: clientY
});
e.preventDefault();
};
_proto._handleInitialEvent = function _handleInitialEvent(e) {
if (this.isDetached) {
return;
}
var _getEventCoordinates3 = getEventCoordinates(e),
clientX = _getEventCoordinates3.clientX,
clientY = _getEventCoordinates3.clientY,
pageX = _getEventCoordinates3.pageX,
pageY = _getEventCoordinates3.pageY;
var node = this.container(),
collides,
offsetData; // Right clicks
if (e.which === 3 || e.button === 2 || !isOverContainer(node, clientX, clientY)) return;
if (!this.globalMouse && node && !contains(node, e.target)) {
var _normalizeDistance = normalizeDistance(0),
top = _normalizeDistance.top,
left = _normalizeDistance.left,
bottom = _normalizeDistance.bottom,
right = _normalizeDistance.right;
offsetData = getBoundsForNode(node);
collides = objectsCollide({
top: offsetData.top - top,
left: offsetData.left - left,
bottom: offsetData.bottom + bottom,
right: offsetData.right + right
}, {
top: pageY,
left: pageX
});
if (!collides) return;
}
var result = this.emit('beforeSelect', this._initialEventData = {
isTouch: /^touch/.test(e.type),
x: pageX,
y: pageY,
clientX: clientX,
clientY: clientY
});
if (result === false) return;
switch (e.type) {
case 'mousedown':
this._removeEndListener = addEventListener$2('mouseup', this._handleTerminatingEvent);
this._onEscListener = addEventListener$2('keydown', this._handleTerminatingEvent);
this._removeMoveListener = addEventListener$2('mousemove', this._handleMoveEvent);
break;
case 'touchstart':
this._handleMoveEvent(e);
this._removeEndListener = addEventListener$2('touchend', this._handleTerminatingEvent);
this._removeMoveListener = addEventListener$2('touchmove', this._handleMoveEvent);
break;
default:
break;
}
};
_proto._handleTerminatingEvent = function _handleTerminatingEvent(e) {
var _getEventCoordinates4 = getEventCoordinates(e),
pageX = _getEventCoordinates4.pageX,
pageY = _getEventCoordinates4.pageY;
this.selecting = false;
this._removeEndListener && this._removeEndListener();
this._removeMoveListener && this._removeMoveListener();
if (!this._initialEventData) return;
var inRoot = !this.container || contains(this.container(), e.target);
var bounds = this._selectRect;
var click = this.isClick(pageX, pageY);
this._initialEventData = null;
if (e.key === 'Escape') {
return this.emit('reset');
}
if (!inRoot) {
return this.emit('reset');
}
if (click && inRoot) {
return this._handleClickEvent(e);
} // User drag-clicked in the Selectable area
if (!click) return this.emit('select', bounds);
};
_proto._handleClickEvent = function _handleClickEvent(e) {
var _getEventCoordinates5 = getEventCoordinates(e),
pageX = _getEventCoordinates5.pageX,
pageY = _getEventCoordinates5.pageY,
clientX = _getEventCoordinates5.clientX,
clientY = _getEventCoordinates5.clientY;
var now = new Date().getTime();
if (this._lastClickData && now - this._lastClickData.timestamp < clickInterval) {
// Double click event
this._lastClickData = null;
return this.emit('doubleClick', {
x: pageX,
y: pageY,
clientX: clientX,
clientY: clientY
});
} // Click event
this._lastClickData = {
timestamp: now
};
return this.emit('click', {
x: pageX,
y: pageY,
clientX: clientX,
clientY: clientY
});
};
_proto._handleMoveEvent = function _handleMoveEvent(e) {
if (this._initialEventData === null || this.isDetached) {
return;
}
var _this$_initialEventDa = this._initialEventData,
x = _this$_initialEventDa.x,
y = _this$_initialEventDa.y;
var _getEventCoordinates6 = getEventCoordinates(e),
pageX = _getEventCoordinates6.pageX,
pageY = _getEventCoordinates6.pageY;
var w = Math.abs(x - pageX);
var h = Math.abs(y - pageY);
var left = Math.min(pageX, x),
top = Math.min(pageY, y),
old = this.selecting; // Prevent emitting selectStart event until mouse is moved.
// in Chrome on Windows, mouseMove event may be fired just after mouseDown event.
if (this.isClick(pageX, pageY) && !old && !(w || h)) {
return;
}
this.selecting = true;
this._selectRect = {
top: top,
left: left,
x: pageX,
y: pageY,
right: left + w,
bottom: top + h
};
if (!old) {
this.emit('selectStart', this._initialEventData);
}
if (!this.isClick(pageX, pageY)) this.emit('selecting', this._selectRect);
e.preventDefault();
};
_proto._keyListener = function _keyListener(e) {
this.ctrl = e.metaKey || e.ctrlKey;
};
_proto.isClick = function isClick(pageX, pageY) {
var _this$_initialEventDa2 = this._initialEventData,
x = _this$_initialEventDa2.x,
y = _this$_initialEventDa2.y,
isTouch = _this$_initialEventDa2.isTouch;
return !isTouch && Math.abs(pageX - x) <= clickTolerance && Math.abs(pageY - y) <= clickTolerance;
};
return Selection;
}();
/**
* Resolve the disance prop from either an Int or an Object
* @return {Object}
*/
function normalizeDistance(distance) {
if (distance === void 0) {
distance = 0;
}
if (typeof distance !== 'object') distance = {
top: distance,
left: distance,
right: distance,
bottom: distance
};
return distance;
}
/**
* Given two objects containing "top", "left", "offsetWidth" and "offsetHeight"
* properties, determine if they collide.
* @param {Object|HTMLElement} a
* @param {Object|HTMLElement} b
* @return {bool}
*/
function objectsCollide(nodeA, nodeB, tolerance) {
if (tolerance === void 0) {
tolerance = 0;
}
var _getBoundsForNode = getBoundsForNode(nodeA),
aTop = _getBoundsForNode.top,
aLeft = _getBoundsForNode.left,
_getBoundsForNode$rig = _getBoundsForNode.right,
aRight = _getBoundsForNode$rig === void 0 ? aLeft : _getBoundsForNode$rig,
_getBoundsForNode$bot = _getBoundsForNode.bottom,
aBottom = _getBoundsForNode$bot === void 0 ? aTop : _getBoundsForNode$bot;
var _getBoundsForNode2 = getBoundsForNode(nodeB),
bTop = _getBoundsForNode2.top,
bLeft = _getBoundsForNode2.left,
_getBoundsForNode2$ri = _getBoundsForNode2.right,
bRight = _getBoundsForNode2$ri === void 0 ? bLeft : _getBoundsForNode2$ri,
_getBoundsForNode2$bo = _getBoundsForNode2.bottom,
bBottom = _getBoundsForNode2$bo === void 0 ? bTop : _getBoundsForNode2$bo;
return !( // 'a' bottom doesn't touch 'b' top
aBottom - tolerance < bTop || // 'a' top doesn't touch 'b' bottom
aTop + tolerance > bBottom || // 'a' right doesn't touch 'b' left
aRight - tolerance < bLeft || // 'a' left doesn't touch 'b' right
aLeft + tolerance > bRight);
}
/**
* Given a node, get everything needed to calculate its boundaries
* @param {HTMLElement} node
* @return {Object}
*/
function getBoundsForNode(node) {
if (!node.getBoundingClientRect) return node;
var rect = node.getBoundingClientRect(),
left = rect.left + pageOffset('left'),
top = rect.top + pageOffset('top');
return {
top: top,
left: left,
right: (node.offsetWidth || 0) + left,
bottom: (node.offsetHeight || 0) + top
};
}
function pageOffset(dir) {
if (dir === 'left') return window.pageXOffset || document.body.scrollLeft || 0;
if (dir === 'top') return window.pageYOffset || document.body.scrollTop || 0;
}
var BackgroundCells =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(BackgroundCells, _React$Component);
function BackgroundCells(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
_this.state = {
selecting: false
};
return _this;
}
var _proto = BackgroundCells.prototype;
_proto.componentDidMount = function componentDidMount() {
this.props.selectable && this._selectable();
};
_proto.componentWillUnmount = function componentWillUnmount() {
this._teardownSelectable();
};
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.selectable && !this.props.selectable) this._selectable();
if (!nextProps.selectable && this.props.selectable) this._teardownSelectable();
};
_proto.render = function render() {
var _this$props = this.props,
range = _this$props.range,
getNow = _this$props.getNow,
getters = _this$props.getters,
currentDate = _this$props.date,
Wrapper = _this$props.components.dateCellWrapper;
var _this$state = this.state,
selecting = _this$state.selecting,
startIdx = _this$state.startIdx,
endIdx = _this$state.endIdx;
var current = getNow();
return React__default.createElement("div", {
className: "rbc-row-bg"
}, range.map(function (date, index) {
var selected = selecting && index >= startIdx && index <= endIdx;
var _getters$dayProp = getters.dayProp(date),
className = _getters$dayProp.className,
style = _getters$dayProp.style;
return React__default.createElement(Wrapper, {
key: index,
value: date,
range: range
}, React__default.createElement("div", {
style: style,
className: clsx('rbc-day-bg', className, selected && 'rbc-selected-cell', eq(date, current, 'day') && 'rbc-today', currentDate && month(currentDate) !== month(date) && 'rbc-off-range-bg')
}));
}));
};
_proto._selectable = function _selectable() {
var _this2 = this;
var node = ReactDOM.findDOMNode(this);
var selector = this._selector = new Selection(this.props.container, {
longPressThreshold: this.props.longPressThreshold
});
var selectorClicksHandler = function selectorClicksHandler(point, actionType) {
if (!isEvent(ReactDOM.findDOMNode(_this2), point)) {
var rowBox = getBoundsForNode(node);
var _this2$props = _this2.props,
range = _this2$props.range,
rtl = _this2$props.rtl;
if (pointInBox(rowBox, point)) {
var currentCell = getSlotAtX(rowBox, point.x, rtl, range.length);
_this2._selectSlot({
startIdx: currentCell,
endIdx: currentCell,
action: actionType,
box: point
});
}
}
_this2._initial = {};
_this2.setState({
selecting: false
});
};
selector.on('selecting', function (box) {
var _this2$props2 = _this2.props,
range = _this2$props2.range,
rtl = _this2$props2.rtl;
var startIdx = -1;
var endIdx = -1;
if (!_this2.state.selecting) {
notify(_this2.props.onSelectStart, [box]);
_this2._initial = {
x: box.x,
y: box.y
};
}
if (selector.isSelected(node)) {
var nodeBox = getBoundsForNode(node);
var _dateCellSelection = dateCellSelection(_this2._initial, nodeBox, box, range.length, rtl);
startIdx = _dateCellSelection.startIdx;
endIdx = _dateCellSelection.endIdx;
}
_this2.setState({
selecting: true,
startIdx: startIdx,
endIdx: endIdx
});
});
selector.on('beforeSelect', function (box) {
if (_this2.props.selectable !== 'ignoreEvents') return;
return !isEvent(ReactDOM.findDOMNode(_this2), box);
});
selector.on('click', function (point) {
return selectorClicksHandler(point, 'click');
});
selector.on('doubleClick', function (point) {
return selectorClicksHandler(point, 'doubleClick');
});
selector.on('select', function (bounds) {
_this2._selectSlot(_extends({}, _this2.state, {
action: 'select',
bounds: bounds
}));
_this2._initial = {};
_this2.setState({
selecting: false
});
notify(_this2.props.onSelectEnd, [_this2.state]);
});
};
_proto._teardownSelectable = function _teardownSelectable() {
if (!this._selector) return;
this._selector.teardown();
this._selector = null;
};
_proto._selectSlot = function _selectSlot(_ref) {
var endIdx = _ref.endIdx,
startIdx = _ref.startIdx,
action = _ref.action,
bounds = _ref.bounds,
box = _ref.box;
if (endIdx !== -1 && startIdx !== -1) this.props.onSelectSlot && this.props.onSelectSlot({
start: startIdx,
end: endIdx,
action: action,
bounds: bounds,
box: box,
resourceId: this.props.resourceId
});
};
return BackgroundCells;
}(React__default.Component);
BackgroundCells.propTypes = {
date: propTypes.instanceOf(Date),
getNow: propTypes.func.isRequired,
getters: propTypes.object.isRequired,
components: propTypes.object.isRequired,
container: propTypes.func,
dayPropGetter: propTypes.func,
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
longPressThreshold: propTypes.number,
onSelectSlot: propTypes.func.isRequired,
onSelectEnd: propTypes.func,
onSelectStart: propTypes.func,
range: propTypes.arrayOf(propTypes.instanceOf(Date)),
rtl: propTypes.bool,
type: propTypes.string,
resourceId: propTypes.any
};
/* eslint-disable react/prop-types */
var EventRowMixin = {
propTypes: {
slotMetrics: propTypes.object.isRequired,
selected: propTypes.object,
isAllDay: propTypes.bool,
accessors: propTypes.object.isRequired,
localizer: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
onSelect: propTypes.func,
onDoubleClick: propTypes.func,
onKeyPress: propTypes.func
},
defaultProps: {
segments: [],
selected: {}
},
renderEvent: function renderEvent(props, event) {
var selected = props.selected,
_ = props.isAllDay,
accessors = props.accessors,
getters = props.getters,
onSelect = props.onSelect,
onDoubleClick = props.onDoubleClick,
onKeyPress = props.onKeyPress,
localizer = props.localizer,
slotMetrics = props.slotMetrics,
components = props.components,
resizable = props.resizable;
var continuesPrior = slotMetrics.continuesPrior(event);
var continuesAfter = slotMetrics.continuesAfter(event);
return React__default.createElement(EventCell, {
event: event,
getters: getters,
localizer: localizer,
accessors: accessors,
components: components,
onSelect: onSelect,
onDoubleClick: onDoubleClick,
onKeyPress: onKeyPress,
continuesPrior: continuesPrior,
continuesAfter: continuesAfter,
slotStart: slotMetrics.first,
slotEnd: slotMetrics.last,
selected: isSelected(event, selected),
resizable: resizable
});
},
renderSpan: function renderSpan(slots, len, key, content) {
if (content === void 0) {
content = ' ';
}
var per = Math.abs(len) / slots * 100 + '%';
return React__default.createElement("div", {
key: key,
className: "rbc-row-segment" // IE10/11 need max-width. flex-basis doesn't respect box-sizing
,
style: {
WebkitFlexBasis: per,
flexBasis: per,
maxWidth: per
}
}, content);
}
};
var EventRow =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(EventRow, _React$Component);
function EventRow() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = EventRow.prototype;
_proto.render = function render() {
var _this = this;
var _this$props = this.props,
segments = _this$props.segments,
slots = _this$props.slotMetrics.slots,
className = _this$props.className;
var lastEnd = 1;
return React__default.createElement("div", {
className: clsx(className, 'rbc-row')
}, segments.reduce(function (row, _ref, li) {
var event = _ref.event,
left = _ref.left,
right = _ref.right,
span = _ref.span;
var key = '_lvl_' + li;
var gap = left - lastEnd;
var content = EventRowMixin.renderEvent(_this.props, event);
if (gap) row.push(EventRowMixin.renderSpan(slots, gap, key + "_gap"));
row.push(EventRowMixin.renderSpan(slots, span, key, content));
lastEnd = right + 1;
return row;
}, []));
};
return EventRow;
}(React__default.Component);
EventRow.propTypes = _extends({
segments: propTypes.array
}, EventRowMixin.propTypes);
EventRow.defaultProps = _extends({}, EventRowMixin.defaultProps);
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq$1(array[length][0], key)) {
return length;
}
}
return -1;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto$1 = Function.prototype,
objectProto$2 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/* Built-in method references that are verified to be native. */
var Map$1 = getNative(root, 'Map');
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$3 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty$3.call(data, key) ? data[key] : undefined;
}
/** Used for built-in method references. */
var objectProto$4 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$4.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key);
}
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map$1 || ListCache),
'string': new Hash
};
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED$2);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$1 = 1,
COMPARE_UNORDERED_FLAG$1 = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag$1 = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq$1(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG$1;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag$1:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/** Used for built-in method references. */
var objectProto$5 = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto$5.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/** Used for built-in method references. */
var objectProto$6 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty$5.call(value, 'callee') &&
!propertyIsEnumerable$1.call(value, 'callee');
};
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]',
arrayTag = '[object Array]',
boolTag$1 = '[object Boolean]',
dateTag$1 = '[object Date]',
errorTag$1 = '[object Error]',
funcTag$1 = '[object Function]',
mapTag$1 = '[object Map]',
numberTag$1 = '[object Number]',
objectTag = '[object Object]',
regexpTag$1 = '[object RegExp]',
setTag$1 = '[object Set]',
stringTag$1 = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag$1 = '[object ArrayBuffer]',
dataViewTag$1 = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] =
typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] =
typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] =
typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] =
typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/** Detect free variable `exports`. */
var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports$1 && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/** Used for built-in method references. */
var objectProto$7 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty$6.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8;
return value === proto;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$2 = 1;
/** Used for built-in method references. */
var objectProto$a = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
/* Built-in method references that are verified to be native. */
var Promise$1 = getNative(root, 'Promise');
/* Built-in method references that are verified to be native. */
var Set$1 = getNative(root, 'Set');
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
/** `Object#toString` result references. */
var mapTag$2 = '[object Map]',
objectTag$1 = '[object Object]',
promiseTag = '[object Promise]',
setTag$2 = '[object Set]',
weakMapTag$1 = '[object WeakMap]';
var dataViewTag$2 = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map$1),
promiseCtorString = toSource(Promise$1),
setCtorString = toSource(Set$1),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$2) ||
(Map$1 && getTag(new Map$1) != mapTag$2) ||
(Promise$1 && getTag(Promise$1.resolve()) != promiseTag) ||
(Set$1 && getTag(new Set$1) != setTag$2) ||
(WeakMap && getTag(new WeakMap) != weakMapTag$1)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag$1 ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag$2;
case mapCtorString: return mapTag$2;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag$2;
case weakMapCtorString: return weakMapTag$1;
}
}
return result;
};
}
var getTag$1 = getTag;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$3 = 1;
/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]',
arrayTag$1 = '[object Array]',
objectTag$2 = '[object Object]';
/** Used for built-in method references. */
var objectProto$b = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag$1 : getTag$1(object),
othTag = othIsArr ? arrayTag$1 : getTag$1(other);
objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
var objIsObj = objTag == objectTag$2,
othIsObj = othTag == objectTag$2,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$4 = 1,
COMPARE_UNORDERED_FLAG$2 = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined,
symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result;
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$5 = 1,
COMPARE_UNORDERED_FLAG$3 = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
};
}
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$1 = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax$1(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
function endOfRange(dateRange, unit) {
if (unit === void 0) {
unit = 'day';
}
return {
first: dateRange[0],
last: add(dateRange[dateRange.length - 1], 1, unit)
};
}
function eventSegments(event, range, accessors) {
var _endOfRange = endOfRange(range),
first = _endOfRange.first,
last = _endOfRange.last;
var slots = diff(first, last, 'day');
var start = max(startOf(accessors.start(event), 'day'), first);
var end = min(ceil(accessors.end(event), 'day'), last);
var padding = findIndex(range, function (x) {
return eq(x, start, 'day');
});
var span = diff(start, end, 'day');
span = Math.min(span, slots);
span = Math.max(span, 1);
return {
event: event,
span: span,
left: padding + 1,
right: Math.max(padding + span, 1)
};
}
function eventLevels(rowSegments, limit) {
if (limit === void 0) {
limit = Infinity;
}
var i,
j,
seg,
levels = [],
extra = [];
for (i = 0; i < rowSegments.length; i++) {
seg = rowSegments[i];
for (j = 0; j < levels.length; j++) {
if (!segsOverlap(seg, levels[j])) break;
}
if (j >= limit) {
extra.push(seg);
} else {
(levels[j] || (levels[j] = [])).push(seg);
}
}
for (i = 0; i < levels.length; i++) {
levels[i].sort(function (a, b) {
return a.left - b.left;
}); //eslint-disable-line
}
return {
levels: levels,
extra: extra
};
}
function inRange$1(e, start, end, accessors) {
var eStart = startOf(accessors.start(e), 'day');
var eEnd = accessors.end(e);
var startsBeforeEnd = lte(eStart, end, 'day'); // when the event is zero duration we need to handle a bit differently
var endsAfterStart = !eq(eStart, eEnd, 'minutes') ? gt(eEnd, start, 'minutes') : gte(eEnd, start, 'minutes');
return startsBeforeEnd && endsAfterStart;
}
function segsOverlap(seg, otherSegs) {
return otherSegs.some(function (otherSeg) {
return otherSeg.left <= seg.right && otherSeg.right >= seg.left;
});
}
function sortEvents(evtA, evtB, accessors) {
var startSort = +startOf(accessors.start(evtA), 'day') - +startOf(accessors.start(evtB), 'day');
var durA = diff(accessors.start(evtA), ceil(accessors.end(evtA), 'day'), 'day');
var durB = diff(accessors.start(evtB), ceil(accessors.end(evtB), 'day'), 'day');
return startSort || // sort by start Day first
Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first
!!accessors.allDay(evtB) - !!accessors.allDay(evtA) || // then allDay single day events
+accessors.start(evtA) - +accessors.start(evtB); // then sort by start time
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil$1 = Math.ceil,
nativeMax$2 = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax$2(nativeCeil$1((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range$1 = createRange();
var isSegmentInSlot = function isSegmentInSlot(seg, slot) {
return seg.left <= slot && seg.right >= slot;
};
var eventsInSlot = function eventsInSlot(segments, slot) {
return segments.filter(function (seg) {
return isSegmentInSlot(seg, slot);
}).length;
};
var EventEndingRow =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(EventEndingRow, _React$Component);
function EventEndingRow() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = EventEndingRow.prototype;
_proto.render = function render() {
var _this$props = this.props,
segments = _this$props.segments,
slots = _this$props.slotMetrics.slots;
var rowSegments = eventLevels(segments).levels[0];
var current = 1,
lastEnd = 1,
row = [];
while (current <= slots) {
var key = '_lvl_' + current;
var _ref = rowSegments.filter(function (seg) {
return isSegmentInSlot(seg, current);
})[0] || {},
event = _ref.event,
left = _ref.left,
right = _ref.right,
span = _ref.span; //eslint-disable-line
if (!event) {
current++;
continue;
}
var gap = Math.max(0, left - lastEnd);
if (this.canRenderSlotEvent(left, span)) {
var content = EventRowMixin.renderEvent(this.props, event);
if (gap) {
row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap'));
}
row.push(EventRowMixin.renderSpan(slots, span, key, content));
lastEnd = current = right + 1;
} else {
if (gap) {
row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap'));
}
row.push(EventRowMixin.renderSpan(slots, 1, key, this.renderShowMore(segments, current)));
lastEnd = current = current + 1;
}
}
return React__default.createElement("div", {
className: "rbc-row"
}, row);
};
_proto.canRenderSlotEvent = function canRenderSlotEvent(slot, span) {
var segments = this.props.segments;
return range$1(slot, slot + span).every(function (s) {
var count = eventsInSlot(segments, s);
return count === 1;
});
};
_proto.renderShowMore = function renderShowMore(segments, slot) {
var _this = this;
var localizer = this.props.localizer;
var count = eventsInSlot(segments, slot);
return count ? React__default.createElement("a", {
key: 'sm_' + slot,
href: "#",
className: 'rbc-show-more',
onClick: function onClick(e) {
return _this.showMore(slot, e);
}
}, localizer.messages.showMore(count)) : false;
};
_proto.showMore = function showMore(slot, e) {
e.preventDefault();
this.props.onShowMore(slot, e.target);
};
return EventEndingRow;
}(React__default.Component);
EventEndingRow.propTypes = _extends({
segments: propTypes.array,
slots: propTypes.number,
onShowMore: propTypes.func
}, EventRowMixin.propTypes);
EventEndingRow.defaultProps = _extends({}, EventRowMixin.defaultProps);
var ScrollableWeekWrapper = function ScrollableWeekWrapper(_ref) {
var children = _ref.children;
return React__default.createElement("div", {
className: "rbc-row-content-scroll-container"
}, children);
};
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (newInputs[i] !== lastInputs[i]) {
return false;
}
}
return true;
}
function memoizeOne(resultFn, isEqual) {
if (isEqual === void 0) { isEqual = areInputsEqual; }
var lastThis;
var lastArgs = [];
var lastResult;
var calledOnce = false;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {
return lastResult;
}
lastResult = resultFn.apply(this, newArgs);
calledOnce = true;
lastThis = this;
lastArgs = newArgs;
return lastResult;
}
return memoized;
}
var isSegmentInSlot$1 = function isSegmentInSlot(seg, slot) {
return seg.left <= slot && seg.right >= slot;
};
var isEqual = function isEqual(a, b) {
return a[0].range === b[0].range && a[0].events === b[0].events;
};
function getSlotMetrics() {
return memoizeOne(function (options) {
var range = options.range,
events = options.events,
maxRows = options.maxRows,
minRows = options.minRows,
accessors = options.accessors;
var _endOfRange = endOfRange(range),
first = _endOfRange.first,
last = _endOfRange.last;
var segments = events.map(function (evt) {
return eventSegments(evt, range, accessors);
});
var _eventLevels = eventLevels(segments, Math.max(maxRows - 1, 1)),
levels = _eventLevels.levels,
extra = _eventLevels.extra;
while (levels.length < minRows) {
levels.push([]);
}
return {
first: first,
last: last,
levels: levels,
extra: extra,
range: range,
slots: range.length,
clone: function clone(args) {
var metrics = getSlotMetrics();
return metrics(_extends({}, options, args));
},
getDateForSlot: function getDateForSlot(slotNumber) {
return range[slotNumber];
},
getSlotForDate: function getSlotForDate(date) {
return range.find(function (r) {
return eq(r, date, 'day');
});
},
getEventsForSlot: function getEventsForSlot(slot) {
return segments.filter(function (seg) {
return isSegmentInSlot$1(seg, slot);
}).map(function (seg) {
return seg.event;
});
},
continuesPrior: function continuesPrior(event) {
return lt(accessors.start(event), first, 'day');
},
continuesAfter: function continuesAfter(event) {
var eventEnd = accessors.end(event);
var singleDayDuration = eq(accessors.start(event), eventEnd, 'minutes');
return singleDayDuration ? gte(eventEnd, last, 'minutes') : gt(eventEnd, last, 'minutes');
}
};
}, isEqual);
}
var DateContentRow =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DateContentRow, _React$Component);
function DateContentRow() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handleSelectSlot = function (slot) {
var _this$props = _this.props,
range = _this$props.range,
onSelectSlot = _this$props.onSelectSlot;
onSelectSlot(range.slice(slot.start, slot.end + 1), slot);
};
_this.handleShowMore = function (slot, target) {
var _this$props2 = _this.props,
range = _this$props2.range,
onShowMore = _this$props2.onShowMore;
var metrics = _this.slotMetrics(_this.props);
var row = qsa(ReactDOM.findDOMNode(_assertThisInitialized(_this)), '.rbc-row-bg')[0];
var cell;
if (row) cell = row.children[slot - 1];
var events = metrics.getEventsForSlot(slot);
onShowMore(events, range[slot - 1], cell, slot, target);
};
_this.createHeadingRef = function (r) {
_this.headingRow = r;
};
_this.createEventRef = function (r) {
_this.eventRow = r;
};
_this.getContainer = function () {
var container = _this.props.container;
return container ? container() : ReactDOM.findDOMNode(_assertThisInitialized(_this));
};
_this.renderHeadingCell = function (date, index) {
var _this$props3 = _this.props,
renderHeader = _this$props3.renderHeader,
getNow = _this$props3.getNow;
return renderHeader({
date: date,
key: "header_" + index,
className: clsx('rbc-date-cell', eq(date, getNow(), 'day') && 'rbc-now')
});
};
_this.renderDummy = function () {
var _this$props4 = _this.props,
className = _this$props4.className,
range = _this$props4.range,
renderHeader = _this$props4.renderHeader,
showAllEvents = _this$props4.showAllEvents;
return React__default.createElement("div", {
className: className
}, React__default.createElement("div", {
className: clsx('rbc-row-content', showAllEvents && 'rbc-row-content-scrollable')
}, renderHeader && React__default.createElement("div", {
className: "rbc-row",
ref: _this.createHeadingRef
}, range.map(_this.renderHeadingCell)), React__default.createElement("div", {
className: "rbc-row",
ref: _this.createEventRef
}, React__default.createElement("div", {
className: "rbc-row-segment"
}, React__default.createElement("div", {
className: "rbc-event"
}, React__default.createElement("div", {
className: "rbc-event-content"
}, "\xA0"))))));
};
_this.slotMetrics = getSlotMetrics();
return _this;
}
var _proto = DateContentRow.prototype;
_proto.getRowLimit = function getRowLimit() {
var eventHeight = height(this.eventRow);
var headingHeight = this.headingRow ? height(this.headingRow) : 0;
var eventSpace = height(ReactDOM.findDOMNode(this)) - headingHeight;
return Math.max(Math.floor(eventSpace / eventHeight), 1);
};
_proto.render = function render() {
var _this$props5 = this.props,
date = _this$props5.date,
rtl = _this$props5.rtl,
range = _this$props5.range,
className = _this$props5.className,
selected = _this$props5.selected,
selectable = _this$props5.selectable,
renderForMeasure = _this$props5.renderForMeasure,
accessors = _this$props5.accessors,
getters = _this$props5.getters,
components = _this$props5.components,
getNow = _this$props5.getNow,
renderHeader = _this$props5.renderHeader,
onSelect = _this$props5.onSelect,
localizer = _this$props5.localizer,
onSelectStart = _this$props5.onSelectStart,
onSelectEnd = _this$props5.onSelectEnd,
onDoubleClick = _this$props5.onDoubleClick,
onKeyPress = _this$props5.onKeyPress,
resourceId = _this$props5.resourceId,
longPressThreshold = _this$props5.longPressThreshold,
isAllDay = _this$props5.isAllDay,
resizable = _this$props5.resizable,
showAllEvents = _this$props5.showAllEvents;
if (renderForMeasure) return this.renderDummy();
var metrics = this.slotMetrics(this.props);
var levels = metrics.levels,
extra = metrics.extra;
var ScrollableWeekComponent = showAllEvents ? ScrollableWeekWrapper : NoopWrapper;
var WeekWrapper = components.weekWrapper;
var eventRowProps = {
selected: selected,
accessors: accessors,
getters: getters,
localizer: localizer,
components: components,
onSelect: onSelect,
onDoubleClick: onDoubleClick,
onKeyPress: onKeyPress,
resourceId: resourceId,
slotMetrics: metrics,
resizable: resizable
};
return React__default.createElement("div", {
className: className,
role: "rowgroup"
}, React__default.createElement(BackgroundCells, {
date: date,
getNow: getNow,
rtl: rtl,
range: range,
selectable: selectable,
container: this.getContainer,
getters: getters,
onSelectStart: onSelectStart,
onSelectEnd: onSelectEnd,
onSelectSlot: this.handleSelectSlot,
components: components,
longPressThreshold: longPressThreshold,
resourceId: resourceId
}), React__default.createElement("div", {
className: clsx('rbc-row-content', showAllEvents && 'rbc-row-content-scrollable'),
role: "row"
}, renderHeader && React__default.createElement("div", {
className: "rbc-row ",
ref: this.createHeadingRef
}, range.map(this.renderHeadingCell)), React__default.createElement(ScrollableWeekComponent, null, React__default.createElement(WeekWrapper, _extends({
isAllDay: isAllDay
}, eventRowProps), levels.map(function (segs, idx) {
return React__default.createElement(EventRow, _extends({
key: idx,
segments: segs
}, eventRowProps));
}), !!extra.length && React__default.createElement(EventEndingRow, _extends({
segments: extra,
onShowMore: this.handleShowMore
}, eventRowProps))))));
};
return DateContentRow;
}(React__default.Component);
DateContentRow.propTypes = {
date: propTypes.instanceOf(Date),
events: propTypes.array.isRequired,
range: propTypes.array.isRequired,
rtl: propTypes.bool,
resizable: propTypes.bool,
resourceId: propTypes.any,
renderForMeasure: propTypes.bool,
renderHeader: propTypes.func,
container: propTypes.func,
selected: propTypes.object,
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
longPressThreshold: propTypes.number,
onShowMore: propTypes.func,
showAllEvents: propTypes.bool,
onSelectSlot: propTypes.func,
onSelect: propTypes.func,
onSelectEnd: propTypes.func,
onSelectStart: propTypes.func,
onDoubleClick: propTypes.func,
onKeyPress: propTypes.func,
dayPropGetter: propTypes.func,
getNow: propTypes.func.isRequired,
isAllDay: propTypes.bool,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object.isRequired,
minRows: propTypes.number.isRequired,
maxRows: propTypes.number.isRequired
};
DateContentRow.defaultProps = {
minRows: 0,
maxRows: Infinity
};
var Header = function Header(_ref) {
var label = _ref.label;
return React__default.createElement("span", {
role: "columnheader",
"aria-sort": "none"
}, label);
};
Header.propTypes = {
label: propTypes.node
};
var DateHeader = function DateHeader(_ref) {
var label = _ref.label,
drilldownView = _ref.drilldownView,
onDrillDown = _ref.onDrillDown;
if (!drilldownView) {
return React__default.createElement("span", null, label);
}
return React__default.createElement("a", {
href: "#",
onClick: onDrillDown,
role: "cell"
}, label);
};
DateHeader.propTypes = {
label: propTypes.node,
date: propTypes.instanceOf(Date),
drilldownView: propTypes.string,
onDrillDown: propTypes.func,
isOffRange: propTypes.bool
};
var eventsForWeek = function eventsForWeek(evts, start, end, accessors) {
return evts.filter(function (e) {
return inRange$1(e, start, end, accessors);
});
};
var MonthView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(MonthView, _React$Component);
function MonthView() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.getContainer = function () {
return ReactDOM.findDOMNode(_assertThisInitialized(_this));
};
_this.renderWeek = function (week, weekIdx) {
var _this$props = _this.props,
events = _this$props.events,
components = _this$props.components,
selectable = _this$props.selectable,
getNow = _this$props.getNow,
selected = _this$props.selected,
date = _this$props.date,
localizer = _this$props.localizer,
longPressThreshold = _this$props.longPressThreshold,
accessors = _this$props.accessors,
getters = _this$props.getters,
showAllEvents = _this$props.showAllEvents;
var _this$state = _this.state,
needLimitMeasure = _this$state.needLimitMeasure,
rowLimit = _this$state.rowLimit;
events = eventsForWeek(events, week[0], week[week.length - 1], accessors);
events.sort(function (a, b) {
return sortEvents(a, b, accessors);
});
return React__default.createElement(DateContentRow, {
key: weekIdx,
ref: weekIdx === 0 ? _this.slotRowRef : undefined,
container: _this.getContainer,
className: "rbc-month-row",
getNow: getNow,
date: date,
range: week,
events: events,
maxRows: showAllEvents ? Infinity : rowLimit,
selected: selected,
selectable: selectable,
components: components,
accessors: accessors,
getters: getters,
localizer: localizer,
renderHeader: _this.readerDateHeading,
renderForMeasure: needLimitMeasure,
onShowMore: _this.handleShowMore,
onSelect: _this.handleSelectEvent,
onDoubleClick: _this.handleDoubleClickEvent,
onKeyPress: _this.handleKeyPressEvent,
onSelectSlot: _this.handleSelectSlot,
longPressThreshold: longPressThreshold,
rtl: _this.props.rtl,
resizable: _this.props.resizable,
showAllEvents: showAllEvents
});
};
_this.readerDateHeading = function (_ref) {
var date = _ref.date,
className = _ref.className,
props = _objectWithoutPropertiesLoose(_ref, ["date", "className"]);
var _this$props2 = _this.props,
currentDate = _this$props2.date,
getDrilldownView = _this$props2.getDrilldownView,
localizer = _this$props2.localizer;
var isOffRange = month(date) !== month(currentDate);
var isCurrent = eq(date, currentDate, 'day');
var drilldownView = getDrilldownView(date);
var label = localizer.format(date, 'dateFormat');
var DateHeaderComponent = _this.props.components.dateHeader || DateHeader;
return React__default.createElement("div", _extends({}, props, {
className: clsx(className, isOffRange && 'rbc-off-range', isCurrent && 'rbc-current'),
role: "cell"
}), React__default.createElement(DateHeaderComponent, {
label: label,
date: date,
drilldownView: drilldownView,
isOffRange: isOffRange,
onDrillDown: function onDrillDown(e) {
return _this.handleHeadingClick(date, drilldownView, e);
}
}));
};
_this.handleSelectSlot = function (range, slotInfo) {
_this._pendingSelection = _this._pendingSelection.concat(range);
clearTimeout(_this._selectTimer);
_this._selectTimer = setTimeout(function () {
return _this.selectDates(slotInfo);
});
};
_this.handleHeadingClick = function (date, view, e) {
e.preventDefault();
_this.clearSelection();
notify(_this.props.onDrillDown, [date, view]);
};
_this.handleSelectEvent = function () {
_this.clearSelection();
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
notify(_this.props.onSelectEvent, args);
};
_this.handleDoubleClickEvent = function () {
_this.clearSelection();
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
notify(_this.props.onDoubleClickEvent, args);
};
_this.handleKeyPressEvent = function () {
_this.clearSelection();
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
notify(_this.props.onKeyPressEvent, args);
};
_this.handleShowMore = function (events, date, cell, slot, target) {
var _this$props3 = _this.props,
popup = _this$props3.popup,
onDrillDown = _this$props3.onDrillDown,
onShowMore = _this$props3.onShowMore,
getDrilldownView = _this$props3.getDrilldownView; //cancel any pending selections so only the event click goes through.
_this.clearSelection();
if (popup) {
var position$1 = position(cell, ReactDOM.findDOMNode(_assertThisInitialized(_this)));
_this.setState({
overlay: {
date: date,
events: events,
position: position$1,
target: target
}
});
} else {
notify(onDrillDown, [date, getDrilldownView(date) || views.DAY]);
}
notify(onShowMore, [events, date, slot]);
};
_this.overlayDisplay = function () {
_this.setState({
overlay: null
});
};
_this._bgRows = [];
_this._pendingSelection = [];
_this.slotRowRef = React__default.createRef();
_this.state = {
rowLimit: 5,
needLimitMeasure: true
};
return _this;
}
var _proto = MonthView.prototype;
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(_ref2) {
var date = _ref2.date;
this.setState({
needLimitMeasure: !eq(date, this.props.date, 'month')
});
};
_proto.componentDidMount = function componentDidMount() {
var _this2 = this;
var running;
if (this.state.needLimitMeasure) this.measureRowLimit(this.props);
window.addEventListener('resize', this._resizeListener = function () {
if (!running) {
request(function () {
running = false;
_this2.setState({
needLimitMeasure: true
}); //eslint-disable-line
});
}
}, false);
};
_proto.componentDidUpdate = function componentDidUpdate() {
if (this.state.needLimitMeasure) this.measureRowLimit(this.props);
};
_proto.componentWillUnmount = function componentWillUnmount() {
window.removeEventListener('resize', this._resizeListener, false);
};
_proto.render = function render() {
var _this$props4 = this.props,
date = _this$props4.date,
localizer = _this$props4.localizer,
className = _this$props4.className,
month = visibleDays(date, localizer),
weeks = chunk(month, 7);
this._weekCount = weeks.length;
return React__default.createElement("div", {
className: clsx('rbc-month-view', className),
role: "table",
"aria-label": "Month View"
}, React__default.createElement("div", {
className: "rbc-row rbc-month-header",
role: "row"
}, this.renderHeaders(weeks[0])), weeks.map(this.renderWeek), this.props.popup && this.renderOverlay());
};
_proto.renderHeaders = function renderHeaders(row) {
var _this$props5 = this.props,
localizer = _this$props5.localizer,
components = _this$props5.components;
var first = row[0];
var last = row[row.length - 1];
var HeaderComponent = components.header || Header;
return range(first, last, 'day').map(function (day, idx) {
return React__default.createElement("div", {
key: 'header_' + idx,
className: "rbc-header"
}, React__default.createElement(HeaderComponent, {
date: day,
localizer: localizer,
label: localizer.format(day, 'weekdayFormat')
}));
});
};
_proto.renderOverlay = function renderOverlay() {
var _this3 = this;
var overlay = this.state && this.state.overlay || {};
var _this$props6 = this.props,
accessors = _this$props6.accessors,
localizer = _this$props6.localizer,
components = _this$props6.components,
getters = _this$props6.getters,
selected = _this$props6.selected,
popupOffset = _this$props6.popupOffset;
return React__default.createElement(Overlay, {
rootClose: true,
placement: "bottom",
show: !!overlay.position,
onHide: function onHide() {
return _this3.setState({
overlay: null
});
},
target: function target() {
return overlay.target;
}
}, function (_ref3) {
var props = _ref3.props;
return React__default.createElement(Popup$1, _extends({}, props, {
popupOffset: popupOffset,
accessors: accessors,
getters: getters,
selected: selected,
components: components,
localizer: localizer,
position: overlay.position,
show: _this3.overlayDisplay,
events: overlay.events,
slotStart: overlay.date,
slotEnd: overlay.end,
onSelect: _this3.handleSelectEvent,
onDoubleClick: _this3.handleDoubleClickEvent,
onKeyPress: _this3.handleKeyPressEvent,
handleDragStart: _this3.props.handleDragStart
}));
});
};
_proto.measureRowLimit = function measureRowLimit() {
this.setState({
needLimitMeasure: false,
rowLimit: this.slotRowRef.current.getRowLimit()
});
};
_proto.selectDates = function selectDates(slotInfo) {
var slots = this._pendingSelection.slice();
this._pendingSelection = [];
slots.sort(function (a, b) {
return +a - +b;
});
notify(this.props.onSelectSlot, {
slots: slots,
start: slots[0],
end: slots[slots.length - 1],
action: slotInfo.action,
bounds: slotInfo.bounds,
box: slotInfo.box
});
};
_proto.clearSelection = function clearSelection() {
clearTimeout(this._selectTimer);
this._pendingSelection = [];
};
return MonthView;
}(React__default.Component);
MonthView.propTypes = {
events: propTypes.array.isRequired,
date: propTypes.instanceOf(Date),
min: propTypes.instanceOf(Date),
max: propTypes.instanceOf(Date),
step: propTypes.number,
getNow: propTypes.func.isRequired,
scrollToTime: propTypes.instanceOf(Date),
rtl: propTypes.bool,
resizable: propTypes.bool,
width: propTypes.number,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object.isRequired,
selected: propTypes.object,
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
longPressThreshold: propTypes.number,
onNavigate: propTypes.func,
onSelectSlot: propTypes.func,
onSelectEvent: propTypes.func,
onDoubleClickEvent: propTypes.func,
onKeyPressEvent: propTypes.func,
onShowMore: propTypes.func,
showAllEvents: propTypes.bool,
onDrillDown: propTypes.func,
getDrilldownView: propTypes.func.isRequired,
popup: propTypes.bool,
handleDragStart: propTypes.func,
popupOffset: propTypes.oneOfType([propTypes.number, propTypes.shape({
x: propTypes.number,
y: propTypes.number
})])
};
MonthView.range = function (date, _ref4) {
var localizer = _ref4.localizer;
var start = firstVisibleDay(date, localizer);
var end = lastVisibleDay(date, localizer);
return {
start: start,
end: end
};
};
MonthView.navigate = function (date, action) {
switch (action) {
case navigate.PREVIOUS:
return add(date, -1, 'month');
case navigate.NEXT:
return add(date, 1, 'month');
default:
return date;
}
};
MonthView.title = function (date, _ref5) {
var localizer = _ref5.localizer;
return localizer.format(date, 'monthHeaderFormat');
};
var getDstOffset = function getDstOffset(start, end) {
return start.getTimezoneOffset() - end.getTimezoneOffset();
};
var getKey$1 = function getKey(min, max, step, slots) {
return "" + +startOf(min, 'minutes') + ("" + +startOf(max, 'minutes')) + (step + "-" + slots);
};
function getSlotMetrics$1(_ref) {
var start = _ref.min,
end = _ref.max,
step = _ref.step,
timeslots = _ref.timeslots;
var key = getKey$1(start, end, step, timeslots); // if the start is on a DST-changing day but *after* the moment of DST
// transition we need to add those extra minutes to our minutesFromMidnight
var daystart = startOf(start, 'day');
var daystartdstoffset = getDstOffset(daystart, start);
var totalMin = 1 + diff(start, end, 'minutes') + getDstOffset(start, end);
var minutesFromMidnight = diff(daystart, start, 'minutes') + daystartdstoffset;
var numGroups = Math.ceil(totalMin / (step * timeslots));
var numSlots = numGroups * timeslots;
var groups = new Array(numGroups);
var slots = new Array(numSlots); // Each slot date is created from "zero", instead of adding `step` to
// the previous one, in order to avoid DST oddities
for (var grp = 0; grp < numGroups; grp++) {
groups[grp] = new Array(timeslots);
for (var slot = 0; slot < timeslots; slot++) {
var slotIdx = grp * timeslots + slot;
var minFromStart = slotIdx * step; // A date with total minutes calculated from the start of the day
slots[slotIdx] = groups[grp][slot] = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, minutesFromMidnight + minFromStart, 0, 0);
}
} // Necessary to be able to select up until the last timeslot in a day
var lastSlotMinFromStart = slots.length * step;
slots.push(new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, minutesFromMidnight + lastSlotMinFromStart, 0, 0));
function positionFromDate(date) {
var diff$1 = diff(start, date, 'minutes') + getDstOffset(start, date);
return Math.min(diff$1, totalMin);
}
return {
groups: groups,
update: function update(args) {
if (getKey$1(args) !== key) return getSlotMetrics$1(args);
return this;
},
dateIsInGroup: function dateIsInGroup(date, groupIndex) {
var nextGroup = groups[groupIndex + 1];
return inRange(date, groups[groupIndex][0], nextGroup ? nextGroup[0] : end, 'minutes');
},
nextSlot: function nextSlot(slot) {
var next = slots[Math.min(slots.indexOf(slot) + 1, slots.length - 1)]; // in the case of the last slot we won't a long enough range so manually get it
if (next === slot) next = add(slot, step, 'minutes');
return next;
},
closestSlotToPosition: function closestSlotToPosition(percent) {
var slot = Math.min(slots.length - 1, Math.max(0, Math.floor(percent * numSlots)));
return slots[slot];
},
closestSlotFromPoint: function closestSlotFromPoint(point, boundaryRect) {
var range = Math.abs(boundaryRect.top - boundaryRect.bottom);
return this.closestSlotToPosition((point.y - boundaryRect.top) / range);
},
closestSlotFromDate: function closestSlotFromDate(date, offset) {
if (offset === void 0) {
offset = 0;
}
if (lt(date, start, 'minutes')) return slots[0];
var diffMins = diff(start, date, 'minutes');
return slots[(diffMins - diffMins % step) / step + offset];
},
startsBeforeDay: function startsBeforeDay(date) {
return lt(date, start, 'day');
},
startsAfterDay: function startsAfterDay(date) {
return gt(date, end, 'day');
},
startsBefore: function startsBefore(date) {
return lt(merge(start, date), start, 'minutes');
},
startsAfter: function startsAfter(date) {
return gt(merge(end, date), end, 'minutes');
},
getRange: function getRange(rangeStart, rangeEnd, ignoreMin, ignoreMax) {
if (!ignoreMin) rangeStart = min(end, max(start, rangeStart));
if (!ignoreMax) rangeEnd = min(end, max(start, rangeEnd));
var rangeStartMin = positionFromDate(rangeStart);
var rangeEndMin = positionFromDate(rangeEnd);
var top = rangeEndMin > step * numSlots && !eq(end, rangeEnd) ? (rangeStartMin - step) / (step * numSlots) * 100 : rangeStartMin / (step * numSlots) * 100;
return {
top: top,
height: rangeEndMin / (step * numSlots) * 100 - top,
start: positionFromDate(rangeStart),
startDate: rangeStart,
end: positionFromDate(rangeEnd),
endDate: rangeEnd
};
},
getCurrentTimePosition: function getCurrentTimePosition(rangeStart) {
var rangeStartMin = positionFromDate(rangeStart);
var top = rangeStartMin / (step * numSlots) * 100;
return top;
}
};
}
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;
}
/** Built-in value references. */
var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$3 = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax$3(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax$3(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
var Event =
/*#__PURE__*/
function () {
function Event(data, _ref) {
var accessors = _ref.accessors,
slotMetrics = _ref.slotMetrics;
var _slotMetrics$getRange = slotMetrics.getRange(accessors.start(data), accessors.end(data)),
start = _slotMetrics$getRange.start,
startDate = _slotMetrics$getRange.startDate,
end = _slotMetrics$getRange.end,
endDate = _slotMetrics$getRange.endDate,
top = _slotMetrics$getRange.top,
height = _slotMetrics$getRange.height;
this.start = start;
this.end = end;
this.startMs = +startDate;
this.endMs = +endDate;
this.top = top;
this.height = height;
this.data = data;
}
/**
* The event's width without any overlap.
*/
_createClass(Event, [{
key: "_width",
get: function get() {
// The container event's width is determined by the maximum number of
// events in any of its rows.
if (this.rows) {
var columns = this.rows.reduce(function (max, row) {
return Math.max(max, row.leaves.length + 1);
}, // add itself
0) + 1; // add the container
return 100 / columns;
}
var availableWidth = 100 - this.container._width; // The row event's width is the space left by the container, divided
// among itself and its leaves.
if (this.leaves) {
return availableWidth / (this.leaves.length + 1);
} // The leaf event's width is determined by its row's width
return this.row._width;
}
/**
* The event's calculated width, possibly with extra width added for
* overlapping effect.
*/
}, {
key: "width",
get: function get() {
var noOverlap = this._width;
var overlap = Math.min(100, this._width * 1.7); // Containers can always grow.
if (this.rows) {
return overlap;
} // Rows can grow if they have leaves.
if (this.leaves) {
return this.leaves.length > 0 ? overlap : noOverlap;
} // Leaves can grow unless they're the last item in a row.
var leaves = this.row.leaves;
var index = leaves.indexOf(this);
return index === leaves.length - 1 ? noOverlap : overlap;
}
}, {
key: "xOffset",
get: function get() {
// Containers have no offset.
if (this.rows) return 0; // Rows always start where their container ends.
if (this.leaves) return this.container._width; // Leaves are spread out evenly on the space left by its row.
var _this$row = this.row,
leaves = _this$row.leaves,
xOffset = _this$row.xOffset,
_width = _this$row._width;
var index = leaves.indexOf(this) + 1;
return xOffset + index * _width;
}
}]);
return Event;
}();
/**
* Return true if event a and b is considered to be on the same row.
*/
function onSameRow(a, b, minimumStartDifference) {
return (// Occupies the same start slot.
Math.abs(b.start - a.start) < minimumStartDifference || // A's start slot overlaps with b's end slot.
b.start > a.start && b.start < a.end
);
}
function sortByRender(events) {
var sortedByTime = sortBy(events, ['startMs', function (e) {
return -e.endMs;
}]);
var sorted = [];
while (sortedByTime.length > 0) {
var event = sortedByTime.shift();
sorted.push(event);
for (var i = 0; i < sortedByTime.length; i++) {
var test = sortedByTime[i]; // Still inside this event, look for next.
if (event.endMs > test.startMs) continue; // We've found the first event of the next event group.
// If that event is not right next to our current event, we have to
// move it here.
if (i > 0) {
var _event = sortedByTime.splice(i, 1)[0];
sorted.push(_event);
} // We've already found the next event group, so stop looking.
break;
}
}
return sorted;
}
function getStyledEvents(_ref2) {
var events = _ref2.events,
minimumStartDifference = _ref2.minimumStartDifference,
slotMetrics = _ref2.slotMetrics,
accessors = _ref2.accessors;
// Create proxy events and order them so that we don't have
// to fiddle with z-indexes.
var proxies = events.map(function (event) {
return new Event(event, {
slotMetrics: slotMetrics,
accessors: accessors
});
});
var eventsInRenderOrder = sortByRender(proxies); // Group overlapping events, while keeping order.
// Every event is always one of: container, row or leaf.
// Containers can contain rows, and rows can contain leaves.
var containerEvents = [];
var _loop = function _loop(i) {
var event = eventsInRenderOrder[i]; // Check if this event can go into a container event.
var container = containerEvents.find(function (c) {
return c.end > event.start || Math.abs(event.start - c.start) < minimumStartDifference;
}); // Couldn't find a container — that means this event is a container.
if (!container) {
event.rows = [];
containerEvents.push(event);
return "continue";
} // Found a container for the event.
event.container = container; // Check if the event can be placed in an existing row.
// Start looking from behind.
var row = null;
for (var j = container.rows.length - 1; !row && j >= 0; j--) {
if (onSameRow(container.rows[j], event, minimumStartDifference)) {
row = container.rows[j];
}
}
if (row) {
// Found a row, so add it.
row.leaves.push(event);
event.row = row;
} else {
// Couldn't find a row – that means this event is a row.
event.leaves = [];
container.rows.push(event);
}
};
for (var i = 0; i < eventsInRenderOrder.length; i++) {
var _ret = _loop(i);
if (_ret === "continue") continue;
} // Return the original events, along with their styles.
return eventsInRenderOrder.map(function (event) {
return {
event: event.data,
style: {
top: event.top,
height: event.height,
width: event.width,
xOffset: Math.max(0, event.xOffset)
}
};
});
}
function getMaxIdxDFS(node, maxIdx, visited) {
for (var i = 0; i < node.friends.length; ++i) {
if (visited.indexOf(node.friends[i]) > -1) continue;
maxIdx = maxIdx > node.friends[i].idx ? maxIdx : node.friends[i].idx; // TODO : trace it by not object but kinda index or something for performance
visited.push(node.friends[i]);
var newIdx = getMaxIdxDFS(node.friends[i], maxIdx, visited);
maxIdx = maxIdx > newIdx ? maxIdx : newIdx;
}
return maxIdx;
}
function noOverlap (_ref) {
var events = _ref.events,
minimumStartDifference = _ref.minimumStartDifference,
slotMetrics = _ref.slotMetrics,
accessors = _ref.accessors;
var styledEvents = getStyledEvents({
events: events,
minimumStartDifference: minimumStartDifference,
slotMetrics: slotMetrics,
accessors: accessors
});
styledEvents.sort(function (a, b) {
a = a.style;
b = b.style;
if (a.top !== b.top) return a.top > b.top ? 1 : -1;else return a.top + a.height < b.top + b.height ? 1 : -1;
});
for (var i = 0; i < styledEvents.length; ++i) {
styledEvents[i].friends = [];
delete styledEvents[i].style.left;
delete styledEvents[i].style.left;
delete styledEvents[i].idx;
delete styledEvents[i].size;
}
for (var _i = 0; _i < styledEvents.length - 1; ++_i) {
var se1 = styledEvents[_i];
var y1 = se1.style.top;
var y2 = se1.style.top + se1.style.height;
for (var j = _i + 1; j < styledEvents.length; ++j) {
var se2 = styledEvents[j];
var y3 = se2.style.top;
var y4 = se2.style.top + se2.style.height; // be friends when overlapped
if (y3 <= y1 && y1 < y4 || y1 <= y3 && y3 < y2) {
// TODO : hashmap would be effective for performance
se1.friends.push(se2);
se2.friends.push(se1);
}
}
}
for (var _i2 = 0; _i2 < styledEvents.length; ++_i2) {
var se = styledEvents[_i2];
var bitmap = [];
for (var _j = 0; _j < 100; ++_j) {
bitmap.push(1);
} // 1 means available
for (var _j2 = 0; _j2 < se.friends.length; ++_j2) {
if (se.friends[_j2].idx !== undefined) bitmap[se.friends[_j2].idx] = 0;
} // 0 means reserved
se.idx = bitmap.indexOf(1);
}
for (var _i3 = 0; _i3 < styledEvents.length; ++_i3) {
var size = 0;
if (styledEvents[_i3].size) continue;
var allFriends = [];
var maxIdx = getMaxIdxDFS(styledEvents[_i3], 0, allFriends);
size = 100 / (maxIdx + 1);
styledEvents[_i3].size = size;
for (var _j3 = 0; _j3 < allFriends.length; ++_j3) {
allFriends[_j3].size = size;
}
}
for (var _i4 = 0; _i4 < styledEvents.length; ++_i4) {
var e = styledEvents[_i4];
e.style.left = e.idx * e.size; // stretch to maximum
var _maxIdx = 0;
for (var _j4 = 0; _j4 < e.friends.length; ++_j4) {
var idx = e.friends[_j4];
_maxIdx = _maxIdx > idx ? _maxIdx : idx;
}
if (_maxIdx <= e.idx) e.size = 100 - e.idx * e.size; // padding between events
// for this feature, `width` is not percentage based unit anymore
// it will be used with calc()
var padding = e.idx === 0 ? 0 : 3;
e.style.width = "calc(" + e.size + "% - " + padding + "px)";
e.style.height = "calc(" + e.style.height + "% - 2px)";
e.style.xOffset = "calc(" + e.style.left + "% + " + padding + "px)";
}
return styledEvents;
}
/*eslint no-unused-vars: "off"*/
var DefaultAlgorithms = {
overlap: getStyledEvents,
'no-overlap': noOverlap
};
function isFunction$1(a) {
return !!(a && a.constructor && a.call && a.apply);
} //
function getStyledEvents$1(_ref) {
var events = _ref.events,
minimumStartDifference = _ref.minimumStartDifference,
slotMetrics = _ref.slotMetrics,
accessors = _ref.accessors,
dayLayoutAlgorithm = _ref.dayLayoutAlgorithm;
var algorithm = dayLayoutAlgorithm;
if (dayLayoutAlgorithm in DefaultAlgorithms) algorithm = DefaultAlgorithms[dayLayoutAlgorithm];
if (!isFunction$1(algorithm)) {
// invalid algorithm
return [];
}
return algorithm.apply(this, arguments);
}
var TimeSlotGroup =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(TimeSlotGroup, _Component);
function TimeSlotGroup() {
return _Component.apply(this, arguments) || this;
}
var _proto = TimeSlotGroup.prototype;
_proto.render = function render() {
var _this$props = this.props,
renderSlot = _this$props.renderSlot,
resource = _this$props.resource,
group = _this$props.group,
getters = _this$props.getters,
_this$props$component = _this$props.components;
_this$props$component = _this$props$component === void 0 ? {} : _this$props$component;
var _this$props$component2 = _this$props$component.timeSlotWrapper,
Wrapper = _this$props$component2 === void 0 ? NoopWrapper : _this$props$component2;
var groupProps = getters ? getters.slotGroupProp() : {};
return React__default.createElement("div", _extends({
className: "rbc-timeslot-group"
}, groupProps), group.map(function (value, idx) {
var slotProps = getters ? getters.slotProp(value, resource) : {};
return React__default.createElement(Wrapper, {
key: idx,
value: value,
resource: resource
}, React__default.createElement("div", _extends({}, slotProps, {
className: clsx('rbc-time-slot', slotProps.className)
}), renderSlot && renderSlot(value, idx)));
}));
};
return TimeSlotGroup;
}(React.Component);
TimeSlotGroup.propTypes = {
renderSlot: propTypes.func,
group: propTypes.array.isRequired,
resource: propTypes.any,
components: propTypes.object,
getters: propTypes.object
};
function stringifyPercent(v) {
return typeof v === 'string' ? v : v + '%';
}
/* eslint-disable react/prop-types */
function TimeGridEvent(props) {
var _extends2, _extends3;
var style = props.style,
className = props.className,
event = props.event,
accessors = props.accessors,
rtl = props.rtl,
selected = props.selected,
label = props.label,
continuesEarlier = props.continuesEarlier,
continuesLater = props.continuesLater,
getters = props.getters,
onClick = props.onClick,
onDoubleClick = props.onDoubleClick,
isBackgroundEvent = props.isBackgroundEvent,
onKeyPress = props.onKeyPress,
_props$components = props.components,
Event = _props$components.event,
EventWrapper = _props$components.eventWrapper;
var title = accessors.title(event);
var tooltip = accessors.tooltip(event);
var end = accessors.end(event);
var start = accessors.start(event);
var userProps = getters.eventProp(event, start, end, selected);
var height = style.height,
top = style.top,
width = style.width,
xOffset = style.xOffset;
var inner = [React__default.createElement("div", {
key: "1",
className: "rbc-event-label"
}, label), React__default.createElement("div", {
key: "2",
className: "rbc-event-content"
}, Event ? React__default.createElement(Event, {
event: event,
title: title
}) : title)];
var eventStyle = isBackgroundEvent ? _extends({}, userProps.style, (_extends2 = {
top: stringifyPercent(top),
height: stringifyPercent(height),
// Adding 10px to take events container right margin into account
width: "calc(" + width + " + 10px)"
}, _extends2[rtl ? 'right' : 'left'] = stringifyPercent(Math.max(0, xOffset)), _extends2)) : _extends({}, userProps.style, (_extends3 = {
top: stringifyPercent(top),
width: stringifyPercent(width),
height: stringifyPercent(height)
}, _extends3[rtl ? 'right' : 'left'] = stringifyPercent(xOffset), _extends3));
return React__default.createElement(EventWrapper, _extends({
type: "time"
}, props), React__default.createElement("div", {
onClick: onClick,
onDoubleClick: onDoubleClick,
style: eventStyle,
onKeyPress: onKeyPress,
title: tooltip ? (typeof label === 'string' ? label + ': ' : '') + tooltip : undefined,
className: clsx(isBackgroundEvent ? 'rbc-background-event' : 'rbc-event', className, userProps.className, {
'rbc-selected': selected,
'rbc-event-continues-earlier': continuesEarlier,
'rbc-event-continues-later': continuesLater
})
}, inner));
}
var DayColumn =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DayColumn, _React$Component);
function DayColumn() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.state = {
selecting: false,
timeIndicatorPosition: null
};
_this.intervalTriggered = false;
_this.renderEvents = function (_ref) {
var events = _ref.events,
isBackgroundEvent = _ref.isBackgroundEvent;
var _this$props = _this.props,
rtl = _this$props.rtl,
selected = _this$props.selected,
accessors = _this$props.accessors,
localizer = _this$props.localizer,
getters = _this$props.getters,
components = _this$props.components,
step = _this$props.step,
timeslots = _this$props.timeslots,
dayLayoutAlgorithm = _this$props.dayLayoutAlgorithm,
resizable = _this$props.resizable;
var _assertThisInitialize = _assertThisInitialized(_this),
slotMetrics = _assertThisInitialize.slotMetrics;
var messages = localizer.messages;
var styledEvents = getStyledEvents$1({
events: events,
accessors: accessors,
slotMetrics: slotMetrics,
minimumStartDifference: Math.ceil(step * timeslots / 2),
dayLayoutAlgorithm: dayLayoutAlgorithm
});
return styledEvents.map(function (_ref2, idx) {
var event = _ref2.event,
style = _ref2.style;
var end = accessors.end(event);
var start = accessors.start(event);
var format = 'eventTimeRangeFormat';
var label;
var startsBeforeDay = slotMetrics.startsBeforeDay(start);
var startsAfterDay = slotMetrics.startsAfterDay(end);
if (startsBeforeDay) format = 'eventTimeRangeEndFormat';else if (startsAfterDay) format = 'eventTimeRangeStartFormat';
if (startsBeforeDay && startsAfterDay) label = messages.allDay;else label = localizer.format({
start: start,
end: end
}, format);
var continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start);
var continuesLater = startsAfterDay || slotMetrics.startsAfter(end);
return React__default.createElement(TimeGridEvent, {
style: style,
event: event,
label: label,
key: 'evt_' + idx,
getters: getters,
rtl: rtl,
components: components,
continuesEarlier: continuesEarlier,
continuesLater: continuesLater,
accessors: accessors,
selected: isSelected(event, selected),
onClick: function onClick(e) {
return _this._select(event, e);
},
onDoubleClick: function onDoubleClick(e) {
return _this._doubleClick(event, e);
},
isBackgroundEvent: isBackgroundEvent,
onKeyPress: function onKeyPress(e) {
return _this._keyPress(event, e);
},
resizable: resizable
});
});
};
_this._selectable = function () {
var node = ReactDOM.findDOMNode(_assertThisInitialized(_this));
var selector = _this._selector = new Selection(function () {
return ReactDOM.findDOMNode(_assertThisInitialized(_this));
}, {
longPressThreshold: _this.props.longPressThreshold
});
var maybeSelect = function maybeSelect(box) {
var onSelecting = _this.props.onSelecting;
var current = _this.state || {};
var state = selectionState(box);
var start = state.startDate,
end = state.endDate;
if (onSelecting) {
if (eq(current.startDate, start, 'minutes') && eq(current.endDate, end, 'minutes') || onSelecting({
start: start,
end: end,
resourceId: _this.props.resource
}) === false) return;
}
if (_this.state.start !== state.start || _this.state.end !== state.end || _this.state.selecting !== state.selecting) {
_this.setState(state);
}
};
var selectionState = function selectionState(point) {
var currentSlot = _this.slotMetrics.closestSlotFromPoint(point, getBoundsForNode(node));
if (!_this.state.selecting) {
_this._initialSlot = currentSlot;
}
var initialSlot = _this._initialSlot;
if (lte(initialSlot, currentSlot)) {
currentSlot = _this.slotMetrics.nextSlot(currentSlot);
} else if (gt(initialSlot, currentSlot)) {
initialSlot = _this.slotMetrics.nextSlot(initialSlot);
}
var selectRange = _this.slotMetrics.getRange(min(initialSlot, currentSlot), max(initialSlot, currentSlot));
return _extends({}, selectRange, {
selecting: true,
top: selectRange.top + "%",
height: selectRange.height + "%"
});
};
var selectorClicksHandler = function selectorClicksHandler(box, actionType) {
if (!isEvent(ReactDOM.findDOMNode(_assertThisInitialized(_this)), box)) {
var _selectionState = selectionState(box),
startDate = _selectionState.startDate,
endDate = _selectionState.endDate;
_this._selectSlot({
startDate: startDate,
endDate: endDate,
action: actionType,
box: box
});
}
_this.setState({
selecting: false
});
};
selector.on('selecting', maybeSelect);
selector.on('selectStart', maybeSelect);
selector.on('beforeSelect', function (box) {
if (_this.props.selectable !== 'ignoreEvents') return;
return !isEvent(ReactDOM.findDOMNode(_assertThisInitialized(_this)), box);
});
selector.on('click', function (box) {
return selectorClicksHandler(box, 'click');
});
selector.on('doubleClick', function (box) {
return selectorClicksHandler(box, 'doubleClick');
});
selector.on('select', function (bounds) {
if (_this.state.selecting) {
_this._selectSlot(_extends({}, _this.state, {
action: 'select',
bounds: bounds
}));
_this.setState({
selecting: false
});
}
});
selector.on('reset', function () {
if (_this.state.selecting) {
_this.setState({
selecting: false
});
}
});
};
_this._teardownSelectable = function () {
if (!_this._selector) return;
_this._selector.teardown();
_this._selector = null;
};
_this._selectSlot = function (_ref3) {
var startDate = _ref3.startDate,
endDate = _ref3.endDate,
action = _ref3.action,
bounds = _ref3.bounds,
box = _ref3.box;
var current = startDate,
slots = [];
while (lte(current, endDate)) {
slots.push(current);
current = new Date(+current + _this.props.step * 60 * 1000); // using Date ensures not to create an endless loop the day DST begins
}
notify(_this.props.onSelectSlot, {
slots: slots,
start: startDate,
end: endDate,
resourceId: _this.props.resource,
action: action,
bounds: bounds,
box: box
});
};
_this._select = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
notify(_this.props.onSelectEvent, args);
};
_this._doubleClick = function () {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
notify(_this.props.onDoubleClickEvent, args);
};
_this._keyPress = function () {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
notify(_this.props.onKeyPressEvent, args);
};
_this.slotMetrics = getSlotMetrics$1(_this.props);
return _this;
}
var _proto = DayColumn.prototype;
_proto.componentDidMount = function componentDidMount() {
this.props.selectable && this._selectable();
if (this.props.isNow) {
this.setTimeIndicatorPositionUpdateInterval();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
this._teardownSelectable();
this.clearTimeIndicatorInterval();
};
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.selectable && !this.props.selectable) this._selectable();
if (!nextProps.selectable && this.props.selectable) this._teardownSelectable();
this.slotMetrics = this.slotMetrics.update(nextProps);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var getNowChanged = !eq(prevProps.getNow(), this.props.getNow(), 'minutes');
if (prevProps.isNow !== this.props.isNow || getNowChanged) {
this.clearTimeIndicatorInterval();
if (this.props.isNow) {
var tail = !getNowChanged && eq(prevProps.date, this.props.date, 'minutes') && prevState.timeIndicatorPosition === this.state.timeIndicatorPosition;
this.setTimeIndicatorPositionUpdateInterval(tail);
}
} else if (this.props.isNow && (!eq(prevProps.min, this.props.min, 'minutes') || !eq(prevProps.max, this.props.max, 'minutes'))) {
this.positionTimeIndicator();
}
}
/**
* @param tail {Boolean} - whether `positionTimeIndicator` call should be
* deferred or called upon setting interval (`true` - if deferred);
*/
;
_proto.setTimeIndicatorPositionUpdateInterval = function setTimeIndicatorPositionUpdateInterval(tail) {
var _this2 = this;
if (tail === void 0) {
tail = false;
}
if (!this.intervalTriggered && !tail) {
this.positionTimeIndicator();
}
this._timeIndicatorTimeout = window.setTimeout(function () {
_this2.intervalTriggered = true;
_this2.positionTimeIndicator();
_this2.setTimeIndicatorPositionUpdateInterval();
}, 60000);
};
_proto.clearTimeIndicatorInterval = function clearTimeIndicatorInterval() {
this.intervalTriggered = false;
window.clearTimeout(this._timeIndicatorTimeout);
};
_proto.positionTimeIndicator = function positionTimeIndicator() {
var _this$props2 = this.props,
min = _this$props2.min,
max = _this$props2.max,
getNow = _this$props2.getNow;
var current = getNow();
if (current >= min && current <= max) {
var top = this.slotMetrics.getCurrentTimePosition(current);
this.intervalTriggered = true;
this.setState({
timeIndicatorPosition: top
});
} else {
this.clearTimeIndicatorInterval();
}
};
_proto.render = function render() {
var _this$props3 = this.props,
max = _this$props3.max,
rtl = _this$props3.rtl,
isNow = _this$props3.isNow,
resource = _this$props3.resource,
accessors = _this$props3.accessors,
localizer = _this$props3.localizer,
_this$props3$getters = _this$props3.getters,
dayProp = _this$props3$getters.dayProp,
getters = _objectWithoutPropertiesLoose(_this$props3$getters, ["dayProp"]),
_this$props3$componen = _this$props3.components,
EventContainer = _this$props3$componen.eventContainerWrapper,
components = _objectWithoutPropertiesLoose(_this$props3$componen, ["eventContainerWrapper"]);
var slotMetrics = this.slotMetrics;
var _this$state = this.state,
selecting = _this$state.selecting,
top = _this$state.top,
height = _this$state.height,
startDate = _this$state.startDate,
endDate = _this$state.endDate;
var selectDates = {
start: startDate,
end: endDate
};
var _dayProp = dayProp(max),
className = _dayProp.className,
style = _dayProp.style;
return React__default.createElement("div", {
style: style,
className: clsx(className, 'rbc-day-slot', 'rbc-time-column', isNow && 'rbc-now', isNow && 'rbc-today', // WHY
selecting && 'rbc-slot-selecting')
}, slotMetrics.groups.map(function (grp, idx) {
return React__default.createElement(TimeSlotGroup, {
key: idx,
group: grp,
resource: resource,
getters: getters,
components: components
});
}), React__default.createElement(EventContainer, {
localizer: localizer,
resource: resource,
accessors: accessors,
getters: getters,
components: components,
slotMetrics: slotMetrics
}, React__default.createElement("div", {
className: clsx('rbc-events-container', rtl && 'rtl')
}, this.renderEvents({
events: this.props.backgroundEvents,
isBackgroundEvent: true
}), this.renderEvents({
events: this.props.events
}))), selecting && React__default.createElement("div", {
className: "rbc-slot-selection",
style: {
top: top,
height: height
}
}, React__default.createElement("span", null, localizer.format(selectDates, 'selectRangeFormat'))), isNow && this.intervalTriggered && React__default.createElement("div", {
className: "rbc-current-time-indicator",
style: {
top: this.state.timeIndicatorPosition + "%"
}
}));
};
return DayColumn;
}(React__default.Component);
DayColumn.propTypes = {
events: propTypes.array.isRequired,
backgroundEvents: propTypes.array.isRequired,
step: propTypes.number.isRequired,
date: propTypes.instanceOf(Date).isRequired,
min: propTypes.instanceOf(Date).isRequired,
max: propTypes.instanceOf(Date).isRequired,
getNow: propTypes.func.isRequired,
isNow: propTypes.bool,
rtl: propTypes.bool,
resizable: propTypes.bool,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object.isRequired,
showMultiDayTimes: propTypes.bool,
culture: propTypes.string,
timeslots: propTypes.number,
selected: propTypes.object,
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
eventOffset: propTypes.number,
longPressThreshold: propTypes.number,
onSelecting: propTypes.func,
onSelectSlot: propTypes.func.isRequired,
onSelectEvent: propTypes.func.isRequired,
onDoubleClickEvent: propTypes.func.isRequired,
onKeyPressEvent: propTypes.func,
className: propTypes.string,
dragThroughEvents: propTypes.bool,
resource: propTypes.any,
dayLayoutAlgorithm: DayLayoutAlgorithmPropType
};
DayColumn.defaultProps = {
dragThroughEvents: true,
timeslots: 2
};
var TimeGutter =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(TimeGutter, _Component);
function TimeGutter() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _Component.call.apply(_Component, [this].concat(args)) || this;
_this.renderSlot = function (value, idx) {
if (idx !== 0) return null;
var _this$props = _this.props,
localizer = _this$props.localizer,
getNow = _this$props.getNow;
var isNow = _this.slotMetrics.dateIsInGroup(getNow(), idx);
return React__default.createElement("span", {
className: clsx('rbc-label', isNow && 'rbc-now')
}, localizer.format(value, 'timeGutterFormat'));
};
var _this$props2 = _this.props,
min = _this$props2.min,
max = _this$props2.max,
timeslots = _this$props2.timeslots,
step = _this$props2.step;
_this.slotMetrics = getSlotMetrics$1({
min: min,
max: max,
timeslots: timeslots,
step: step
});
return _this;
}
var _proto = TimeGutter.prototype;
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) {
var min = nextProps.min,
max = nextProps.max,
timeslots = nextProps.timeslots,
step = nextProps.step;
this.slotMetrics = this.slotMetrics.update({
min: min,
max: max,
timeslots: timeslots,
step: step
});
};
_proto.render = function render() {
var _this2 = this;
var _this$props3 = this.props,
resource = _this$props3.resource,
components = _this$props3.components,
getters = _this$props3.getters;
return React__default.createElement("div", {
className: "rbc-time-gutter rbc-time-column"
}, this.slotMetrics.groups.map(function (grp, idx) {
return React__default.createElement(TimeSlotGroup, {
key: idx,
group: grp,
resource: resource,
components: components,
renderSlot: _this2.renderSlot,
getters: getters
});
}));
};
return TimeGutter;
}(React.Component);
TimeGutter.propTypes = {
min: propTypes.instanceOf(Date).isRequired,
max: propTypes.instanceOf(Date).isRequired,
timeslots: propTypes.number.isRequired,
step: propTypes.number.isRequired,
getNow: propTypes.func.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object,
localizer: propTypes.object.isRequired,
resource: propTypes.string
};
function getWidth(node, client) {
var win = isWindow(node);
return win ? win.innerWidth : client ? node.clientWidth : offset(node).width;
}
var size;
function scrollbarSize(recalc) {
if (!size && size !== 0 || recalc) {
if (canUseDOM) {
var scrollDiv = document.createElement('div');
scrollDiv.style.position = 'absolute';
scrollDiv.style.top = '-9999px';
scrollDiv.style.width = '50px';
scrollDiv.style.height = '50px';
scrollDiv.style.overflow = 'scroll';
document.body.appendChild(scrollDiv);
size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
}
}
return size;
}
var ResourceHeader = function ResourceHeader(_ref) {
var label = _ref.label;
return React__default.createElement(React__default.Fragment, null, label);
};
ResourceHeader.propTypes = {
label: propTypes.node,
index: propTypes.number,
resource: propTypes.object
};
var TimeGridHeader =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TimeGridHeader, _React$Component);
function TimeGridHeader() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handleHeaderClick = function (date, view, e) {
e.preventDefault();
notify(_this.props.onDrillDown, [date, view]);
};
_this.renderRow = function (resource) {
var _this$props = _this.props,
events = _this$props.events,
rtl = _this$props.rtl,
selectable = _this$props.selectable,
getNow = _this$props.getNow,
range = _this$props.range,
getters = _this$props.getters,
localizer = _this$props.localizer,
accessors = _this$props.accessors,
components = _this$props.components,
resizable = _this$props.resizable;
var resourceId = accessors.resourceId(resource);
var eventsToDisplay = resource ? events.filter(function (event) {
return accessors.resource(event) === resourceId;
}) : events;
return React__default.createElement(DateContentRow, {
isAllDay: true,
rtl: rtl,
getNow: getNow,
minRows: 2,
range: range,
events: eventsToDisplay,
resourceId: resourceId,
className: "rbc-allday-cell",
selectable: selectable,
selected: _this.props.selected,
components: components,
accessors: accessors,
getters: getters,
localizer: localizer,
onSelect: _this.props.onSelectEvent,
onDoubleClick: _this.props.onDoubleClickEvent,
onKeyPress: _this.props.onKeyPressEvent,
onSelectSlot: _this.props.onSelectSlot,
longPressThreshold: _this.props.longPressThreshold,
resizable: resizable
});
};
return _this;
}
var _proto = TimeGridHeader.prototype;
_proto.renderHeaderCells = function renderHeaderCells(range) {
var _this2 = this;
var _this$props2 = this.props,
localizer = _this$props2.localizer,
getDrilldownView = _this$props2.getDrilldownView,
getNow = _this$props2.getNow,
dayProp = _this$props2.getters.dayProp,
_this$props2$componen = _this$props2.components.header,
HeaderComponent = _this$props2$componen === void 0 ? Header : _this$props2$componen;
var today = getNow();
return range.map(function (date, i) {
var drilldownView = getDrilldownView(date);
var label = localizer.format(date, 'dayFormat');
var _dayProp = dayProp(date),
className = _dayProp.className,
style = _dayProp.style;
var header = React__default.createElement(HeaderComponent, {
date: date,
label: label,
localizer: localizer
});
return React__default.createElement("div", {
key: i,
style: style,
className: clsx('rbc-header', className, eq(date, today, 'day') && 'rbc-today')
}, drilldownView ? React__default.createElement("a", {
href: "#",
onClick: function onClick(e) {
return _this2.handleHeaderClick(date, drilldownView, e);
}
}, header) : React__default.createElement("span", null, header));
});
};
_proto.render = function render() {
var _this3 = this;
var _this$props3 = this.props,
width = _this$props3.width,
rtl = _this$props3.rtl,
resources = _this$props3.resources,
range = _this$props3.range,
events = _this$props3.events,
getNow = _this$props3.getNow,
accessors = _this$props3.accessors,
selectable = _this$props3.selectable,
components = _this$props3.components,
getters = _this$props3.getters,
scrollRef = _this$props3.scrollRef,
localizer = _this$props3.localizer,
isOverflowing = _this$props3.isOverflowing,
_this$props3$componen = _this$props3.components,
TimeGutterHeader = _this$props3$componen.timeGutterHeader,
_this$props3$componen2 = _this$props3$componen.resourceHeader,
ResourceHeaderComponent = _this$props3$componen2 === void 0 ? ResourceHeader : _this$props3$componen2,
resizable = _this$props3.resizable;
var style = {};
if (isOverflowing) {
style[rtl ? 'marginLeft' : 'marginRight'] = scrollbarSize() + "px";
}
var groupedEvents = resources.groupEvents(events);
return React__default.createElement("div", {
style: style,
ref: scrollRef,
className: clsx('rbc-time-header', isOverflowing && 'rbc-overflowing')
}, React__default.createElement("div", {
className: "rbc-label rbc-time-header-gutter",
style: {
width: width,
minWidth: width,
maxWidth: width
}
}, TimeGutterHeader && React__default.createElement(TimeGutterHeader, null)), resources.map(function (_ref, idx) {
var id = _ref[0],
resource = _ref[1];
return React__default.createElement("div", {
className: "rbc-time-header-content",
key: id || idx
}, resource && React__default.createElement("div", {
className: "rbc-row rbc-row-resource",
key: "resource_" + idx
}, React__default.createElement("div", {
className: "rbc-header"
}, React__default.createElement(ResourceHeaderComponent, {
index: idx,
label: accessors.resourceTitle(resource),
resource: resource
}))), React__default.createElement("div", {
className: "rbc-row rbc-time-header-cell" + (range.length <= 1 ? ' rbc-time-header-cell-single-day' : '')
}, _this3.renderHeaderCells(range)), React__default.createElement(DateContentRow, {
isAllDay: true,
rtl: rtl,
getNow: getNow,
minRows: 2,
range: range,
events: groupedEvents.get(id) || [],
resourceId: resource && id,
className: "rbc-allday-cell",
selectable: selectable,
selected: _this3.props.selected,
components: components,
accessors: accessors,
getters: getters,
localizer: localizer,
onSelect: _this3.props.onSelectEvent,
onDoubleClick: _this3.props.onDoubleClickEvent,
onKeyPress: _this3.props.onKeyPressEvent,
onSelectSlot: _this3.props.onSelectSlot,
longPressThreshold: _this3.props.longPressThreshold,
resizable: resizable
}));
}));
};
return TimeGridHeader;
}(React__default.Component);
TimeGridHeader.propTypes = {
range: propTypes.array.isRequired,
events: propTypes.array.isRequired,
resources: propTypes.object,
getNow: propTypes.func.isRequired,
isOverflowing: propTypes.bool,
rtl: propTypes.bool,
resizable: propTypes.bool,
width: propTypes.number,
localizer: propTypes.object.isRequired,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
selected: propTypes.object,
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
longPressThreshold: propTypes.number,
onSelectSlot: propTypes.func,
onSelectEvent: propTypes.func,
onDoubleClickEvent: propTypes.func,
onKeyPressEvent: propTypes.func,
onDrillDown: propTypes.func,
getDrilldownView: propTypes.func.isRequired,
scrollRef: propTypes.any
};
var NONE = {};
function Resources(resources, accessors) {
return {
map: function map(fn) {
if (!resources) return [fn([NONE, null], 0)];
return resources.map(function (resource, idx) {
return fn([accessors.resourceId(resource), resource], idx);
});
},
groupEvents: function groupEvents(events) {
var eventsByResource = new Map();
if (!resources) {
// Return all events if resources are not provided
eventsByResource.set(NONE, events);
return eventsByResource;
}
events.forEach(function (event) {
var id = accessors.resource(event) || NONE;
var resourceEvents = eventsByResource.get(id) || [];
resourceEvents.push(event);
eventsByResource.set(id, resourceEvents);
});
return eventsByResource;
}
};
}
var TimeGrid =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(TimeGrid, _Component);
function TimeGrid(props) {
var _this;
_this = _Component.call(this, props) || this;
_this.handleScroll = function (e) {
if (_this.scrollRef.current) {
_this.scrollRef.current.scrollLeft = e.target.scrollLeft;
}
};
_this.handleResize = function () {
cancel(_this.rafHandle);
_this.rafHandle = request(_this.checkOverflow);
};
_this.gutterRef = function (ref) {
_this.gutter = ref && ReactDOM.findDOMNode(ref);
};
_this.handleSelectAlldayEvent = function () {
//cancel any pending selections so only the event click goes through.
_this.clearSelection();
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
notify(_this.props.onSelectEvent, args);
};
_this.handleSelectAllDaySlot = function (slots, slotInfo) {
var onSelectSlot = _this.props.onSelectSlot;
notify(onSelectSlot, {
slots: slots,
start: slots[0],
end: slots[slots.length - 1],
action: slotInfo.action,
resourceId: slotInfo.resourceId
});
};
_this.checkOverflow = function () {
if (_this._updatingOverflow) return;
var content = _this.contentRef.current;
var isOverflowing = content.scrollHeight > content.clientHeight;
if (_this.state.isOverflowing !== isOverflowing) {
_this._updatingOverflow = true;
_this.setState({
isOverflowing: isOverflowing
}, function () {
_this._updatingOverflow = false;
});
}
};
_this.memoizedResources = memoizeOne(function (resources, accessors) {
return Resources(resources, accessors);
});
_this.state = {
gutterWidth: undefined,
isOverflowing: null
};
_this.scrollRef = React__default.createRef();
_this.contentRef = React__default.createRef();
_this._scrollRatio = null;
return _this;
}
var _proto = TimeGrid.prototype;
_proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {
this.calculateScroll();
};
_proto.componentDidMount = function componentDidMount() {
this.checkOverflow();
if (this.props.width == null) {
this.measureGutter();
}
this.applyScroll();
window.addEventListener('resize', this.handleResize);
};
_proto.componentWillUnmount = function componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
cancel(this.rafHandle);
if (this.measureGutterAnimationFrameRequest) {
window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest);
}
};
_proto.componentDidUpdate = function componentDidUpdate() {
if (this.props.width == null) {
this.measureGutter();
}
this.applyScroll(); //this.checkOverflow()
};
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) {
var _this$props = this.props,
range = _this$props.range,
scrollToTime = _this$props.scrollToTime; // When paginating, reset scroll
if (!eq(nextProps.range[0], range[0], 'minute') || !eq(nextProps.scrollToTime, scrollToTime, 'minute')) {
this.calculateScroll(nextProps);
}
};
_proto.renderEvents = function renderEvents(range, events, backgroundEvents, now) {
var _this2 = this;
var _this$props2 = this.props,
min = _this$props2.min,
max = _this$props2.max,
components = _this$props2.components,
accessors = _this$props2.accessors,
localizer = _this$props2.localizer,
dayLayoutAlgorithm = _this$props2.dayLayoutAlgorithm;
var resources = this.memoizedResources(this.props.resources, accessors);
var groupedEvents = resources.groupEvents(events);
var groupedBackgroundEvents = resources.groupEvents(backgroundEvents);
return resources.map(function (_ref, i) {
var id = _ref[0],
resource = _ref[1];
return range.map(function (date, jj) {
var daysEvents = (groupedEvents.get(id) || []).filter(function (event) {
return inRange(date, accessors.start(event), accessors.end(event), 'day');
});
var daysBackgroundEvents = (groupedBackgroundEvents.get(id) || []).filter(function (event) {
return inRange(date, accessors.start(event), accessors.end(event), 'day');
});
return React__default.createElement(DayColumn, _extends({}, _this2.props, {
localizer: localizer,
min: merge(date, min),
max: merge(date, max),
resource: resource && id,
components: components,
isNow: eq(date, now, 'day'),
key: i + '-' + jj,
date: date,
events: daysEvents,
backgroundEvents: daysBackgroundEvents,
dayLayoutAlgorithm: dayLayoutAlgorithm
}));
});
});
};
_proto.render = function render() {
var _this$props3 = this.props,
events = _this$props3.events,
backgroundEvents = _this$props3.backgroundEvents,
range = _this$props3.range,
width = _this$props3.width,
rtl = _this$props3.rtl,
selected = _this$props3.selected,
getNow = _this$props3.getNow,
resources = _this$props3.resources,
components = _this$props3.components,
accessors = _this$props3.accessors,
getters = _this$props3.getters,
localizer = _this$props3.localizer,
min = _this$props3.min,
max = _this$props3.max,
showMultiDayTimes = _this$props3.showMultiDayTimes,
longPressThreshold = _this$props3.longPressThreshold,
resizable = _this$props3.resizable;
width = width || this.state.gutterWidth;
var start = range[0],
end = range[range.length - 1];
this.slots = range.length;
var allDayEvents = [],
rangeEvents = [],
rangeBackgroundEvents = [];
events.forEach(function (event) {
if (inRange$1(event, start, end, accessors)) {
var eStart = accessors.start(event),
eEnd = accessors.end(event);
if (accessors.allDay(event) || isJustDate(eStart) && isJustDate(eEnd) || !showMultiDayTimes && !eq(eStart, eEnd, 'day')) {
allDayEvents.push(event);
} else {
rangeEvents.push(event);
}
}
});
backgroundEvents.forEach(function (event) {
if (inRange$1(event, start, end, accessors)) {
rangeBackgroundEvents.push(event);
}
});
allDayEvents.sort(function (a, b) {
return sortEvents(a, b, accessors);
});
return React__default.createElement("div", {
className: clsx('rbc-time-view', resources && 'rbc-time-view-resources')
}, React__default.createElement(TimeGridHeader, {
range: range,
events: allDayEvents,
width: width,
rtl: rtl,
getNow: getNow,
localizer: localizer,
selected: selected,
resources: this.memoizedResources(resources, accessors),
selectable: this.props.selectable,
accessors: accessors,
getters: getters,
components: components,
scrollRef: this.scrollRef,
isOverflowing: this.state.isOverflowing,
longPressThreshold: longPressThreshold,
onSelectSlot: this.handleSelectAllDaySlot,
onSelectEvent: this.handleSelectAlldayEvent,
onDoubleClickEvent: this.props.onDoubleClickEvent,
onKeyPressEvent: this.props.onKeyPressEvent,
onDrillDown: this.props.onDrillDown,
getDrilldownView: this.props.getDrilldownView,
resizable: resizable
}), React__default.createElement("div", {
ref: this.contentRef,
className: "rbc-time-content",
onScroll: this.handleScroll
}, React__default.createElement(TimeGutter, {
date: start,
ref: this.gutterRef,
localizer: localizer,
min: merge(start, min),
max: merge(start, max),
step: this.props.step,
getNow: this.props.getNow,
timeslots: this.props.timeslots,
components: components,
className: "rbc-time-gutter",
getters: getters
}), this.renderEvents(range, rangeEvents, rangeBackgroundEvents, getNow())));
};
_proto.clearSelection = function clearSelection() {
clearTimeout(this._selectTimer);
this._pendingSelection = [];
};
_proto.measureGutter = function measureGutter() {
var _this3 = this;
if (this.measureGutterAnimationFrameRequest) {
window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest);
}
this.measureGutterAnimationFrameRequest = window.requestAnimationFrame(function () {
var width = getWidth(_this3.gutter);
if (width && _this3.state.gutterWidth !== width) {
_this3.setState({
gutterWidth: width
});
}
});
};
_proto.applyScroll = function applyScroll() {
if (this._scrollRatio != null) {
var content = this.contentRef.current;
content.scrollTop = content.scrollHeight * this._scrollRatio; // Only do this once
this._scrollRatio = null;
}
};
_proto.calculateScroll = function calculateScroll(props) {
if (props === void 0) {
props = this.props;
}
var _props = props,
min = _props.min,
max = _props.max,
scrollToTime = _props.scrollToTime;
var diffMillis = scrollToTime - startOf(scrollToTime, 'day');
var totalMillis = diff(max, min);
this._scrollRatio = diffMillis / totalMillis;
};
return TimeGrid;
}(React.Component);
TimeGrid.propTypes = {
events: propTypes.array.isRequired,
backgroundEvents: propTypes.array.isRequired,
resources: propTypes.array,
step: propTypes.number,
timeslots: propTypes.number,
range: propTypes.arrayOf(propTypes.instanceOf(Date)),
min: propTypes.instanceOf(Date),
max: propTypes.instanceOf(Date),
getNow: propTypes.func.isRequired,
scrollToTime: propTypes.instanceOf(Date),
showMultiDayTimes: propTypes.bool,
rtl: propTypes.bool,
resizable: propTypes.bool,
width: propTypes.number,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object.isRequired,
selected: propTypes.object,
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
longPressThreshold: propTypes.number,
onNavigate: propTypes.func,
onSelectSlot: propTypes.func,
onSelectEnd: propTypes.func,
onSelectStart: propTypes.func,
onSelectEvent: propTypes.func,
onDoubleClickEvent: propTypes.func,
onKeyPressEvent: propTypes.func,
onDrillDown: propTypes.func,
getDrilldownView: propTypes.func.isRequired,
dayLayoutAlgorithm: DayLayoutAlgorithmPropType
};
TimeGrid.defaultProps = {
step: 30,
timeslots: 2,
min: startOf(new Date(), 'day'),
max: endOf(new Date(), 'day'),
scrollToTime: startOf(new Date(), 'day')
};
var Day =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Day, _React$Component);
function Day() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Day.prototype;
_proto.render = function render() {
var _this$props = this.props,
date = _this$props.date,
props = _objectWithoutPropertiesLoose(_this$props, ["date"]);
var range = Day.range(date);
return React__default.createElement(TimeGrid, _extends({}, props, {
range: range,
eventOffset: 10
}));
};
return Day;
}(React__default.Component);
Day.propTypes = {
date: propTypes.instanceOf(Date).isRequired
};
Day.range = function (date) {
return [startOf(date, 'day')];
};
Day.navigate = function (date, action) {
switch (action) {
case navigate.PREVIOUS:
return add(date, -1, 'day');
case navigate.NEXT:
return add(date, 1, 'day');
default:
return date;
}
};
Day.title = function (date, _ref) {
var localizer = _ref.localizer;
return localizer.format(date, 'dayHeaderFormat');
};
var Week =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Week, _React$Component);
function Week() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Week.prototype;
_proto.render = function render() {
var _this$props = this.props,
date = _this$props.date,
props = _objectWithoutPropertiesLoose(_this$props, ["date"]);
var range = Week.range(date, this.props);
return React__default.createElement(TimeGrid, _extends({}, props, {
range: range,
eventOffset: 15
}));
};
return Week;
}(React__default.Component);
Week.propTypes = {
date: propTypes.instanceOf(Date).isRequired
};
Week.defaultProps = TimeGrid.defaultProps;
Week.navigate = function (date, action) {
switch (action) {
case navigate.PREVIOUS:
return add(date, -1, 'week');
case navigate.NEXT:
return add(date, 1, 'week');
default:
return date;
}
};
Week.range = function (date, _ref) {
var localizer = _ref.localizer;
var firstOfWeek = localizer.startOfWeek();
var start = startOf(date, 'week', firstOfWeek);
var end = endOf(date, 'week', firstOfWeek);
return range(start, end);
};
Week.title = function (date, _ref2) {
var localizer = _ref2.localizer;
var _Week$range = Week.range(date, {
localizer: localizer
}),
start = _Week$range[0],
rest = _Week$range.slice(1);
return localizer.format({
start: start,
end: rest.pop()
}, 'dayRangeHeaderFormat');
};
function workWeekRange(date, options) {
return Week.range(date, options).filter(function (d) {
return [6, 0].indexOf(d.getDay()) === -1;
});
}
var WorkWeek =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(WorkWeek, _React$Component);
function WorkWeek() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = WorkWeek.prototype;
_proto.render = function render() {
var _this$props = this.props,
date = _this$props.date,
props = _objectWithoutPropertiesLoose(_this$props, ["date"]);
var range = workWeekRange(date, this.props);
return React__default.createElement(TimeGrid, _extends({}, props, {
range: range,
eventOffset: 15
}));
};
return WorkWeek;
}(React__default.Component);
WorkWeek.propTypes = {
date: propTypes.instanceOf(Date).isRequired
};
WorkWeek.defaultProps = TimeGrid.defaultProps;
WorkWeek.range = workWeekRange;
WorkWeek.navigate = Week.navigate;
WorkWeek.title = function (date, _ref) {
var localizer = _ref.localizer;
var _workWeekRange = workWeekRange(date, {
localizer: localizer
}),
start = _workWeekRange[0],
rest = _workWeekRange.slice(1);
return localizer.format({
start: start,
end: rest.pop()
}, 'dayRangeHeaderFormat');
};
function hasClass(element, className) {
if (element.classList) return !!className && element.classList.contains(className);
return (" " + (element.className.baseVal || element.className) + " ").indexOf(" " + className + " ") !== -1;
}
function addClass(element, className) {
if (element.classList) element.classList.add(className);else if (!hasClass(element, className)) if (typeof element.className === 'string') element.className = element.className + " " + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + " " + className);
}
function replaceClassName(origClass, classToRemove) {
return origClass.replace(new RegExp("(^|\\s)" + classToRemove + "(?:\\s|$)", 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, '');
}
function removeClass(element, className) {
if (element.classList) {
element.classList.remove(className);
} else if (typeof element.className === 'string') {
element.className = replaceClassName(element.className, className);
} else {
element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));
}
}
function Agenda(_ref) {
var selected = _ref.selected,
getters = _ref.getters,
accessors = _ref.accessors,
localizer = _ref.localizer,
components = _ref.components,
length = _ref.length,
date = _ref.date,
events = _ref.events;
var headerRef = React.useRef(null);
var dateColRef = React.useRef(null);
var timeColRef = React.useRef(null);
var contentRef = React.useRef(null);
var tbodyRef = React.useRef(null);
React.useEffect(function () {
_adjustHeader();
});
var renderDay = function renderDay(day, events, dayKey) {
var Event = components.event,
AgendaDate = components.date;
events = events.filter(function (e) {
return inRange$1(e, startOf(day, 'day'), endOf(day, 'day'), accessors);
});
return events.map(function (event, idx) {
var title = accessors.title(event);
var end = accessors.end(event);
var start = accessors.start(event);
var userProps = getters.eventProp(event, start, end, isSelected(event, selected));
var dateLabel = idx === 0 && localizer.format(day, 'agendaDateFormat');
var first = idx === 0 ? React__default.createElement("td", {
rowSpan: events.length,
className: "rbc-agenda-date-cell"
}, AgendaDate ? React__default.createElement(AgendaDate, {
day: day,
label: dateLabel
}) : dateLabel) : false;
return React__default.createElement("tr", {
key: dayKey + '_' + idx,
className: userProps.className,
style: userProps.style
}, first, React__default.createElement("td", {
className: "rbc-agenda-time-cell"
}, timeRangeLabel(day, event)), React__default.createElement("td", {
className: "rbc-agenda-event-cell"
}, Event ? React__default.createElement(Event, {
event: event,
title: title
}) : title));
}, []);
};
var timeRangeLabel = function timeRangeLabel(day, event) {
var labelClass = '',
TimeComponent = components.time,
label = localizer.messages.allDay;
var end = accessors.end(event);
var start = accessors.start(event);
if (!accessors.allDay(event)) {
if (eq(start, end)) {
label = localizer.format(start, 'agendaTimeFormat');
} else if (eq(start, end, 'day')) {
label = localizer.format({
start: start,
end: end
}, 'agendaTimeRangeFormat');
} else if (eq(day, start, 'day')) {
label = localizer.format(start, 'agendaTimeFormat');
} else if (eq(day, end, 'day')) {
label = localizer.format(end, 'agendaTimeFormat');
}
}
if (gt(day, start, 'day')) labelClass = 'rbc-continues-prior';
if (lt(day, end, 'day')) labelClass += ' rbc-continues-after';
return React__default.createElement("span", {
className: labelClass.trim()
}, TimeComponent ? React__default.createElement(TimeComponent, {
event: event,
day: day,
label: label
}) : label);
};
var _adjustHeader = function _adjustHeader() {
if (!tbodyRef.current) return;
var header = headerRef.current;
var firstRow = tbodyRef.current.firstChild;
if (!firstRow) return;
var isOverflowing = contentRef.current.scrollHeight > contentRef.current.clientHeight;
var _widths = [];
var widths = _widths;
_widths = [getWidth(firstRow.children[0]), getWidth(firstRow.children[1])];
if (widths[0] !== _widths[0] || widths[1] !== _widths[1]) {
dateColRef.current.style.width = _widths[0] + 'px';
timeColRef.current.style.width = _widths[1] + 'px';
}
if (isOverflowing) {
addClass(header, 'rbc-header-overflowing');
header.style.marginRight = scrollbarSize() + 'px';
} else {
removeClass(header, 'rbc-header-overflowing');
}
};
var messages = localizer.messages;
var end = add(date, length, 'day');
var range$1 = range(date, end, 'day');
events = events.filter(function (event) {
return inRange$1(event, date, end, accessors);
});
events.sort(function (a, b) {
return +accessors.start(a) - +accessors.start(b);
});
return React__default.createElement("div", {
className: "rbc-agenda-view"
}, events.length !== 0 ? React__default.createElement(React__default.Fragment, null, React__default.createElement("table", {
ref: headerRef,
className: "rbc-agenda-table"
}, React__default.createElement("thead", null, React__default.createElement("tr", null, React__default.createElement("th", {
className: "rbc-header",
ref: dateColRef
}, messages.date), React__default.createElement("th", {
className: "rbc-header",
ref: timeColRef
}, messages.time), React__default.createElement("th", {
className: "rbc-header"
}, messages.event)))), React__default.createElement("div", {
className: "rbc-agenda-content",
ref: contentRef
}, React__default.createElement("table", {
className: "rbc-agenda-table"
}, React__default.createElement("tbody", {
ref: tbodyRef
}, range$1.map(function (day, idx) {
return renderDay(day, events, idx);
}))))) : React__default.createElement("span", {
className: "rbc-agenda-empty"
}, messages.noEventsInRange));
}
Agenda.propTypes = {
events: propTypes.array,
date: propTypes.instanceOf(Date),
length: propTypes.number.isRequired,
selected: propTypes.object,
accessors: propTypes.object.isRequired,
components: propTypes.object.isRequired,
getters: propTypes.object.isRequired,
localizer: propTypes.object.isRequired
};
Agenda.defaultProps = {
length: 30
};
Agenda.range = function (start, _ref2) {
var _ref2$length = _ref2.length,
length = _ref2$length === void 0 ? Agenda.defaultProps.length : _ref2$length;
var end = add(start, length, 'day');
return {
start: start,
end: end
};
};
Agenda.navigate = function (date, action, _ref3) {
var _ref3$length = _ref3.length,
length = _ref3$length === void 0 ? Agenda.defaultProps.length : _ref3$length;
switch (action) {
case navigate.PREVIOUS:
return add(date, -length, 'day');
case navigate.NEXT:
return add(date, length, 'day');
default:
return date;
}
};
Agenda.title = function (start, _ref4) {
var _ref4$length = _ref4.length,
length = _ref4$length === void 0 ? Agenda.defaultProps.length : _ref4$length,
localizer = _ref4.localizer;
var end = add(start, length, 'day');
return localizer.format({
start: start,
end: end
}, 'agendaHeaderFormat');
};
var _VIEWS;
var VIEWS = (_VIEWS = {}, _VIEWS[views.MONTH] = MonthView, _VIEWS[views.WEEK] = Week, _VIEWS[views.WORK_WEEK] = WorkWeek, _VIEWS[views.DAY] = Day, _VIEWS[views.AGENDA] = Agenda, _VIEWS);
function moveDate(View, _ref) {
var action = _ref.action,
date = _ref.date,
today = _ref.today,
props = _objectWithoutPropertiesLoose(_ref, ["action", "date", "today"]);
View = typeof View === 'string' ? VIEWS[View] : View;
switch (action) {
case navigate.TODAY:
date = today || new Date();
break;
case navigate.DATE:
break;
default:
!(View && typeof View.navigate === 'function') ? invariant_1(false, 'Calendar View components must implement a static `.navigate(date, action)` method.s') : void 0;
date = View.navigate(date, action, props);
}
return date;
}
var Toolbar =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Toolbar, _React$Component);
function Toolbar() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.navigate = function (action) {
_this.props.onNavigate(action);
};
_this.view = function (view) {
_this.props.onView(view);
};
return _this;
}
var _proto = Toolbar.prototype;
_proto.render = function render() {
var _this$props = this.props,
messages = _this$props.localizer.messages,
label = _this$props.label;
return React__default.createElement("div", {
className: "rbc-toolbar"
}, React__default.createElement("span", {
className: "rbc-btn-group"
}, React__default.createElement("button", {
type: "button",
onClick: this.navigate.bind(null, navigate.TODAY)
}, messages.today), React__default.createElement("button", {
type: "button",
onClick: this.navigate.bind(null, navigate.PREVIOUS)
}, messages.previous), React__default.createElement("button", {
type: "button",
onClick: this.navigate.bind(null, navigate.NEXT)
}, messages.next)), React__default.createElement("span", {
className: "rbc-toolbar-label"
}, label), React__default.createElement("span", {
className: "rbc-btn-group"
}, this.viewNamesGroup(messages)));
};
_proto.viewNamesGroup = function viewNamesGroup(messages) {
var _this2 = this;
var viewNames = this.props.views;
var view = this.props.view;
if (viewNames.length > 1) {
return viewNames.map(function (name) {
return React__default.createElement("button", {
type: "button",
key: name,
className: clsx({
'rbc-active': view === name
}),
onClick: _this2.view.bind(null, name)
}, messages[name]);
});
}
};
return Toolbar;
}(React__default.Component);
Toolbar.propTypes = {
view: propTypes.string.isRequired,
views: propTypes.arrayOf(propTypes.string).isRequired,
label: propTypes.node.isRequired,
localizer: propTypes.object,
onNavigate: propTypes.func.isRequired,
onView: propTypes.func.isRequired
};
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/** Used for built-in method references. */
var objectProto$c = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$a = objectProto$c.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty$a.call(object, key) && eq$1(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
/** Used for built-in method references. */
var objectProto$d = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$b = objectProto$d.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty$b.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn$1(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn$1(source), object);
}
/** Detect free variable `exports`. */
var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;
/** Built-in value references. */
var Buffer$1 = moduleExports$2 ? root.Buffer : undefined,
allocUnsafe = Buffer$1 ? Buffer$1.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn$1, getSymbolsIn);
}
/** Used for built-in method references. */
var objectProto$e = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$c = objectProto$e.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty$c.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/** Used to convert symbols to primitives and strings. */
var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined,
symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/** `Object#toString` result references. */
var boolTag$2 = '[object Boolean]',
dateTag$2 = '[object Date]',
mapTag$3 = '[object Map]',
numberTag$2 = '[object Number]',
regexpTag$2 = '[object RegExp]',
setTag$3 = '[object Set]',
stringTag$2 = '[object String]',
symbolTag$2 = '[object Symbol]';
var arrayBufferTag$2 = '[object ArrayBuffer]',
dataViewTag$3 = '[object DataView]',
float32Tag$1 = '[object Float32Array]',
float64Tag$1 = '[object Float64Array]',
int8Tag$1 = '[object Int8Array]',
int16Tag$1 = '[object Int16Array]',
int32Tag$1 = '[object Int32Array]',
uint8Tag$1 = '[object Uint8Array]',
uint8ClampedTag$1 = '[object Uint8ClampedArray]',
uint16Tag$1 = '[object Uint16Array]',
uint32Tag$1 = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag$2:
return cloneArrayBuffer(object);
case boolTag$2:
case dateTag$2:
return new Ctor(+object);
case dataViewTag$3:
return cloneDataView(object, isDeep);
case float32Tag$1: case float64Tag$1:
case int8Tag$1: case int16Tag$1: case int32Tag$1:
case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
return cloneTypedArray(object, isDeep);
case mapTag$3:
return new Ctor;
case numberTag$2:
case stringTag$2:
return new Ctor(object);
case regexpTag$2:
return cloneRegExp(object);
case setTag$3:
return new Ctor;
case symbolTag$2:
return cloneSymbol(object);
}
}
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/** `Object#toString` result references. */
var mapTag$4 = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag$1(value) == mapTag$4;
}
/* Node.js helper references. */
var nodeIsMap = nodeUtil && nodeUtil.isMap;
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/** `Object#toString` result references. */
var setTag$4 = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag$1(value) == setTag$4;
}
/* Node.js helper references. */
var nodeIsSet = nodeUtil && nodeUtil.isSet;
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag$3 = '[object Arguments]',
arrayTag$2 = '[object Array]',
boolTag$3 = '[object Boolean]',
dateTag$3 = '[object Date]',
errorTag$2 = '[object Error]',
funcTag$2 = '[object Function]',
genTag$1 = '[object GeneratorFunction]',
mapTag$5 = '[object Map]',
numberTag$3 = '[object Number]',
objectTag$3 = '[object Object]',
regexpTag$3 = '[object RegExp]',
setTag$5 = '[object Set]',
stringTag$3 = '[object String]',
symbolTag$3 = '[object Symbol]',
weakMapTag$2 = '[object WeakMap]';
var arrayBufferTag$3 = '[object ArrayBuffer]',
dataViewTag$4 = '[object DataView]',
float32Tag$2 = '[object Float32Array]',
float64Tag$2 = '[object Float64Array]',
int8Tag$2 = '[object Int8Array]',
int16Tag$2 = '[object Int16Array]',
int32Tag$2 = '[object Int32Array]',
uint8Tag$2 = '[object Uint8Array]',
uint8ClampedTag$2 = '[object Uint8ClampedArray]',
uint16Tag$2 = '[object Uint16Array]',
uint32Tag$2 = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag$3] = cloneableTags[arrayTag$2] =
cloneableTags[arrayBufferTag$3] = cloneableTags[dataViewTag$4] =
cloneableTags[boolTag$3] = cloneableTags[dateTag$3] =
cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
cloneableTags[int32Tag$2] = cloneableTags[mapTag$5] =
cloneableTags[numberTag$3] = cloneableTags[objectTag$3] =
cloneableTags[regexpTag$3] = cloneableTags[setTag$5] =
cloneableTags[stringTag$3] = cloneableTags[symbolTag$3] =
cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
cloneableTags[errorTag$2] = cloneableTags[funcTag$2] =
cloneableTags[weakMapTag$2] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag$1(value),
isFunc = tag == funcTag$2 || tag == genTag$1;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag$3 || tag == argsTag$3 || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
return result;
}
if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
/** `Object#toString` result references. */
var objectTag$4 = '[object Object]';
/** Used for built-in method references. */
var funcProto$2 = Function.prototype,
objectProto$f = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$2 = funcProto$2.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$d = objectProto$f.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString$2.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag$4) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty$d.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString$2.call(Ctor) == objectCtorString;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 1,
CLONE_FLAT_FLAG$1 = 2,
CLONE_SYMBOLS_FLAG$1 = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG$1 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
/** Used for built-in method references. */
var objectProto$g = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$e = objectProto$g.hasOwnProperty;
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn$1(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(eq$1(value, objectProto$g[key]) && !hasOwnProperty$e.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function transform(object, iteratee, accumulator) {
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
iteratee = baseIteratee(iteratee, 4);
if (accumulator == null) {
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
accumulator = {};
}
}
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
/**
* Retrieve via an accessor-like property
*
* accessor(obj, 'name') // => retrieves obj['name']
* accessor(data, func) // => retrieves func(data)
* ... otherwise null
*/
function accessor$1(data, field) {
var value = null;
if (typeof field === 'function') value = field(data);else if (typeof field === 'string' && typeof data === 'object' && data != null && field in data) value = data[field];
return value;
}
var wrapAccessor = function wrapAccessor(acc) {
return function (data) {
return accessor$1(data, acc);
};
};
function viewNames$1(_views) {
return !Array.isArray(_views) ? Object.keys(_views) : _views;
}
function isValidView(view, _ref) {
var _views = _ref.views;
var names = viewNames$1(_views);
return names.indexOf(view) !== -1;
}
/**
* react-big-calendar is a full featured Calendar component for managing events and dates. It uses
* modern `flexbox` for layout, making it super responsive and performant. Leaving most of the layout heavy lifting
* to the browser. __note:__ The default styles use `height: 100%` which means your container must set an explicit
* height (feel free to adjust the styles to suit your specific needs).
*
* Big Calendar is unopiniated about editing and moving events, preferring to let you implement it in a way that makes
* the most sense to your app. It also tries not to be prescriptive about your event data structures, just tell it
* how to find the start and end datetimes and you can pass it whatever you want.
*
* One thing to note is that, `react-big-calendar` treats event start/end dates as an _exclusive_ range.
* which means that the event spans up to, but not including, the end date. In the case
* of displaying events on whole days, end dates are rounded _up_ to the next day. So an
* event ending on `Apr 8th 12:00:00 am` will not appear on the 8th, whereas one ending
* on `Apr 8th 12:01:00 am` will. If you want _inclusive_ ranges consider providing a
* function `endAccessor` that returns the end date + 1 day for those events that end at midnight.
*/
var Calendar =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Calendar, _React$Component);
function Calendar() {
var _this;
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
_this.getViews = function () {
var views = _this.props.views;
if (Array.isArray(views)) {
return transform(views, function (obj, name) {
return obj[name] = VIEWS[name];
}, {});
}
if (typeof views === 'object') {
return mapValues(views, function (value, key) {
if (value === true) {
return VIEWS[key];
}
return value;
});
}
return VIEWS;
};
_this.getView = function () {
var views = _this.getViews();
return views[_this.props.view];
};
_this.getDrilldownView = function (date) {
var _this$props = _this.props,
view = _this$props.view,
drilldownView = _this$props.drilldownView,
getDrilldownView = _this$props.getDrilldownView;
if (!getDrilldownView) return drilldownView;
return getDrilldownView(date, view, Object.keys(_this.getViews()));
};
_this.handleRangeChange = function (date, viewComponent, view) {
var _this$props2 = _this.props,
onRangeChange = _this$props2.onRangeChange,
localizer = _this$props2.localizer;
if (onRangeChange) {
if (viewComponent.range) {
onRangeChange(viewComponent.range(date, {
localizer: localizer
}), view);
} else {
{
console.error('onRangeChange prop not supported for this view');
}
}
}
};
_this.handleNavigate = function (action, newDate) {
var _this$props3 = _this.props,
view = _this$props3.view,
date = _this$props3.date,
getNow = _this$props3.getNow,
onNavigate = _this$props3.onNavigate,
props = _objectWithoutPropertiesLoose(_this$props3, ["view", "date", "getNow", "onNavigate"]);
var ViewComponent = _this.getView();
var today = getNow();
date = moveDate(ViewComponent, _extends({}, props, {
action: action,
date: newDate || date || today,
today: today
}));
onNavigate(date, view, action);
_this.handleRangeChange(date, ViewComponent);
};
_this.handleViewChange = function (view) {
if (view !== _this.props.view && isValidView(view, _this.props)) {
_this.props.onView(view);
}
var views = _this.getViews();
_this.handleRangeChange(_this.props.date || _this.props.getNow(), views[view], view);
};
_this.handleSelectEvent = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
notify(_this.props.onSelectEvent, args);
};
_this.handleDoubleClickEvent = function () {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
notify(_this.props.onDoubleClickEvent, args);
};
_this.handleKeyPressEvent = function () {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
notify(_this.props.onKeyPressEvent, args);
};
_this.handleSelectSlot = function (slotInfo) {
notify(_this.props.onSelectSlot, slotInfo);
};
_this.handleDrillDown = function (date, view) {
var onDrillDown = _this.props.onDrillDown;
if (onDrillDown) {
onDrillDown(date, view, _this.drilldownView);
return;
}
if (view) _this.handleViewChange(view);
_this.handleNavigate(navigate.DATE, date);
};
_this.state = {
context: _this.getContext(_this.props)
};
return _this;
}
var _proto = Calendar.prototype;
_proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({
context: this.getContext(nextProps)
});
};
_proto.getContext = function getContext(_ref2) {
var startAccessor = _ref2.startAccessor,
endAccessor = _ref2.endAccessor,
allDayAccessor = _ref2.allDayAccessor,
tooltipAccessor = _ref2.tooltipAccessor,
titleAccessor = _ref2.titleAccessor,
resourceAccessor = _ref2.resourceAccessor,
resourceIdAccessor = _ref2.resourceIdAccessor,
resourceTitleAccessor = _ref2.resourceTitleAccessor,
eventPropGetter = _ref2.eventPropGetter,
backgroundEventPropGetter = _ref2.backgroundEventPropGetter,
slotPropGetter = _ref2.slotPropGetter,
slotGroupPropGetter = _ref2.slotGroupPropGetter,
dayPropGetter = _ref2.dayPropGetter,
view = _ref2.view,
views = _ref2.views,
localizer = _ref2.localizer,
culture = _ref2.culture,
_ref2$messages = _ref2.messages,
messages$1 = _ref2$messages === void 0 ? {} : _ref2$messages,
_ref2$components = _ref2.components,
components = _ref2$components === void 0 ? {} : _ref2$components,
_ref2$formats = _ref2.formats,
formats = _ref2$formats === void 0 ? {} : _ref2$formats;
var names = viewNames$1(views);
var msgs = messages(messages$1);
return {
viewNames: names,
localizer: mergeWithDefaults(localizer, culture, formats, msgs),
getters: {
eventProp: function eventProp() {
return eventPropGetter && eventPropGetter.apply(void 0, arguments) || {};
},
backgroundEventProp: function backgroundEventProp() {
return backgroundEventPropGetter && backgroundEventPropGetter.apply(void 0, arguments) || {};
},
slotProp: function slotProp() {
return slotPropGetter && slotPropGetter.apply(void 0, arguments) || {};
},
slotGroupProp: function slotGroupProp() {
return slotGroupPropGetter && slotGroupPropGetter.apply(void 0, arguments) || {};
},
dayProp: function dayProp() {
return dayPropGetter && dayPropGetter.apply(void 0, arguments) || {};
}
},
components: defaults(components[view] || {}, omit(components, names), {
eventWrapper: NoopWrapper,
backgroundEventWrapper: NoopWrapper,
eventContainerWrapper: NoopWrapper,
dateCellWrapper: NoopWrapper,
weekWrapper: NoopWrapper,
timeSlotWrapper: NoopWrapper
}),
accessors: {
start: wrapAccessor(startAccessor),
end: wrapAccessor(endAccessor),
allDay: wrapAccessor(allDayAccessor),
tooltip: wrapAccessor(tooltipAccessor),
title: wrapAccessor(titleAccessor),
resource: wrapAccessor(resourceAccessor),
resourceId: wrapAccessor(resourceIdAccessor),
resourceTitle: wrapAccessor(resourceTitleAccessor)
}
};
};
_proto.render = function render() {
var _this$props4 = this.props,
view = _this$props4.view,
toolbar = _this$props4.toolbar,
events = _this$props4.events,
_this$props4$backgrou = _this$props4.backgroundEvents,
backgroundEvents = _this$props4$backgrou === void 0 ? [] : _this$props4$backgrou,
style = _this$props4.style,
className = _this$props4.className,
elementProps = _this$props4.elementProps,
current = _this$props4.date,
getNow = _this$props4.getNow,
length = _this$props4.length,
showMultiDayTimes = _this$props4.showMultiDayTimes,
onShowMore = _this$props4.onShowMore,
_0 = _this$props4.components,
_1 = _this$props4.formats,
_2 = _this$props4.messages,
_3 = _this$props4.culture,
props = _objectWithoutPropertiesLoose(_this$props4, ["view", "toolbar", "events", "backgroundEvents", "style", "className", "elementProps", "date", "getNow", "length", "showMultiDayTimes", "onShowMore", "components", "formats", "messages", "culture"]);
current = current || getNow();
var View = this.getView();
var _this$state$context = this.state.context,
accessors = _this$state$context.accessors,
components = _this$state$context.components,
getters = _this$state$context.getters,
localizer = _this$state$context.localizer,
viewNames = _this$state$context.viewNames;
var CalToolbar = components.toolbar || Toolbar;
var label = View.title(current, {
localizer: localizer,
length: length
});
return React__default.createElement("div", _extends({}, elementProps, {
className: clsx(className, 'rbc-calendar', props.rtl && 'rbc-rtl'),
style: style
}), toolbar && React__default.createElement(CalToolbar, {
date: current,
view: view,
views: viewNames,
label: label,
onView: this.handleViewChange,
onNavigate: this.handleNavigate,
localizer: localizer
}), React__default.createElement(View, _extends({}, props, {
events: events,
backgroundEvents: backgroundEvents,
date: current,
getNow: getNow,
length: length,
localizer: localizer,
getters: getters,
components: components,
accessors: accessors,
showMultiDayTimes: showMultiDayTimes,
getDrilldownView: this.getDrilldownView,
onNavigate: this.handleNavigate,
onDrillDown: this.handleDrillDown,
onSelectEvent: this.handleSelectEvent,
onDoubleClickEvent: this.handleDoubleClickEvent,
onKeyPressEvent: this.handleKeyPressEvent,
onSelectSlot: this.handleSelectSlot,
onShowMore: onShowMore
})));
}
/**
*
* @param date
* @param viewComponent
* @param {'month'|'week'|'work_week'|'day'|'agenda'} [view] - optional
* parameter. It appears when range change on view changing. It could be handy
* when you need to have both: range and view type at once, i.e. for manage rbc
* state via url
*/
;
return Calendar;
}(React__default.Component);
Calendar.defaultProps = {
elementProps: {},
popup: false,
toolbar: true,
view: views.MONTH,
views: [views.MONTH, views.WEEK, views.DAY, views.AGENDA],
step: 30,
length: 30,
drilldownView: views.DAY,
titleAccessor: 'title',
tooltipAccessor: 'title',
allDayAccessor: 'allDay',
startAccessor: 'start',
endAccessor: 'end',
resourceAccessor: 'resourceId',
resourceIdAccessor: 'id',
resourceTitleAccessor: 'title',
longPressThreshold: 250,
getNow: function getNow() {
return new Date();
},
dayLayoutAlgorithm: 'overlap'
};
Calendar.propTypes = {
localizer: propTypes.object.isRequired,
/**
* Props passed to main calendar `<div>`.
*
*/
elementProps: propTypes.object,
/**
* The current date value of the calendar. Determines the visible view range.
* If `date` is omitted then the result of `getNow` is used; otherwise the
* current date is used.
*
* @controllable onNavigate
*/
date: propTypes.instanceOf(Date),
/**
* The current view of the calendar.
*
* @default 'month'
* @controllable onView
*/
view: propTypes.string,
/**
* The initial view set for the Calendar.
* @type Calendar.Views ('month'|'week'|'work_week'|'day'|'agenda')
* @default 'month'
*/
defaultView: propTypes.string,
/**
* An array of event objects to display on the calendar. Events objects
* can be any shape, as long as the Calendar knows how to retrieve the
* following details of the event:
*
* - start time
* - end time
* - title
* - whether its an "all day" event or not
* - any resource the event may be related to
*
* Each of these properties can be customized or generated dynamically by
* setting the various "accessor" props. Without any configuration the default
* event should look like:
*
* ```js
* Event {
* title: string,
* start: Date,
* end: Date,
* allDay?: boolean
* resource?: any,
* }
* ```
*/
events: propTypes.arrayOf(propTypes.object),
/**
* An array of background event objects to display on the calendar. Background
* Events behave similarly to Events but are not factored into Event overlap logic,
* allowing them to sit behind any Events that may occur during the same period.
* Background Events objects can be any shape, as long as the Calendar knows how to
* retrieve the following details of the event:
*
* - start time
* - end time
*
* Each of these properties can be customized or generated dynamically by
* setting the various "accessor" props. Without any configuration the default
* event should look like:
*
* ```js
* BackgroundEvent {
* start: Date,
* end: Date,
* }
* ```
*/
backgroundEvents: propTypes.arrayOf(propTypes.object),
/**
* Accessor for the event title, used to display event information. Should
* resolve to a `renderable` value.
*
* ```js
* string | (event: Object) => string
* ```
*
* @type {(func|string)}
*/
titleAccessor: accessor,
/**
* Accessor for the event tooltip. Should
* resolve to a `renderable` value. Removes the tooltip if null.
*
* ```js
* string | (event: Object) => string
* ```
*
* @type {(func|string)}
*/
tooltipAccessor: accessor,
/**
* Determines whether the event should be considered an "all day" event and ignore time.
* Must resolve to a `boolean` value.
*
* ```js
* string | (event: Object) => boolean
* ```
*
* @type {(func|string)}
*/
allDayAccessor: accessor,
/**
* The start date/time of the event. Must resolve to a JavaScript `Date` object.
*
* ```js
* string | (event: Object) => Date
* ```
*
* @type {(func|string)}
*/
startAccessor: accessor,
/**
* The end date/time of the event. Must resolve to a JavaScript `Date` object.
*
* ```js
* string | (event: Object) => Date
* ```
*
* @type {(func|string)}
*/
endAccessor: accessor,
/**
* Returns the id of the `resource` that the event is a member of. This
* id should match at least one resource in the `resources` array.
*
* ```js
* string | (event: Object) => Date
* ```
*
* @type {(func|string)}
*/
resourceAccessor: accessor,
/**
* An array of resource objects that map events to a specific resource.
* Resource objects, like events, can be any shape or have any properties,
* but should be uniquly identifiable via the `resourceIdAccessor`, as
* well as a "title" or name as provided by the `resourceTitleAccessor` prop.
*/
resources: propTypes.arrayOf(propTypes.object),
/**
* Provides a unique identifier for each resource in the `resources` array
*
* ```js
* string | (resource: Object) => any
* ```
*
* @type {(func|string)}
*/
resourceIdAccessor: accessor,
/**
* Provides a human readable name for the resource object, used in headers.
*
* ```js
* string | (resource: Object) => any
* ```
*
* @type {(func|string)}
*/
resourceTitleAccessor: accessor,
/**
* Determines the current date/time which is highlighted in the views.
*
* The value affects which day is shaded and which time is shown as
* the current time. It also affects the date used by the Today button in
* the toolbar.
*
* Providing a value here can be useful when you are implementing time zones
* using the `startAccessor` and `endAccessor` properties.
*
* @type {func}
* @default () => new Date()
*/
getNow: propTypes.func,
/**
* Callback fired when the `date` value changes.
*
* @controllable date
*/
onNavigate: propTypes.func,
/**
* Callback fired when the `view` value changes.
*
* @controllable view
*/
onView: propTypes.func,
/**
* Callback fired when date header, or the truncated events links are clicked
*
*/
onDrillDown: propTypes.func,
/**
*
* ```js
* (dates: Date[] | { start: Date; end: Date }, view: 'month'|'week'|'work_week'|'day'|'agenda'|undefined) => void
* ```
*
* Callback fired when the visible date range changes. Returns an Array of dates
* or an object with start and end dates for BUILTIN views. Optionally new `view`
* will be returned when callback called after view change.
*
* Custom views may return something different.
*/
onRangeChange: propTypes.func,
/**
* A callback fired when a date selection is made. Only fires when `selectable` is `true`.
*
* ```js
* (
* slotInfo: {
* start: Date,
* end: Date,
* resourceId: (number|string),
* slots: Array<Date>,
* action: "select" | "click" | "doubleClick",
* bounds: ?{ // For "select" action
* x: number,
* y: number,
* top: number,
* right: number,
* left: number,
* bottom: number,
* },
* box: ?{ // For "click" or "doubleClick" actions
* clientX: number,
* clientY: number,
* x: number,
* y: number,
* },
* }
* ) => any
* ```
*/
onSelectSlot: propTypes.func,
/**
* Callback fired when a calendar event is selected.
*
* ```js
* (event: Object, e: SyntheticEvent) => any
* ```
*
* @controllable selected
*/
onSelectEvent: propTypes.func,
/**
* Callback fired when a calendar event is clicked twice.
*
* ```js
* (event: Object, e: SyntheticEvent) => void
* ```
*/
onDoubleClickEvent: propTypes.func,
/**
* Callback fired when a focused calendar event recieves a key press.
*
* ```js
* (event: Object, e: SyntheticEvent) => void
* ```
*/
onKeyPressEvent: propTypes.func,
/**
* Callback fired when dragging a selection in the Time views.
*
* Returning `false` from the handler will prevent a selection.
*
* ```js
* (range: { start: Date, end: Date, resourceId: (number|string) }) => ?boolean
* ```
*/
onSelecting: propTypes.func,
/**
* Callback fired when a +{count} more is clicked
*
* ```js
* (events: Object, date: Date) => any
* ```
*/
onShowMore: propTypes.func,
/**
* Displays all events on the month view instead of
* having some hidden behind +{count} more. This will
* cause the rows in the month view to be scrollable if
* the number of events exceed the height of the row.
*/
showAllEvents: propTypes.bool,
/**
* The selected event, if any.
*/
selected: propTypes.object,
/**
* An array of built-in view names to allow the calendar to display.
* accepts either an array of builtin view names,
*
* ```jsx
* views={['month', 'day', 'agenda']}
* ```
* or an object hash of the view name and the component (or boolean for builtin).
*
* ```jsx
* views={{
* month: true,
* week: false,
* myweek: WorkWeekViewComponent,
* }}
* ```
*
* Custom views can be any React component, that implements the following
* interface:
*
* ```js
* interface View {
* static title(date: Date, { formats: DateFormat[], culture: string?, ...props }): string
* static navigate(date: Date, action: 'PREV' | 'NEXT' | 'DATE'): Date
* }
* ```
*
* @type Views ('month'|'week'|'work_week'|'day'|'agenda')
* @View
['month', 'week', 'day', 'agenda']
*/
views: views$1,
/**
* The string name of the destination view for drill-down actions, such
* as clicking a date header, or the truncated events links. If
* `getDrilldownView` is also specified it will be used instead.
*
* Set to `null` to disable drill-down actions.
*
* ```js
* <Calendar
* drilldownView="agenda"
* />
* ```
*/
drilldownView: propTypes.string,
/**
* Functionally equivalent to `drilldownView`, but accepts a function
* that can return a view name. It's useful for customizing the drill-down
* actions depending on the target date and triggering view.
*
* Return `null` to disable drill-down actions.
*
* ```js
* <Calendar
* getDrilldownView={(targetDate, currentViewName, configuredViewNames) =>
* if (currentViewName === 'month' && configuredViewNames.includes('week'))
* return 'week'
*
* return null;
* }}
* />
* ```
*/
getDrilldownView: propTypes.func,
/**
* Determines the end date from date prop in the agenda view
* date prop + length (in number of days) = end date
*/
length: propTypes.number,
/**
* Determines whether the toolbar is displayed
*/
toolbar: propTypes.bool,
/**
* Show truncated events in an overlay when you click the "+_x_ more" link.
*/
popup: propTypes.bool,
/**
* Distance in pixels, from the edges of the viewport, the "show more" overlay should be positioned.
*
* ```jsx
* <Calendar popupOffset={30}/>
* <Calendar popupOffset={{x: 30, y: 20}}/>
* ```
*/
popupOffset: propTypes.oneOfType([propTypes.number, propTypes.shape({
x: propTypes.number,
y: propTypes.number
})]),
/**
* Allows mouse selection of ranges of dates/times.
*
* The 'ignoreEvents' option prevents selection code from running when a
* drag begins over an event. Useful when you want custom event click or drag
* logic
*/
selectable: propTypes.oneOf([true, false, 'ignoreEvents']),
/**
* Specifies the number of miliseconds the user must press and hold on the screen for a touch
* to be considered a "long press." Long presses are used for time slot selection on touch
* devices.
*
* @type {number}
* @default 250
*/
longPressThreshold: propTypes.number,
/**
* Determines the selectable time increments in week and day views, in minutes.
*/
step: propTypes.number,
/**
* The number of slots per "section" in the time grid views. Adjust with `step`
* to change the default of 1 hour long groups, with 30 minute slots.
*/
timeslots: propTypes.number,
/**
*Switch the calendar to a `right-to-left` read direction.
*/
rtl: propTypes.bool,
/**
* Optionally provide a function that returns an object of className or style props
* to be applied to the the event node.
*
* ```js
* (
* event: Object,
* start: Date,
* end: Date,
* isSelected: boolean
* ) => { className?: string, style?: Object }
* ```
*/
eventPropGetter: propTypes.func,
/**
* Optionally provide a function that returns an object of className or style props
* to be applied to the time-slot node. Caution! Styles that change layout or
* position may break the calendar in unexpected ways.
*
* ```js
* (date: Date, resourceId: (number|string)) => { className?: string, style?: Object }
* ```
*/
slotPropGetter: propTypes.func,
/**
* Optionally provide a function that returns an object of props to be applied
* to the time-slot group node. Useful to dynamically change the sizing of time nodes.
* ```js
* () => { style?: Object }
* ```
*/
slotGroupPropGetter: propTypes.func,
/**
* Optionally provide a function that returns an object of className or style props
* to be applied to the the day background. Caution! Styles that change layout or
* position may break the calendar in unexpected ways.
*
* ```js
* (date: Date) => { className?: string, style?: Object }
* ```
*/
dayPropGetter: propTypes.func,
/**
* Support to show multi-day events with specific start and end times in the
* main time grid (rather than in the all day header).
*
* **Note: This may cause calendars with several events to look very busy in
* the week and day views.**
*/
showMultiDayTimes: propTypes.bool,
/**
* Constrains the minimum _time_ of the Day and Week views.
*/
min: propTypes.instanceOf(Date),
/**
* Constrains the maximum _time_ of the Day and Week views.
*/
max: propTypes.instanceOf(Date),
/**
* Determines how far down the scroll pane is initially scrolled down.
*/
scrollToTime: propTypes.instanceOf(Date),
/**
* Specify a specific culture code for the Calendar.
*
* **Note: it's generally better to handle this globally via your i18n library.**
*/
culture: propTypes.string,
/**
* Localizer specific formats, tell the Calendar how to format and display dates.
*
* `format` types are dependent on the configured localizer; both Moment and Globalize
* accept strings of tokens according to their own specification, such as: `'DD mm yyyy'`.
*
* ```jsx
* let formats = {
* dateFormat: 'dd',
*
* dayFormat: (date, , localizer) =>
* localizer.format(date, 'DDD', culture),
*
* dayRangeHeaderFormat: ({ start, end }, culture, localizer) =>
* localizer.format(start, { date: 'short' }, culture) + ' – ' +
* localizer.format(end, { date: 'short' }, culture)
* }
*
* <Calendar formats={formats} />
* ```
*
* All localizers accept a function of
* the form `(date: Date, culture: ?string, localizer: Localizer) -> string`
*/
formats: propTypes.shape({
/**
* Format for the day of the month heading in the Month view.
* e.g. "01", "02", "03", etc
*/
dateFormat: dateFormat,
/**
* A day of the week format for Week and Day headings,
* e.g. "Wed 01/04"
*
*/
dayFormat: dateFormat,
/**
* Week day name format for the Month week day headings,
* e.g: "Sun", "Mon", "Tue", etc
*
*/
weekdayFormat: dateFormat,
/**
* The timestamp cell formats in Week and Time views, e.g. "4:00 AM"
*/
timeGutterFormat: dateFormat,
/**
* Toolbar header format for the Month view, e.g "2015 April"
*
*/
monthHeaderFormat: dateFormat,
/**
* Toolbar header format for the Week views, e.g. "Mar 29 - Apr 04"
*/
dayRangeHeaderFormat: dateRangeFormat,
/**
* Toolbar header format for the Day view, e.g. "Wednesday Apr 01"
*/
dayHeaderFormat: dateFormat,
/**
* Toolbar header format for the Agenda view, e.g. "4/1/2015 – 5/1/2015"
*/
agendaHeaderFormat: dateRangeFormat,
/**
* A time range format for selecting time slots, e.g "8:00am – 2:00pm"
*/
selectRangeFormat: dateRangeFormat,
agendaDateFormat: dateFormat,
agendaTimeFormat: dateFormat,
agendaTimeRangeFormat: dateRangeFormat,
/**
* Time range displayed on events.
*/
eventTimeRangeFormat: dateRangeFormat,
/**
* An optional event time range for events that continue onto another day
*/
eventTimeRangeStartFormat: dateFormat,
/**
* An optional event time range for events that continue from another day
*/
eventTimeRangeEndFormat: dateFormat
}),
/**
* Customize how different sections of the calendar render by providing custom Components.
* In particular the `Event` component can be specified for the entire calendar, or you can
* provide an individual component for each view type.
*
* ```jsx
* let components = {
* event: MyEvent, // used by each view (Month, Day, Week)
* eventWrapper: MyEventWrapper,
* eventContainerWrapper: MyEventContainerWrapper,
* dateCellWrapper: MyDateCellWrapper,
* timeSlotWrapper: MyTimeSlotWrapper,
* timeGutterHeader: MyTimeGutterWrapper,
* toolbar: MyToolbar,
* agenda: {
* event: MyAgendaEvent // with the agenda view use a different component to render events
* time: MyAgendaTime,
* date: MyAgendaDate,
* },
* day: {
* header: MyDayHeader,
* event: MyDayEvent,
* },
* week: {
* header: MyWeekHeader,
* event: MyWeekEvent,
* },
* month: {
* header: MyMonthHeader,
* dateHeader: MyMonthDateHeader,
* event: MyMonthEvent,
* }
* }
* <Calendar components={components} />
* ```
*/
components: propTypes.shape({
event: propTypes.elementType,
eventWrapper: propTypes.elementType,
eventContainerWrapper: propTypes.elementType,
dateCellWrapper: propTypes.elementType,
timeSlotWrapper: propTypes.elementType,
timeGutterHeader: propTypes.elementType,
resourceHeader: propTypes.elementType,
toolbar: propTypes.elementType,
agenda: propTypes.shape({
date: propTypes.elementType,
time: propTypes.elementType,
event: propTypes.elementType
}),
day: propTypes.shape({
header: propTypes.elementType,
event: propTypes.elementType
}),
week: propTypes.shape({
header: propTypes.elementType,
event: propTypes.elementType
}),
month: propTypes.shape({
header: propTypes.elementType,
dateHeader: propTypes.elementType,
event: propTypes.elementType
})
}),
/**
* String messages used throughout the component, override to provide localizations
*/
messages: propTypes.shape({
allDay: propTypes.node,
previous: propTypes.node,
next: propTypes.node,
today: propTypes.node,
month: propTypes.node,
week: propTypes.node,
day: propTypes.node,
agenda: propTypes.node,
date: propTypes.node,
time: propTypes.node,
event: propTypes.node,
noEventsInRange: propTypes.node,
showMore: propTypes.func
}),
/**
* A day event layout(arrangement) algorithm.
* `overlap` allows events to be overlapped.
* `no-overlap` resizes events to avoid overlap.
* or custom `Function(events, minimumStartDifference, slotMetrics, accessors)`
*/
dayLayoutAlgorithm: DayLayoutAlgorithmPropType
};
var Calendar$1 = uncontrollable(Calendar, {
view: 'onView',
date: 'onNavigate',
selected: 'onSelectEvent'
});
var dateRangeFormat$1 = function dateRangeFormat(_ref, culture, local) {
var start = _ref.start,
end = _ref.end;
return local.format(start, 'L', culture) + ' – ' + local.format(end, 'L', culture);
};
var timeRangeFormat = function timeRangeFormat(_ref2, culture, local) {
var start = _ref2.start,
end = _ref2.end;
return local.format(start, 'LT', culture) + ' – ' + local.format(end, 'LT', culture);
};
var timeRangeStartFormat = function timeRangeStartFormat(_ref3, culture, local) {
var start = _ref3.start;
return local.format(start, 'LT', culture) + ' – ';
};
var timeRangeEndFormat = function timeRangeEndFormat(_ref4, culture, local) {
var end = _ref4.end;
return ' – ' + local.format(end, 'LT', culture);
};
var weekRangeFormat = function weekRangeFormat(_ref5, culture, local) {
var start = _ref5.start,
end = _ref5.end;
return local.format(start, 'MMMM DD', culture) + ' – ' + local.format(end, eq(start, end, 'month') ? 'DD' : 'MMMM DD', culture);
};
var formats = {
dateFormat: 'DD',
dayFormat: 'DD ddd',
weekdayFormat: 'ddd',
selectRangeFormat: timeRangeFormat,
eventTimeRangeFormat: timeRangeFormat,
eventTimeRangeStartFormat: timeRangeStartFormat,
eventTimeRangeEndFormat: timeRangeEndFormat,
timeGutterFormat: 'LT',
monthHeaderFormat: 'MMMM YYYY',
dayHeaderFormat: 'dddd MMM DD',
dayRangeHeaderFormat: weekRangeFormat,
agendaHeaderFormat: dateRangeFormat$1,
agendaDateFormat: 'ddd MMM DD',
agendaTimeFormat: 'LT',
agendaTimeRangeFormat: timeRangeFormat
};
function moment (moment) {
var locale = function locale(m, c) {
return c ? m.locale(c) : m;
};
return new DateLocalizer({
formats: formats,
firstOfWeek: function firstOfWeek(culture) {
var data = culture ? moment.localeData(culture) : moment.localeData();
return data ? data.firstDayOfWeek() : 0;
},
format: function format(value, _format, culture) {
return locale(moment(value), culture).format(_format);
}
});
}
var dateRangeFormat$2 = function dateRangeFormat(_ref, culture, local) {
var start = _ref.start,
end = _ref.end;
return local.format(start, 'd', culture) + ' – ' + local.format(end, 'd', culture);
};
var timeRangeFormat$1 = function timeRangeFormat(_ref2, culture, local) {
var start = _ref2.start,
end = _ref2.end;
return local.format(start, 't', culture) + ' – ' + local.format(end, 't', culture);
};
var timeRangeStartFormat$1 = function timeRangeStartFormat(_ref3, culture, local) {
var start = _ref3.start;
return local.format(start, 't', culture) + ' – ';
};
var timeRangeEndFormat$1 = function timeRangeEndFormat(_ref4, culture, local) {
var end = _ref4.end;
return ' – ' + local.format(end, 't', culture);
};
var weekRangeFormat$1 = function weekRangeFormat(_ref5, culture, local) {
var start = _ref5.start,
end = _ref5.end;
return local.format(start, 'MMM dd', culture) + ' – ' + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture);
};
var formats$1 = {
dateFormat: 'dd',
dayFormat: 'ddd dd/MM',
weekdayFormat: 'ddd',
selectRangeFormat: timeRangeFormat$1,
eventTimeRangeFormat: timeRangeFormat$1,
eventTimeRangeStartFormat: timeRangeStartFormat$1,
eventTimeRangeEndFormat: timeRangeEndFormat$1,
timeGutterFormat: 't',
monthHeaderFormat: 'Y',
dayHeaderFormat: 'dddd MMM dd',
dayRangeHeaderFormat: weekRangeFormat$1,
agendaHeaderFormat: dateRangeFormat$2,
agendaDateFormat: 'ddd MMM dd',
agendaTimeFormat: 't',
agendaTimeRangeFormat: timeRangeFormat$1
};
function oldGlobalize (globalize) {
function getCulture(culture) {
return culture ? globalize.findClosestCulture(culture) : globalize.culture();
}
function firstOfWeek(culture) {
culture = getCulture(culture);
return culture && culture.calendar.firstDay || 0;
}
return new DateLocalizer({
firstOfWeek: firstOfWeek,
formats: formats$1,
format: function format(value, _format, culture) {
return globalize.format(value, _format, culture);
}
});
}
var dateRangeFormat$3 = function dateRangeFormat(_ref, culture, local) {
var start = _ref.start,
end = _ref.end;
return local.format(start, {
date: 'short'
}, culture) + ' – ' + local.format(end, {
date: 'short'
}, culture);
};
var timeRangeFormat$2 = function timeRangeFormat(_ref2, culture, local) {
var start = _ref2.start,
end = _ref2.end;
return local.format(start, {
time: 'short'
}, culture) + ' – ' + local.format(end, {
time: 'short'
}, culture);
};
var timeRangeStartFormat$2 = function timeRangeStartFormat(_ref3, culture, local) {
var start = _ref3.start;
return local.format(start, {
time: 'short'
}, culture) + ' – ';
};
var timeRangeEndFormat$2 = function timeRangeEndFormat(_ref4, culture, local) {
var end = _ref4.end;
return ' – ' + local.format(end, {
time: 'short'
}, culture);
};
var weekRangeFormat$2 = function weekRangeFormat(_ref5, culture, local) {
var start = _ref5.start,
end = _ref5.end;
return local.format(start, 'MMM dd', culture) + ' – ' + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture);
};
var formats$2 = {
dateFormat: 'dd',
dayFormat: 'eee dd/MM',
weekdayFormat: 'eee',
selectRangeFormat: timeRangeFormat$2,
eventTimeRangeFormat: timeRangeFormat$2,
eventTimeRangeStartFormat: timeRangeStartFormat$2,
eventTimeRangeEndFormat: timeRangeEndFormat$2,
timeGutterFormat: {
time: 'short'
},
monthHeaderFormat: 'MMMM yyyy',
dayHeaderFormat: 'eeee MMM dd',
dayRangeHeaderFormat: weekRangeFormat$2,
agendaHeaderFormat: dateRangeFormat$3,
agendaDateFormat: 'eee MMM dd',
agendaTimeFormat: {
time: 'short'
},
agendaTimeRangeFormat: timeRangeFormat$2
};
function globalize (globalize) {
var locale = function locale(culture) {
return culture ? globalize(culture) : globalize;
}; // return the first day of the week from the locale data. Defaults to 'world'
// territory if no territory is derivable from CLDR.
// Failing to use CLDR supplemental (not loaded?), revert to the original
// method of getting first day of week.
function firstOfWeek(culture) {
try {
var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
var cldr = locale(culture).cldr;
var territory = cldr.attributes.territory;
var weekData = cldr.get('supplemental').weekData;
var firstDay = weekData.firstDay[territory || '001'];
return days.indexOf(firstDay);
} catch (e) {
{
console.error('Failed to accurately determine first day of the week.' + ' Is supplemental data loaded into CLDR?');
} // maybe cldr supplemental is not loaded? revert to original method
var date = new Date(); //cldr-data doesn't seem to be zero based
var localeDay = Math.max(parseInt(locale(culture).formatDate(date, {
raw: 'e'
}), 10) - 1, 0);
return Math.abs(date.getDay() - localeDay);
}
}
if (!globalize.load) return oldGlobalize(globalize);
return new DateLocalizer({
firstOfWeek: firstOfWeek,
formats: formats$2,
format: function format(value, _format, culture) {
_format = typeof _format === 'string' ? {
raw: _format
} : _format;
return locale(culture).formatDate(value, _format);
}
});
}
var dateRangeFormat$4 = function dateRangeFormat(_ref, culture, local) {
var start = _ref.start,
end = _ref.end;
return local.format(start, 'P', culture) + " \u2013 " + local.format(end, 'P', culture);
};
var timeRangeFormat$3 = function timeRangeFormat(_ref2, culture, local) {
var start = _ref2.start,
end = _ref2.end;
return local.format(start, 'p', culture) + " \u2013 " + local.format(end, 'p', culture);
};
var timeRangeStartFormat$3 = function timeRangeStartFormat(_ref3, culture, local) {
var start = _ref3.start;
return local.format(start, 'h:mma', culture) + " \u2013 ";
};
var timeRangeEndFormat$3 = function timeRangeEndFormat(_ref4, culture, local) {
var end = _ref4.end;
return " \u2013 " + local.format(end, 'h:mma', culture);
};
var weekRangeFormat$3 = function weekRangeFormat(_ref5, culture, local) {
var start = _ref5.start,
end = _ref5.end;
return local.format(start, 'MMMM dd', culture) + " \u2013 " + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMMM dd', culture);
};
var formats$3 = {
dateFormat: 'dd',
dayFormat: 'dd eee',
weekdayFormat: 'cccc',
selectRangeFormat: timeRangeFormat$3,
eventTimeRangeFormat: timeRangeFormat$3,
eventTimeRangeStartFormat: timeRangeStartFormat$3,
eventTimeRangeEndFormat: timeRangeEndFormat$3,
timeGutterFormat: 'p',
monthHeaderFormat: 'MMMM yyyy',
dayHeaderFormat: 'cccc MMM dd',
dayRangeHeaderFormat: weekRangeFormat$3,
agendaHeaderFormat: dateRangeFormat$4,
agendaDateFormat: 'ccc MMM dd',
agendaTimeFormat: 'p',
agendaTimeRangeFormat: timeRangeFormat$3
};
var dateFnsLocalizer = function dateFnsLocalizer(_ref6) {
var startOfWeek = _ref6.startOfWeek,
getDay = _ref6.getDay,
_format = _ref6.format,
locales = _ref6.locales;
return new DateLocalizer({
formats: formats$3,
firstOfWeek: function firstOfWeek(culture) {
return getDay(startOfWeek(new Date(), {
locale: locales[culture]
}));
},
format: function format(value, formatString, culture) {
return _format(new Date(value), formatString, {
locale: locales[culture]
});
}
});
};
var components = {
eventWrapper: NoopWrapper,
timeSlotWrapper: NoopWrapper,
dateCellWrapper: NoopWrapper
};
exports.Calendar = Calendar$1;
exports.DateLocalizer = DateLocalizer;
exports.Navigate = navigate;
exports.Views = views;
exports.components = components;
exports.dateFnsLocalizer = dateFnsLocalizer;
exports.globalizeLocalizer = globalize;
exports.momentLocalizer = moment;
exports.move = moveDate;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
/**
* @license Highcharts JS v9.2.2 (2021-08-24)
*
* Vector plot series module
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/vector', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Series/Vector/VectorSeries.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Core/Globals.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (A, H, SeriesRegistry, U) {
/* *
*
* Vector plot series module
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var animObject = A.animObject;
var Series = SeriesRegistry.series,
ScatterSeries = SeriesRegistry.seriesTypes.scatter;
var arrayMax = U.arrayMax,
extend = U.extend,
merge = U.merge,
pick = U.pick;
/* *
*
* Class
*
* */
/**
* The vector series class.
*
* @private
* @class
* @name Highcharts.seriesTypes.vector
*
* @augments Highcharts.seriesTypes.scatter
*/
var VectorSeries = /** @class */ (function (_super) {
__extends(VectorSeries, _super);
function VectorSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.lengthMax = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* Fade in the arrows on initializing series.
* @private
*/
VectorSeries.prototype.animate = function (init) {
if (init) {
this.markerGroup.attr({
opacity: 0.01
});
}
else {
this.markerGroup.animate({
opacity: 1
}, animObject(this.options.animation));
}
};
/**
* Create a single arrow. It is later rotated around the zero
* centerpoint.
* @private
*/
VectorSeries.prototype.arrow = function (point) {
var path,
fraction = point.length / this.lengthMax,
u = fraction * this.options.vectorLength / 20,
o = {
start: 10 * u,
center: 0,
end: -10 * u
}[this.options.rotationOrigin] || 0;
// The stem and the arrow head. Draw the arrow first with rotation
// 0, which is the arrow pointing down (vector from north to south).
path = [
['M', 0, 7 * u + o],
['L', -1.5 * u, 7 * u + o],
['L', 0, 10 * u + o],
['L', 1.5 * u, 7 * u + o],
['L', 0, 7 * u + o],
['L', 0, -10 * u + o] // top
];
return path;
};
/*
drawLegendSymbol: function (legend, item) {
let options = legend.options,
symbolHeight = legend.symbolHeight,
square = options.squareSymbol,
symbolWidth = square ? symbolHeight : legend.symbolWidth,
path = this.arrow.call({
lengthMax: 1,
options: {
vectorLength: symbolWidth
}
}, {
length: 1
});
item.legendLine = this.chart.renderer.path(path)
.addClass('highcharts-point')
.attr({
zIndex: 3,
translateY: symbolWidth / 2,
rotation: 270,
'stroke-width': 1,
'stroke': 'black'
}).add(item.legendGroup);
},
*/
/**
* @private
*/
VectorSeries.prototype.drawPoints = function () {
var chart = this.chart;
this.points.forEach(function (point) {
var plotX = point.plotX,
plotY = point.plotY;
if (this.options.clip === false ||
chart.isInsidePlot(plotX, plotY, { inverted: chart.inverted })) {
if (!point.graphic) {
point.graphic = this.chart.renderer
.path()
.add(this.markerGroup)
.addClass('highcharts-point ' +
'highcharts-color-' +
pick(point.colorIndex, point.series.colorIndex));
}
point.graphic
.attr({
d: this.arrow(point),
translateX: plotX,
translateY: plotY,
rotation: point.direction
});
if (!this.chart.styledMode) {
point.graphic
.attr(this.pointAttribs(point));
}
}
else if (point.graphic) {
point.graphic = point.graphic.destroy();
}
}, this);
};
/**
* Get presentational attributes.
* @private
*/
VectorSeries.prototype.pointAttribs = function (point, state) {
var options = this.options,
stroke = point.color || this.color,
strokeWidth = this.options.lineWidth;
if (state) {
stroke = options.states[state].color || stroke;
strokeWidth =
(options.states[state].lineWidth || strokeWidth) +
(options.states[state].lineWidthPlus || 0);
}
return {
'stroke': stroke,
'stroke-width': strokeWidth
};
};
/**
* @private
*/
VectorSeries.prototype.translate = function () {
Series.prototype.translate.call(this);
this.lengthMax = arrayMax(this.lengthData);
};
/**
* A vector plot is a type of cartesian chart where each point has an X and
* Y position, a length and a direction. Vectors are drawn as arrows.
*
* @sample {highcharts|highstock} highcharts/demo/vector-plot/
* Vector pot
*
* @since 6.0.0
* @extends plotOptions.scatter
* @excluding boostThreshold, marker, connectEnds, connectNulls,
* cropThreshold, dashStyle, dragDrop, gapSize, gapUnit,
* dataGrouping, linecap, shadow, stacking, step, jitter,
* boostBlending
* @product highcharts highstock
* @requires modules/vector
* @optionparent plotOptions.vector
*/
VectorSeries.defaultOptions = merge(ScatterSeries.defaultOptions, {
/**
* The line width for each vector arrow.
*/
lineWidth: 2,
/**
* @ignore
*/
marker: null,
/**
* What part of the vector it should be rotated around. Can be one of
* `start`, `center` and `end`. When `start`, the vectors will start
* from the given [x, y] position, and when `end` the vectors will end
* in the [x, y] position.
*
* @sample highcharts/plotoptions/vector-rotationorigin-start/
* Rotate from start
*
* @validvalue ["start", "center", "end"]
*/
rotationOrigin: 'center',
states: {
hover: {
/**
* Additonal line width for the vector errors when they are
* hovered.
*/
lineWidthPlus: 1
}
},
tooltip: {
/**
* @default [{point.x}, {point.y}] Length: {point.length} Direction: {point.direction}°
*/
pointFormat: '<b>[{point.x}, {point.y}]</b><br/>Length: <b>{point.length}</b><br/>Direction: <b>{point.direction}\u00B0</b><br/>'
},
/**
* Maximum length of the arrows in the vector plot. The individual arrow
* length is computed between 0 and this value.
*/
vectorLength: 20
});
return VectorSeries;
}(ScatterSeries));
extend(VectorSeries.prototype, {
/**
* @ignore
* @deprecated
*/
drawGraph: H.noop,
/**
* @ignore
* @deprecated
*/
getSymbol: H.noop,
/**
* @ignore
* @deprecated
*/
markerAttribs: H.noop,
parallelArrays: ['x', 'y', 'length', 'direction'],
pointArrayMap: ['y', 'length', 'direction']
});
SeriesRegistry.registerSeriesType('vector', VectorSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A `vector` series. If the [type](#series.vector.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.vector
* @excluding dataParser, dataURL, boostThreshold, boostBlending
* @product highcharts highstock
* @requires modules/vector
* @apioption series.vector
*/
/**
* An array of data points for the series. For the `vector` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 4 values. In this case, the values correspond to
* to `x,y,length,direction`. If the first value is a string, it is applied
* as the name of the point, and the `x` value is inferred.
* ```js
* data: [
* [0, 0, 10, 90],
* [0, 1, 5, 180],
* [1, 1, 2, 270]
* ]
* ```
*
* 2. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.area.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 0,
* y: 0,
* name: "Point2",
* length: 10,
* direction: 90
* }, {
* x: 1,
* y: 1,
* name: "Point1",
* direction: 270
* }]
* ```
*
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<Array<(number|string),number,number,number>|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.vector.data
*/
/**
* The length of the vector. The rendered length will relate to the
* `vectorLength` setting.
*
* @type {number}
* @product highcharts highstock
* @apioption series.vector.data.length
*/
/**
* The vector direction in degrees, where 0 is north (pointing towards south).
*
* @type {number}
* @product highcharts highstock
* @apioption series.vector.data.direction
*/
''; // adds doclets above to the transpiled file
return VectorSeries;
});
_registerModule(_modules, 'masters/modules/vector.src.js', [], function () {
});
})); |
/* airbrake-js v1.3.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Airbrake = {}));
}(this, (function (exports) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/**
* @this {Promise}
*/
function finallyConstructor(callback) {
var constructor = this.constructor;
return this.then(
function(value) {
// @ts-ignore
return constructor.resolve(callback()).then(function() {
return value;
});
},
function(reason) {
// @ts-ignore
return constructor.resolve(callback()).then(function() {
// @ts-ignore
return constructor.reject(reason);
});
}
);
}
// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;
function isArray(x) {
return Boolean(x && typeof x.length !== 'undefined');
}
function noop() {}
// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
return function() {
fn.apply(thisArg, arguments);
};
}
/**
* @constructor
* @param {Function} fn
*/
function Promise$1(fn) {
if (!(this instanceof Promise$1))
throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
/** @type {!number} */
this._state = 0;
/** @type {!boolean} */
this._handled = false;
/** @type {Promise|undefined} */
this._value = undefined;
/** @type {!Array<!Function>} */
this._deferreds = [];
doResolve(fn, this);
}
function handle(self, deferred) {
while (self._state === 3) {
self = self._value;
}
if (self._state === 0) {
self._deferreds.push(deferred);
return;
}
self._handled = true;
Promise$1._immediateFn(function() {
var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
var ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return;
}
resolve(deferred.promise, ret);
});
}
function resolve(self, newValue) {
try {
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self)
throw new TypeError('A promise cannot be resolved with itself.');
if (
newValue &&
(typeof newValue === 'object' || typeof newValue === 'function')
) {
var then = newValue.then;
if (newValue instanceof Promise$1) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
reject(self, e);
}
}
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise$1._immediateFn(function() {
if (!self._handled) {
Promise$1._unhandledRejectionFn(self._value);
}
});
}
for (var i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]);
}
self._deferreds = null;
}
/**
* @constructor
*/
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, self) {
var done = false;
try {
fn(
function(value) {
if (done) return;
done = true;
resolve(self, value);
},
function(reason) {
if (done) return;
done = true;
reject(self, reason);
}
);
} catch (ex) {
if (done) return;
done = true;
reject(self, ex);
}
}
Promise$1.prototype['catch'] = function(onRejected) {
return this.then(null, onRejected);
};
Promise$1.prototype.then = function(onFulfilled, onRejected) {
// @ts-ignore
var prom = new this.constructor(noop);
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom;
};
Promise$1.prototype['finally'] = finallyConstructor;
Promise$1.all = function(arr) {
return new Promise$1(function(resolve, reject) {
if (!isArray(arr)) {
return reject(new TypeError('Promise.all accepts an array'));
}
var args = Array.prototype.slice.call(arr);
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(
val,
function(val) {
res(i, val);
},
reject
);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise$1.resolve = function(value) {
if (value && typeof value === 'object' && value.constructor === Promise$1) {
return value;
}
return new Promise$1(function(resolve) {
resolve(value);
});
};
Promise$1.reject = function(value) {
return new Promise$1(function(resolve, reject) {
reject(value);
});
};
Promise$1.race = function(arr) {
return new Promise$1(function(resolve, reject) {
if (!isArray(arr)) {
return reject(new TypeError('Promise.race accepts an array'));
}
for (var i = 0, len = arr.length; i < len; i++) {
Promise$1.resolve(arr[i]).then(resolve, reject);
}
});
};
// Use polyfill for setImmediate for performance gains
Promise$1._immediateFn =
// @ts-ignore
(typeof setImmediate === 'function' &&
function(fn) {
// @ts-ignore
setImmediate(fn);
}) ||
function(fn) {
setTimeoutFunc(fn, 0);
};
Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
}
};
var FILTERED = '[Filtered]';
var MAX_OBJ_LENGTH = 128;
// jsonifyNotice serializes notice to JSON and truncates params,
// environment and session keys.
function jsonifyNotice(notice, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.maxLength, maxLength = _c === void 0 ? 64000 : _c, _d = _b.keysBlocklist, keysBlocklist = _d === void 0 ? [] : _d;
if (notice.errors) {
for (var i = 0; i < notice.errors.length; i++) {
var t = new Truncator({ keysBlocklist: keysBlocklist });
notice.errors[i] = t.truncate(notice.errors[i]);
}
}
var s = '';
var keys = ['context', 'params', 'environment', 'session'];
for (var level = 0; level < 8; level++) {
var opts = { level: level, keysBlocklist: keysBlocklist };
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
var obj = notice[key];
if (obj) {
notice[key] = truncate(obj, opts);
}
}
s = JSON.stringify(notice);
if (s.length < maxLength) {
return s;
}
}
var params = {
json: s.slice(0, Math.floor(maxLength / 2)) + '...',
};
keys.push('errors');
for (var _e = 0, keys_2 = keys; _e < keys_2.length; _e++) {
var key = keys_2[_e];
var obj = notice[key];
if (!obj) {
continue;
}
s = JSON.stringify(obj);
params[key] = s.length;
}
var err = new Error("airbrake: notice exceeds max length and can't be truncated");
err.params = params;
throw err;
}
function scale(num, level) {
return num >> level || 1;
}
var Truncator = /** @class */ (function () {
function Truncator(opts) {
this.maxStringLength = 1024;
this.maxObjectLength = MAX_OBJ_LENGTH;
this.maxArrayLength = MAX_OBJ_LENGTH;
this.maxDepth = 8;
this.keys = [];
this.keysBlocklist = [];
this.seen = [];
var level = opts.level || 0;
this.keysBlocklist = opts.keysBlocklist || [];
this.maxStringLength = scale(this.maxStringLength, level);
this.maxObjectLength = scale(this.maxObjectLength, level);
this.maxArrayLength = scale(this.maxArrayLength, level);
this.maxDepth = scale(this.maxDepth, level);
}
Truncator.prototype.truncate = function (value, key, depth) {
if (key === void 0) { key = ''; }
if (depth === void 0) { depth = 0; }
if (value === null || value === undefined) {
return value;
}
switch (typeof value) {
case 'boolean':
case 'number':
case 'function':
return value;
case 'string':
return this.truncateString(value);
case 'object':
break;
default:
return this.truncateString(String(value));
}
if (value instanceof String) {
return this.truncateString(value.toString());
}
if (value instanceof Boolean ||
value instanceof Number ||
value instanceof Date ||
value instanceof RegExp) {
return value;
}
if (value instanceof Error) {
return this.truncateString(value.toString());
}
if (this.seen.indexOf(value) >= 0) {
return "[Circular " + this.getPath(value) + "]";
}
var type = objectType(value);
depth++;
if (depth > this.maxDepth) {
return "[Truncated " + type + "]";
}
this.keys.push(key);
this.seen.push(value);
switch (type) {
case 'Array':
return this.truncateArray(value, depth);
case 'Object':
return this.truncateObject(value, depth);
default:
var saved = this.maxDepth;
this.maxDepth = 0;
var obj = this.truncateObject(value, depth);
obj.__type = type;
this.maxDepth = saved;
return obj;
}
};
Truncator.prototype.getPath = function (value) {
var index = this.seen.indexOf(value);
var path = [this.keys[index]];
for (var i = index; i >= 0; i--) {
var sub = this.seen[i];
if (sub && getAttr(sub, path[0]) === value) {
value = sub;
path.unshift(this.keys[i]);
}
}
return '~' + path.join('.');
};
Truncator.prototype.truncateString = function (s) {
if (s.length > this.maxStringLength) {
return s.slice(0, this.maxStringLength) + '...';
}
return s;
};
Truncator.prototype.truncateArray = function (arr, depth) {
if (depth === void 0) { depth = 0; }
var length = 0;
var dst = [];
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
dst.push(this.truncate(el, i.toString(), depth));
length++;
if (length >= this.maxArrayLength) {
break;
}
}
return dst;
};
Truncator.prototype.truncateObject = function (obj, depth) {
if (depth === void 0) { depth = 0; }
var length = 0;
var dst = {};
for (var key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
continue;
}
if (isBlocklisted(key, this.keysBlocklist)) {
dst[key] = FILTERED;
continue;
}
var value = getAttr(obj, key);
if (value === undefined || typeof value === 'function') {
continue;
}
dst[key] = this.truncate(value, key, depth);
length++;
if (length >= this.maxObjectLength) {
break;
}
}
return dst;
};
return Truncator;
}());
function truncate(value, opts) {
if (opts === void 0) { opts = {}; }
var t = new Truncator(opts);
return t.truncate(value);
}
function getAttr(obj, attr) {
// Ignore browser specific exception trying to read an attribute (#79).
try {
return obj[attr];
}
catch (_) {
return;
}
}
function objectType(obj) {
var s = Object.prototype.toString.apply(obj);
return s.slice('[object '.length, -1);
}
function isBlocklisted(key, keysBlocklist) {
for (var _i = 0, keysBlocklist_1 = keysBlocklist; _i < keysBlocklist_1.length; _i++) {
var v = keysBlocklist_1[_i];
if (v === key) {
return true;
}
if (v instanceof RegExp) {
if (key.match(v)) {
return true;
}
}
}
return false;
}
var Span = /** @class */ (function () {
function Span(metric, name, startTime) {
this._dur = 0;
this._level = 0;
this._metric = metric;
this.name = name;
this.startTime = startTime || new Date();
}
Span.prototype.end = function (endTime) {
this.endTime = endTime ? endTime : new Date();
this._dur += this.endTime.getTime() - this.startTime.getTime();
this._metric._incGroup(this.name, this._dur);
this._metric = null;
};
Span.prototype._pause = function () {
if (this._paused()) {
return;
}
var now = new Date();
this._dur += now.getTime() - this.startTime.getTime();
this.startTime = null;
};
Span.prototype._resume = function () {
if (!this._paused()) {
return;
}
this.startTime = new Date();
};
Span.prototype._paused = function () {
return this.startTime == null;
};
return Span;
}());
var BaseMetric = /** @class */ (function () {
function BaseMetric() {
this._spans = {};
this._groups = {};
this.startTime = new Date();
}
BaseMetric.prototype.end = function (endTime) {
if (!this.endTime) {
this.endTime = endTime || new Date();
}
};
BaseMetric.prototype.isRecording = function () {
return true;
};
BaseMetric.prototype.startSpan = function (name, startTime) {
var span = this._spans[name];
if (span) {
span._level++;
}
else {
span = new Span(this, name, startTime);
this._spans[name] = span;
}
};
BaseMetric.prototype.endSpan = function (name, endTime) {
var span = this._spans[name];
if (!span) {
console.error('airbrake: span=%s does not exist', name);
return;
}
if (span._level > 0) {
span._level--;
}
else {
span.end(endTime);
delete this._spans[span.name];
}
};
BaseMetric.prototype._incGroup = function (name, ms) {
this._groups[name] = (this._groups[name] || 0) + ms;
};
BaseMetric.prototype._duration = function () {
if (!this.endTime) {
this.endTime = new Date();
}
return this.endTime.getTime() - this.startTime.getTime();
};
return BaseMetric;
}());
var NoopMetric = /** @class */ (function () {
function NoopMetric() {
}
NoopMetric.prototype.isRecording = function () {
return false;
};
NoopMetric.prototype.startSpan = function (_name, _startTime) { };
NoopMetric.prototype.endSpan = function (_name, _startTime) { };
NoopMetric.prototype._incGroup = function (_name, _ms) { };
return NoopMetric;
}());
var Scope = /** @class */ (function () {
function Scope() {
this._noopMetric = new NoopMetric();
this._context = {};
this._historyMaxLen = 20;
this._history = [];
}
Scope.prototype.clone = function () {
var clone = new Scope();
clone._context = __assign({}, this._context);
clone._history = this._history.slice();
return clone;
};
Scope.prototype.setContext = function (context) {
this._context = __assign(__assign({}, this._context), context);
};
Scope.prototype.context = function () {
var ctx = __assign({}, this._context);
if (this._history.length > 0) {
ctx.history = this._history.slice();
}
return ctx;
};
Scope.prototype.pushHistory = function (state) {
if (this._isDupState(state)) {
if (this._lastRecord.num) {
this._lastRecord.num++;
}
else {
this._lastRecord.num = 2;
}
return;
}
if (!state.date) {
state.date = new Date();
}
this._history.push(state);
this._lastRecord = state;
if (this._history.length > this._historyMaxLen) {
this._history = this._history.slice(-this._historyMaxLen);
}
};
Scope.prototype._isDupState = function (state) {
if (!this._lastRecord) {
return false;
}
for (var key in state) {
if (!state.hasOwnProperty(key) || key === 'date') {
continue;
}
if (state[key] !== this._lastRecord[key]) {
return false;
}
}
return true;
};
Scope.prototype.routeMetric = function () {
return this._routeMetric || this._noopMetric;
};
Scope.prototype.setRouteMetric = function (metric) {
this._routeMetric = metric;
};
Scope.prototype.queueMetric = function () {
return this._queueMetric || this._noopMetric;
};
Scope.prototype.setQueueMetric = function (metric) {
this._queueMetric = metric;
};
return Scope;
}());
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var stackframe = createCommonjsModule(function (module, exports) {
(function(root, factory) {
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
{
module.exports = factory();
}
}(commonjsGlobal, function() {
function _isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function _capitalize(str) {
return str.charAt(0).toUpperCase() + str.substring(1);
}
function _getter(p) {
return function() {
return this[p];
};
}
var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel'];
var numericProps = ['columnNumber', 'lineNumber'];
var stringProps = ['fileName', 'functionName', 'source'];
var arrayProps = ['args'];
var props = booleanProps.concat(numericProps, stringProps, arrayProps);
function StackFrame(obj) {
if (!obj) return;
for (var i = 0; i < props.length; i++) {
if (obj[props[i]] !== undefined) {
this['set' + _capitalize(props[i])](obj[props[i]]);
}
}
}
StackFrame.prototype = {
getArgs: function() {
return this.args;
},
setArgs: function(v) {
if (Object.prototype.toString.call(v) !== '[object Array]') {
throw new TypeError('Args must be an Array');
}
this.args = v;
},
getEvalOrigin: function() {
return this.evalOrigin;
},
setEvalOrigin: function(v) {
if (v instanceof StackFrame) {
this.evalOrigin = v;
} else if (v instanceof Object) {
this.evalOrigin = new StackFrame(v);
} else {
throw new TypeError('Eval Origin must be an Object or StackFrame');
}
},
toString: function() {
var fileName = this.getFileName() || '';
var lineNumber = this.getLineNumber() || '';
var columnNumber = this.getColumnNumber() || '';
var functionName = this.getFunctionName() || '';
if (this.getIsEval()) {
if (fileName) {
return '[eval] (' + fileName + ':' + lineNumber + ':' + columnNumber + ')';
}
return '[eval]:' + lineNumber + ':' + columnNumber;
}
if (functionName) {
return functionName + ' (' + fileName + ':' + lineNumber + ':' + columnNumber + ')';
}
return fileName + ':' + lineNumber + ':' + columnNumber;
}
};
StackFrame.fromString = function StackFrame$$fromString(str) {
var argsStartIndex = str.indexOf('(');
var argsEndIndex = str.lastIndexOf(')');
var functionName = str.substring(0, argsStartIndex);
var args = str.substring(argsStartIndex + 1, argsEndIndex).split(',');
var locationString = str.substring(argsEndIndex + 1);
if (locationString.indexOf('@') === 0) {
var parts = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString, '');
var fileName = parts[1];
var lineNumber = parts[2];
var columnNumber = parts[3];
}
return new StackFrame({
functionName: functionName,
args: args || undefined,
fileName: fileName,
lineNumber: lineNumber || undefined,
columnNumber: columnNumber || undefined
});
};
for (var i = 0; i < booleanProps.length; i++) {
StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);
StackFrame.prototype['set' + _capitalize(booleanProps[i])] = (function(p) {
return function(v) {
this[p] = Boolean(v);
};
})(booleanProps[i]);
}
for (var j = 0; j < numericProps.length; j++) {
StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]);
StackFrame.prototype['set' + _capitalize(numericProps[j])] = (function(p) {
return function(v) {
if (!_isNumber(v)) {
throw new TypeError(p + ' must be a Number');
}
this[p] = Number(v);
};
})(numericProps[j]);
}
for (var k = 0; k < stringProps.length; k++) {
StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]);
StackFrame.prototype['set' + _capitalize(stringProps[k])] = (function(p) {
return function(v) {
this[p] = String(v);
};
})(stringProps[k]);
}
return StackFrame;
}));
});
var errorStackParser = createCommonjsModule(function (module, exports) {
(function(root, factory) {
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
{
module.exports = factory(stackframe);
}
}(commonjsGlobal, function ErrorStackParser(StackFrame) {
var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+:\d+/;
var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+:\d+|\(native\))/m;
var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code])?$/;
return {
/**
* Given an Error object, extract the most information from it.
*
* @param {Error} error object
* @return {Array} of StackFrames
*/
parse: function ErrorStackParser$$parse(error) {
if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') {
return this.parseOpera(error);
} else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {
return this.parseV8OrIE(error);
} else if (error.stack) {
return this.parseFFOrSafari(error);
} else {
throw new Error('Cannot parse given Error object');
}
},
// Separate line and column numbers from a string of the form: (URI:Line:Column)
extractLocation: function ErrorStackParser$$extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (urlLike.indexOf(':') === -1) {
return [urlLike];
}
var regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
var parts = regExp.exec(urlLike.replace(/[()]/g, ''));
return [parts[1], parts[2] || undefined, parts[3] || undefined];
},
parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) {
var filtered = error.stack.split('\n').filter(function(line) {
return !!line.match(CHROME_IE_STACK_REGEXP);
}, this);
return filtered.map(function(line) {
if (line.indexOf('(eval ') > -1) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^()]*)|(\),.*$)/g, '');
}
var sanitizedLine = line.replace(/^\s+/, '').replace(/\(eval code/g, '(');
// capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in
// case it has spaces in it, as the string is split on \s+ later on
var location = sanitizedLine.match(/ (\((.+):(\d+):(\d+)\)$)/);
// remove the parenthesized location from the line, if it was matched
sanitizedLine = location ? sanitizedLine.replace(location[0], '') : sanitizedLine;
var tokens = sanitizedLine.split(/\s+/).slice(1);
// if a location was matched, pass it to extractLocation() otherwise pop the last token
var locationParts = this.extractLocation(location ? location[1] : tokens.pop());
var functionName = tokens.join(' ') || undefined;
var fileName = ['eval', '<anonymous>'].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0];
return new StackFrame({
functionName: functionName,
fileName: fileName,
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
});
}, this);
},
parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) {
var filtered = error.stack.split('\n').filter(function(line) {
return !line.match(SAFARI_NATIVE_CODE_REGEXP);
}, this);
return filtered.map(function(line) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
if (line.indexOf(' > eval') > -1) {
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ':$1');
}
if (line.indexOf('@') === -1 && line.indexOf(':') === -1) {
// Safari eval frames only have function names and nothing else
return new StackFrame({
functionName: line
});
} else {
var functionNameRegex = /((.*".+"[^@]*)?[^@]*)(?:@)/;
var matches = line.match(functionNameRegex);
var functionName = matches && matches[1] ? matches[1] : undefined;
var locationParts = this.extractLocation(line.replace(functionNameRegex, ''));
return new StackFrame({
functionName: functionName,
fileName: locationParts[0],
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
});
}
}, this);
},
parseOpera: function ErrorStackParser$$parseOpera(e) {
if (!e.stacktrace || (e.message.indexOf('\n') > -1 &&
e.message.split('\n').length > e.stacktrace.split('\n').length)) {
return this.parseOpera9(e);
} else if (!e.stack) {
return this.parseOpera10(e);
} else {
return this.parseOpera11(e);
}
},
parseOpera9: function ErrorStackParser$$parseOpera9(e) {
var lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
var lines = e.message.split('\n');
var result = [];
for (var i = 2, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push(new StackFrame({
fileName: match[2],
lineNumber: match[1],
source: lines[i]
}));
}
}
return result;
},
parseOpera10: function ErrorStackParser$$parseOpera10(e) {
var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;
var lines = e.stacktrace.split('\n');
var result = [];
for (var i = 0, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push(
new StackFrame({
functionName: match[3] || undefined,
fileName: match[2],
lineNumber: match[1],
source: lines[i]
})
);
}
}
return result;
},
// Opera 10.65+ Error.stack very similar to FF/Safari
parseOpera11: function ErrorStackParser$$parseOpera11(error) {
var filtered = error.stack.split('\n').filter(function(line) {
return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);
}, this);
return filtered.map(function(line) {
var tokens = line.split('@');
var locationParts = this.extractLocation(tokens.pop());
var functionCall = (tokens.shift() || '');
var functionName = functionCall
.replace(/<anonymous function(: (\w+))?>/, '$2')
.replace(/\([^)]*\)/g, '') || undefined;
var argsRaw;
if (functionCall.match(/\(([^)]*)\)/)) {
argsRaw = functionCall.replace(/^[^(]+\(([^)]*)\)$/, '$1');
}
var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ?
undefined : argsRaw.split(',');
return new StackFrame({
functionName: functionName,
args: args,
fileName: locationParts[0],
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
});
}, this);
}
};
}));
});
var hasConsole = typeof console === 'object' && console.warn;
function parse(err) {
try {
return errorStackParser.parse(err);
}
catch (parseErr) {
if (hasConsole && err.stack) {
console.warn('ErrorStackParser:', parseErr.toString(), err.stack);
}
}
if (err.fileName) {
return [err];
}
return [];
}
function espProcessor(err) {
var backtrace = [];
if (err.noStack) {
backtrace.push({
function: err.functionName || '',
file: err.fileName || '',
line: err.lineNumber || 0,
column: err.columnNumber || 0,
});
}
else {
var frames_2 = parse(err);
if (frames_2.length === 0) {
try {
throw new Error('fake');
}
catch (fakeErr) {
frames_2 = parse(fakeErr);
frames_2.shift();
frames_2.shift();
}
}
for (var _i = 0, frames_1 = frames_2; _i < frames_1.length; _i++) {
var frame = frames_1[_i];
backtrace.push({
function: frame.functionName || '',
file: frame.fileName || '',
line: frame.lineNumber || 0,
column: frame.columnNumber || 0,
});
}
}
var type = err.name ? err.name : '';
var msg = err.message ? String(err.message) : String(err);
return {
type: type,
message: msg,
backtrace: backtrace,
};
}
var re = new RegExp([
'^',
'\\[(\\$.+)\\]',
'\\s',
'([\\s\\S]+)',
'$',
].join(''));
function angularMessageFilter(notice) {
var err = notice.errors[0];
if (err.type !== '' && err.type !== 'Error') {
return notice;
}
var m = err.message.match(re);
if (m !== null) {
err.type = m[1];
err.message = m[2];
}
return notice;
}
function makeDebounceFilter() {
var lastNoticeJSON;
var timeout;
return function (notice) {
var s = JSON.stringify(notice.errors);
if (s === lastNoticeJSON) {
return null;
}
if (timeout) {
clearTimeout(timeout);
}
lastNoticeJSON = s;
timeout = setTimeout(function () {
lastNoticeJSON = '';
}, 1000);
return notice;
};
}
var IGNORED_MESSAGES = [
'Script error',
'Script error.',
'InvalidAccessError',
];
function ignoreNoiseFilter(notice) {
var err = notice.errors[0];
if (err.type === '' && IGNORED_MESSAGES.indexOf(err.message) !== -1) {
return null;
}
if (err.backtrace && err.backtrace.length > 0) {
var frame = err.backtrace[0];
if (frame.file === '<anonymous>') {
return null;
}
}
return notice;
}
var re$1 = new RegExp([
'^',
'Uncaught\\s',
'(.+?)',
':\\s',
'(.+)',
'$',
].join(''));
function uncaughtMessageFilter(notice) {
var err = notice.errors[0];
if (err.type !== '' && err.type !== 'Error') {
return notice;
}
var m = err.message.match(re$1);
if (m !== null) {
err.type = m[1];
err.message = m[2];
}
return notice;
}
var browserPonyfill = createCommonjsModule(function (module, exports) {
var __self__ = (function (root) {
function F() {
this.fetch = false;
this.DOMException = root.DOMException;
}
F.prototype = root;
return new F();
})(typeof self !== 'undefined' ? self : commonjsGlobal);
(function(self) {
var irrelevant = (function (exports) {
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob:
'FileReader' in self &&
'Blob' in self &&
(function() {
try {
new Blob();
return true
} catch (e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
};
function isDataView(obj) {
return obj && DataView.prototype.isPrototypeOf(obj)
}
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isArrayBufferView =
ArrayBuffer.isView ||
function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
};
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value);
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return {done: value === undefined, value: value}
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
};
}
return iterator
}
function Headers(headers) {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ', ' + value : value;
};
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null
};
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
};
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return iteratorFor(items)
};
Headers.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items)
};
Headers.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return iteratorFor(items)
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join('')
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
return Promise.resolve(new Blob([this._bodyText]))
}
};
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
} else {
return this.blob().then(readBlobAsArrayBuffer)
}
};
}
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
};
}
this.json = function() {
return this.text().then(JSON.parse)
};
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method
}
function Request(input, options) {
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers(input.headers);
}
this.method = input.method;
this.mode = input.mode;
this.signal = input.signal;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || 'same-origin';
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers);
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal;
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body);
}
Request.prototype.clone = function() {
return new Request(this, {body: this._bodyInit})
};
function decode(body) {
var form = new FormData();
body
.trim()
.split('&')
.forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form
}
function parseHeaders(rawHeaders) {
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
preProcessedHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!options) {
options = {};
}
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = 'statusText' in options ? options.statusText : 'OK';
this.headers = new Headers(options.headers);
this.url = options.url || '';
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
};
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''});
response.type = 'error';
return response
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
};
exports.DOMException = self.DOMException;
try {
new exports.DOMException();
} catch (err) {
exports.DOMException = function(message, name) {
this.message = message;
this.name = name;
var error = Error(message);
this.stack = error.stack;
};
exports.DOMException.prototype = Object.create(Error.prototype);
exports.DOMException.prototype.constructor = exports.DOMException;
}
function fetch(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
if (request.signal && request.signal.aborted) {
return reject(new exports.DOMException('Aborted', 'AbortError'))
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options));
};
xhr.onerror = function() {
reject(new TypeError('Network request failed'));
};
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'));
};
xhr.onabort = function() {
reject(new exports.DOMException('Aborted', 'AbortError'));
};
xhr.open(request.method, request.url, true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob';
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
if (request.signal) {
request.signal.addEventListener('abort', abortXhr);
xhr.onreadystatechange = function() {
// DONE (success or failure)
if (xhr.readyState === 4) {
request.signal.removeEventListener('abort', abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
}
fetch.polyfill = true;
if (!self.fetch) {
self.fetch = fetch;
self.Headers = Headers;
self.Request = Request;
self.Response = Response;
}
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.fetch = fetch;
return exports;
}({}));
})(__self__);
delete __self__.fetch.polyfill;
exports = __self__.fetch; // To enable: import fetch from 'cross-fetch'
exports.default = __self__.fetch; // For TypeScript consumers without esModuleInterop.
exports.fetch = __self__.fetch; // To enable: import {fetch} from 'cross-fetch'
exports.Headers = __self__.Headers;
exports.Request = __self__.Request;
exports.Response = __self__.Response;
module.exports = exports;
});
var errors = {
unauthorized: new Error('airbrake: unauthorized: project id or key are wrong'),
ipRateLimited: new Error('airbrake: IP is rate limited'),
};
var rateLimitReset = 0;
function request(req) {
var utime = Date.now() / 1000;
if (utime < rateLimitReset) {
return Promise$1.reject(errors.ipRateLimited);
}
var opt = {
method: req.method,
body: req.body,
};
return browserPonyfill(req.url, opt).then(function (resp) {
if (resp.status === 401) {
throw errors.unauthorized;
}
if (resp.status === 429) {
var s = resp.headers.get('X-RateLimit-Delay');
if (!s) {
throw errors.ipRateLimited;
}
var n = parseInt(s, 10);
if (n > 0) {
rateLimitReset = Date.now() / 1000 + n;
}
throw errors.ipRateLimited;
}
if (resp.status === 204) {
return { json: null };
}
if (resp.status === 404) {
throw new Error('404 Not Found');
}
if (resp.status >= 200 && resp.status < 300) {
return resp.json().then(function (json) {
return { json: json };
});
}
if (resp.status >= 400 && resp.status < 500) {
return resp.json().then(function (json) {
var err = new Error(json.message);
throw err;
});
}
return resp.text().then(function (body) {
var err = new Error("airbrake: fetch: unexpected response: code=" + resp.status + " body='" + body + "'");
throw err;
});
});
}
function makeRequester(api) {
return function (req) {
return request$1(req, api);
};
}
var rateLimitReset$1 = 0;
function request$1(req, api) {
var utime = Date.now() / 1000;
if (utime < rateLimitReset$1) {
return Promise$1.reject(errors.ipRateLimited);
}
return new Promise$1(function (resolve, reject) {
api({
url: req.url,
method: req.method,
body: req.body,
headers: {
'content-type': 'application/json',
},
timeout: req.timeout,
}, function (error, resp, body) {
if (error) {
reject(error);
return;
}
if (!resp.statusCode) {
error = new Error("airbrake: request: response statusCode is " + resp.statusCode);
reject(error);
return;
}
if (resp.statusCode === 401) {
reject(errors.unauthorized);
return;
}
if (resp.statusCode === 429) {
reject(errors.ipRateLimited);
var h = resp.headers['x-ratelimit-delay'];
if (!h) {
return;
}
var s = void 0;
if (typeof h === 'string') {
s = h;
}
else if (h instanceof Array) {
s = h[0];
}
else {
return;
}
var n = parseInt(s, 10);
if (n > 0) {
rateLimitReset$1 = Date.now() / 1000 + n;
}
return;
}
if (resp.statusCode === 204) {
resolve({ json: null });
return;
}
if (resp.statusCode >= 200 && resp.statusCode < 300) {
var json = void 0;
try {
json = JSON.parse(body);
}
catch (err) {
reject(err);
return;
}
resolve(json);
return;
}
if (resp.statusCode >= 400 && resp.statusCode < 500) {
var json = void 0;
try {
json = JSON.parse(body);
}
catch (err) {
reject(err);
return;
}
error = new Error(json.message);
reject(error);
return;
}
body = body.trim();
error = new Error("airbrake: node: unexpected response: code=" + resp.statusCode + " body='" + body + "'");
reject(error);
});
});
}
function makeRequester$1(opts) {
if (opts.request) {
return makeRequester(opts.request);
}
return request;
}
var tdigest;
var hasTdigest = false;
try {
tdigest = require('tdigest');
hasTdigest = true;
}
catch (err) { }
var TDigestStat = /** @class */ (function () {
function TDigestStat() {
this.count = 0;
this.sum = 0;
this.sumsq = 0;
this._td = new tdigest.Digest();
}
TDigestStat.prototype.add = function (ms) {
if (ms === 0) {
ms = 0.00001;
}
this.count += 1;
this.sum += ms;
this.sumsq += ms * ms;
if (this._td) {
this._td.push(ms);
}
};
TDigestStat.prototype.toJSON = function () {
return {
count: this.count,
sum: this.sum,
sumsq: this.sumsq,
tdigestCentroids: tdigestCentroids(this._td),
};
};
return TDigestStat;
}());
var TDigestStatGroups = /** @class */ (function (_super) {
__extends(TDigestStatGroups, _super);
function TDigestStatGroups() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.groups = {};
return _this;
}
TDigestStatGroups.prototype.addGroups = function (totalMs, groups) {
this.add(totalMs);
for (var name_1 in groups) {
if (groups.hasOwnProperty(name_1)) {
this.addGroup(name_1, groups[name_1]);
}
}
};
TDigestStatGroups.prototype.addGroup = function (name, ms) {
var stat = this.groups[name];
if (!stat) {
stat = new TDigestStat();
this.groups[name] = stat;
}
stat.add(ms);
};
TDigestStatGroups.prototype.toJSON = function () {
return {
count: this.count,
sum: this.sum,
sumsq: this.sumsq,
tdigestCentroids: tdigestCentroids(this._td),
groups: this.groups,
};
};
return TDigestStatGroups;
}(TDigestStat));
function tdigestCentroids(td) {
var means = [];
var counts = [];
td.centroids.each(function (c) {
means.push(c.mean);
counts.push(c.n);
});
return {
mean: means,
count: counts,
};
}
var FLUSH_INTERVAL = 15000; // 15 seconds
var QueryInfo = /** @class */ (function () {
function QueryInfo(query) {
if (query === void 0) { query = ''; }
this.method = '';
this.route = '';
this.query = '';
this.func = '';
this.file = '';
this.line = 0;
this.startTime = new Date();
this.query = query;
}
QueryInfo.prototype._duration = function () {
if (!this.endTime) {
this.endTime = new Date();
}
return this.endTime.getTime() - this.startTime.getTime();
};
return QueryInfo;
}());
var QueriesStats = /** @class */ (function () {
function QueriesStats(opt) {
this._m = {};
this._opt = opt;
this._url = opt.host + "/api/v5/projects/" + opt.projectId + "/queries-stats?key=" + opt.projectKey;
this._requester = makeRequester$1(opt);
}
QueriesStats.prototype.start = function (query) {
if (query === void 0) { query = ''; }
return new QueryInfo(query);
};
QueriesStats.prototype.notify = function (q) {
var _this = this;
if (!hasTdigest) {
return;
}
var ms = q._duration();
var minute = 60 * 1000;
var startTime = new Date(Math.floor(q.startTime.getTime() / minute) * minute);
var key = {
method: q.method,
route: q.route,
query: q.query,
func: q.func,
file: q.file,
line: q.line,
time: startTime,
};
var keyStr = JSON.stringify(key);
var stat = this._m[keyStr];
if (!stat) {
stat = new TDigestStat();
this._m[keyStr] = stat;
}
stat.add(ms);
if (this._timer) {
return;
}
this._timer = setTimeout(function () {
_this._flush();
}, FLUSH_INTERVAL);
};
QueriesStats.prototype._flush = function () {
var queries = [];
for (var keyStr in this._m) {
if (!this._m.hasOwnProperty(keyStr)) {
continue;
}
var key = JSON.parse(keyStr);
var v = __assign(__assign({}, key), this._m[keyStr].toJSON());
queries.push(v);
}
this._m = {};
this._timer = null;
var outJSON = JSON.stringify({
environment: this._opt.environment,
queries: queries,
});
var req = {
method: 'POST',
url: this._url,
body: outJSON,
};
this._requester(req)
.then(function (_resp) {
// nothing
})
.catch(function (err) {
if (console.error) {
console.error('can not report queries stats', err);
}
});
};
return QueriesStats;
}());
var FLUSH_INTERVAL$1 = 15000; // 15 seconds
var QueueMetric = /** @class */ (function (_super) {
__extends(QueueMetric, _super);
function QueueMetric(queue) {
var _this = _super.call(this) || this;
_this.queue = queue;
_this.startTime = new Date();
return _this;
}
return QueueMetric;
}(BaseMetric));
var QueuesStats = /** @class */ (function () {
function QueuesStats(opt) {
this._m = {};
this._opt = opt;
this._url = opt.host + "/api/v5/projects/" + opt.projectId + "/queues-stats?key=" + opt.projectKey;
this._requester = makeRequester$1(opt);
}
QueuesStats.prototype.notify = function (q) {
var _this = this;
if (!hasTdigest) {
return;
}
var ms = q._duration();
if (ms === 0) {
ms = 0.00001;
}
var minute = 60 * 1000;
var startTime = new Date(Math.floor(q.startTime.getTime() / minute) * minute);
var key = {
queue: q.queue,
time: startTime,
};
var keyStr = JSON.stringify(key);
var stat = this._m[keyStr];
if (!stat) {
stat = new TDigestStatGroups();
this._m[keyStr] = stat;
}
stat.addGroups(ms, q._groups);
if (this._timer) {
return;
}
this._timer = setTimeout(function () {
_this._flush();
}, FLUSH_INTERVAL$1);
};
QueuesStats.prototype._flush = function () {
var queues = [];
for (var keyStr in this._m) {
if (!this._m.hasOwnProperty(keyStr)) {
continue;
}
var key = JSON.parse(keyStr);
var v = __assign(__assign({}, key), this._m[keyStr].toJSON());
queues.push(v);
}
this._m = {};
this._timer = null;
var outJSON = JSON.stringify({
environment: this._opt.environment,
queues: queues,
});
var req = {
method: 'POST',
url: this._url,
body: outJSON,
};
this._requester(req)
.then(function (_resp) {
// nothing
})
.catch(function (err) {
if (console.error) {
console.error('can not report queues breakdowns', err);
}
});
};
return QueuesStats;
}());
var FLUSH_INTERVAL$2 = 15000; // 15 seconds
var RouteMetric = /** @class */ (function (_super) {
__extends(RouteMetric, _super);
function RouteMetric(method, route, statusCode, contentType) {
if (method === void 0) { method = ''; }
if (route === void 0) { route = ''; }
if (statusCode === void 0) { statusCode = 0; }
if (contentType === void 0) { contentType = ''; }
var _this = _super.call(this) || this;
_this.method = method;
_this.route = route;
_this.statusCode = statusCode;
_this.contentType = contentType;
_this.startTime = new Date();
return _this;
}
return RouteMetric;
}(BaseMetric));
var RoutesStats = /** @class */ (function () {
function RoutesStats(opt) {
this._m = {};
this._opt = opt;
this._url = opt.host + "/api/v5/projects/" + opt.projectId + "/routes-stats?key=" + opt.projectKey;
this._requester = makeRequester$1(opt);
}
RoutesStats.prototype.notify = function (req) {
var _this = this;
if (!hasTdigest) {
return;
}
var ms = req._duration();
var minute = 60 * 1000;
var startTime = new Date(Math.floor(req.startTime.getTime() / minute) * minute);
var key = {
method: req.method,
route: req.route,
statusCode: req.statusCode,
time: startTime,
};
var keyStr = JSON.stringify(key);
var stat = this._m[keyStr];
if (!stat) {
stat = new TDigestStat();
this._m[keyStr] = stat;
}
stat.add(ms);
if (this._timer) {
return;
}
this._timer = setTimeout(function () {
_this._flush();
}, FLUSH_INTERVAL$2);
};
RoutesStats.prototype._flush = function () {
var routes = [];
for (var keyStr in this._m) {
if (!this._m.hasOwnProperty(keyStr)) {
continue;
}
var key = JSON.parse(keyStr);
var v = __assign(__assign({}, key), this._m[keyStr].toJSON());
routes.push(v);
}
this._m = {};
this._timer = null;
var outJSON = JSON.stringify({
environment: this._opt.environment,
routes: routes,
});
var req = {
method: 'POST',
url: this._url,
body: outJSON,
};
this._requester(req)
.then(function (_resp) {
// nothing
})
.catch(function (err) {
if (console.error) {
console.error('can not report routes stats', err);
}
});
};
return RoutesStats;
}());
var RoutesBreakdowns = /** @class */ (function () {
function RoutesBreakdowns(opt) {
this._m = {};
this._opt = opt;
this._url = opt.host + "/api/v5/projects/" + opt.projectId + "/routes-breakdowns?key=" + opt.projectKey;
this._requester = makeRequester$1(opt);
}
RoutesBreakdowns.prototype.notify = function (req) {
var _this = this;
if (!hasTdigest) {
return;
}
if (req.statusCode < 200 ||
(req.statusCode >= 300 && req.statusCode < 400) ||
req.statusCode === 404 ||
Object.keys(req._groups).length === 0) {
return;
}
var ms = req._duration();
if (ms === 0) {
ms = 0.00001;
}
var minute = 60 * 1000;
var startTime = new Date(Math.floor(req.startTime.getTime() / minute) * minute);
var key = {
method: req.method,
route: req.route,
responseType: this._responseType(req),
time: startTime,
};
var keyStr = JSON.stringify(key);
var stat = this._m[keyStr];
if (!stat) {
stat = new TDigestStatGroups();
this._m[keyStr] = stat;
}
stat.addGroups(ms, req._groups);
if (this._timer) {
return;
}
this._timer = setTimeout(function () {
_this._flush();
}, FLUSH_INTERVAL$2);
};
RoutesBreakdowns.prototype._flush = function () {
var routes = [];
for (var keyStr in this._m) {
if (!this._m.hasOwnProperty(keyStr)) {
continue;
}
var key = JSON.parse(keyStr);
var v = __assign(__assign({}, key), this._m[keyStr].toJSON());
routes.push(v);
}
this._m = {};
this._timer = null;
var outJSON = JSON.stringify({
environment: this._opt.environment,
routes: routes,
});
var req = {
method: 'POST',
url: this._url,
body: outJSON,
};
this._requester(req)
.then(function (_resp) {
// nothing
})
.catch(function (err) {
if (console.error) {
console.error('can not report routes breakdowns', err);
}
});
};
RoutesBreakdowns.prototype._responseType = function (req) {
if (req.statusCode >= 500) {
return '5xx';
}
if (req.statusCode >= 400) {
return '4xx';
}
if (!req.contentType) {
return '';
}
return req.contentType.split(';')[0].split('/')[-1];
};
return RoutesBreakdowns;
}());
var NOTIFIER_NAME = 'airbrake-js/browser';
var NOTIFIER_VERSION = '1.3.0';
var NOTIFIER_URL = 'https://github.com/airbrake/airbrake-js/tree/master/packages/browser';
var BaseNotifier = /** @class */ (function () {
function BaseNotifier(opt) {
var _this = this;
this._filters = [];
this._performanceFilters = [];
this._scope = new Scope();
this._onClose = [];
if (!opt.projectId || !opt.projectKey) {
throw new Error('airbrake: projectId and projectKey are required');
}
this._opt = opt;
this._opt.host = this._opt.host || 'https://api.airbrake.io';
this._opt.timeout = this._opt.timeout || 10000;
this._opt.keysBlocklist = this._opt.keysBlocklist ||
this._opt.keysBlacklist || [/password/, /secret/];
this._url = this._opt.host + "/api/v3/projects/" + this._opt.projectId + "/notices?key=" + this._opt.projectKey;
this._processor = this._opt.processor || espProcessor;
this._requester = makeRequester$1(this._opt);
this.addFilter(ignoreNoiseFilter);
this.addFilter(makeDebounceFilter());
this.addFilter(uncaughtMessageFilter);
this.addFilter(angularMessageFilter);
this.addFilter(function (notice) {
notice.context.notifier = {
name: NOTIFIER_NAME,
version: NOTIFIER_VERSION,
url: NOTIFIER_URL,
};
if (_this._opt.environment) {
notice.context.environment = _this._opt.environment;
}
return notice;
});
this.routes = new Routes(this);
this.queues = new Queues(this);
this.queries = new QueriesStats(this._opt);
}
BaseNotifier.prototype.close = function () {
for (var _i = 0, _a = this._onClose; _i < _a.length; _i++) {
var fn = _a[_i];
fn();
}
};
BaseNotifier.prototype.scope = function () {
return this._scope;
};
BaseNotifier.prototype.setActiveScope = function (scope) {
this._scope = scope;
};
BaseNotifier.prototype.addFilter = function (filter) {
this._filters.push(filter);
};
BaseNotifier.prototype.addPerformanceFilter = function (performanceFilter) {
this._performanceFilters.push(performanceFilter);
};
BaseNotifier.prototype.notify = function (err) {
var notice = {
errors: [],
context: __assign(__assign({ severity: 'error' }, this.scope().context()), err.context),
params: err.params || {},
environment: err.environment || {},
session: err.session || {},
};
if (typeof err !== 'object' || err.error === undefined) {
err = { error: err };
}
if (!err.error) {
notice.error = new Error("airbrake: got err=" + JSON.stringify(err.error) + ", wanted an Error");
return Promise$1.resolve(notice);
}
var error = this._processor(err.error);
notice.errors.push(error);
for (var _i = 0, _a = this._filters; _i < _a.length; _i++) {
var filter = _a[_i];
var r = filter(notice);
if (r === null) {
notice.error = new Error('airbrake: error is filtered');
return Promise$1.resolve(notice);
}
notice = r;
}
if (!notice.context) {
notice.context = {};
}
notice.context.language = 'JavaScript';
return this._sendNotice(notice);
};
BaseNotifier.prototype._sendNotice = function (notice) {
var body = jsonifyNotice(notice, {
keysBlocklist: this._opt.keysBlocklist,
});
if (this._opt.reporter) {
if (typeof this._opt.reporter === 'function') {
return this._opt.reporter(notice);
}
else {
console.warn('airbrake: options.reporter must be a function');
}
}
var req = {
method: 'POST',
url: this._url,
body: body,
};
return this._requester(req)
.then(function (resp) {
notice.id = resp.json.id;
return notice;
})
.catch(function (err) {
notice.error = err;
return notice;
});
};
BaseNotifier.prototype.wrap = function (fn, props) {
if (props === void 0) { props = []; }
if (fn._airbrake) {
return fn;
}
// tslint:disable-next-line:no-this-assignment
var client = this;
var airbrakeWrapper = function () {
var fnArgs = Array.prototype.slice.call(arguments);
var wrappedArgs = client._wrapArguments(fnArgs);
try {
return fn.apply(this, wrappedArgs);
}
catch (err) {
client.notify({ error: err, params: { arguments: fnArgs } });
this._ignoreNextWindowError();
throw err;
}
};
for (var prop in fn) {
if (fn.hasOwnProperty(prop)) {
airbrakeWrapper[prop] = fn[prop];
}
}
for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
var prop = props_1[_i];
if (fn.hasOwnProperty(prop)) {
airbrakeWrapper[prop] = fn[prop];
}
}
airbrakeWrapper._airbrake = true;
airbrakeWrapper.inner = fn;
return airbrakeWrapper;
};
BaseNotifier.prototype._wrapArguments = function (args) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (typeof arg === 'function') {
args[i] = this.wrap(arg);
}
}
return args;
};
BaseNotifier.prototype._ignoreNextWindowError = function () { };
BaseNotifier.prototype.call = function (fn) {
var _args = [];
for (var _i = 1; _i < arguments.length; _i++) {
_args[_i - 1] = arguments[_i];
}
var wrapper = this.wrap(fn);
return wrapper.apply(this, Array.prototype.slice.call(arguments, 1));
};
return BaseNotifier;
}());
var Routes = /** @class */ (function () {
function Routes(notifier) {
this._notifier = notifier;
this._routes = new RoutesStats(notifier._opt);
this._breakdowns = new RoutesBreakdowns(notifier._opt);
}
Routes.prototype.start = function (method, route, statusCode, contentType) {
if (method === void 0) { method = ''; }
if (route === void 0) { route = ''; }
if (statusCode === void 0) { statusCode = 0; }
if (contentType === void 0) { contentType = ''; }
var metric = new RouteMetric(method, route, statusCode, contentType);
var scope = this._notifier.scope().clone();
scope.setContext({ httpMethod: method, route: route });
scope.setRouteMetric(metric);
this._notifier.setActiveScope(scope);
return metric;
};
Routes.prototype.notify = function (req) {
req.end();
for (var _i = 0, _a = this._notifier._performanceFilters; _i < _a.length; _i++) {
var performanceFilter = _a[_i];
if (performanceFilter(req) === null) {
return;
}
}
this._routes.notify(req);
this._breakdowns.notify(req);
};
return Routes;
}());
var Queues = /** @class */ (function () {
function Queues(notifier) {
this._notifier = notifier;
this._queues = new QueuesStats(notifier._opt);
}
Queues.prototype.start = function (queue) {
var metric = new QueueMetric(queue);
var scope = this._notifier.scope().clone();
scope.setContext({ queue: queue });
scope.setQueueMetric(metric);
this._notifier.setActiveScope(scope);
return metric;
};
Queues.prototype.notify = function (q) {
q.end();
this._queues.notify(q);
};
return Queues;
}());
function windowFilter(notice) {
if (window.navigator && window.navigator.userAgent) {
notice.context.userAgent = window.navigator.userAgent;
}
if (window.location) {
notice.context.url = String(window.location);
// Set root directory to group errors on different subdomains together.
notice.context.rootDirectory =
window.location.protocol + '//' + window.location.host;
}
return notice;
}
var CONSOLE_METHODS = ['debug', 'log', 'info', 'warn', 'error'];
function instrumentConsole(notifier) {
var _loop_1 = function (m) {
if (!(m in console)) {
return "continue";
}
var oldFn = console[m];
var newFn = (function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
oldFn.apply(console, args);
notifier.scope().pushHistory({
type: 'log',
severity: m,
arguments: args,
});
});
newFn.inner = oldFn;
console[m] = newFn;
};
// tslint:disable-next-line:no-this-assignment
for (var _i = 0, CONSOLE_METHODS_1 = CONSOLE_METHODS; _i < CONSOLE_METHODS_1.length; _i++) {
var m = CONSOLE_METHODS_1[_i];
_loop_1(m);
}
}
var elemAttrs = ['type', 'name', 'src'];
function instrumentDOM(notifier) {
var handler = makeEventHandler(notifier);
if (window.addEventListener) {
window.addEventListener('load', handler);
window.addEventListener('error', function (event) {
if (getProp(event, 'error')) {
return;
}
handler(event);
}, true);
}
if (typeof document === 'object' && document.addEventListener) {
document.addEventListener('DOMContentLoaded', handler);
document.addEventListener('click', handler);
document.addEventListener('keypress', handler);
}
}
function makeEventHandler(notifier) {
return function (event) {
var target = getProp(event, 'target');
if (!target) {
return;
}
var state = { type: event.type };
try {
state.target = elemPath(target);
}
catch (err) {
state.target = "<" + String(err) + ">";
}
notifier.scope().pushHistory(state);
};
}
function elemName(elem) {
if (!elem) {
return '';
}
var s = [];
if (elem.tagName) {
s.push(elem.tagName.toLowerCase());
}
if (elem.id) {
s.push('#');
s.push(elem.id);
}
if (elem.classList && Array.from) {
s.push('.');
s.push(Array.from(elem.classList).join('.'));
}
else if (elem.className) {
var str = classNameString(elem.className);
if (str !== '') {
s.push('.');
s.push(str);
}
}
if (elem.getAttribute) {
for (var _i = 0, elemAttrs_1 = elemAttrs; _i < elemAttrs_1.length; _i++) {
var attr = elemAttrs_1[_i];
var value = elem.getAttribute(attr);
if (value) {
s.push("[" + attr + "=\"" + value + "\"]");
}
}
}
return s.join('');
}
function classNameString(name) {
if (name.split) {
return name.split(' ').join('.');
}
if (name.baseVal && name.baseVal.split) {
// SVGAnimatedString
return name.baseVal.split(' ').join('.');
}
console.error('unsupported HTMLElement.className type', typeof name);
return '';
}
function elemPath(elem) {
var maxLen = 10;
var path = [];
var parent = elem;
while (parent) {
var name_1 = elemName(parent);
if (name_1 !== '') {
path.push(name_1);
if (path.length > maxLen) {
break;
}
}
parent = parent.parentNode;
}
if (path.length === 0) {
return String(elem);
}
return path.reverse().join(' > ');
}
function getProp(obj, prop) {
try {
return obj[prop];
}
catch (_) {
// Permission denied to access property
return null;
}
}
function instrumentFetch(notifier) {
// tslint:disable-next-line:no-this-assignment
var oldFetch = window.fetch;
window.fetch = function (req, options) {
var state = {
type: 'xhr',
date: new Date(),
};
state.method = options && options.method ? options.method : 'GET';
if (typeof req === 'string') {
state.url = req;
}
else {
state.method = req.method;
state.url = req.url;
}
// Some platforms (e.g. react-native) implement fetch via XHR.
notifier._ignoreNextXHR++;
setTimeout(function () { return notifier._ignoreNextXHR--; });
return oldFetch
.apply(this, arguments)
.then(function (resp) {
state.statusCode = resp.status;
state.duration = new Date().getTime() - state.date.getTime();
notifier.scope().pushHistory(state);
return resp;
})
.catch(function (err) {
state.error = err;
state.duration = new Date().getTime() - state.date.getTime();
notifier.scope().pushHistory(state);
throw err;
});
};
}
var lastLocation = '';
// In some environments (i.e. Cypress) document.location may sometimes be null
function getCurrentLocation() {
return document.location && document.location.pathname;
}
function instrumentLocation(notifier) {
lastLocation = getCurrentLocation();
var oldFn = window.onpopstate;
window.onpopstate = function abOnpopstate(_event) {
var url = getCurrentLocation();
if (url) {
recordLocation(notifier, url);
}
if (oldFn) {
return oldFn.apply(this, arguments);
}
};
var oldPushState = history.pushState;
history.pushState = function abPushState(_state, _title, url) {
if (url) {
recordLocation(notifier, url.toString());
}
oldPushState.apply(this, arguments);
};
}
function recordLocation(notifier, url) {
var index = url.indexOf('://');
if (index >= 0) {
url = url.slice(index + 3);
index = url.indexOf('/');
url = index >= 0 ? url.slice(index) : '/';
}
else if (url.charAt(0) !== '/') {
url = '/' + url;
}
notifier.scope().pushHistory({
type: 'location',
from: lastLocation,
to: url,
});
lastLocation = url;
}
function instrumentXHR(notifier) {
function recordReq(req) {
var state = req.__state;
state.statusCode = req.status;
state.duration = new Date().getTime() - state.date.getTime();
notifier.scope().pushHistory(state);
}
var oldOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function abOpen(method, url, _async, _user, _password) {
if (notifier._ignoreNextXHR === 0) {
this.__state = {
type: 'xhr',
method: method,
url: url,
};
}
oldOpen.apply(this, arguments);
};
var oldSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function abSend(_data) {
var oldFn = this.onreadystatechange;
this.onreadystatechange = function (_ev) {
if (this.readyState === 4 && this.__state) {
recordReq(this);
}
if (oldFn) {
return oldFn.apply(this, arguments);
}
};
if (this.__state) {
this.__state.date = new Date();
}
return oldSend.apply(this, arguments);
};
}
var Notifier = /** @class */ (function (_super) {
__extends(Notifier, _super);
function Notifier(opt) {
var _this = _super.call(this, opt) || this;
_this.offline = false;
_this.todo = [];
_this._ignoreWindowError = 0;
_this._ignoreNextXHR = 0;
if (typeof window === 'undefined') {
return _this;
}
_this.addFilter(windowFilter);
if (window.addEventListener) {
_this.onOnline = _this.onOnline.bind(_this);
window.addEventListener('online', _this.onOnline);
_this.onOffline = _this.onOffline.bind(_this);
window.addEventListener('offline', _this.onOffline);
_this.onUnhandledrejection = _this.onUnhandledrejection.bind(_this);
window.addEventListener('unhandledrejection', _this.onUnhandledrejection);
_this._onClose.push(function () {
window.removeEventListener('online', _this.onOnline);
window.removeEventListener('offline', _this.onOffline);
window.removeEventListener('unhandledrejection', _this.onUnhandledrejection);
});
}
// TODO: deprecated
if (_this._opt.ignoreWindowError) {
opt.instrumentation.onerror = false;
}
_this._instrument(opt.instrumentation);
return _this;
}
Notifier.prototype._instrument = function (opt) {
if (opt === void 0) { opt = {}; }
opt.console = !isDevEnv(this._opt.environment);
if (enabled(opt.onerror)) {
// tslint:disable-next-line:no-this-assignment
var self_1 = this;
var oldHandler_1 = window.onerror;
window.onerror = function abOnerror() {
if (oldHandler_1) {
oldHandler_1.apply(this, arguments);
}
self_1.onerror.apply(self_1, arguments);
};
}
instrumentDOM(this);
if (enabled(opt.fetch) && typeof fetch === 'function') {
instrumentFetch(this);
}
if (enabled(opt.history) && typeof history === 'object') {
instrumentLocation(this);
}
if (enabled(opt.console) && typeof console === 'object') {
instrumentConsole(this);
}
if (enabled(opt.xhr) && typeof XMLHttpRequest !== 'undefined') {
instrumentXHR(this);
}
};
Notifier.prototype.notify = function (err) {
var _this = this;
if (this.offline) {
return new Promise$1(function (resolve, reject) {
_this.todo.push({
err: err,
resolve: resolve,
reject: reject,
});
while (_this.todo.length > 100) {
var j = _this.todo.shift();
if (j === undefined) {
break;
}
j.resolve({
error: new Error('airbrake: offline queue is too large'),
});
}
});
}
return _super.prototype.notify.call(this, err);
};
Notifier.prototype.onOnline = function () {
this.offline = false;
var _loop_1 = function (j) {
this_1.notify(j.err).then(function (notice) {
j.resolve(notice);
});
};
var this_1 = this;
for (var _i = 0, _a = this.todo; _i < _a.length; _i++) {
var j = _a[_i];
_loop_1(j);
}
this.todo = [];
};
Notifier.prototype.onOffline = function () {
this.offline = true;
};
Notifier.prototype.onUnhandledrejection = function (e) {
// Handle native or bluebird Promise rejections
// https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection
// http://bluebirdjs.com/docs/api/error-management-configuration.html
var reason = e.reason || (e.detail && e.detail.reason);
if (!reason) {
return;
}
var msg = reason.message || String(reason);
if (msg.indexOf && msg.indexOf('airbrake: ') === 0) {
return;
}
this.notify(reason);
};
Notifier.prototype.onerror = function (message, filename, line, column, err) {
if (this._ignoreWindowError > 0) {
return;
}
if (err) {
this.notify({
error: err,
context: {
windowError: true,
},
});
return;
}
// Ignore errors without file or line.
if (!filename || !line) {
return;
}
this.notify({
error: {
message: message,
fileName: filename,
lineNumber: line,
columnNumber: column,
noStack: true,
},
context: {
windowError: true,
},
});
};
Notifier.prototype._ignoreNextWindowError = function () {
var _this = this;
this._ignoreWindowError++;
setTimeout(function () { return _this._ignoreWindowError--; });
};
return Notifier;
}(BaseNotifier));
function isDevEnv(env) {
return env && env.startsWith && env.startsWith('dev');
}
function enabled(v) {
return v === undefined || v === true;
}
exports.BaseNotifier = BaseNotifier;
exports.Notifier = Notifier;
exports.QueryInfo = QueryInfo;
exports.Scope = Scope;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=airbrake.js.map
|
/*!
* inputmask.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2018 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.1-beta.6
*/
!function(factory) {
"function" == typeof define && define.amd ? define([ "./dependencyLibs/inputmask.dependencyLib", "./global/window", "./global/document" ], factory) : "object" == typeof exports ? module.exports = factory(require("./dependencyLibs/inputmask.dependencyLib"), require("./global/window"), require("./global/document")) : window.Inputmask = factory(window.dependencyLib || jQuery, window, document);
}(function($, window, document, undefined) {
var ua = navigator.userAgent, mobile = isInputEventSupported("touchstart"), iemobile = /iemobile/i.test(ua), iphone = /iphone/i.test(ua) && !iemobile;
function Inputmask(alias, options, internal) {
if (!(this instanceof Inputmask)) return new Inputmask(alias, options, internal);
this.el = undefined, this.events = {}, this.maskset = undefined, this.refreshValue = !1,
!0 !== internal && ($.isPlainObject(alias) ? options = alias : (options = options || {},
alias && (options.alias = alias)), this.opts = $.extend(!0, {}, this.defaults, options),
this.noMasksCache = options && options.definitions !== undefined, this.userOptions = options || {},
this.isRTL = this.opts.numericInput, resolveAlias(this.opts.alias, options, this.opts));
}
function resolveAlias(aliasStr, options, opts) {
var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
return aliasDefinition ? (aliasDefinition.alias && resolveAlias(aliasDefinition.alias, undefined, opts),
$.extend(!0, opts, aliasDefinition), $.extend(!0, opts, options), !0) : (null === opts.mask && (opts.mask = aliasStr),
!1);
}
function generateMaskSet(opts, nocache) {
function generateMask(mask, metadata, opts) {
var regexMask = !1;
if (null !== mask && "" !== mask || ((regexMask = null !== opts.regex) ? mask = (mask = opts.regex).replace(/^(\^)(.*)(\$)$/, "$2") : (regexMask = !0,
mask = ".*")), 1 === mask.length && !1 === opts.greedy && 0 !== opts.repeat && (opts.placeholder = ""),
opts.repeat > 0 || "*" === opts.repeat || "+" === opts.repeat) {
var repeatStart = "*" === opts.repeat ? 0 : "+" === opts.repeat ? 1 : opts.repeat;
mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
}
var masksetDefinition, maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask;
return Inputmask.prototype.masksCache[maskdefKey] === undefined || !0 === nocache ? (masksetDefinition = {
mask: mask,
maskToken: Inputmask.prototype.analyseMask(mask, regexMask, opts),
validPositions: {},
_buffer: undefined,
buffer: undefined,
tests: {},
excludes: {},
metadata: metadata,
maskLength: undefined
}, !0 !== nocache && (Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition,
masksetDefinition = $.extend(!0, {}, Inputmask.prototype.masksCache[maskdefKey]))) : masksetDefinition = $.extend(!0, {}, Inputmask.prototype.masksCache[maskdefKey]),
masksetDefinition;
}
if ($.isFunction(opts.mask) && (opts.mask = opts.mask(opts)), $.isArray(opts.mask)) {
if (opts.mask.length > 1) {
if (null === opts.keepStatic) {
opts.keepStatic = "auto";
for (var i = 0; i < opts.mask.length; i++) if (opts.mask[i].charAt(0) !== opts.mask[0].charAt(0)) {
opts.keepStatic = !0;
break;
}
}
var altMask = opts.groupmarker[0];
return $.each(opts.isRTL ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
altMask.length > 1 && (altMask += opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0]),
msk.mask === undefined || $.isFunction(msk.mask) ? altMask += msk : altMask += msk.mask;
}), generateMask(altMask += opts.groupmarker[1], opts.mask, opts);
}
opts.mask = opts.mask.pop();
}
return opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask) ? generateMask(opts.mask.mask, opts.mask, opts) : generateMask(opts.mask, opts.mask, opts);
}
function isInputEventSupported(eventName) {
var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el;
return isSupported || (el.setAttribute(evName, "return;"), isSupported = "function" == typeof el[evName]),
el = null, isSupported;
}
function maskScope(actionObj, maskset, opts) {
maskset = maskset || this.maskset, opts = opts || this.opts;
var undoValue, $el, maxLength, colorMask, inputmask = this, el = this.el, isRTL = this.isRTL, skipKeyPressEvent = !1, skipInputEvent = !1, ignorable = !1, mouseEnter = !1, originalPlaceholder = "";
function getMaskTemplate(baseOnInput, minimalPos, includeMode, noJit, clearOptionalTail) {
!0 !== noJit && (undefined, 0);
var greedy = opts.greedy;
clearOptionalTail && (opts.greedy = !1), minimalPos = minimalPos || 0;
var ndxIntlzr, test, testPos, maskTemplate = [], pos = 0, lvp = getLastValidPosition();
do {
if (!0 === baseOnInput && getMaskSet().validPositions[pos]) test = (testPos = clearOptionalTail && !0 === getMaskSet().validPositions[pos].match.optionality && getMaskSet().validPositions[pos + 1] === undefined && (!0 === getMaskSet().validPositions[pos].generatedInput || getMaskSet().validPositions[pos].input == opts.skipOptionalPartCharacter && pos > 0) ? determineTestTemplate(pos, getTests(pos, ndxIntlzr, pos - 1)) : getMaskSet().validPositions[pos]).match,
ndxIntlzr = testPos.locator.slice(), maskTemplate.push(!0 === includeMode ? testPos.input : !1 === includeMode ? test.nativeDef : getPlaceholder(pos, test)); else {
test = (testPos = getTestTemplate(pos, ndxIntlzr, pos - 1)).match, ndxIntlzr = testPos.locator.slice();
var jitMasking = !0 !== noJit && (!1 !== opts.jitMasking ? opts.jitMasking : test.jit);
!1 === jitMasking || jitMasking === undefined || pos < lvp || "number" == typeof jitMasking && isFinite(jitMasking) && jitMasking > pos ? maskTemplate.push(!1 === includeMode ? test.nativeDef : getPlaceholder(pos, test)) : test.jit && test.optionalQuantifier !== undefined && (pos,
0);
}
"auto" === opts.keepStatic && test.newBlockMarker && null !== test.fn && (opts.keepStatic = pos - 1),
pos++;
} while ((maxLength === undefined || pos < maxLength) && (null !== test.fn || "" !== test.def) || minimalPos > pos);
return "" === maskTemplate[maskTemplate.length - 1] && maskTemplate.pop(), !1 === includeMode && getMaskSet().maskLength !== undefined || (getMaskSet().maskLength = pos - 1),
opts.greedy = greedy, maskTemplate;
}
function getMaskSet() {
return maskset;
}
function resetMaskSet(soft) {
var maskset = getMaskSet();
maskset.buffer = undefined, !0 !== soft && (maskset.validPositions = {}, maskset.p = 0);
}
function getLastValidPosition(closestTo, strict, validPositions) {
var before = -1, after = -1, valids = validPositions || getMaskSet().validPositions;
for (var posNdx in closestTo === undefined && (closestTo = -1), valids) {
var psNdx = parseInt(posNdx);
valids[psNdx] && (strict || !0 !== valids[psNdx].generatedInput) && (psNdx <= closestTo && (before = psNdx),
psNdx >= closestTo && (after = psNdx));
}
return -1 === before || before == closestTo ? after : -1 == after ? before : closestTo - before < after - closestTo ? before : after;
}
function getDecisionTaker(tst) {
var decisionTaker = tst.locator[tst.alternation];
return "string" == typeof decisionTaker && decisionTaker.length > 0 && (decisionTaker = decisionTaker.split(",")[0]),
decisionTaker !== undefined ? decisionTaker.toString() : "";
}
function getLocator(tst, align) {
var locator = (tst.alternation != undefined ? tst.mloc[getDecisionTaker(tst)] : tst.locator).join("");
if ("" !== locator) for (;locator.length < align; ) locator += "0";
return locator;
}
function determineTestTemplate(pos, tests) {
for (var tstLocator, closest, bestMatch, targetLocator = getLocator(getTest(pos = pos > 0 ? pos - 1 : 0)), ndx = 0; ndx < tests.length; ndx++) {
var tst = tests[ndx];
tstLocator = getLocator(tst, targetLocator.length);
var distance = Math.abs(tstLocator - targetLocator);
(closest === undefined || "" !== tstLocator && distance < closest || bestMatch && bestMatch.match.optionality && "master" === bestMatch.match.newBlockMarker && (!tst.match.optionality || !tst.match.newBlockMarker) || bestMatch && bestMatch.match.optionalQuantifier && !tst.match.optionalQuantifier) && (closest = distance,
bestMatch = tst);
}
return bestMatch;
}
function getTestTemplate(pos, ndxIntlzr, tstPs) {
return getMaskSet().validPositions[pos] || determineTestTemplate(pos, getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
}
function getTest(pos, tests) {
return getMaskSet().validPositions[pos] ? getMaskSet().validPositions[pos] : (tests || getTests(pos))[0];
}
function positionCanMatchDefinition(pos, def) {
for (var valid = !1, tests = getTests(pos), tndx = 0; tndx < tests.length; tndx++) if (tests[tndx].match && tests[tndx].match.def === def) {
valid = !0;
break;
}
return valid;
}
function getTests(pos, ndxIntlzr, tstPs) {
var latestMatch, maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [ 0 ], matches = [], insertStop = !1, cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "";
function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) {
function handleMatch(match, loopNdx, quantifierRecurse) {
function isFirstMatch(latestMatch, tokenGroup) {
var firstMatch = 0 === $.inArray(latestMatch, tokenGroup.matches);
return firstMatch || $.each(tokenGroup.matches, function(ndx, match) {
if (!0 === match.isQuantifier ? firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]) : !0 === match.isOptional ? firstMatch = isFirstMatch(latestMatch, match) : !0 === match.isAlternate && (firstMatch = isFirstMatch(latestMatch, match)),
firstMatch) return !1;
}), firstMatch;
}
function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
var bestMatch, indexPos;
if ((getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) && $.each(getMaskSet().tests[pos] || [ getMaskSet().validPositions[pos] ], function(ndx, lmnt) {
if (lmnt.mloc[alternateNdx]) return bestMatch = lmnt, !1;
var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation, ndxPos = lmnt.locator[alternation] !== undefined ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
(indexPos === undefined || ndxPos < indexPos) && -1 !== ndxPos && (bestMatch = lmnt,
indexPos = ndxPos);
}), bestMatch) {
var bestMatchAltIndex = bestMatch.locator[bestMatch.alternation];
return (bestMatch.mloc[alternateNdx] || bestMatch.mloc[bestMatchAltIndex] || bestMatch.locator).slice((targetAlternation !== undefined ? targetAlternation : bestMatch.alternation) + 1);
}
return targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
}
function isSubsetOf(source, target) {
function expand(pattern) {
for (var start, end, expanded = [], i = 0, l = pattern.length; i < l; i++) if ("-" === pattern.charAt(i)) for (end = pattern.charCodeAt(i + 1); ++start < end; ) expanded.push(String.fromCharCode(start)); else start = pattern.charCodeAt(i),
expanded.push(pattern.charAt(i));
return expanded.join("");
}
return opts.regex && null !== source.match.fn && null !== target.match.fn ? -1 !== expand(target.match.def.replace(/[\[\]]/g, "")).indexOf(expand(source.match.def.replace(/[\[\]]/g, ""))) : source.match.def === target.match.nativeDef;
}
function setMergeLocators(targetMatch, altMatch) {
if (altMatch === undefined || targetMatch.alternation === altMatch.alternation && -1 === targetMatch.locator[targetMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation])) {
targetMatch.mloc = targetMatch.mloc || {};
var locNdx = targetMatch.locator[targetMatch.alternation];
if (locNdx !== undefined) {
if ("string" == typeof locNdx && (locNdx = locNdx.split(",")[0]), targetMatch.mloc[locNdx] === undefined && (targetMatch.mloc[locNdx] = targetMatch.locator.slice()),
altMatch !== undefined) {
for (var ndx in altMatch.mloc) "string" == typeof ndx && (ndx = ndx.split(",")[0]),
targetMatch.mloc[ndx] === undefined && (targetMatch.mloc[ndx] = altMatch.mloc[ndx]);
targetMatch.locator[targetMatch.alternation] = Object.keys(targetMatch.mloc).join(",");
}
return !0;
}
targetMatch.alternation = undefined;
}
return !1;
}
if (testPos > 5e3) throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask;
if (testPos === pos && match.matches === undefined) return matches.push({
match: match,
locator: loopNdx.reverse(),
cd: cacheDependency,
mloc: {}
}), !0;
if (match.matches !== undefined) {
if (match.isGroup && quantifierRecurse !== match) {
if (match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx, quantifierRecurse)) return !0;
} else if (match.isOptional) {
var optionalToken = match;
if (match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) {
if ($.each(matches, function(ndx, mtch) {
mtch.match.optionality = !0;
}), latestMatch = matches[matches.length - 1].match, quantifierRecurse !== undefined || !isFirstMatch(latestMatch, optionalToken)) return !0;
insertStop = !0, testPos = pos;
}
} else if (match.isAlternator) {
var maltMatches, alternateToken = match, malternateMatches = [], currentMatches = matches.slice(), loopNdxCnt = loopNdx.length, altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
if (-1 === altIndex || "string" == typeof altIndex) {
var amndx, currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr = [];
if ("string" == typeof altIndex) altIndexArr = altIndex.split(","); else for (amndx = 0; amndx < alternateToken.matches.length; amndx++) altIndexArr.push(amndx.toString());
if (getMaskSet().excludes[pos]) {
for (var altIndexArrClone = altIndexArr.slice(), i = 0, el = getMaskSet().excludes[pos].length; i < el; i++) altIndexArr.splice(altIndexArr.indexOf(getMaskSet().excludes[pos][i].toString()), 1);
0 === altIndexArr.length && (getMaskSet().excludes[pos] = undefined, altIndexArr = altIndexArrClone);
}
(!0 === opts.keepStatic || isFinite(parseInt(opts.keepStatic)) && currentPos >= opts.keepStatic) && (altIndexArr = altIndexArr.slice(0, 1));
for (var unMatchedAlternation = !1, ndx = 0; ndx < altIndexArr.length; ndx++) {
amndx = parseInt(altIndexArr[ndx]), matches = [], ndxInitializer = "string" == typeof altIndex && resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice(),
alternateToken.matches[amndx] && handleMatch(alternateToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse) ? match = !0 : 0 === ndx && (unMatchedAlternation = !0),
maltMatches = matches.slice(), testPos = currentPos, matches = [];
for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
var altMatch = maltMatches[ndx1], dropMatch = !1;
altMatch.match.jit = altMatch.match.jit || unMatchedAlternation, altMatch.alternation = altMatch.alternation || loopNdxCnt,
setMergeLocators(altMatch);
for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
var altMatch2 = malternateMatches[ndx2];
if ("string" != typeof altIndex || altMatch.alternation !== undefined && -1 !== $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr)) {
if (altMatch.match.nativeDef === altMatch2.match.nativeDef) {
dropMatch = !0, setMergeLocators(altMatch2, altMatch);
break;
}
if (isSubsetOf(altMatch, altMatch2)) {
setMergeLocators(altMatch, altMatch2) && (dropMatch = !0, malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch));
break;
}
if (isSubsetOf(altMatch2, altMatch)) {
setMergeLocators(altMatch2, altMatch);
break;
}
if (target = altMatch2, null === (source = altMatch).match.fn && null !== target.match.fn && target.match.fn.test(source.match.def, getMaskSet(), pos, !1, opts, !1)) {
setMergeLocators(altMatch, altMatch2) && (dropMatch = !0, malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch));
break;
}
}
}
dropMatch || malternateMatches.push(altMatch);
}
}
matches = currentMatches.concat(malternateMatches), testPos = pos, insertStop = matches.length > 0,
match = malternateMatches.length > 0, ndxInitializer = ndxInitializerClone.slice();
} else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse);
if (match) return !0;
} else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) for (var qt = match, qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && testPos <= pos; qndx++) {
var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
if (match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), tokenGroup)) {
if ((latestMatch = matches[matches.length - 1].match).optionalQuantifier = qndx > qt.quantifier.min - 1,
latestMatch.jit = qndx + tokenGroup.matches.indexOf(latestMatch) >= qt.quantifier.jit,
isFirstMatch(latestMatch, tokenGroup) && qndx > qt.quantifier.min - 1) {
insertStop = !0, testPos = pos;
break;
}
if (qt.quantifier.jit !== undefined && isNaN(qt.quantifier.max) && latestMatch.optionalQuantifier && getMaskSet().validPositions[pos - 1] === undefined) {
matches.pop(), insertStop = !0, testPos = pos, cacheDependency = undefined;
break;
}
return !0;
}
} else if (match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) return !0;
} else testPos++;
var source, target;
}
for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) if (!0 !== maskToken.matches[tndx].isQuantifier) {
var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse);
if (match && testPos === pos) return match;
if (testPos > pos) break;
}
}
if (pos > -1) {
if (ndxIntlzr === undefined) {
for (var test, previousPos = pos - 1; (test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1; ) previousPos--;
test !== undefined && previousPos > -1 && (ndxInitializer = function(pos, tests) {
var locator = [];
return $.isArray(tests) || (tests = [ tests ]), tests.length > 0 && (tests[0].alternation === undefined ? 0 === (locator = determineTestTemplate(pos, tests.slice()).locator.slice()).length && (locator = tests[0].locator.slice()) : $.each(tests, function(ndx, tst) {
if ("" !== tst.def) if (0 === locator.length) locator = tst.locator.slice(); else for (var i = 0; i < locator.length; i++) tst.locator[i] && -1 === locator[i].toString().indexOf(tst.locator[i]) && (locator[i] += "," + tst.locator[i]);
})), locator;
}(previousPos, test), cacheDependency = ndxInitializer.join(""), testPos = previousPos);
}
if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) return getMaskSet().tests[pos];
for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
if (resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]) && testPos === pos || testPos > pos) break;
}
}
return (0 === matches.length || insertStop) && matches.push({
match: {
fn: null,
optionality: !1,
casing: null,
def: "",
placeholder: ""
},
locator: [],
mloc: {},
cd: cacheDependency
}), ndxIntlzr !== undefined && getMaskSet().tests[pos] ? $.extend(!0, [], matches) : (getMaskSet().tests[pos] = $.extend(!0, [], matches),
getMaskSet().tests[pos]);
}
function getBufferTemplate() {
return getMaskSet()._buffer === undefined && (getMaskSet()._buffer = getMaskTemplate(!1, 1),
getMaskSet().buffer === undefined && (getMaskSet().buffer = getMaskSet()._buffer.slice())),
getMaskSet()._buffer;
}
function getBuffer(noCache) {
return getMaskSet().buffer !== undefined && !0 !== noCache || (getMaskSet().buffer = getMaskTemplate(!0, getLastValidPosition(), !0)),
getMaskSet().buffer;
}
function refreshFromBuffer(start, end, buffer) {
var i, p;
if (!0 === start) resetMaskSet(), start = 0, end = buffer.length; else for (i = start; i < end; i++) delete getMaskSet().validPositions[i];
for (p = start, i = start; i < end; i++) if (resetMaskSet(!0), buffer[i] !== opts.skipOptionalPartCharacter) {
var valResult = isValid(p, buffer[i], !0, !0);
!1 !== valResult && (resetMaskSet(!0), p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1);
}
}
function checkAlternationMatch(altArr1, altArr2, na) {
for (var naNdx, altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = !1, naArr = na !== undefined ? na.split(",") : [], i = 0; i < naArr.length; i++) -1 !== (naNdx = altArr1.indexOf(naArr[i])) && altArr1.splice(naNdx, 1);
for (var alndx = 0; alndx < altArr1.length; alndx++) if (-1 !== $.inArray(altArr1[alndx], altArrC)) {
isMatch = !0;
break;
}
return isMatch;
}
function alternate(pos, c, strict, fromSetValid, rAltPos) {
var lastAlt, alternation, altPos, prevAltPos, i, validPos, decisionPos, validPsClone = $.extend(!0, {}, getMaskSet().validPositions), isValidRslt = !1, lAltPos = rAltPos !== undefined ? rAltPos : getLastValidPosition();
if (-1 === lAltPos && rAltPos === undefined) alternation = (prevAltPos = getTest(lastAlt = 0)).alternation; else for (;lAltPos >= 0; lAltPos--) if ((altPos = getMaskSet().validPositions[lAltPos]) && altPos.alternation !== undefined) {
if (prevAltPos && prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) break;
lastAlt = lAltPos, alternation = getMaskSet().validPositions[lastAlt].alternation,
prevAltPos = altPos;
}
if (alternation !== undefined) {
decisionPos = parseInt(lastAlt), getMaskSet().excludes[decisionPos] = getMaskSet().excludes[decisionPos] || [],
!0 !== pos && getMaskSet().excludes[decisionPos].push(getDecisionTaker(prevAltPos));
var validInputsClone = [], staticInputsBeforePos = 0;
for (i = decisionPos; i < getLastValidPosition(undefined, !0) + 1; i++) (validPos = getMaskSet().validPositions[i]) && !0 !== validPos.generatedInput ? validInputsClone.push(validPos.input) : i < pos && staticInputsBeforePos++,
delete getMaskSet().validPositions[i];
for (;getMaskSet().excludes[decisionPos] && getMaskSet().excludes[decisionPos].length < 10; ) {
var posOffset = -1 * staticInputsBeforePos, validInputs = validInputsClone.slice();
for (getMaskSet().tests[decisionPos] = undefined, resetMaskSet(!0), isValidRslt = !0; validInputs.length > 0; ) {
var input = validInputs.shift();
if (!(isValidRslt = isValid(getLastValidPosition(undefined, !0) + 1, input, !1, fromSetValid, !0))) break;
}
if (isValidRslt && c !== undefined) {
var targetLvp = getLastValidPosition(pos) + 1;
for (i = decisionPos; i < getLastValidPosition() + 1; i++) ((validPos = getMaskSet().validPositions[i]) === undefined || null == validPos.match.fn) && i < pos + posOffset && posOffset++;
isValidRslt = isValid((pos += posOffset) > targetLvp ? targetLvp : pos, c, strict, fromSetValid, !0);
}
if (isValidRslt) break;
if (resetMaskSet(), prevAltPos = getTest(decisionPos), getMaskSet().validPositions = $.extend(!0, {}, validPsClone),
!getMaskSet().excludes[decisionPos]) {
isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
break;
}
var decisionTaker = getDecisionTaker(prevAltPos);
if (-1 !== getMaskSet().excludes[decisionPos].indexOf(decisionTaker)) {
isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
break;
}
for (getMaskSet().excludes[decisionPos].push(decisionTaker), i = decisionPos; i < getLastValidPosition(undefined, !0) + 1; i++) delete getMaskSet().validPositions[i];
}
}
return getMaskSet().excludes[decisionPos] = undefined, isValidRslt;
}
function isValid(pos, c, strict, fromSetValid, fromAlternate, validateOnly) {
function isSelection(posObj) {
return isRTL ? posObj.begin - posObj.end > 1 || posObj.begin - posObj.end == 1 : posObj.end - posObj.begin > 1 || posObj.end - posObj.begin == 1;
}
strict = !0 === strict;
var maskPos = pos;
function _isValid(position, c, strict) {
var rslt = !1;
return $.each(getTests(position), function(ndx, tst) {
var test = tst.match;
if (getBuffer(!0), !1 !== (rslt = null != test.fn ? test.fn.test(c, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && "" !== test.def && {
c: getPlaceholder(position, test, !0) || test.def,
pos: position
})) {
var elem = rslt.c !== undefined ? rslt.c : c, validatedPos = position;
return elem = elem === opts.skipOptionalPartCharacter && null === test.fn ? getPlaceholder(position, test, !0) || test.def : elem,
rslt.remove !== undefined && ($.isArray(rslt.remove) || (rslt.remove = [ rslt.remove ]),
$.each(rslt.remove.sort(function(a, b) {
return b - a;
}), function(ndx, lmnt) {
revalidateMask({
begin: lmnt,
end: lmnt + 1
});
})), rslt.insert !== undefined && ($.isArray(rslt.insert) || (rslt.insert = [ rslt.insert ]),
$.each(rslt.insert.sort(function(a, b) {
return a - b;
}), function(ndx, lmnt) {
isValid(lmnt.pos, lmnt.c, !0, fromSetValid);
})), !0 !== rslt && rslt.pos !== undefined && rslt.pos !== position && (validatedPos = rslt.pos),
!0 !== rslt && rslt.pos === undefined && rslt.c === undefined ? !1 : (revalidateMask(pos, $.extend({}, tst, {
input: function(elem, test, pos) {
switch (opts.casing || test.casing) {
case "upper":
elem = elem.toUpperCase();
break;
case "lower":
elem = elem.toLowerCase();
break;
case "title":
var posBefore = getMaskSet().validPositions[pos - 1];
elem = 0 === pos || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE) ? elem.toUpperCase() : elem.toLowerCase();
break;
default:
if ($.isFunction(opts.casing)) {
var args = Array.prototype.slice.call(arguments);
args.push(getMaskSet().validPositions), elem = opts.casing.apply(this, args);
}
}
return elem;
}(elem, test, validatedPos)
}), fromSetValid, validatedPos) || (rslt = !1), !1);
}
}), rslt;
}
pos.begin !== undefined && (maskPos = isRTL ? pos.end : pos.begin);
var result = !0, positionsClone = $.extend(!0, {}, getMaskSet().validPositions);
if ($.isFunction(opts.preValidation) && !strict && !0 !== fromSetValid && !0 !== validateOnly && (result = opts.preValidation(getBuffer(), maskPos, c, isSelection(pos), opts, getMaskSet())),
!0 === result) {
if (trackbackPositions(undefined, maskPos, !0), (maxLength === undefined || maskPos < maxLength) && (result = _isValid(maskPos, c, strict),
(!strict || !0 === fromSetValid) && !1 === result && !0 !== validateOnly)) {
var currentPosValid = getMaskSet().validPositions[maskPos];
if (!currentPosValid || null !== currentPosValid.match.fn || currentPosValid.match.def !== c && c !== opts.skipOptionalPartCharacter) {
if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && !isMask(maskPos, !0)) for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) if (!1 !== (result = _isValid(nPos, c, strict))) {
result = trackbackPositions(maskPos, result.pos !== undefined ? result.pos : nPos) || result,
maskPos = nPos;
break;
}
} else result = {
caret: seekNext(maskPos)
};
}
!1 !== result || !1 === opts.keepStatic || null != opts.regex && !isComplete(getBuffer()) || strict || !0 === fromAlternate || (result = alternate(maskPos, c, strict, fromSetValid)),
!0 === result && (result = {
pos: maskPos
});
}
if ($.isFunction(opts.postValidation) && !1 !== result && !strict && !0 !== fromSetValid && !0 !== validateOnly) {
var postResult = opts.postValidation(getBuffer(!0), result, opts);
if (postResult !== undefined) {
if (postResult.refreshFromBuffer && postResult.buffer) {
var refresh = postResult.refreshFromBuffer;
refreshFromBuffer(!0 === refresh ? refresh : refresh.start, refresh.end, postResult.buffer);
}
result = !0 === postResult ? result : postResult;
}
}
return result && result.pos === undefined && (result.pos = maskPos), !1 !== result && !0 !== validateOnly || (resetMaskSet(!0),
getMaskSet().validPositions = $.extend(!0, {}, positionsClone)), result;
}
function trackbackPositions(originalPos, newPos, fillOnly) {
var result;
if (originalPos === undefined) for (originalPos = newPos - 1; originalPos > 0 && !getMaskSet().validPositions[originalPos]; originalPos--) ;
for (var ps = originalPos; ps < newPos; ps++) {
if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, !0)) if (0 == ps ? getTest(ps) : getMaskSet().validPositions[ps - 1]) {
var tests = getTests(ps).slice();
"" === tests[tests.length - 1].match.def && tests.pop();
var bestMatch = determineTestTemplate(ps, tests);
if ((bestMatch = $.extend({}, bestMatch, {
input: getPlaceholder(ps, bestMatch.match, !0) || bestMatch.match.def
})).generatedInput = !0, revalidateMask(ps, bestMatch, !0), !0 !== fillOnly) {
var cvpInput = getMaskSet().validPositions[newPos].input;
getMaskSet().validPositions[newPos] = undefined, result = isValid(newPos, cvpInput, !0, !0);
}
}
}
return result;
}
function revalidateMask(pos, validTest, fromSetValid, validatedPos) {
function IsEnclosedStatic(pos, valids, selection) {
var posMatch = valids[pos];
if (posMatch !== undefined && (null === posMatch.match.fn && !0 !== posMatch.match.optionality || posMatch.input === opts.radixPoint)) {
var prevMatch = selection.begin <= pos - 1 ? valids[pos - 1] && null === valids[pos - 1].match.fn && valids[pos - 1] : valids[pos - 1], nextMatch = selection.end > pos + 1 ? valids[pos + 1] && null === valids[pos + 1].match.fn && valids[pos + 1] : valids[pos + 1];
return prevMatch && nextMatch;
}
return !1;
}
var begin = pos.begin !== undefined ? pos.begin : pos, end = pos.end !== undefined ? pos.end : pos;
if (pos.begin > pos.end && (begin = pos.end, end = pos.begin), validatedPos = validatedPos !== undefined ? validatedPos : begin,
begin !== end || opts.insertMode && getMaskSet().validPositions[validatedPos] !== undefined && fromSetValid === undefined) {
var positionsClone = $.extend(!0, {}, getMaskSet().validPositions), lvp = getLastValidPosition(undefined, !0);
for (getMaskSet().p = begin, i = lvp; i >= begin; i--) getMaskSet().validPositions[i] && "+" === getMaskSet().validPositions[i].match.nativeDef && (opts.isNegative = !1),
delete getMaskSet().validPositions[i];
var valid = !0, j = validatedPos, needsValidation = (getMaskSet().validPositions,
!1), posMatch = j, i = j;
for (validTest && (getMaskSet().validPositions[validatedPos] = $.extend(!0, {}, validTest),
posMatch++, j++, begin < end && i++); i <= lvp; i++) {
var t = positionsClone[i];
if (t !== undefined && (i >= end || i >= begin && !0 !== t.generatedInput && IsEnclosedStatic(i, positionsClone, {
begin: begin,
end: end
}))) {
for (;"" !== getTest(posMatch).match.def; ) {
if (!1 === needsValidation && positionsClone[posMatch] && positionsClone[posMatch].match.nativeDef === t.match.nativeDef) getMaskSet().validPositions[posMatch] = $.extend(!0, {}, positionsClone[posMatch]),
getMaskSet().validPositions[posMatch].input = t.input, trackbackPositions(undefined, posMatch, !0),
j = posMatch + 1, valid = !0; else if (positionCanMatchDefinition(posMatch, t.match.def)) {
var result = isValid(posMatch, t.input, !0, !0);
valid = !1 !== result, j = result.caret || result.insert ? getLastValidPosition() : posMatch + 1,
needsValidation = !0;
} else if (!(valid = !0 === t.generatedInput || t.input === opts.radixPoint && !0 === opts.numericInput) && "" === getTest(posMatch).match.def) break;
if (valid) break;
posMatch++;
}
"" == getTest(posMatch).match.def && (valid = !1), posMatch = j;
}
if (!valid) break;
}
if (!valid) return getMaskSet().validPositions = $.extend(!0, {}, positionsClone),
resetMaskSet(!0), !1;
} else validTest && (getMaskSet().validPositions[validatedPos] = $.extend(!0, {}, validTest));
return resetMaskSet(!0), !0;
}
function isMask(pos, strict) {
var test = getTestTemplate(pos).match;
if ("" === test.def && (test = getTest(pos).match), null != test.fn) return test.fn;
if (!0 !== strict && pos > -1) {
var tests = getTests(pos);
return tests.length > 1 + ("" === tests[tests.length - 1].match.def ? 1 : 0);
}
return !1;
}
function seekNext(pos, newBlock) {
for (var position = pos + 1; "" !== getTest(position).match.def && (!0 === newBlock && (!0 !== getTest(position).match.newBlockMarker || !isMask(position)) || !0 !== newBlock && !isMask(position)); ) position++;
return position;
}
function seekPrevious(pos, newBlock) {
var tests, position = pos;
if (position <= 0) return 0;
for (;--position > 0 && (!0 === newBlock && !0 !== getTest(position).match.newBlockMarker || !0 !== newBlock && !isMask(position) && ((tests = getTests(position)).length < 2 || 2 === tests.length && "" === tests[1].match.def)); ) ;
return position;
}
function writeBuffer(input, buffer, caretPos, event, triggerEvents) {
if (event && $.isFunction(opts.onBeforeWrite)) {
var result = opts.onBeforeWrite.call(inputmask, event, buffer, caretPos, opts);
if (result) {
if (result.refreshFromBuffer) {
var refresh = result.refreshFromBuffer;
refreshFromBuffer(!0 === refresh ? refresh : refresh.start, refresh.end, result.buffer || buffer),
buffer = getBuffer(!0);
}
caretPos !== undefined && (caretPos = result.caret !== undefined ? result.caret : caretPos);
}
}
if (input !== undefined && (input.inputmask._valueSet(buffer.join("")), caretPos === undefined || event !== undefined && "blur" === event.type ? renderColorMask(input, caretPos, 0 === buffer.length) : caret(input, caretPos),
!0 === triggerEvents)) {
var $input = $(input), nptVal = input.inputmask._valueGet();
skipInputEvent = !0, $input.trigger("input"), setTimeout(function() {
nptVal === getBufferTemplate().join("") ? $input.trigger("cleared") : !0 === isComplete(buffer) && $input.trigger("complete");
}, 0);
}
}
function getPlaceholder(pos, test, returnPL) {
if ((test = test || getTest(pos).match).placeholder !== undefined || !0 === returnPL) return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
if (null === test.fn) {
if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
var prevTest, tests = getTests(pos), staticAlternations = [];
if (tests.length > 1 + ("" === tests[tests.length - 1].match.def ? 1 : 0)) for (var i = 0; i < tests.length; i++) if (!0 !== tests[i].match.optionality && !0 !== tests[i].match.optionalQuantifier && (null === tests[i].match.fn || prevTest === undefined || !1 !== tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, !0, opts)) && (staticAlternations.push(tests[i]),
null === tests[i].match.fn && (prevTest = tests[i]), staticAlternations.length > 1 && /[0-9a-bA-Z]/.test(staticAlternations[0].match.def))) return opts.placeholder.charAt(pos % opts.placeholder.length);
}
return test.def;
}
return opts.placeholder.charAt(pos % opts.placeholder.length);
}
var valueBuffer, EventRuler = {
on: function(input, eventName, eventHandler) {
var ev = function(e) {
var that = this;
if (that.inputmask === undefined && "FORM" !== this.nodeName) {
var imOpts = $.data(that, "_inputmask_opts");
imOpts ? new Inputmask(imOpts).mask(that) : EventRuler.off(that);
} else {
if ("setvalue" === e.type || "FORM" === this.nodeName || !(that.disabled || that.readOnly && !("keydown" === e.type && e.ctrlKey && 67 === e.keyCode || !1 === opts.tabThrough && e.keyCode === Inputmask.keyCode.TAB))) {
switch (e.type) {
case "input":
if (!0 === skipInputEvent) return skipInputEvent = !1, e.preventDefault();
if (mobile) {
var args = arguments;
return setTimeout(function() {
eventHandler.apply(that, args), caret(that, that.inputmask.caretPos, undefined, !0);
}, 0), !1;
}
break;
case "keydown":
skipKeyPressEvent = !1, skipInputEvent = !1;
break;
case "keypress":
if (!0 === skipKeyPressEvent) return e.preventDefault();
skipKeyPressEvent = !0;
break;
case "click":
if (iemobile || iphone) {
args = arguments;
return setTimeout(function() {
eventHandler.apply(that, args);
}, 0), !1;
}
}
var returnVal = eventHandler.apply(that, arguments);
return !1 === returnVal && (e.preventDefault(), e.stopPropagation()), returnVal;
}
e.preventDefault();
}
};
input.inputmask.events[eventName] = input.inputmask.events[eventName] || [], input.inputmask.events[eventName].push(ev),
-1 !== $.inArray(eventName, [ "submit", "reset" ]) ? null !== input.form && $(input.form).on(eventName, ev) : $(input).on(eventName, ev);
},
off: function(input, event) {
var events;
input.inputmask && input.inputmask.events && (event ? (events = [])[event] = input.inputmask.events[event] : events = input.inputmask.events,
$.each(events, function(eventName, evArr) {
for (;evArr.length > 0; ) {
var ev = evArr.pop();
-1 !== $.inArray(eventName, [ "submit", "reset" ]) ? null !== input.form && $(input.form).off(eventName, ev) : $(input).off(eventName, ev);
}
delete input.inputmask.events[eventName];
}));
}
}, EventHandlers = {
keydownEvent: function(e) {
var $input = $(this), k = e.keyCode, pos = caret(this);
if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI || e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut")) e.preventDefault(),
handleRemove(this, k, pos), writeBuffer(this, getBuffer(!0), getMaskSet().p, e, this.inputmask._valueGet() !== getBuffer().join("")); else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) {
e.preventDefault();
var caretPos = seekNext(getLastValidPosition());
caret(this, e.shiftKey ? pos.begin : caretPos, caretPos, !0);
} else k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP ? (e.preventDefault(),
caret(this, 0, e.shiftKey ? pos.begin : 0, !0)) : (opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || 90 === k && e.ctrlKey) && !0 !== e.altKey ? (checkVal(this, !0, !1, undoValue.split("")),
$input.trigger("click")) : k !== Inputmask.keyCode.INSERT || e.shiftKey || e.ctrlKey ? !0 === opts.tabThrough && k === Inputmask.keyCode.TAB && (!0 === e.shiftKey ? (null === getTest(pos.begin).match.fn && (pos.begin = seekNext(pos.begin)),
pos.end = seekPrevious(pos.begin, !0), pos.begin = seekPrevious(pos.end, !0)) : (pos.begin = seekNext(pos.begin, !0),
pos.end = seekNext(pos.begin, !0), pos.end < getMaskSet().maskLength && pos.end--),
pos.begin < getMaskSet().maskLength && (e.preventDefault(), caret(this, pos.begin, pos.end))) : (opts.insertMode = !opts.insertMode,
this.setAttribute("im-insert", opts.insertMode));
opts.onKeyDown.call(this, e, getBuffer(), caret(this).begin, opts), ignorable = -1 !== $.inArray(k, opts.ignorables);
},
keypressEvent: function(e, checkval, writeOut, strict, ndx) {
var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode;
if (!(!0 === checkval || e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable)) return k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("") && (undoValue = getBuffer().join(""),
setTimeout(function() {
$input.trigger("change");
}, 0)), !0;
if (k) {
46 === k && !1 === e.shiftKey && "" !== opts.radixPoint && (k = opts.radixPoint.charCodeAt(0));
var forwardPosition, pos = checkval ? {
begin: ndx,
end: ndx
} : caret(input), c = String.fromCharCode(k), offset = 0;
if (opts._radixDance && opts.numericInput) {
var caretPos = getBuffer().indexOf(opts.radixPoint.charAt(0)) + 1;
pos.begin <= caretPos && (k === opts.radixPoint.charCodeAt(0) && (offset = 1), pos.begin -= 1,
pos.end -= 1);
}
getMaskSet().writeOutBuffer = !0;
var valResult = isValid(pos, c, strict);
if (!1 !== valResult && (resetMaskSet(!0), forwardPosition = valResult.caret !== undefined ? valResult.caret : seekNext(valResult.pos.begin ? valResult.pos.begin : valResult.pos),
getMaskSet().p = forwardPosition), forwardPosition = (opts.numericInput && valResult.caret === undefined ? seekPrevious(forwardPosition) : forwardPosition) + offset,
!1 !== writeOut && (setTimeout(function() {
opts.onKeyValidation.call(input, k, valResult, opts);
}, 0), getMaskSet().writeOutBuffer && !1 !== valResult)) {
var buffer = getBuffer();
writeBuffer(input, buffer, forwardPosition, e, !0 !== checkval);
}
if (e.preventDefault(), checkval) return !1 !== valResult && (valResult.forwardPosition = forwardPosition),
valResult;
}
},
pasteEvent: function(e) {
var tempValue, ev = e.originalEvent || e, inputValue = ($(this), this.inputmask._valueGet(!0)), caretPos = caret(this);
isRTL && (tempValue = caretPos.end, caretPos.end = caretPos.begin, caretPos.begin = tempValue);
var valueBeforeCaret = inputValue.substr(0, caretPos.begin), valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("") && (valueBeforeCaret = ""),
valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("") && (valueAfterCaret = ""),
window.clipboardData && window.clipboardData.getData) inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret; else {
if (!ev.clipboardData || !ev.clipboardData.getData) return !0;
inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
}
var pasteValue = inputValue;
if ($.isFunction(opts.onBeforePaste)) {
if (!1 === (pasteValue = opts.onBeforePaste.call(inputmask, inputValue, opts))) return e.preventDefault();
pasteValue || (pasteValue = inputValue);
}
return checkVal(this, !1, !1, pasteValue.toString().split("")), writeBuffer(this, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join("")),
e.preventDefault();
},
inputFallBackEvent: function(e) {
var input = this, inputValue = input.inputmask._valueGet();
if (getBuffer().join("") !== inputValue) {
var caretPos = caret(input);
if (inputValue = function(input, inputValue, caretPos) {
if (iemobile) {
var inputChar = inputValue.replace(getBuffer().join(""), "");
if (1 === inputChar.length) {
var iv = inputValue.split("");
iv.splice(caretPos.begin, 0, inputChar), inputValue = iv.join("");
}
}
return inputValue;
}(0, inputValue = function(input, inputValue, caretPos) {
return "." === inputValue.charAt(caretPos.begin - 1) && "" !== opts.radixPoint && ((inputValue = inputValue.split(""))[caretPos.begin - 1] = opts.radixPoint.charAt(0),
inputValue = inputValue.join("")), inputValue;
}(0, inputValue, caretPos), caretPos), getBuffer().join("") !== inputValue) {
var buffer = getBuffer().join(""), offset = !opts.numericInput && inputValue.length > buffer.length ? -1 : 0, frontPart = inputValue.substr(0, caretPos.begin), backPart = inputValue.substr(caretPos.begin), frontBufferPart = buffer.substr(0, caretPos.begin + offset), backBufferPart = buffer.substr(caretPos.begin + offset), selection = caretPos, entries = "", isEntry = !1;
if (frontPart !== frontBufferPart) {
for (var fpl = (isEntry = frontPart.length >= frontBufferPart.length) ? frontPart.length : frontBufferPart.length, i = 0; frontPart.charAt(i) === frontBufferPart.charAt(i) && i < fpl; i++) ;
isEntry && (0 === offset && (selection.begin = i), entries += frontPart.slice(i, selection.end));
}
if (backPart !== backBufferPart && (backPart.length > backBufferPart.length ? entries += backPart.slice(0, 1) : backPart.length < backBufferPart.length && (selection.end += backBufferPart.length - backPart.length,
isEntry || "" === opts.radixPoint || "" !== backPart || frontPart.charAt(selection.begin + offset - 1) !== opts.radixPoint || (selection.begin--,
entries = opts.radixPoint))), writeBuffer(input, getBuffer(), {
begin: selection.begin + offset,
end: selection.end + offset
}), entries.length > 0) $.each(entries.split(""), function(ndx, entry) {
var keypress = new $.Event("keypress");
keypress.which = entry.charCodeAt(0), ignorable = !1, EventHandlers.keypressEvent.call(input, keypress);
}); else {
selection.begin === selection.end - 1 && (selection.begin = seekPrevious(selection.begin + 1),
selection.begin === selection.end - 1 ? caret(input, selection.begin) : caret(input, selection.begin, selection.end));
var keydown = new $.Event("keydown");
keydown.keyCode = opts.numericInput ? Inputmask.keyCode.BACKSPACE : Inputmask.keyCode.DELETE,
EventHandlers.keydownEvent.call(input, keydown);
}
e.preventDefault();
}
}
},
beforeInputEvent: function(e) {
if (e.cancelable) {
var input = this;
switch (e.inputType) {
case "insertText":
return $.each(e.data.split(""), function(ndx, entry) {
var keypress = new $.Event("keypress");
keypress.which = entry.charCodeAt(0), ignorable = !1, EventHandlers.keypressEvent.call(input, keypress);
}), e.preventDefault();
case "deleteContentBackward":
return (keydown = new $.Event("keydown")).keyCode = Inputmask.keyCode.BACKSPACE,
EventHandlers.keydownEvent.call(input, keydown), e.preventDefault();
case "deleteContentForward":
var keydown;
return (keydown = new $.Event("keydown")).keyCode = Inputmask.keyCode.DELETE, EventHandlers.keydownEvent.call(input, keydown),
e.preventDefault();
}
}
},
setValueEvent: function(e) {
this.inputmask.refreshValue = !1;
var value = (value = e && e.detail ? e.detail[0] : arguments[1]) || this.inputmask._valueGet(!0);
$.isFunction(opts.onBeforeMask) && (value = opts.onBeforeMask.call(inputmask, value, opts) || value),
checkVal(this, !0, !1, value = value.split("")), undoValue = getBuffer().join(""),
(opts.clearMaskOnLostFocus || opts.clearIncomplete) && this.inputmask._valueGet() === getBufferTemplate().join("") && this.inputmask._valueSet("");
},
focusEvent: function(e) {
var nptValue = this.inputmask._valueGet();
opts.showMaskOnFocus && (!opts.showMaskOnHover || opts.showMaskOnHover && "" === nptValue) && (this.inputmask._valueGet() !== getBuffer().join("") ? writeBuffer(this, getBuffer(), seekNext(getLastValidPosition())) : !1 === mouseEnter && caret(this, seekNext(getLastValidPosition()))),
!0 === opts.positionCaretOnTab && !1 === mouseEnter && EventHandlers.clickEvent.apply(this, [ e, !0 ]),
undoValue = getBuffer().join("");
},
mouseleaveEvent: function(e) {
mouseEnter = !1, opts.clearMaskOnLostFocus && document.activeElement !== this && (this.placeholder = originalPlaceholder);
},
clickEvent: function(e, tabbed) {
var input = this;
setTimeout(function() {
if (document.activeElement === input) {
var selectedCaret = caret(input);
if (tabbed && (isRTL ? selectedCaret.end = selectedCaret.begin : selectedCaret.begin = selectedCaret.end),
selectedCaret.begin === selectedCaret.end) switch (opts.positionCaretOnClick) {
case "none":
break;
case "select":
caret(input, 0, getBuffer().length);
break;
case "ignore":
caret(input, seekNext(getLastValidPosition()));
break;
case "radixFocus":
if (function(clickPos) {
if ("" !== opts.radixPoint) {
var vps = getMaskSet().validPositions;
if (vps[clickPos] === undefined || vps[clickPos].input === getPlaceholder(clickPos)) {
if (clickPos < seekNext(-1)) return !0;
var radixPos = $.inArray(opts.radixPoint, getBuffer());
if (-1 !== radixPos) {
for (var vp in vps) if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) return !1;
return !0;
}
}
}
return !1;
}(selectedCaret.begin)) {
var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
break;
}
default:
var clickPosition = selectedCaret.begin, lvclickPosition = getLastValidPosition(clickPosition, !0), lastPosition = seekNext(lvclickPosition);
if (clickPosition < lastPosition) caret(input, isMask(clickPosition, !0) || isMask(clickPosition - 1, !0) ? clickPosition : seekNext(clickPosition)); else {
var lvp = getMaskSet().validPositions[lvclickPosition], tt = getTestTemplate(lastPosition, lvp ? lvp.match.locator : undefined, lvp), placeholder = getPlaceholder(lastPosition, tt.match);
if ("" !== placeholder && getBuffer()[lastPosition] !== placeholder && !0 !== tt.match.optionalQuantifier && !0 !== tt.match.newBlockMarker || !isMask(lastPosition, opts.keepStatic) && tt.match.def === placeholder) {
var newPos = seekNext(lastPosition);
(clickPosition >= newPos || clickPosition === lastPosition) && (lastPosition = newPos);
}
caret(input, lastPosition);
}
}
}
}, 0);
},
cutEvent: function(e) {
$(this);
var pos = caret(this), ev = e.originalEvent || e, clipboardData = window.clipboardData || ev.clipboardData, clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join("")),
document.execCommand && document.execCommand("copy"), handleRemove(this, Inputmask.keyCode.DELETE, pos),
writeBuffer(this, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
},
blurEvent: function(e) {
var $input = $(this);
if (this.inputmask) {
this.placeholder = originalPlaceholder;
var nptValue = this.inputmask._valueGet(), buffer = getBuffer().slice();
"" === nptValue && colorMask === undefined || (opts.clearMaskOnLostFocus && (-1 === getLastValidPosition() && nptValue === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer)),
!1 === isComplete(buffer) && (setTimeout(function() {
$input.trigger("incomplete");
}, 0), opts.clearIncomplete && (resetMaskSet(), buffer = opts.clearMaskOnLostFocus ? [] : getBufferTemplate().slice())),
writeBuffer(this, buffer, undefined, e)), undoValue !== getBuffer().join("") && (undoValue = buffer.join(""),
$input.trigger("change"));
}
},
mouseenterEvent: function(e) {
mouseEnter = !0, document.activeElement !== this && opts.showMaskOnHover && (this.placeholder = getBuffer().join(""));
},
submitEvent: function(e) {
undoValue !== getBuffer().join("") && $el.trigger("change"), opts.clearMaskOnLostFocus && -1 === getLastValidPosition() && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("") && el.inputmask._valueSet(""),
opts.clearIncomplete && !1 === isComplete(getBuffer()) && el.inputmask._valueSet(""),
opts.removeMaskOnSubmit && (el.inputmask._valueSet(el.inputmask.unmaskedvalue(), !0),
setTimeout(function() {
writeBuffer(el, getBuffer());
}, 0));
},
resetEvent: function(e) {
el.inputmask.refreshValue = !0, setTimeout(function() {
$el.trigger("setvalue");
}, 0);
}
};
function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
var inputmask = this || input.inputmask, inputValue = nptvl.slice(), charCodes = "", initialNdx = -1, result = undefined;
if (resetMaskSet(), strict || !0 === opts.autoUnmask) initialNdx = seekNext(initialNdx); else {
var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""), matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
matches && matches.length > 0 && (inputValue.splice(0, matches.length * staticInput.length),
initialNdx = seekNext(initialNdx));
}
-1 === initialNdx ? (getMaskSet().p = seekNext(initialNdx), initialNdx = 0) : getMaskSet().p = initialNdx,
inputmask.caretPos = {
begin: initialNdx
}, $.each(inputValue, function(ndx, charCode) {
if (charCode !== undefined) if (getMaskSet().validPositions[ndx] === undefined && inputValue[ndx] === getPlaceholder(ndx) && isMask(ndx, !0) && !1 === isValid(ndx, inputValue[ndx], !0, undefined, undefined, !0)) getMaskSet().p++; else {
var keypress = new $.Event("_checkval");
keypress.which = charCode.charCodeAt(0), charCodes += charCode;
var lvp = getLastValidPosition(undefined, !0);
!function(ndx, charCodes) {
return -1 !== getMaskTemplate(!0, 0, !1).slice(ndx, seekNext(ndx)).join("").replace(/'/g, "").indexOf(charCodes) && !isMask(ndx) && (getTest(ndx).match.nativeDef === charCodes.charAt(0) || null === getTest(ndx).match.fn && getTest(ndx).match.nativeDef === "'" + charCodes.charAt(0) || " " === getTest(ndx).match.nativeDef && (getTest(ndx + 1).match.nativeDef === charCodes.charAt(0) || null === getTest(ndx + 1).match.fn && getTest(ndx + 1).match.nativeDef === "'" + charCodes.charAt(0)));
}(initialNdx, charCodes) ? (result = EventHandlers.keypressEvent.call(input, keypress, !0, !1, strict, inputmask.caretPos.begin)) && (initialNdx = inputmask.caretPos.begin + 1,
charCodes = "") : result = EventHandlers.keypressEvent.call(input, keypress, !0, !1, strict, lvp + 1),
result && (writeBuffer(undefined, getBuffer(), result.forwardPosition, keypress, !1),
inputmask.caretPos = {
begin: result.forwardPosition,
end: result.forwardPosition
});
}
}), writeOut && writeBuffer(input, getBuffer(), result ? result.forwardPosition : undefined, initiatingEvent || new $.Event("checkval"), initiatingEvent && "input" === initiatingEvent.type);
}
function unmaskedvalue(input) {
if (input) {
if (input.inputmask === undefined) return input.value;
input.inputmask && input.inputmask.refreshValue && EventHandlers.setValueEvent.call(input);
}
var umValue = [], vps = getMaskSet().validPositions;
for (var pndx in vps) vps[pndx].match && null != vps[pndx].match.fn && umValue.push(vps[pndx].input);
var unmaskedValue = 0 === umValue.length ? "" : (isRTL ? umValue.reverse() : umValue).join("");
if ($.isFunction(opts.onUnMask)) {
var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
unmaskedValue = opts.onUnMask.call(inputmask, bufferValue, unmaskedValue, opts);
}
return unmaskedValue;
}
function translatePosition(pos) {
return !isRTL || "number" != typeof pos || opts.greedy && "" === opts.placeholder || !el || (pos = el.inputmask._valueGet().length - pos),
pos;
}
function caret(input, begin, end, notranslate) {
var range;
if (begin === undefined) return "selectionStart" in input ? (begin = input.selectionStart,
end = input.selectionEnd) : window.getSelection ? (range = window.getSelection().getRangeAt(0)).commonAncestorContainer.parentNode !== input && range.commonAncestorContainer !== input || (begin = range.startOffset,
end = range.endOffset) : document.selection && document.selection.createRange && (end = (begin = 0 - (range = document.selection.createRange()).duplicate().moveStart("character", -input.inputmask._valueGet().length)) + range.text.length),
{
begin: notranslate ? begin : translatePosition(begin),
end: notranslate ? end : translatePosition(end)
};
if ($.isArray(begin) && (end = isRTL ? begin[0] : begin[1], begin = isRTL ? begin[1] : begin[0]),
begin.begin !== undefined && (end = isRTL ? begin.begin : begin.end, begin = isRTL ? begin.end : begin.begin),
"number" == typeof begin) {
begin = notranslate ? begin : translatePosition(begin), end = "number" == typeof (end = notranslate ? end : translatePosition(end)) ? end : begin;
var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
if (input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0, input.inputmask.caretPos = {
begin: begin,
end: end
}, "selectionStart" in input) input.selectionStart = begin, input.selectionEnd = end; else if (window.getSelection) {
if (range = document.createRange(), input.firstChild === undefined || null === input.firstChild) {
var textNode = document.createTextNode("");
input.appendChild(textNode);
}
range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length),
range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length),
range.collapse(!0);
var sel = window.getSelection();
sel.removeAllRanges(), sel.addRange(range);
} else input.createTextRange && ((range = input.createTextRange()).collapse(!0),
range.moveEnd("character", end), range.moveStart("character", begin), range.select());
renderColorMask(input, {
begin: begin,
end: end
});
}
}
function determineLastRequiredPosition(returnDefinition) {
var pos, testPos, buffer = getMaskTemplate(!0, getLastValidPosition(), !0, !0), bl = buffer.length, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp], ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined;
for (pos = lvp + 1; pos < buffer.length; pos++) ndxIntlzr = (testPos = getTestTemplate(pos, ndxIntlzr, pos - 1)).locator.slice(),
positions[pos] = $.extend(!0, {}, testPos);
var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
for (pos = bl - 1; pos > lvp && (((testPos = positions[pos]).match.optionality || testPos.match.optionalQuantifier && testPos.match.newBlockMarker || lvTestAlt && (lvTestAlt !== positions[pos].locator[lvTest.alternation] && null != testPos.match.fn || null === testPos.match.fn && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && "" !== getTests(pos)[0].def)) && buffer[pos] === getPlaceholder(pos, testPos.match)); pos--) bl--;
return returnDefinition ? {
l: bl,
def: positions[bl] ? positions[bl].match : undefined
} : bl;
}
function clearOptionalTail(buffer) {
buffer.length = 0;
for (var lmnt, template = getMaskTemplate(!0, 0, !0, undefined, !0); (lmnt = template.shift()) !== undefined; ) buffer.push(lmnt);
return buffer;
}
function isComplete(buffer) {
if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
if ("*" === opts.repeat) return undefined;
var complete = !1, lrp = determineLastRequiredPosition(!0), aml = seekPrevious(lrp.l);
if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
complete = !0;
for (var i = 0; i <= aml; i++) {
var test = getTestTemplate(i).match;
if (null !== test.fn && getMaskSet().validPositions[i] === undefined && !0 !== test.optionality && !0 !== test.optionalQuantifier || null === test.fn && buffer[i] !== getPlaceholder(i, test)) {
complete = !1;
break;
}
}
}
return complete;
}
function handleRemove(input, k, pos, strict, fromIsValid) {
if ((opts.numericInput || isRTL) && (k === Inputmask.keyCode.BACKSPACE ? k = Inputmask.keyCode.DELETE : k === Inputmask.keyCode.DELETE && (k = Inputmask.keyCode.BACKSPACE),
isRTL)) {
var pend = pos.end;
pos.end = pos.begin, pos.begin = pend;
}
if (k === Inputmask.keyCode.BACKSPACE && pos.end - pos.begin < 1 ? (pos.begin = seekPrevious(pos.begin),
getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator && pos.begin--) : k === Inputmask.keyCode.DELETE && pos.begin === pos.end && (pos.end = isMask(pos.end, !0) && getMaskSet().validPositions[pos.end] && getMaskSet().validPositions[pos.end].input !== opts.radixPoint ? pos.end + 1 : seekNext(pos.end) + 1,
getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator && pos.end++),
revalidateMask(pos), !0 !== strict && !1 !== opts.keepStatic || null !== opts.regex) {
var result = alternate(!0);
if (result) {
var newPos = result.caret !== undefined ? result.caret : result.pos ? seekNext(result.pos.begin ? result.pos.begin : result.pos) : getLastValidPosition(-1, !0);
(k !== Inputmask.keyCode.DELETE || pos.begin > newPos) && pos.begin;
}
}
var lvp = getLastValidPosition(pos.begin, !0);
if (lvp < pos.begin || -1 === pos.begin) getMaskSet().p = seekNext(lvp); else if (!0 !== strict && (getMaskSet().p = pos.begin,
!0 !== fromIsValid)) for (;getMaskSet().p < lvp && getMaskSet().validPositions[getMaskSet().p] === undefined; ) getMaskSet().p++;
}
function initializeColorMask(input) {
var computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
var template = document.createElement("div");
template.style.width = computedStyle.width, template.style.textAlign = computedStyle.textAlign,
colorMask = document.createElement("div"), input.inputmask.colorMask = colorMask,
colorMask.className = "im-colormask", input.parentNode.insertBefore(colorMask, input),
input.parentNode.removeChild(input), colorMask.appendChild(input), colorMask.appendChild(template),
input.style.left = template.offsetLeft + "px", $(colorMask).on("mouseleave", function(e) {
return EventHandlers.mouseleaveEvent.call(input, [ e ]);
}), $(colorMask).on("mouseenter", function(e) {
return EventHandlers.mouseenterEvent.call(input, [ e ]);
}), $(colorMask).on("click", function(e) {
return caret(input, function(clientx) {
var caretPos, e = document.createElement("span");
for (var style in computedStyle) isNaN(style) && -1 !== style.indexOf("font") && (e.style[style] = computedStyle[style]);
e.style.textTransform = computedStyle.textTransform, e.style.letterSpacing = computedStyle.letterSpacing,
e.style.position = "absolute", e.style.height = "auto", e.style.width = "auto",
e.style.visibility = "hidden", e.style.whiteSpace = "nowrap", document.body.appendChild(e);
var itl, inputText = input.inputmask._valueGet(), previousWidth = 0;
for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
if (e.innerHTML += inputText.charAt(caretPos) || "_", e.offsetWidth >= clientx) {
var offset1 = clientx - previousWidth, offset2 = e.offsetWidth - clientx;
e.innerHTML = inputText.charAt(caretPos), caretPos = (offset1 -= e.offsetWidth / 3) < offset2 ? caretPos - 1 : caretPos;
break;
}
previousWidth = e.offsetWidth;
}
return document.body.removeChild(e), caretPos;
}(e.clientX)), EventHandlers.clickEvent.call(input, [ e ]);
});
}
function renderColorMask(input, caretPos, clear) {
var test, testPos, ndxIntlzr, maskTemplate = [], isStatic = !1, pos = 0;
function setEntry(entry) {
if (entry === undefined && (entry = ""), isStatic || null !== test.fn && testPos.input !== undefined) if (isStatic && (null !== test.fn && testPos.input !== undefined || "" === test.def)) {
isStatic = !1;
var mtl = maskTemplate.length;
maskTemplate[mtl - 1] = maskTemplate[mtl - 1] + "</span>", maskTemplate.push(entry);
} else maskTemplate.push(entry); else isStatic = !0, maskTemplate.push("<span class='im-static'>" + entry);
}
if (colorMask !== undefined) {
var buffer = getBuffer();
if (caretPos === undefined ? caretPos = caret(input) : caretPos.begin === undefined && (caretPos = {
begin: caretPos,
end: caretPos
}), !0 !== clear) {
var lvp = getLastValidPosition();
do {
getMaskSet().validPositions[pos] ? (testPos = getMaskSet().validPositions[pos],
test = testPos.match, ndxIntlzr = testPos.locator.slice(), setEntry(buffer[pos])) : (testPos = getTestTemplate(pos, ndxIntlzr, pos - 1),
test = testPos.match, ndxIntlzr = testPos.locator.slice(), !1 === opts.jitMasking || pos < lvp || "number" == typeof opts.jitMasking && isFinite(opts.jitMasking) && opts.jitMasking > pos ? setEntry(getPlaceholder(pos, test)) : isStatic = !1),
pos++;
} while ((maxLength === undefined || pos < maxLength) && (null !== test.fn || "" !== test.def) || lvp > pos || isStatic);
isStatic && setEntry(), document.activeElement === input && (maskTemplate.splice(caretPos.begin, 0, caretPos.begin === caretPos.end || caretPos.end > getMaskSet().maskLength ? '<mark class="im-caret" style="border-right-width: 1px;border-right-style: solid;">' : '<mark class="im-caret-select">'),
maskTemplate.splice(caretPos.end + 1, 0, "</mark>"));
}
var template = colorMask.getElementsByTagName("div")[0];
template.innerHTML = maskTemplate.join(""), input.inputmask.positionColorMask(input, template);
}
}
if (Inputmask.prototype.positionColorMask = function(input, template) {
input.style.left = template.offsetLeft + "px";
}, actionObj !== undefined) switch (actionObj.action) {
case "isComplete":
return el = actionObj.el, isComplete(getBuffer());
case "unmaskedvalue":
return el !== undefined && actionObj.value === undefined || (valueBuffer = actionObj.value,
valueBuffer = ($.isFunction(opts.onBeforeMask) && opts.onBeforeMask.call(inputmask, valueBuffer, opts) || valueBuffer).split(""),
checkVal.call(this, undefined, !1, !1, valueBuffer), $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite.call(inputmask, undefined, getBuffer(), 0, opts)),
unmaskedvalue(el);
case "mask":
!function(elem) {
EventRuler.off(elem);
var isSupported = function(input, opts) {
var elementType = input.getAttribute("type"), isSupported = "INPUT" === input.tagName && -1 !== $.inArray(elementType, opts.supportsInputType) || input.isContentEditable || "TEXTAREA" === input.tagName;
if (!isSupported) if ("INPUT" === input.tagName) {
var el = document.createElement("input");
el.setAttribute("type", elementType), isSupported = "text" === el.type, el = null;
} else isSupported = "partial";
return !1 !== isSupported ? function(npt) {
var valueGet, valueSet;
function getter() {
return this.inputmask ? this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : -1 !== getLastValidPosition() || !0 !== opts.nullable ? document.activeElement === this && opts.clearMaskOnLostFocus ? (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") : valueGet.call(this) : "" : valueGet.call(this);
}
function setter(value) {
valueSet.call(this, value), this.inputmask && $(this).trigger("setvalue", [ value ]);
}
if (!npt.inputmask.__valueGet) {
if (!0 !== opts.noValuePatching) {
if (Object.getOwnPropertyDescriptor) {
"function" != typeof Object.getPrototypeOf && (Object.getPrototypeOf = "object" == typeof "test".__proto__ ? function(object) {
return object.__proto__;
} : function(object) {
return object.constructor.prototype;
});
var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
valueProperty && valueProperty.get && valueProperty.set ? (valueGet = valueProperty.get,
valueSet = valueProperty.set, Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: !0
})) : "INPUT" !== npt.tagName && (valueGet = function() {
return this.textContent;
}, valueSet = function(value) {
this.textContent = value;
}, Object.defineProperty(npt, "value", {
get: getter,
set: setter,
configurable: !0
}));
} else document.__lookupGetter__ && npt.__lookupGetter__("value") && (valueGet = npt.__lookupGetter__("value"),
valueSet = npt.__lookupSetter__("value"), npt.__defineGetter__("value", getter),
npt.__defineSetter__("value", setter));
npt.inputmask.__valueGet = valueGet, npt.inputmask.__valueSet = valueSet;
}
npt.inputmask._valueGet = function(overruleRTL) {
return isRTL && !0 !== overruleRTL ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
}, npt.inputmask._valueSet = function(value, overruleRTL) {
valueSet.call(this.el, null === value || value === undefined ? "" : !0 !== overruleRTL && isRTL ? value.split("").reverse().join("") : value);
}, valueGet === undefined && (valueGet = function() {
return this.value;
}, valueSet = function(value) {
this.value = value;
}, function(type) {
if ($.valHooks && ($.valHooks[type] === undefined || !0 !== $.valHooks[type].inputmaskpatch)) {
var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
return elem.value;
}, valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
return elem.value = value, elem;
};
$.valHooks[type] = {
get: function(elem) {
if (elem.inputmask) {
if (elem.inputmask.opts.autoUnmask) return elem.inputmask.unmaskedvalue();
var result = valhookGet(elem);
return -1 !== getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) || !0 !== opts.nullable ? result : "";
}
return valhookGet(elem);
},
set: function(elem, value) {
var result, $elem = $(elem);
return result = valhookSet(elem, value), elem.inputmask && $elem.trigger("setvalue", [ value ]),
result;
},
inputmaskpatch: !0
};
}
}(npt.type), function(npt) {
EventRuler.on(npt, "mouseenter", function(event) {
var $input = $(this);
this.inputmask._valueGet() !== getBuffer().join("") && $input.trigger("setvalue");
});
}(npt));
}
}(input) : input.inputmask = undefined, isSupported;
}(elem, opts);
if (!1 !== isSupported && ($el = $(el = elem), originalPlaceholder = el.placeholder,
-1 === (maxLength = el !== undefined ? el.maxLength : undefined) && (maxLength = undefined),
!0 === opts.colorMask && initializeColorMask(el), mobile && ("inputmode" in el && (el.inputmode = opts.inputmode,
el.setAttribute("inputmode", opts.inputmode)), !0 === opts.disablePredictiveText && ("autocorrect" in el ? el.autocorrect = !1 : (!0 !== opts.colorMask && initializeColorMask(el),
el.type = "password"))), !0 === isSupported && (el.setAttribute("im-insert", opts.insertMode),
EventRuler.on(el, "submit", EventHandlers.submitEvent), EventRuler.on(el, "reset", EventHandlers.resetEvent),
EventRuler.on(el, "blur", EventHandlers.blurEvent), EventRuler.on(el, "focus", EventHandlers.focusEvent),
!0 !== opts.colorMask && (EventRuler.on(el, "click", EventHandlers.clickEvent),
EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent), EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent)),
EventRuler.on(el, "paste", EventHandlers.pasteEvent), EventRuler.on(el, "cut", EventHandlers.cutEvent),
EventRuler.on(el, "complete", opts.oncomplete), EventRuler.on(el, "incomplete", opts.onincomplete),
EventRuler.on(el, "cleared", opts.oncleared), mobile || !0 === opts.inputEventOnly ? el.removeAttribute("maxLength") : (EventRuler.on(el, "keydown", EventHandlers.keydownEvent),
EventRuler.on(el, "keypress", EventHandlers.keypressEvent)), EventRuler.on(el, "input", EventHandlers.inputFallBackEvent),
EventRuler.on(el, "beforeinput", EventHandlers.beforeInputEvent)), EventRuler.on(el, "setvalue", EventHandlers.setValueEvent),
undoValue = getBufferTemplate().join(""), "" !== el.inputmask._valueGet(!0) || !1 === opts.clearMaskOnLostFocus || document.activeElement === el)) {
var initialValue = $.isFunction(opts.onBeforeMask) && opts.onBeforeMask.call(inputmask, el.inputmask._valueGet(!0), opts) || el.inputmask._valueGet(!0);
"" !== initialValue && checkVal(el, !0, !1, initialValue.split(""));
var buffer = getBuffer().slice();
undoValue = buffer.join(""), !1 === isComplete(buffer) && opts.clearIncomplete && resetMaskSet(),
opts.clearMaskOnLostFocus && document.activeElement !== el && (-1 === getLastValidPosition() ? buffer = [] : clearOptionalTail(buffer)),
(!1 === opts.clearMaskOnLostFocus || opts.showMaskOnFocus && document.activeElement === el || "" !== el.inputmask._valueGet(!0)) && writeBuffer(el, buffer),
document.activeElement === el && caret(el, seekNext(getLastValidPosition()));
}
}(el);
break;
case "format":
return valueBuffer = ($.isFunction(opts.onBeforeMask) && opts.onBeforeMask.call(inputmask, actionObj.value, opts) || actionObj.value).split(""),
checkVal.call(this, undefined, !0, !1, valueBuffer), actionObj.metadata ? {
value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
metadata: maskScope.call(this, {
action: "getmetadata"
}, maskset, opts)
} : isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");
case "isValid":
actionObj.value ? (valueBuffer = actionObj.value.split(""), checkVal.call(this, undefined, !0, !0, valueBuffer)) : actionObj.value = getBuffer().join("");
for (var buffer = getBuffer(), rl = determineLastRequiredPosition(), lmib = buffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ;
return buffer.splice(rl, lmib + 1 - rl), isComplete(buffer) && actionObj.value === getBuffer().join("");
case "getemptymask":
return getBufferTemplate().join("");
case "remove":
if (el && el.inputmask) $.data(el, "_inputmask_opts", null), $el = $(el), el.inputmask._valueSet(opts.autoUnmask ? unmaskedvalue(el) : el.inputmask._valueGet(!0)),
EventRuler.off(el), el.inputmask.colorMask && ((colorMask = el.inputmask.colorMask).removeChild(el),
colorMask.parentNode.insertBefore(el, colorMask), colorMask.parentNode.removeChild(colorMask)),
Object.getOwnPropertyDescriptor && Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value") && el.inputmask.__valueGet && Object.defineProperty(el, "value", {
get: el.inputmask.__valueGet,
set: el.inputmask.__valueSet,
configurable: !0
}) : document.__lookupGetter__ && el.__lookupGetter__("value") && el.inputmask.__valueGet && (el.__defineGetter__("value", el.inputmask.__valueGet),
el.__defineSetter__("value", el.inputmask.__valueSet)), el.inputmask = undefined;
return el;
case "getmetadata":
if ($.isArray(maskset.metadata)) {
var maskTarget = getMaskTemplate(!0, 0, !1).join("");
return $.each(maskset.metadata, function(ndx, mtdt) {
if (mtdt.mask === maskTarget) return maskTarget = mtdt, !1;
}), maskTarget;
}
return maskset.metadata;
}
}
return Inputmask.prototype = {
dataAttribute: "data-inputmask",
defaults: {
placeholder: "_",
optionalmarker: [ "[", "]" ],
quantifiermarker: [ "{", "}" ],
groupmarker: [ "(", ")" ],
alternatormarker: "|",
escapeChar: "\\",
mask: null,
regex: null,
oncomplete: $.noop,
onincomplete: $.noop,
oncleared: $.noop,
repeat: 0,
greedy: !1,
autoUnmask: !1,
removeMaskOnSubmit: !1,
clearMaskOnLostFocus: !0,
insertMode: !0,
clearIncomplete: !1,
alias: null,
onKeyDown: $.noop,
onBeforeMask: null,
onBeforePaste: function(pastedValue, opts) {
return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(this, pastedValue, opts) : pastedValue;
},
onBeforeWrite: null,
onUnMask: null,
showMaskOnFocus: !0,
showMaskOnHover: !0,
onKeyValidation: $.noop,
skipOptionalPartCharacter: " ",
numericInput: !1,
rightAlign: !1,
undoOnEscape: !0,
radixPoint: "",
_radixDance: !1,
groupSeparator: "",
keepStatic: null,
positionCaretOnTab: !0,
tabThrough: !1,
supportsInputType: [ "text", "tel", "password", "search" ],
ignorables: [ 8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 229 ],
isComplete: null,
preValidation: null,
postValidation: null,
staticDefinitionSymbol: undefined,
jitMasking: !1,
nullable: !0,
inputEventOnly: !1,
noValuePatching: !1,
positionCaretOnClick: "lvp",
casing: null,
inputmode: "verbatim",
colorMask: !1,
disablePredictiveText: !1,
importDataAttributes: !0
},
definitions: {
9: {
validator: "[0-91-9]",
definitionSymbol: "*"
},
a: {
validator: "[A-Za-zА-яЁёÀ-ÿµ]",
definitionSymbol: "*"
},
"*": {
validator: "[0-91-9A-Za-zА-яЁёÀ-ÿµ]"
}
},
aliases: {},
masksCache: {},
mask: function(elems) {
var that = this;
return "string" == typeof elems && (elems = document.getElementById(elems) || document.querySelectorAll(elems)),
elems = elems.nodeName ? [ elems ] : elems, $.each(elems, function(ndx, el) {
var scopedOpts = $.extend(!0, {}, that.opts);
if (function(npt, opts, userOptions, dataAttribute) {
if (!0 === opts.importDataAttributes) {
var option, dataoptions, optionData, p, attrOptions = npt.getAttribute(dataAttribute);
function importOption(option, optionData) {
null !== (optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option)) && ("string" == typeof optionData && (0 === option.indexOf("on") ? optionData = window[optionData] : "false" === optionData ? optionData = !1 : "true" === optionData && (optionData = !0)),
userOptions[option] = optionData);
}
if (attrOptions && "" !== attrOptions && (attrOptions = attrOptions.replace(/'/g, '"'),
dataoptions = JSON.parse("{" + attrOptions + "}")), dataoptions) for (p in optionData = undefined,
dataoptions) if ("alias" === p.toLowerCase()) {
optionData = dataoptions[p];
break;
}
for (option in importOption("alias", optionData), userOptions.alias && resolveAlias(userOptions.alias, userOptions, opts),
opts) {
if (dataoptions) for (p in optionData = undefined, dataoptions) if (p.toLowerCase() === option.toLowerCase()) {
optionData = dataoptions[p];
break;
}
importOption(option, optionData);
}
}
return $.extend(!0, opts, userOptions), ("rtl" === npt.dir || opts.rightAlign) && (npt.style.textAlign = "right"),
("rtl" === npt.dir || opts.numericInput) && (npt.dir = "ltr", npt.removeAttribute("dir"),
opts.isRTL = !0), Object.keys(userOptions).length;
}(el, scopedOpts, $.extend(!0, {}, that.userOptions), that.dataAttribute)) {
var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
maskset !== undefined && (el.inputmask !== undefined && (el.inputmask.opts.autoUnmask = !0,
el.inputmask.remove()), el.inputmask = new Inputmask(undefined, undefined, !0),
el.inputmask.opts = scopedOpts, el.inputmask.noMasksCache = that.noMasksCache, el.inputmask.userOptions = $.extend(!0, {}, that.userOptions),
el.inputmask.isRTL = scopedOpts.isRTL || scopedOpts.numericInput, el.inputmask.el = el,
el.inputmask.maskset = maskset, $.data(el, "_inputmask_opts", scopedOpts), maskScope.call(el.inputmask, {
action: "mask"
}));
}
}), elems && elems[0] && elems[0].inputmask || this;
},
option: function(options, noremask) {
return "string" == typeof options ? this.opts[options] : "object" == typeof options ? ($.extend(this.userOptions, options),
this.el && !0 !== noremask && this.mask(this.el), this) : void 0;
},
unmaskedvalue: function(value) {
return this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache),
maskScope.call(this, {
action: "unmaskedvalue",
value: value
});
},
remove: function() {
return maskScope.call(this, {
action: "remove"
});
},
getemptymask: function() {
return this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache),
maskScope.call(this, {
action: "getemptymask"
});
},
hasMaskedValue: function() {
return !this.opts.autoUnmask;
},
isComplete: function() {
return this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache),
maskScope.call(this, {
action: "isComplete"
});
},
getmetadata: function() {
return this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache),
maskScope.call(this, {
action: "getmetadata"
});
},
isValid: function(value) {
return this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache),
maskScope.call(this, {
action: "isValid",
value: value
});
},
format: function(value, metadata) {
return this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache),
maskScope.call(this, {
action: "format",
value: value,
metadata: metadata
});
},
setValue: function(value) {
this.el && $(this.el).trigger("setvalue", [ value ]);
},
analyseMask: function(mask, regexMask, opts) {
var match, m, openingToken, currentOpeningToken, alternator, lastMatch, tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?(?:\|[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g, regexTokenizer = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, escaped = !1, currentToken = new MaskToken(), openenings = [], maskTokens = [];
function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
this.matches = [], this.openGroup = isGroup || !1, this.alternatorGroup = !1, this.isGroup = isGroup || !1,
this.isOptional = isOptional || !1, this.isQuantifier = isQuantifier || !1, this.isAlternator = isAlternator || !1,
this.quantifier = {
min: 1,
max: 1
};
}
function insertTestDefinition(mtoken, element, position) {
position = position !== undefined ? position : mtoken.matches.length;
var prevMatch = mtoken.matches[position - 1];
if (regexMask) 0 === element.indexOf("[") || escaped && /\\d|\\s|\\w]/i.test(element) || "." === element ? mtoken.matches.splice(position++, 0, {
fn: new RegExp(element, opts.casing ? "i" : ""),
optionality: !1,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element,
casing: null,
def: element,
placeholder: undefined,
nativeDef: element
}) : (escaped && (element = element[element.length - 1]), $.each(element.split(""), function(ndx, lmnt) {
prevMatch = mtoken.matches[position - 1], mtoken.matches.splice(position++, 0, {
fn: null,
optionality: !1,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== lmnt && null !== prevMatch.fn,
casing: null,
def: opts.staticDefinitionSymbol || lmnt,
placeholder: opts.staticDefinitionSymbol !== undefined ? lmnt : undefined,
nativeDef: (escaped ? "'" : "") + lmnt
});
})), escaped = !1; else {
var maskdef = (opts.definitions ? opts.definitions[element] : undefined) || Inputmask.prototype.definitions[element];
maskdef && !escaped ? mtoken.matches.splice(position++, 0, {
fn: maskdef.validator ? "string" == typeof maskdef.validator ? new RegExp(maskdef.validator, opts.casing ? "i" : "") : new function() {
this.test = maskdef.validator;
}() : new RegExp("."),
optionality: !1,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== (maskdef.definitionSymbol || element),
casing: maskdef.casing,
def: maskdef.definitionSymbol || element,
placeholder: maskdef.placeholder,
nativeDef: element
}) : (mtoken.matches.splice(position++, 0, {
fn: null,
optionality: !1,
newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element && null !== prevMatch.fn,
casing: null,
def: opts.staticDefinitionSymbol || element,
placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
nativeDef: (escaped ? "'" : "") + element
}), escaped = !1);
}
}
function defaultCase() {
if (openenings.length > 0) {
if (insertTestDefinition(currentOpeningToken = openenings[openenings.length - 1], m),
currentOpeningToken.isAlternator) {
alternator = openenings.pop();
for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup && (alternator.matches[mndx].isGroup = !1);
openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1]).matches.push(alternator) : currentToken.matches.push(alternator);
}
} else insertTestDefinition(currentToken, m);
}
function groupify(matches) {
var groupToken = new MaskToken(!0);
return groupToken.openGroup = !1, groupToken.matches = matches, groupToken;
}
for (regexMask && (opts.optionalmarker[0] = undefined, opts.optionalmarker[1] = undefined); match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask); ) {
if (m = match[0], regexMask) switch (m.charAt(0)) {
case "?":
m = "{0,1}";
break;
case "+":
case "*":
m = "{" + m + "}";
}
if (escaped) defaultCase(); else switch (m.charAt(0)) {
case "(?=":
case "(?!":
case "(?<=":
case "(?<!":
break;
case opts.escapeChar:
escaped = !0, regexMask && defaultCase();
break;
case opts.optionalmarker[1]:
case opts.groupmarker[1]:
if ((openingToken = openenings.pop()).openGroup = !1, openingToken !== undefined) if (openenings.length > 0) {
if ((currentOpeningToken = openenings[openenings.length - 1]).matches.push(openingToken),
currentOpeningToken.isAlternator) {
alternator = openenings.pop();
for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1,
alternator.matches[mndx].alternatorGroup = !1;
openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1]).matches.push(alternator) : currentToken.matches.push(alternator);
}
} else currentToken.matches.push(openingToken); else defaultCase();
break;
case opts.optionalmarker[0]:
openenings.push(new MaskToken(!1, !0));
break;
case opts.groupmarker[0]:
openenings.push(new MaskToken(!0));
break;
case opts.quantifiermarker[0]:
var quantifier = new MaskToken(!1, !1, !0), mqj = (m = m.replace(/[{}]/g, "")).split("|"), mq = mqj[0].split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 === mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]);
"*" !== mq0 && "+" !== mq0 || (mq0 = "*" === mq1 ? 0 : 1), quantifier.quantifier = {
min: mq0,
max: mq1,
jit: mqj[1]
};
var matches = openenings.length > 0 ? openenings[openenings.length - 1].matches : currentToken.matches;
if ((match = matches.pop()).isAlternator) {
matches.push(match), matches = match.matches;
var groupToken = new MaskToken(!0), tmpMatch = matches.pop();
matches.push(groupToken), matches = groupToken.matches, match = tmpMatch;
}
match.isGroup || (match = groupify([ match ])), matches.push(match), matches.push(quantifier);
break;
case opts.alternatormarker:
function groupQuantifier(matches) {
var lastMatch = matches.pop();
return lastMatch.isQuantifier && (lastMatch = groupify([ matches.pop(), lastMatch ])),
lastMatch;
}
if (openenings.length > 0) {
var subToken = (currentOpeningToken = openenings[openenings.length - 1]).matches[currentOpeningToken.matches.length - 1];
lastMatch = currentOpeningToken.openGroup && (subToken.matches === undefined || !1 === subToken.isGroup && !1 === subToken.isAlternator) ? openenings.pop() : groupQuantifier(currentOpeningToken.matches);
} else lastMatch = groupQuantifier(currentToken.matches);
if (lastMatch.isAlternator) openenings.push(lastMatch); else if (lastMatch.alternatorGroup ? (alternator = openenings.pop(),
lastMatch.alternatorGroup = !1) : alternator = new MaskToken(!1, !1, !1, !0), alternator.matches.push(lastMatch),
openenings.push(alternator), lastMatch.openGroup) {
lastMatch.openGroup = !1;
var alternatorGroup = new MaskToken(!0);
alternatorGroup.alternatorGroup = !0, openenings.push(alternatorGroup);
}
break;
default:
defaultCase();
}
}
for (;openenings.length > 0; ) openingToken = openenings.pop(), currentToken.matches.push(openingToken);
return currentToken.matches.length > 0 && (!function verifyGroupMarker(maskToken) {
maskToken && maskToken.matches && $.each(maskToken.matches, function(ndx, token) {
var nextToken = maskToken.matches[ndx + 1];
(nextToken === undefined || nextToken.matches === undefined || !1 === nextToken.isQuantifier) && token && token.isGroup && (token.isGroup = !1,
regexMask || (insertTestDefinition(token, opts.groupmarker[0], 0), !0 !== token.openGroup && insertTestDefinition(token, opts.groupmarker[1]))),
verifyGroupMarker(token);
});
}(currentToken), maskTokens.push(currentToken)), (opts.numericInput || opts.isRTL) && function reverseTokens(maskToken) {
for (var match in maskToken.matches = maskToken.matches.reverse(), maskToken.matches) if (maskToken.matches.hasOwnProperty(match)) {
var intMatch = parseInt(match);
if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) {
var qt = maskToken.matches[match];
maskToken.matches.splice(match, 1), maskToken.matches.splice(intMatch + 1, 0, qt);
}
maskToken.matches[match].matches !== undefined ? maskToken.matches[match] = reverseTokens(maskToken.matches[match]) : maskToken.matches[match] = ((st = maskToken.matches[match]) === opts.optionalmarker[0] ? st = opts.optionalmarker[1] : st === opts.optionalmarker[1] ? st = opts.optionalmarker[0] : st === opts.groupmarker[0] ? st = opts.groupmarker[1] : st === opts.groupmarker[1] && (st = opts.groupmarker[0]),
st);
}
var st;
return maskToken;
}(maskTokens[0]), maskTokens;
}
}, Inputmask.extendDefaults = function(options) {
$.extend(!0, Inputmask.prototype.defaults, options);
}, Inputmask.extendDefinitions = function(definition) {
$.extend(!0, Inputmask.prototype.definitions, definition);
}, Inputmask.extendAliases = function(alias) {
$.extend(!0, Inputmask.prototype.aliases, alias);
}, Inputmask.format = function(value, options, metadata) {
return Inputmask(options).format(value, metadata);
}, Inputmask.unmask = function(value, options) {
return Inputmask(options).unmaskedvalue(value);
}, Inputmask.isValid = function(value, options) {
return Inputmask(options).isValid(value);
}, Inputmask.remove = function(elems) {
"string" == typeof elems && (elems = document.getElementById(elems) || document.querySelectorAll(elems)),
elems = elems.nodeName ? [ elems ] : elems, $.each(elems, function(ndx, el) {
el.inputmask && el.inputmask.remove();
});
}, Inputmask.setValue = function(elems, value) {
"string" == typeof elems && (elems = document.getElementById(elems) || document.querySelectorAll(elems)),
elems = elems.nodeName ? [ elems ] : elems, $.each(elems, function(ndx, el) {
el.inputmask ? el.inputmask.setValue(value) : $(el).trigger("setvalue", [ value ]);
});
}, Inputmask.escapeRegex = function(str) {
return str.replace(new RegExp("(\\" + [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ].join("|\\") + ")", "gim"), "\\$1");
}, Inputmask.keyCode = {
BACKSPACE: 8,
BACKSPACE_SAFARI: 127,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38,
X: 88,
CONTROL: 17
}, Inputmask;
}); |
/*! UIkit 3.6.11 | https://www.getuikit.com | (c) 2014 - 2021 YOOtheme | MIT License */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) :
typeof define === 'function' && define.amd ? define('uikitslider_parallax', ['uikit-util'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitSlider_parallax = factory(global.UIkit.util));
}(this, (function (uikitUtil) { 'use strict';
var Media = {
props: {
media: Boolean
},
data: {
media: false
},
computed: {
matchMedia: function() {
var media = toMedia(this.media);
return !media || window.matchMedia(media).matches;
}
}
};
function toMedia(value) {
if (uikitUtil.isString(value)) {
if (value[0] === '@') {
var name = "breakpoint-" + (value.substr(1));
value = uikitUtil.toFloat(uikitUtil.getCssVar(name));
} else if (isNaN(value)) {
return value;
}
}
return value && !isNaN(value) ? ("(min-width: " + value + "px)") : false;
}
var loadSVG = uikitUtil.cacheFunction(function (src) { return new uikitUtil.Promise(function (resolve, reject) {
if (!src) {
reject();
return;
}
if (uikitUtil.startsWith(src, 'data:')) {
resolve(decodeURIComponent(src.split(',')[1]));
} else {
uikitUtil.ajax(src).then(
function (xhr) { return resolve(xhr.response); },
function () { return reject('SVG not found.'); }
);
}
}); }
);
function getMaxPathLength(el) {
return Math.ceil(Math.max.apply(Math, [ 0 ].concat( uikitUtil.$$('[stroke]', el).map(function (stroke) {
try {
return stroke.getTotalLength();
} catch (e) {
return 0;
}
}) )));
}
var props = ['x', 'y', 'bgx', 'bgy', 'rotate', 'scale', 'color', 'backgroundColor', 'borderColor', 'opacity', 'blur', 'hue', 'grayscale', 'invert', 'saturate', 'sepia', 'fopacity', 'stroke'];
var Parallax = {
mixins: [Media],
props: props.reduce(function (props, prop) {
props[prop] = 'list';
return props;
}, {}),
data: props.reduce(function (data, prop) {
data[prop] = undefined;
return data;
}, {}),
computed: {
props: function(properties, $el) {
var this$1 = this;
return props.reduce(function (props, prop) {
if (uikitUtil.isUndefined(properties[prop])) {
return props;
}
var isColor = prop.match(/color/i);
var isCssProp = isColor || prop === 'opacity';
var pos, bgPos, diff;
var steps = properties[prop].slice();
if (isCssProp) {
uikitUtil.css($el, prop, '');
}
if (steps.length < 2) {
steps.unshift((prop === 'scale'
? 1
: isCssProp
? uikitUtil.css($el, prop)
: 0) || 0);
}
var unit = getUnit(steps);
if (isColor) {
var ref = $el.style;
var color = ref.color;
steps = steps.map(function (step) { return parseColor($el, step); });
$el.style.color = color;
} else if (uikitUtil.startsWith(prop, 'bg')) {
var attr = prop === 'bgy' ? 'height' : 'width';
steps = steps.map(function (step) { return uikitUtil.toPx(step, attr, this$1.$el); });
uikitUtil.css($el, ("background-position-" + (prop[2])), '');
bgPos = uikitUtil.css($el, 'backgroundPosition').split(' ')[prop[2] === 'x' ? 0 : 1]; // IE 11 can't read background-position-[x|y]
if (this$1.covers) {
var min = Math.min.apply(Math, steps);
var max = Math.max.apply(Math, steps);
var down = steps.indexOf(min) < steps.indexOf(max);
diff = max - min;
steps = steps.map(function (step) { return step - (down ? min : max); });
pos = (down ? -diff : 0) + "px";
} else {
pos = bgPos;
}
} else {
steps = steps.map(uikitUtil.toFloat);
}
if (prop === 'stroke') {
if (!steps.some(function (step) { return step; })) {
return props;
}
var length = getMaxPathLength(this$1.$el);
uikitUtil.css($el, 'strokeDasharray', length);
if (unit === '%') {
steps = steps.map(function (step) { return step * length / 100; });
}
steps = steps.reverse();
prop = 'strokeDashoffset';
}
props[prop] = {steps: steps, unit: unit, pos: pos, bgPos: bgPos, diff: diff};
return props;
}, {});
},
bgProps: function() {
var this$1 = this;
return ['bgx', 'bgy'].filter(function (bg) { return bg in this$1.props; });
},
covers: function(_, $el) {
return covers($el);
}
},
disconnected: function() {
delete this._image;
},
update: {
read: function(data) {
var this$1 = this;
if (!this.matchMedia) {
return;
}
if (!data.image && this.covers && this.bgProps.length) {
var src = uikitUtil.css(this.$el, 'backgroundImage').replace(/^none|url\(["']?(.+?)["']?\)$/, '$1');
if (src) {
var img = new Image();
img.src = src;
data.image = img;
if (!img.naturalWidth) {
img.onload = function () { return this$1.$update(); };
}
}
}
var image = data.image;
if (!image || !image.naturalWidth) {
return;
}
var dimEl = {
width: this.$el.offsetWidth,
height: this.$el.offsetHeight
};
var dimImage = {
width: image.naturalWidth,
height: image.naturalHeight
};
var dim = uikitUtil.Dimensions.cover(dimImage, dimEl);
this.bgProps.forEach(function (prop) {
var ref = this$1.props[prop];
var diff = ref.diff;
var bgPos = ref.bgPos;
var steps = ref.steps;
var attr = prop === 'bgy' ? 'height' : 'width';
var span = dim[attr] - dimEl[attr];
if (span < diff) {
dimEl[attr] = dim[attr] + diff - span;
} else if (span > diff) {
var posPercentage = dimEl[attr] / uikitUtil.toPx(bgPos, attr, this$1.$el);
if (posPercentage) {
this$1.props[prop].steps = steps.map(function (step) { return step - (span - diff) / posPercentage; });
}
}
dim = uikitUtil.Dimensions.cover(dimImage, dimEl);
});
data.dim = dim;
},
write: function(ref) {
var dim = ref.dim;
if (!this.matchMedia) {
uikitUtil.css(this.$el, {backgroundSize: '', backgroundRepeat: ''});
return;
}
dim && uikitUtil.css(this.$el, {
backgroundSize: ((dim.width) + "px " + (dim.height) + "px"),
backgroundRepeat: 'no-repeat'
});
},
events: ['resize']
},
methods: {
reset: function() {
var this$1 = this;
uikitUtil.each(this.getCss(0), function (_, prop) { return uikitUtil.css(this$1.$el, prop, ''); });
},
getCss: function(percent) {
var ref = this;
var props = ref.props;
return Object.keys(props).reduce(function (css, prop) {
var ref = props[prop];
var steps = ref.steps;
var unit = ref.unit;
var pos = ref.pos;
var value = getValue(steps, percent);
switch (prop) {
// transforms
case 'x':
case 'y': {
unit = unit || 'px';
css.transform += " translate" + (uikitUtil.ucfirst(prop)) + "(" + (uikitUtil.toFloat(value).toFixed(unit === 'px' ? 0 : 2)) + unit + ")";
break;
}
case 'rotate':
unit = unit || 'deg';
css.transform += " rotate(" + (value + unit) + ")";
break;
case 'scale':
css.transform += " scale(" + value + ")";
break;
// bg image
case 'bgy':
case 'bgx':
css[("background-position-" + (prop[2]))] = "calc(" + pos + " + " + value + "px)";
break;
// color
case 'color':
case 'backgroundColor':
case 'borderColor': {
var ref$1 = getStep(steps, percent);
var start = ref$1[0];
var end = ref$1[1];
var p = ref$1[2];
css[prop] = "rgba(" + (start.map(function (value, i) {
value = value + p * (end[i] - value);
return i === 3 ? uikitUtil.toFloat(value) : parseInt(value, 10);
}).join(',')) + ")";
break;
}
// CSS Filter
case 'blur':
unit = unit || 'px';
css.filter += " blur(" + (value + unit) + ")";
break;
case 'hue':
unit = unit || 'deg';
css.filter += " hue-rotate(" + (value + unit) + ")";
break;
case 'fopacity':
unit = unit || '%';
css.filter += " opacity(" + (value + unit) + ")";
break;
case 'grayscale':
case 'invert':
case 'saturate':
case 'sepia':
unit = unit || '%';
css.filter += " " + prop + "(" + (value + unit) + ")";
break;
default:
css[prop] = value;
}
return css;
}, {transform: '', filter: ''});
}
}
};
function parseColor(el, color) {
return uikitUtil.css(uikitUtil.css(el, 'color', color), 'color')
.split(/[(),]/g)
.slice(1, -1)
.concat(1)
.slice(0, 4)
.map(uikitUtil.toFloat);
}
function getStep(steps, percent) {
var count = steps.length - 1;
var index = Math.min(Math.floor(count * percent), count - 1);
var step = steps.slice(index, index + 2);
step.push(percent === 1 ? 1 : percent % (1 / count) * count);
return step;
}
function getValue(steps, percent, digits) {
if ( digits === void 0 ) digits = 2;
var ref = getStep(steps, percent);
var start = ref[0];
var end = ref[1];
var p = ref[2];
return (uikitUtil.isNumber(start)
? start + Math.abs(start - end) * p * (start < end ? 1 : -1)
: +end
).toFixed(digits);
}
function getUnit(steps) {
return steps.reduce(function (unit, step) { return uikitUtil.isString(step) && step.replace(/-|\d/g, '').trim() || unit; }, '');
}
function covers(el) {
var ref = el.style;
var backgroundSize = ref.backgroundSize;
var covers = uikitUtil.css(uikitUtil.css(el, 'backgroundSize', ''), 'backgroundSize') === 'cover';
el.style.backgroundSize = backgroundSize;
return covers;
}
var Component = {
mixins: [Parallax],
data: {
selItem: '!li'
},
computed: {
item: function(ref, $el) {
var selItem = ref.selItem;
return uikitUtil.query(selItem, $el);
}
},
events: [
{
name: 'itemin itemout',
self: true,
el: function() {
return this.item;
},
handler: function(ref) {
var this$1 = this;
var type = ref.type;
var ref_detail = ref.detail;
var percent = ref_detail.percent;
var duration = ref_detail.duration;
var timing = ref_detail.timing;
var dir = ref_detail.dir;
uikitUtil.fastdom.read(function () {
var propsFrom = this$1.getCss(getCurrentPercent(type, dir, percent));
var propsTo = this$1.getCss(isIn(type) ? .5 : dir > 0 ? 1 : 0);
uikitUtil.fastdom.write(function () {
uikitUtil.css(this$1.$el, propsFrom);
uikitUtil.Transition.start(this$1.$el, propsTo, duration, timing).catch(uikitUtil.noop);
});
});
}
},
{
name: 'transitioncanceled transitionend',
self: true,
el: function() {
return this.item;
},
handler: function() {
uikitUtil.Transition.cancel(this.$el);
}
},
{
name: 'itemtranslatein itemtranslateout',
self: true,
el: function() {
return this.item;
},
handler: function(ref) {
var this$1 = this;
var type = ref.type;
var ref_detail = ref.detail;
var percent = ref_detail.percent;
var dir = ref_detail.dir;
uikitUtil.fastdom.read(function () {
var props = this$1.getCss(getCurrentPercent(type, dir, percent));
uikitUtil.fastdom.write(function () { return uikitUtil.css(this$1.$el, props); });
});
}
}
]
};
function isIn(type) {
return uikitUtil.endsWith(type, 'in');
}
function getCurrentPercent(type, dir, percent) {
percent /= 2;
return !isIn(type)
? dir < 0
? percent
: 1 - percent
: dir < 0
? 1 - percent
: percent;
}
if (typeof window !== 'undefined' && window.UIkit) {
window.UIkit.component('sliderParallax', Component);
}
return Component;
})));
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('./turn-order-c2bfc680.js');
require('immer');
require('lodash.isplainobject');
require('./reducer-77599f21.js');
var ai = require('./ai-7339b9e7.js');
exports.Bot = ai.Bot;
exports.MCTSBot = ai.MCTSBot;
exports.RandomBot = ai.RandomBot;
exports.Simulate = ai.Simulate;
exports.Step = ai.Step;
|
/*!
* Module dependencies
*/
var MPromise = require('mpromise');
var util = require('util');
/**
* Promise constructor.
*
* Promises are returned from executed queries. Example:
*
* var query = Candy.find({ bar: true });
* var promise = query.exec();
*
* DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird,
* if native promises are not present) but still
* support plugging in your own ES6-compatible promises library. Mongoose 5.0
* will **not** support mpromise.
*
* @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature
* @inherits mpromise https://github.com/aheckmann/mpromise
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `err`: Emits when the promise is rejected
* @event `complete`: Emits when the promise is fulfilled
* @api public
* @deprecated
*/
function Promise(fn) {
MPromise.call(this, fn);
}
/**
* ES6-style promise constructor wrapper around mpromise.
*
* @param {Function} resolver
* @return {Promise} new promise
* @api public
*/
Promise.ES6 = function(resolver) {
var promise = new Promise();
// No try/catch for backwards compatibility
resolver(
function() {
promise.complete.apply(promise, arguments);
},
function(e) {
promise.error(e);
});
return promise;
};
/*!
* Inherit from mpromise
*/
Promise.prototype = Object.create(MPromise.prototype, {
constructor: {
value: Promise,
enumerable: false,
writable: true,
configurable: true
}
});
/*!
* ignore
*/
Promise.prototype.then = util.deprecate(Promise.prototype.then,
'Mongoose: mpromise (mongoose\'s default promise library) is deprecated, ' +
'plug in your own promise library instead: ' +
'http://mongoosejs.com/docs/promises.html');
/**
* ES6-style `.catch()` shorthand
*
* @method catch
* @memberOf Promise
* @param {Function} onReject
* @return {Promise}
* @api public
*/
Promise.prototype.catch = function(onReject) {
return this.then(null, onReject);
};
/*!
* Override event names for backward compatibility.
*/
Promise.SUCCESS = 'complete';
Promise.FAILURE = 'err';
/**
* Adds `listener` to the `event`.
*
* If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event.
*
* @see mpromise#on https://github.com/aheckmann/mpromise#on
* @method on
* @memberOf Promise
* @param {String} event
* @param {Function} listener
* @return {Promise} this
* @api public
*/
/**
* Rejects this promise with `reason`.
*
* If the promise has already been fulfilled or rejected, not action is taken.
*
* @see mpromise#reject https://github.com/aheckmann/mpromise#reject
* @method reject
* @memberOf Promise
* @param {Object|String|Error} reason
* @return {Promise} this
* @api public
*/
/**
* Rejects this promise with `err`.
*
* If the promise has already been fulfilled or rejected, not action is taken.
*
* Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`.
*
* @api public
* @param {Error|String} err
* @return {Promise} this
*/
Promise.prototype.error = function(err) {
if (!(err instanceof Error)) {
if (err instanceof Object) {
err = util.inspect(err);
}
err = new Error(err);
}
return this.reject(err);
};
/**
* Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed.
*
* If the promise has already been fulfilled or rejected, not action is taken.
*
* `err` will be cast to an Error if not already instanceof Error.
*
* _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._
*
* @param {Error} [err] error or null
* @param {Object} [val] value to fulfill the promise with
* @api public
* @deprecated
*/
Promise.prototype.resolve = function(err) {
if (err) return this.error(err);
return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1));
};
/**
* Adds a single function as a listener to both err and complete.
*
* It will be executed with traditional node.js argument position when the promise is resolved.
*
* promise.addBack(function (err, args...) {
* if (err) return handleError(err);
* console.log('success');
* })
*
* Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve).
*
* _Deprecated. Use `onResolve` instead._
*
* @method addBack
* @param {Function} listener
* @return {Promise} this
* @deprecated
*/
Promise.prototype.addBack = Promise.prototype.onResolve;
/**
* Fulfills this promise with passed arguments.
*
* @method fulfill
* @receiver Promise
* @see https://github.com/aheckmann/mpromise#fulfill
* @param {any} args
* @api public
* @deprecated
*/
/**
* Fulfills this promise with passed arguments.
*
* Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).
*
* _Deprecated. Use `fulfill` instead._
*
* @method complete
* @receiver Promise
* @param {any} args
* @api public
* @deprecated
*/
Promise.prototype.complete = MPromise.prototype.fulfill;
/**
* Adds a listener to the `complete` (success) event.
*
* Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill).
*
* _Deprecated. Use `onFulfill` instead._
*
* @method addCallback
* @param {Function} listener
* @return {Promise} this
* @api public
* @deprecated
*/
Promise.prototype.addCallback = Promise.prototype.onFulfill;
/**
* Adds a listener to the `err` (rejected) event.
*
* Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject).
*
* _Deprecated. Use `onReject` instead._
*
* @method addErrback
* @param {Function} listener
* @return {Promise} this
* @api public
* @deprecated
*/
Promise.prototype.addErrback = Promise.prototype.onReject;
/**
* Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.
*
* Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification.
*
* ####Example:
*
* var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
* promise.then(function (meetups) {
* var ids = meetups.map(function (m) {
* return m._id;
* });
* return People.find({ meetups: { $in: ids }).exec();
* }).then(function (people) {
* if (people.length < 10000) {
* throw new Error('Too few people!!!');
* } else {
* throw new Error('Still need more people!!!');
* }
* }).then(null, function (err) {
* assert.ok(err instanceof Error);
* });
*
* @see promises-A+ https://github.com/promises-aplus/promises-spec
* @see mpromise#then https://github.com/aheckmann/mpromise#then
* @method then
* @memberOf Promise
* @param {Function} onFulFill
* @param {Function} onReject
* @return {Promise} newPromise
* @deprecated
*/
/**
* Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.
*
* ####Example:
*
* var p = new Promise;
* p.then(function(){ throw new Error('shucks') });
* setTimeout(function () {
* p.fulfill();
* // error was caught and swallowed by the promise returned from
* // p.then(). we either have to always register handlers on
* // the returned promises or we can do the following...
* }, 10);
*
* // this time we use .end() which prevents catching thrown errors
* var p = new Promise;
* var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--
* setTimeout(function () {
* p.fulfill(); // throws "shucks"
* }, 10);
*
* @api public
* @see mpromise#end https://github.com/aheckmann/mpromise#end
* @method end
* @memberOf Promise
* @deprecated
*/
/*!
* expose
*/
module.exports = Promise;
|
var SerialPort = require("serialport").SerialPort
var util = require('util')
var EventEmitter = require('events').EventEmitter;
util.inherits(SerialTransport, EventEmitter);
function SerialTransport(device,baud){
var self = this
self.serialport = new SerialPort(device, {
baudrate: baud,
parser: require("serialport").parsers.byteLength(32)
});
self.serialport.on('data',self.emit.bind(self,'data'))
self.serialport.open(function(){
self.active = true
})
}
SerialTransport.prototype.write = function(data){
if(this.active)
this.serialport.write(data)
}
module.exports = SerialTransport |
// PopUp.js
// A popup modal containing extra info.
// Can accept a title prop that will be display as header text at top of the popup text
// Image source passed as image prop will be displayed in black region at the top of the popup
// onClose is called when the Close button is clicked. Must be an arrow function that changes an isVisible prop in the parent component to false
// visible must be a boolean state in the parent component
import React, { Component } from "react";
import { Text, View, Modal, StyleSheet, Image } from "react-native";
import { MediaQueryStyleSheet } from "react-native-responsive";
import Button from "../components/Button";
import I18n from "../i18n/i18n";
import * as colors from "../styles/colors";
export default class PopUp extends Component {
render() {
let imageStyle = this.props.image != null
? styles.activeImage
: styles.disabledImage;
return (
<Modal
animationType={"fade"}
transparent={true}
onRequestClose={this.props.onClose}
visible={this.props.visible}
>
<View style={styles.modalBackground}>
<View style={{ backgroundColor: "#1B1B1B" }}>
<Image
source={this.props.image}
style={imageStyle}
resizeMode="contain"
/>
</View>
<View style={styles.modalInnerContainer}>
<Text style={styles.modalTitle}>{this.props.title}</Text>
<Text style={styles.modalText}>{this.props.children}</Text>
<Button onPress={this.props.onClose}>
{I18n.t("closeButton")}
</Button>
</View>
</View>
</Modal>
);
}
}
const styles = MediaQueryStyleSheet.create(
// Base styles
{
modalBackground: {
flex: 1,
justifyContent: "center",
alignItems: "stretch",
padding: 20,
backgroundColor: colors.modalBlue
},
modalText: {
fontFamily: "Roboto-Light",
color: colors.black,
fontSize: 15,
margin: 5
},
modalTitle: {
fontFamily: "Roboto-Bold",
color: colors.black,
fontSize: 20,
margin: 5
},
modalInnerContainer: {
alignItems: "stretch",
backgroundColor: colors.white,
padding: 20,
elevation: 5,
borderRadius: 4,
},
activeImage: {
alignSelf: "center",
height: 150,
margin: 10
},
disabledImage: {
height: 0,
width: 0
}
},
// Responsive styles
{
"@media (min-device-height: 700)": {
modalBackground: {
backgroundColor: colors.modalTransparent,
justifyContent: "flex-end",
paddingBottom: 50
},
activeImage: {
height: 300,
width: 300
},
modalTitle: {
fontSize: 30
},
modalText: {
fontSize: 18
}
},
"@media (min-device-height: 1000)": {
modalBackground: {
paddingBottom: 100,
paddingLeft: 120,
paddingRight: 120
}
}
}
);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M16.83 5L15 3H9L7.17 5H2v16h20V5h-5.17zM12 18c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-9l-1.25 2.75L8 13l2.75 1.25L12 17l1.25-2.75L16 13l-2.75-1.25z" />
, 'CameraEnhanceSharp');
|
// Copyright IBM Corp. 2013,2016. All Rights Reserved.
// Node module: strong-remoting
// This file is licensed under the Artistic License 2.0.
// License text available at https://opensource.org/licenses/Artistic-2.0
var g = require('strong-globalize')();
/*!
* Expose `SharedMethod`.
*/
module.exports = SharedMethod;
var debug = require('debug')('strong-remoting:shared-method');
var util = require('util');
var traverse = require('traverse');
var assert = require('assert');
/**
* Create a new `SharedMethod` (remote method) with the given `fn`.
* See also [Remote methods](http://docs.strongloop.com/display/LB/Remote+methods).
*
* @property {String} name The method name.
* @property {String[]} aliases An array of method aliases.
* @property {Boolean} isStatic Whether the method is static; from `options.isStatic`.
* Default is `true`.
* @property {Array|Object} accepts See `options.accepts`.
* @property {Array|Object} returns See `options.returns`.
* @property {Array|Object} errors See `options.errors`.
* @property {String} description Text description of the method.
* @property {String} notes Additional notes, used by API documentation generators like
* Swagger.
* @property {String} http
* @property {String} rest
* @property {String} shared
* @property {Boolean} [documented] Default: true. Set to `false` to exclude the method
* from Swagger metadata.
*
* @param {Function} fn The `Function` to be invoked when the method is invoked.
* @param {String} name The name of the `SharedMethod`.
* @param {SharedClass} sharedClass The `SharedClass` to which the method will be attached.
*
* @options {Object} options See below.
* @property {Array|Object} [accepts] Defines either a single argument as an object or an
* ordered set of arguments as an array.
* @property {String} [accepts.arg] The name of the argument.
* @property {String} [accepts.description] Text description of the argument, used by API
* documentation generators like Swagger.
* @property {String} [accepts.http] HTTP mapping for the argument. See argument mapping in
* [the docs](http://docs.strongloop.com/x/-Yw6#Remotemethods-HTTPmappingofinputarguments).
* @property {String} [accepts.http.source] The HTTP source for the argument. May be one
* of the following:
*
* - `req` - the Express `Request` object.
* - `res` - the Express `Response` object.
* - `body` - the `req.body` value.
* - `form` - `req.body[argumentName]`.
* - `query` - `req.query[argumentName]`.
* - `path` - `req.params[argumentName]`.
* - `header` - `req.headers[argumentName]`.
* - `context` - the current `HttpContext`.
* @property {Object} [accepts.rest] The REST mapping / settings for the argument.
* @property {String} [accepts.type] Argument datatype; must be a
* [Loopback type](http://docs.strongloop.com/display/LB/LoopBack+types).
* @property {Array} [aliases] A list of aliases for the method.
* @property {Array|Object} [errors] Object or `Array` containing error definitions.
* @property {Array} [http] HTTP-only options.
* @property {Number} [http.errorStatus] Default error status code.
* @property {String} [http.path] HTTP path (relative to the model) at which the method is
* exposed.
* @property {Number} [http.status] Default status code when the callback is called
* _without_ an error.
* @property {String} [http.verb] HTTP method (verb) at which the method is available.
* One of: get, post (default), put, del, or all
* @property {Boolean} [isStatic] Whether the method is a static method or a prototype
* method.
* @property {Array|Object} [returns] Specifies the remote method's callback arguments;
* either a single argument as an object or an ordered set of arguments as an array.
* The `err` argument is assumed; do not specify. NOTE: Can have the same properties as
* `accepts`, except for `http.target`.
*
* Additionally, one of the callback arguments can have `type: 'file'` and
* `root:true`, in which case this argument is sent in the raw form as
* a response body. Allowed values: `String`, `Buffer` or `ReadableStream`
* @property {Boolean} [shared] Whether the method is shared. Default is `true`.
* @property {Number} [status] The default status code.
* @end
*
* @class
*/
function SharedMethod(fn, name, sc, options) {
if (typeof options === 'boolean') {
options = { isStatic: options };
}
this.fn = fn;
fn = fn || {};
this.name = name;
assert(typeof name === 'string', 'The method name must be a string');
options = options || {};
this.aliases = options.aliases || [];
var isStatic = this.isStatic = options.isStatic || false;
this.accepts = options.accepts || fn.accepts || [];
this.returns = options.returns || fn.returns || [];
this.errors = options.errors || fn.errors || [];
this.description = options.description || fn.description;
this.accessType = options.accessType || fn.accessType;
this.notes = options.notes || fn.notes;
this.documented = options.documented !== false && fn.documented !== false;
this.http = options.http || fn.http || {};
this.rest = options.rest || fn.rest || {};
this.shared = options.shared;
if (this.shared === undefined) {
this.shared = true;
}
if (fn.shared === false) {
this.shared = false;
}
this.sharedClass = sc;
if (sc) {
this.ctor = sc.ctor;
this.sharedCtor = sc.sharedCtor;
}
if (name === 'sharedCtor') {
this.isSharedCtor = true;
}
if (this.accepts && !Array.isArray(this.accepts)) {
this.accepts = [this.accepts];
}
this.accepts.forEach(normalizeArgumentDescriptor);
if (this.returns && !Array.isArray(this.returns)) {
this.returns = [this.returns];
}
this.returns.forEach(normalizeArgumentDescriptor);
var firstReturns = this.returns[0];
var streamTypes = ['ReadableStream', 'WriteableStream', 'DuplexStream'];
if (firstReturns && firstReturns.type && streamTypes.indexOf(firstReturns.type) > -1) {
this.streams = {returns: firstReturns};
}
if (this.errors && !Array.isArray(this.errors)) {
this.errors = [this.errors];
}
if (/^prototype\./.test(name)) {
var msg = 'Incorrect API usage. Shared methods on prototypes should be ' +
'created via `new SharedMethod(fn, "name", { isStatic: false })`';
throw new Error(msg);
}
this.stringName = (sc ? sc.name : '') + (isStatic ? '.' : '.prototype.') + name;
}
function normalizeArgumentDescriptor(desc) {
if (desc.type === 'array')
desc.type = ['any'];
}
/**
* Create a new `SharedMethod` with the given `fn`. The function should include
* all the method options.
*
* @param {Function} fn
* @param {Function} name
* @param {SharedClass} SharedClass
* @param {Boolean} isStatic
*/
SharedMethod.fromFunction = function(fn, name, sharedClass, isStatic) {
return new SharedMethod(fn, name, sharedClass, {
isStatic: isStatic,
accepts: fn.accepts,
returns: fn.returns,
errors: fn.errors,
description: fn.description,
notes: fn.notes,
http: fn.http,
rest: fn.rest
});
};
SharedMethod.prototype.getReturnArgDescByName = function(name) {
var returns = this.returns;
var desc;
for (var i = 0; i < returns.length; i++) {
desc = returns[i];
if (desc && ((desc.arg || desc.name) === name)) {
return desc;
}
}
};
/**
* Execute the remote method using the given arg data.
*
* @param {Object} scope `this` parameter for the invocation
* @param {Object} args containing named argument data
* @param {Object=} remotingOptions remote-objects options
* @param {Function} cb callback `fn(err, result)` containing named result data
*/
SharedMethod.prototype.invoke = function(scope, args, remotingOptions, ctx, cb) {
var accepts = this.accepts;
var returns = this.returns;
var errors = this.errors;
var method = this.getFunction();
var sharedMethod = this;
var formattedArgs = [];
if (typeof ctx === 'function') {
cb = ctx;
ctx = undefined;
}
if (cb === undefined && typeof remotingOptions === 'function') {
cb = remotingOptions;
remotingOptions = {};
}
// map the given arg data in order they are expected in
if (accepts) {
for (var i = 0; i < accepts.length; i++) {
var desc = accepts[i];
var name = desc.name || desc.arg;
var uarg = SharedMethod.convertArg(desc, args[name]);
try {
uarg = coerceAccepts(uarg, desc, name);
} catch (e) {
debug('- %s - ' + e.message, sharedMethod.name);
return cb(e);
}
// Add the argument even if it's undefined to stick with the accepts
formattedArgs.push(uarg);
}
}
// define the callback
function callback(err) {
if (err) {
return cb(err);
}
// args without err
var rawArgs = [].slice.call(arguments, 1);
var result = SharedMethod.toResult(returns, rawArgs, ctx);
debug('- %s - result %j', sharedMethod.name, result);
cb(null, result);
}
// add in the required callback
formattedArgs.push(callback);
debug('- %s - invoke with', this.name, formattedArgs);
// invoke
try {
var retval = method.apply(scope, formattedArgs);
if (retval && typeof retval.then === 'function') {
return retval.then(
function(args) {
if (returns.length === 1) args = [args];
var result = SharedMethod.toResult(returns, args);
debug('- %s - promise result %j', sharedMethod.name, result);
cb(null, result);
},
cb // error handler
);
}
return retval;
} catch (err) {
debug('error caught during the invocation of %s', this.name);
return cb(err);
}
};
function badArgumentError(msg) {
var err = new Error(msg);
err.statusCode = 400;
return err;
}
function internalServerError(msg) {
var err = new Error(msg);
err.statusCode = 500;
return err;
}
function escapeRegex(d) {
// see http://stackoverflow.com/a/6969486/69868
return d.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/**
* Coerce an 'accepts' value into its final type.
* If using HTTP, some coercion is already done in http-context.
*
* This should only do very simple coercion.
*
* @param {*} uarg Argument value.
* @param {Object} desc Argument description.
* @return {*} Coerced argument.
*/
function coerceAccepts(uarg, desc) {
var message;
var name = desc.name || desc.arg;
var targetType = convertToBasicRemotingType(desc.type);
var targetTypeIsArray = Array.isArray(targetType) && targetType.length === 1;
// If coercing an array to an erray,
// then coerce all members of the array too
if (targetTypeIsArray && Array.isArray(uarg)) {
return uarg.map(function(arg, ix) {
// when coercing array items, use only name and type,
// ignore all other root settings like "required"
return coerceAccepts(arg, {
name: name + '[' + ix + ']',
type: targetType[0]
});
});
}
var actualType = SharedMethod.getType(uarg, targetType);
// convert values to the correct type
// TODO(bajtos) Move conversions to HttpContext (and friends)
// SharedMethod should only check that argument values match argument types.
var conversionNeeded = targetType !== 'any' &&
actualType !== 'undefined' &&
actualType !== targetType;
if (conversionNeeded) {
// JSON.parse can throw, so catch this error.
try {
uarg = convertValueToTargetType(name, uarg, targetType);
actualType = SharedMethod.getType(uarg, targetType);
} catch (e) {
message = g.f('invalid value for argument \'%s\' of type ' +
'\'%s\': %s. Received type was %s. Error: %s',
name, targetType, uarg, typeof uarg, e.message);
throw badArgumentError(message);
}
}
var typeMismatch = targetType !== 'any' &&
actualType !== 'undefined' &&
targetType !== actualType &&
// In JavaScript, an array is an object too (typeof [] === 'object').
// However, SharedMethod.getType([]) returns 'array' instead of 'object'.
// We must explicitly allow assignment of an array value to an argument
// of type 'object'.
!(targetType === 'object' && actualType === 'array');
if (typeMismatch) {
message = g.f('Invalid value for argument \'%s\' of type ' +
'\'%s\': %s. Received type was converted to %s.',
name, targetType, uarg, typeof uarg);
throw badArgumentError(message);
}
// Verify that a required argument has a value
// FIXME(bajtos) "null" should be treated as no value too
if (actualType === 'undefined') {
if (desc.required) {
throw badArgumentError(g.f('%s is a required argument', name));
} else {
return undefined;
}
}
if (actualType === 'number' && Number.isNaN(uarg)) {
throw badArgumentError(g.f('%s must be a {{number}}', name));
}
if (actualType === 'integer') {
if (Number.isNaN(uarg)) {
throw badArgumentError(g.f('%s must be an {{integer}}', name));
}
if (!Number.isSafeInteger(uarg)) {
throw badArgumentError(g.f('%s must be a safe {{integer}}', name));
}
}
return uarg;
}
/**
* Returns an appropriate type based on a type specifier from remoting
* metadata.
* @param {Object} type A type specifier from remoting metadata,
* e.g. "[Number]" or "MyModel" from `accepts[0].type`.
* @returns {String} A type name compatible with the values returned by
* `SharedMethod.getType()`, e.g. "string" or "array".
*/
function convertToBasicRemotingType(type) {
if (Array.isArray(type)) {
return type.map(convertToBasicRemotingType);
}
if (typeof type === 'object') {
type = type.modelName || type.name;
}
if (SharedMethod.isFileType(type)) {
return 'file';
}
type = String(type).toLowerCase();
switch (type) {
case 'string':
case 'number':
case 'integer':
case 'date':
case 'boolean':
case 'buffer':
case 'object':
case 'any':
return type;
case 'array':
return ['any'].map(convertToBasicRemotingType);
default:
// custom types like MyModel
return 'object';
}
}
function convertValueToTargetType(argName, value, targetType) {
switch (targetType) {
case 'string':
return String(value).valueOf();
case 'date':
return new Date(value);
case 'number':
case 'integer':
return Number(value).valueOf();
case 'boolean':
return Boolean(value).valueOf();
// Other types such as 'object', 'array',
// ModelClass, ['string'], or [ModelClass]
default:
switch (typeof value) {
case 'string':
return JSON.parse(value);
case 'object':
return value;
default:
throw badArgumentError(g.f('%s must be %s', argName, targetType));
}
}
}
/**
* Returns an appropriate type based on `val`.
* @param {*} val The value to determine the type for
* @returns {String} The type name
*/
SharedMethod.getType = function(val, targetType) {
var type = typeof val;
switch (type) {
case 'undefined':
case 'boolean':
case 'function':
case 'string':
return type;
case 'number':
return Number.isInteger(val) && targetType === 'integer' ?
'integer' : 'number';
case 'object':
// null
if (val === null) {
return 'null';
}
// buffer
if (Buffer.isBuffer(val)) {
return 'buffer';
}
// array
if (Array.isArray(val)) {
return 'array';
}
// date
if (val instanceof Date) {
return 'date';
}
// object
return 'object';
}
};
/**
* Returns a reformatted Object valid for consumption as remoting function
* arguments
*/
SharedMethod.convertArg = function(accept, raw) {
var isComputedArgument = accept.http && (
typeof accept.http === 'function' ||
accept.http.source === 'req' ||
accept.http.source === 'res' ||
accept.http.source === 'context');
if (isComputedArgument) {
return raw;
}
if (raw === null || typeof raw !== 'object') {
return raw;
}
if (typeof raw === 'object' &&
raw.constructor !== Object &&
raw.constructor !== Array) {
// raw is not plain
return raw;
}
var data = traverse(raw).forEach(function(x) {
if (x === null || typeof x !== 'object') {
return x;
}
var result = x;
if (x.$type === 'base64' || x.$type === 'date') {
switch (x.$type) {
case 'base64':
result = new Buffer(x.$data, 'base64');
break;
case 'date':
result = new Date(x.$data);
break;
}
this.update(result);
}
return result;
});
return data;
};
SharedMethod.isFileType = function(argSpec) {
// Only all-lowercase value "file" is recognized as the special file type
// Other spellings, most notably "File", are treated as custom types (models)
return argSpec === 'file';
};
/**
* Returns a reformatted Object valid for consumption as JSON from an Array of
* results from a remoting function, based on `returns`.
*/
SharedMethod.toResult = function(returns, raw, ctx) {
var result = {};
if (!returns.length) {
return;
}
returns = returns.filter(function(item, index) {
if (index >= raw.length) {
return false;
}
if (ctx && ctx.setReturnArgByName(item.name || item.arg, raw[index])) {
return false;
}
if (item.root) {
var targetType = convertToBasicRemotingType(item.type);
var isFile = SharedMethod.isFileType(item.type);
result = isFile ? raw[index] : convert(raw[index], targetType, item.name);
return false;
}
return true;
});
returns.forEach(function(item, index) {
var name = item.name || item.arg;
var targetType = convertToBasicRemotingType(item.type);
if (SharedMethod.isFileType(item.type)) {
g.warn('%s: discarded non-root return argument %s of type "{{file}}"',
this.stringName,
name);
return;
}
var value = convert(raw[index], targetType, name);
result[name] = value;
});
return result;
function convert(val, targetType, argName) {
var targetTypeIsIntegerArray = Array.isArray(targetType) &&
targetType.length === 1 && targetType[0] === 'integer';
if (targetTypeIsIntegerArray && Array.isArray(val)) {
var arrayTargetType = targetType[0];
return val.map(function(intVal) {
return convert(intVal, arrayTargetType, argName);
});
}
var actualType = SharedMethod.getType(val, targetType);
switch (actualType) {
case 'date':
return {
$type: 'date',
$data: val.toString()
};
case 'buffer':
return {
$type: 'base64',
$data: val.toString('base64')
};
default:
if (targetType === 'integer') {
var message;
if (!Number.isInteger(val)) {
message = g.f(
'Invalid return value for argument \'%s\' of type ' +
'\'%s\': %s. Received type was %s.',
argName, targetType, val, typeof val);
throw internalServerError(message);
}
if (!Number.isSafeInteger(val)) {
message = g.f(
'Unsafe integer value returned for argument \'%s\' of type ' +
'\'%s\': %s.',
argName, targetType, val);
throw internalServerError(message);
}
return val;
}
return val;
}
}
};
/**
* Get the function the `SharedMethod` will `invoke()`.
*/
SharedMethod.prototype.getFunction = function() {
var fn;
if (!this.ctor) return this.fn;
if (this.isStatic) {
fn = this.ctor[this.name];
} else {
fn = this.ctor.prototype[this.name];
}
return fn || this.fn;
};
/**
* Determine if this shared method invokes the given "suspect" function.
*
* @example
* ```js
* sharedMethod.isDelegateFor(myClass.myMethod); // pass a function
* sharedMethod.isDelegateFor(myClass.prototype.myInstMethod);
* sharedMethod.isDelegateFor('myMethod', true); // check for a static method by name
* sharedMethod.isDelegateFor('myInstMethod', false); // instance method by name
* ```
*
* @param {String|Function} suspect The name of the suspected function
* or a `Function`.
* @returns Boolean True if the shared method invokes the given function; false otherwise.
*/
SharedMethod.prototype.isDelegateFor = function(suspect, isStatic) {
var type = typeof suspect;
isStatic = isStatic || false;
if (suspect) {
switch (type) {
case 'function':
return this.getFunction() === suspect;
case 'string':
if (this.isStatic !== isStatic) return false;
return this.name === suspect || this.aliases.indexOf(suspect) !== -1;
}
}
return false;
};
/**
* Determine if this shared method invokes the given "suspect" function.
*
* @example
* ```js
* sharedMethod.isDelegateForName('myMethod'); // check for a static method by name
* sharedMethod.isDelegateForName('prototype.myInstMethod'); // instance method by name
* ```
*
* @returns Boolean True if the shared method invokes the given function; false otherwise.
*/
SharedMethod.prototype.isDelegateForName = function(suspect) {
assert(typeof suspect === 'string', 'argument of isDelegateForName should be string');
var m = suspect.match(/^prototype\.(.*)$/);
var isStatic = !m;
var baseName = isStatic ? suspect : m[1];
return this.isDelegateFor(baseName, isStatic);
};
/**
* Add an alias
*
* @param {String} alias Alias method name.
*/
SharedMethod.prototype.addAlias = function(alias) {
if (this.aliases.indexOf(alias) === -1) {
this.aliases.push(alias);
}
};
// To support Node v.0.10.x
if (typeof Number.isInteger === 'undefined') {
Number.isInteger = function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
}
if (typeof Number.MAX_SAFE_INTEGER === 'undefined') {
Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
}
if (typeof Number.isSafeInteger === 'undefined') {
Number.isSafeInteger = function(value) {
return Number.isInteger(value) &&
Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};
}
|
/*
* Copyright (C) 2012 by CoNarrative
*/
glu.DataModel = glu.extend(glu.Viewmodel, {
constructor : function(config) {
glu.log.debug('BEGIN datamodel construction');
this._private = this._private || {};
config.recType = config.recType || config.model || config.modelType;
if (config.recType) {
this._private.model = glu.walk(config.ns + '.models.' + config.recType);
} else {
if (glu.isArray(config.fields)) {
for (var i = 0, len = config.fields.length; i < len; i++) {
if (glu.isString(config.fields[i])) {
config.fields[i] = {
name : config.fields[i],
type : 'string'
};
//TODO: Infer datatype here
}
}
}
this._private.model = {
fields : config.fields
};
}
this._private.recType = config.recType;
delete config.recType;
this._private.url = config.url || '/' + config.recType + '/read';
this._private.saveurl = config.saveUrl || '/' + config.recType + '/save';
this._private.dirtyCount = 0;
delete config.url;
delete config.saveurl;
if (glu.isFunction(config.params)) {
this._private.paramGenerator = config.params;
delete config.params;
}
//load in initial values into record
if (Ext.getVersion().major > 3 || Ext.getProvider().provider == 'touch') {
//TODO: Make sure we only create the models once ... fix the "rectype" system so that
//it more closely mimics Ext 4.0 models
var modelId = Ext.id();
Ext.define(modelId, {
extend : 'Ext.data.Model',
fields : this._private.model.fields
});
this.reader = new Ext.data.reader.Json({
model : modelId
});
} else {
this.reader = new Ext.data.JsonReader({}, this._private.model.fields);
}
//TODO: clean this up by calling loadData instead
//workaround for new Ext 4.1 behavior...
var idProp = 'id';
if (config[idProp] === undefined) {
config[idProp] = '';
}
var initialRecord = this.reader.readRecords([
config
]).records[0];
this._private.record = initialRecord;
glu.apply(this, initialRecord.data);
this._private.data = this._private.data || {};
glu.apply(this._private.data, initialRecord.data);
//create isDirty formulas
this._private.record.fields.each(function(rec) {
var name = rec.name + 'IsDirty';
config[name] = {
on : [rec.name + 'Changed'],
formula : function() {
return this.isModified(rec.name);
}
}
}, this);
config.isDirty = false;
//call Viewmodel constructor
glu.DataModel.superclass.constructor.apply(this, arguments);
glu.log.debug('END datamodel construction');
},
setRaw : function(fieldName, value, suppressDirtyEvent) {
var rec = this._private.record;
//check if part of fields and if so, set it in the record too...
if (rec.fields.containsKey(fieldName)) {
var wasDirty = this.isModified(fieldName);
rec.set(fieldName, value);
if (rec.modified && value == rec.modified[fieldName]) {
//remove dirty indicator
delete rec.modified[fieldName];
}
var isDirtyNow = this.isModified(fieldName);
if (!wasDirty && isDirtyNow)
this._private.dirtyCount++;
if (wasDirty && !isDirtyNow)
this._private.dirtyCount--;
}
glu.DataModel.superclass.setRaw.apply(this, arguments);
if (rec.fields.containsKey(fieldName)) {
this.set('isDirty', this._private.dirtyCount > 0);
}
},
isModified : function(propName) {
var rec = this._private.record;
return rec.hasOwnProperty('modified') && rec.modified.hasOwnProperty(propName);
},
asObject : function() {
return glu.apply({}, this._private.record.data);
},
load : function(id) {
var url = this.url;
if (this.appendId) {
url = url + (glu.string(url).endsWith('/') ? '' : '/') + id;
}
if (this.paramGenerator) {
var config = {
params : {}
};
config.params = glu.apply(config.params, this._serialize(Ext.createDelegate(this._private.paramGenerator, this)()));
}
var jsonData = {
id : id
};
if (config.params) {
jsonData.params = config.params;
}
Ext.Ajax.request({
url : url,
method : 'POST',
jsonData : jsonData,
scope : this,
success : function(response, opts) {
var responseObj = Ext.decode(response.responseText);
if (responseObj.success) {
var data = responseObj[this.root];
this.loadData(data);
} else {
Ext.Msg.alert('Status', responseObj.message);
}
}
// failure: function(response, opts) {
// var responseText = (response.responseText ? response.responseText : 'Unable to contact the server. Please try again later.');
// Ext.Msg.alert('Status', 'Unable to contact the server. Please try again later.');
// }
});
},
save : function() {
var url = this.saveurl;
if (this.appendId) {
url = url + (glu.string(url).endsWith('/') ? '' : '/') + id;
}
if (this._private.paramGenerator) {
var config = {
params : {}
};
config.params = glu.apply(config.params, this._serialize(Ext.createDelegate(this._private.paramGenerator, this)()));
}
var jsonData = {
model : this._private.model.name,
data : this.getChanges(),
id : this.getId()
};
if (config.params) {
jsonData.params = config.params;
}
Ext.Ajax.request({
url : url,
method : 'POST',
jsonData : jsonData,
scope : this,
success : function(response, opts) {
var responseObj = Ext.decode(response.responseText);
if (responseObj.success) {
var data = responseObj[this.root];
// if we got data back, then replace the existing record with this newly established record.
if (data) {
this._private.record = new this._private.record(data, data[this._private.model.idProperty]);
this.loadData(data);
} else {
this._private.record.commit(true);
}
} else {
Ext.Msg.alert('Status', responseObj.message);
}
},
failure : function(response, opts) {
// var responseText = (response.responseText ? response.responseText : 'Unable to contact the server. Please try again later.');
Ext.Msg.alert('Status', 'Unable to contact the server. Please try again later.');
}
});
},
getFieldModel : function() {
return this._private.model;
},
_serialize : function(data) {
if (data) {
for (var k in data) {
if (glu.isArray(data[k])) {
data[k] = glu.json.stringify(data[k]);
}
}
}
return data;
},
loadData : function(rawData) {
//workaround for new Ext 4.1 behavior...
var idProp = 'id';
if (rawData[idProp] === undefined) {
rawData[idProp] = '';
}
var data = this.reader.readRecords([
rawData
]).records[0].data;
for (var k in data) {
this.setRaw(k, data[k]);
}
this.commit();
},
getId : function() {
return this._private.record.get(this._private.model.idProperty);
},
getFieldConfig : function(fieldName) {
// TODO: convert model fields to objects instead of arrays, globally
for (var i = 0; i < this._private.model.fields.length; i++) {
if (this._private.model.fields[i].name == fieldName) {
return this._private.model.fields[i]
}
}
return null;
},
commit : function() {
this._private.record.commit(true);
for (var i = 0; i < this._private.model.fields.length; i++) {
var field = this._private.model.fields[i].name || this._private.model.fields[i];
this.set(field + 'IsDirty', false);
}
this._private.dirtyCount = 0;
this.set('isDirty', false);
},
getOriginalValue : function(fieldName) {
if (this.isModified(fieldName)) {
return this._private.record.modified[fieldName];
} else {
return this.get(fieldName);
}
},
getChanges : function() {
return this._private.record.getChanges();
},
revert : function() {
this._private.record.reject(true);
this.loadData(this._private.record.data);
this.commit();
}
});
glu.mreg('datamodel', glu.DataModel);
|
module.exports = {
__depends__: [ require('diagram-js/lib/features/move') ],
__init__: ['bpmnReplacePreview'],
bpmnReplacePreview: [ 'type', require('./BpmnReplacePreview') ]
};
|
const { ModuleFederationPlugin } = require("../../../../").container;
/** @type {import("../../../../").Configuration} */
module.exports = {
optimization: {
chunkIds: "named",
moduleIds: "named"
},
output: {
strictModuleExceptionHandling: true
},
plugins: [
new ModuleFederationPlugin({
name: "container",
library: { type: "commonjs-module" },
filename: "container.js",
exposes: ["./module"],
remotes: {
remote: "./container.js",
invalid: "./invalid.js"
}
})
],
experiments: {
topLevelAwait: true
}
};
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Defines a search query.
*
*/
class Query {
/**
* Create a Query.
* @member {string} text The query string. Use this string as the query term
* in a new search request.
* @member {string} [displayText] The display version of the query term. This
* version of the query term may contain special characters that highlight
* the search term found in the query string. The string contains the
* highlighting characters only if the query enabled hit highlighting
* @member {string} [webSearchUrl] The URL that takes the user to the Bing
* search results page for the query.Only related search results include this
* field.
* @member {string} [searchLink]
*/
constructor() {
}
/**
* Defines the metadata of Query
*
* @returns {object} metadata of Query
*
*/
mapper() {
return {
required: false,
serializedName: 'Query',
type: {
name: 'Composite',
className: 'Query',
modelProperties: {
text: {
required: true,
serializedName: 'text',
type: {
name: 'String'
}
},
displayText: {
required: false,
readOnly: true,
serializedName: 'displayText',
type: {
name: 'String'
}
},
webSearchUrl: {
required: false,
readOnly: true,
serializedName: 'webSearchUrl',
type: {
name: 'String'
}
},
searchLink: {
required: false,
readOnly: true,
serializedName: 'searchLink',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = Query;
|
var Dispatcher = require('flux').Dispatcher;
var _ = require('lodash');
var dispatcher = _.extend(new Dispatcher(), {
/**
* A bridge function between the views and the dispatcher, marking the action
* as a view action. Another variant here could be handleServerAction.
* @param {object} action The data coming from the view.
*/
handleViewAction: function(action) {
this.dispatch({
source: 'VIEW_ACTION',
action: action
});
}
});
module.exports = dispatcher;
|
'use strict';
var convert = require('./convert'),
func = convert('dropRight', require('../dropRight'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2Ryb3BSaWdodC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLElBQUksVUFBVSxRQUFRLFdBQVIsQ0FBZDtJQUNJLE9BQU8sUUFBUSxXQUFSLEVBQXFCLFFBQVEsY0FBUixDQUFyQixDQURYOztBQUdBLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoiZHJvcFJpZ2h0LmpzIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGNvbnZlcnQgPSByZXF1aXJlKCcuL2NvbnZlcnQnKSxcbiAgICBmdW5jID0gY29udmVydCgnZHJvcFJpZ2h0JywgcmVxdWlyZSgnLi4vZHJvcFJpZ2h0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19 |
(function (subdivision) {
'use strict';
subdivision.systemPaths = {
prefix: 'subdivision'
};
subdivision.vent = subdivision.createEventBus();
//This will move to service file
function buildServicesInternal() {
if (_.isFunction(subdivision.buildServices)) {
subdivision.vent.trigger('before:buildServices');
return subdivision.buildServices().then(function () {
subdivision.vent.trigger('after:buildServices');
});
} else {
return Promise.resolve();
}
}
function buildCommandsInternal() {
var commands = subdivision.build(subdivision.systemPaths.commands);
_.forEach(commands, function (command) {
subdivision.addCommand(command, true);
});
}
function buildConditionsInternal() {
var conditions = subdivision.build(subdivision.systemPaths.conditions);
_.forEach(conditions, function (condition) {
subdivision.addCondition(condition, true);
});
}
subdivision.start = function () {
subdivision.vent.trigger('before:start');
if (subdivision.defaultManifest) {
subdivision.vent.trigger('before:readDefaultManifest');
subdivision.readManifest(subdivision.defaultManifest);
subdivision.vent.trigger('after:readDefaultManifest');
}
subdivision.$generateBuilders();
subdivision.vent.trigger('before:buildConditions');
buildConditionsInternal();
subdivision.vent.trigger('after:buildConditions');
subdivision.vent.trigger('before:buildCommands');
buildCommandsInternal();
subdivision.vent.trigger('after:buildCommands');
//This will be a generic initializer
return buildServicesInternal().then(function () {
subdivision.vent.trigger('after:start');
});
};
})(subdivision); |
/*
* Copyright 2003-2006, 2009, 2017, United States Government, as represented by the Administrator of the
* National Aeronautics and Space Administration. All rights reserved.
*
* The NASAWorldWind/WebWorldWind platform is 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.
*/
/**
* @exports Matrix3
*/
define([
'../error/ArgumentError',
'../util/Logger'
],
function (ArgumentError,
Logger) {
"use strict";
/**
* Constructs a 3 x 3 matrix.
* @alias Matrix3
* @constructor
* @classdesc Represents a 3 x 3 double precision matrix stored in a Float64Array in row-major order.
* @param {Number} m11 matrix element at row 1, column 1.
* @param {Number} m12 matrix element at row 1, column 2.
* @param {Number} m13 matrix element at row 1, column 3.
* @param {Number} m21 matrix element at row 2, column 1.
* @param {Number} m22 matrix element at row 2, column 2.
* @param {Number} m23 matrix element at row 2, column 3.
* @param {Number} m31 matrix element at row 3, column 1.
* @param {Number} m32 matrix element at row 3, column 2.
* @param {Number} m33 matrix element at row 3, column 3.
*/
var Matrix3 = function (m11, m12, m13,
m21, m22, m23,
m31, m32, m33) {
this[0] = m11;
this[1] = m12;
this[2] = m13;
this[3] = m21;
this[4] = m22;
this[5] = m23;
this[6] = m31;
this[7] = m32;
this[8] = m33;
};
// Derives from Float64Array.
Matrix3.prototype = new Float64Array(9);
/**
* Creates an identity matrix.
* @returns {Matrix3} A new identity matrix.
*/
Matrix3.fromIdentity = function () {
return new Matrix3(
1, 0, 0,
0, 1, 0,
0, 0, 1
);
};
/**
* Sets this matrix to one that flips and shifts the y-axis.
* <p>
* The resultant matrix maps Y=0 to Y=1 and Y=1 to Y=0. All existing values are overwritten. This matrix is
* usually used to change the coordinate origin from an upper left coordinate origin to a lower left coordinate
* origin. This is typically necessary to align the coordinate system of images (top-left origin) with that of
* OpenGL (bottom-left origin).
* @returns {Matrix3} This matrix set to values described above.
*/
Matrix3.prototype.setToUnitYFlip = function () {
this[0] = 1;
this[1] = 0;
this[2] = 0;
this[3] = 0;
this[4] = -1;
this[5] = 1;
this[6] = 0;
this[7] = 0;
this[8] = 1;
return this;
};
/**
* Multiplies this matrix by a specified matrix.
*
* @param {Matrix3} matrix The matrix to multiply with this matrix.
* @returns {Matrix3} This matrix after multiplying it by the specified matrix.
* @throws {ArgumentError} if the specified matrix is null or undefined.
*/
Matrix3.prototype.multiplyMatrix = function (matrix) {
if (!matrix) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Matrix3", "multiplyMatrix", "missingMatrix"));
}
var ma = this,
mb = matrix,
ma0, ma1, ma2;
// Row 1
ma0 = ma[0];
ma1 = ma[1];
ma2 = ma[2];
ma[0] = (ma0 * mb[0]) + (ma1 * mb[3]) + (ma2 * mb[6]);
ma[1] = (ma0 * mb[1]) + (ma1 * mb[4]) + (ma2 * mb[7]);
ma[2] = (ma0 * mb[2]) + (ma1 * mb[5]) + (ma2 * mb[8]);
// Row 2
ma0 = ma[3];
ma1 = ma[4];
ma2 = ma[5];
ma[3] = (ma0 * mb[0]) + (ma1 * mb[3]) + (ma2 * mb[6]);
ma[4] = (ma0 * mb[1]) + (ma1 * mb[4]) + (ma2 * mb[7]);
ma[5] = (ma0 * mb[2]) + (ma1 * mb[5]) + (ma2 * mb[8]);
// Row 3
ma0 = ma[6];
ma1 = ma[7];
ma2 = ma[8];
ma[6] = (ma0 * mb[0]) + (ma1 * mb[3]) + (ma2 * mb[6]);
ma[7] = (ma0 * mb[1]) + (ma1 * mb[4]) + (ma2 * mb[7]);
ma[8] = (ma0 * mb[2]) + (ma1 * mb[5]) + (ma2 * mb[8]);
return this;
};
/**
* Multiplies this matrix by a matrix that transforms normalized coordinates from a source sector to a destination
* sector. Normalized coordinates within a sector range from 0 to 1, with (0, 0) indicating the lower left corner
* and (1, 1) indicating the upper right. The resultant matrix maps a normalized source coordinate (X, Y) to its
* corresponding normalized destination coordinate (X', Y').
* <p/>
* This matrix typically necessary to transform texture coordinates from one geographic region to another. For
* example, the texture coordinates for a terrain tile spanning one region must be transformed to coordinates
* appropriate for an image tile spanning a potentially different region.
*
* @param {Sector} src the source sector
* @param {Sector} dst the destination sector
*
* @returns {Matrix3} this matrix multiplied by the transform matrix implied by values described above
*/
Matrix3.prototype.multiplyByTileTransform = function (src, dst) {
var srcDeltaLat = src.deltaLatitude();
var srcDeltaLon = src.deltaLongitude();
var dstDeltaLat = dst.deltaLatitude();
var dstDeltaLon = dst.deltaLongitude();
var xs = srcDeltaLon / dstDeltaLon;
var ys = srcDeltaLat / dstDeltaLat;
var xt = (src.minLongitude - dst.minLongitude) / dstDeltaLon;
var yt = (src.minLatitude - dst.minLatitude) / dstDeltaLat;
// This is equivalent to the following operation, but is potentially much faster:
/*var m = new Matrix3(
xs, 0, xt,
0, ys, yt,
0, 0, 1);
this.multiplyMatrix(m);*/
// This inline version eliminates unnecessary multiplication by 1 and 0 in the matrix's components, reducing
// the total number of primitive operations from 63 to 18.
var m = this;
// Must be done before modifying m0, m1, etc. below.
m[2] += (m[0] * xt) + (m[1] * yt);
m[5] += (m[3] * xt) + (m[4] * yt);
m[8] += (m[6] * xt) + (m[6] * yt);
m[0] *= xs;
m[1] *= ys;
m[3] *= xs;
m[4] *= ys;
m[6] *= xs;
m[7] *= ys;
return this;
};
/**
* Stores this matrix's components in column-major order in a specified array.
* <p>
* The array must have space for at least 9 elements. This matrix's components are stored in the array
* starting with row 0 column 0 in index 0, row 1 column 0 in index 1, row 2 column 0 in index 2, and so on.
*
* @param {Float32Array | Float64Array | Number[]} result An array of at least 9 elements. Upon return,
* contains this matrix's components in column-major.
* @returns {Float32Array} The specified result array.
* @throws {ArgumentError} If the specified result array in null or undefined.
*/
Matrix3.prototype.columnMajorComponents = function (result) {
if (!result) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "Matrix3", "columnMajorComponents", "missingResult"));
}
// Column 1
result[0] = this[0];
result[1] = this[3];
result[2] = this[6];
// Column 2
result[3] = this[1];
result[4] = this[4];
result[5] = this[7];
// Column 3
result[6] = this[2];
result[7] = this[5];
result[8] = this[8];
return result;
};
return Matrix3;
}); |
const colors = require(`./colors`).default
module.exports = {
colors,
mobile: `(min-width: 400px)`,
Mobile: `@media (min-width: 400px)`,
phablet: `(min-width: 550px)`,
Phablet: `@media (min-width: 550px)`,
tablet: `(min-width: 750px)`,
Tablet: `@media (min-width: 750px)`,
desktop: `(min-width: 1000px)`,
Desktop: `@media (min-width: 1000px)`,
hd: `(min-width: 1200px)`,
Hd: `@media (min-width: 1200px)`,
VHd: `@media (min-width: 1450px)`,
VVHd: `@media (min-width: 1650px)`,
maxWidth: 35,
maxWidthWithSidebar: 26,
radius: 2,
radiusLg: 4,
gutters: {
default: 1.25,
HdR: 2.5,
VHdR: 3,
VVHdR: 4.5,
},
shadowKeyUmbraOpacity: 0.1,
shadowKeyPenumbraOpacity: 0.07,
shadowAmbientShadowOpacity: 0.06,
animation: {
curveDefault: `cubic-bezier(0.4, 0, 0.2, 1)`,
speedDefault: `250ms`,
speedFast: `100ms`,
speedSlow: `350ms`,
},
logoOffset: 1.8,
headerHeight: `3.5rem`,
bannerHeight: `2.5rem`,
sidebarUtilityHeight: `2.5rem`,
pageHeadingDesktopWidth: `3.5rem`,
}
|
'use strict';
module.exports = function generate__limit(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $isMax = $keyword == 'maximum',
$exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
$schemaExcl = it.schema[$exclusiveKeyword],
$isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data,
$op = $isMax ? '<' : '>',
$notOp = $isMax ? '>' : '<';
if ($isDataExcl) {
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
$exclusive = 'exclusive' + $lvl,
$opExpr = 'op' + $lvl,
$opStr = '\' + ' + $opExpr + ' + \'';
out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
$schemaValueExcl = 'schemaExcl' + $lvl;
out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { ';
var $errorKeyword = $exclusiveKeyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else if( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
} else {
var $exclusive = $schemaExcl === true,
$opStr = $op;
if (!$exclusive) $opStr += '=';
var $opExpr = '\'' + $opStr + '\'';
out += ' if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ' + ($data) + ' ' + ($notOp);
if ($exclusive) {
out += '=';
}
out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {';
}
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ' + ($opStr) + ' ';
if ($isData) {
out += '\' + ' + ($schemaValue);
} else {
out += '' + ($schema) + '\'';
}
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
|
import { indexOfItemContainingTarget } from "../core/dom.js";
import ReactiveElement from "../core/ReactiveElement.js"; // eslint-disable-line no-unused-vars
import {
firstRender,
raiseChangeEvents,
render,
setState,
state,
tap,
} from "./internal.js";
/**
* A tap/mousedown on a list item makes that item current.
*
* This simple mixin is useful in list-like elements like [ListBox](ListBox),
* where a tap/mousedown on a list item implicitly selects it.
*
* The standard use for this mixin is in list-like elements. Native list
* boxes don't appear to be consistent with regard to whether they select
* on mousedown or click/mouseup. This mixin assumes the use of mousedown.
* On touch devices, that event appears to trigger when the touch is *released*.
*
* This mixin only listens to mousedown events for the primary mouse button
* (typically the left button). Right clicks are ignored so that the browser may
* display a context menu.
*
* This mixin expects the component to provide an `state.items` member. It also
* expects the component to define a `state.currentIndex` member; you can
* provide that yourself, or use [ItemsCursorMixin](ItemsCursorMixin).
*
* If the component receives an event that doesn't correspond to an item (e.g.,
* the user taps on the element background visible between items), the cursor
* will be removed. However, if the component sets `state.currentItemRequired` to
* true, a background tap will *not* remove the cursor.
*
* @module TapCursorMixin
* @param {Constructor<ReactiveElement>} Base
*/
export default function TapCursorMixin(Base) {
// The class prototype added by the mixin.
return class TapCursor extends Base {
constructor() {
// @ts-ignore
super();
this.addEventListener("mousedown", (event) => {
// Only process events for the main (usually left) button.
if (event.button !== 0) {
return;
}
this[raiseChangeEvents] = true;
this[tap](event);
this[raiseChangeEvents] = false;
});
}
[render](/** @type {ChangedFlags} */ changed) {
if (super[render]) {
super[render](changed);
}
if (this[firstRender]) {
Object.assign(this.style, {
touchAction: "manipulation", // for iOS Safari
mozUserSelect: "none",
msUserSelect: "none",
webkitUserSelect: "none",
userSelect: "none",
});
}
}
[tap](/** @type {MouseEvent} */ event) {
// In some situations, the event target will not be the child which was
// originally clicked on. E.g., if the item clicked on is a button, the
// event seems to be raised in phase 2 (AT_TARGET) — but the event target
// will be the component, not the item that was clicked on. Instead of
// using the event target, we get the first node in the event's composed
// path.
// @ts-ignore
const target = event.composedPath
? event.composedPath()[0]
: event.target;
// Find which item was clicked on and, if found, make it current. Ignore
// clicks on disabled items.
//
// For elements which don't require a cursor, a background click will
// determine the item was null, in which we case we'll remove the cursor.
const { items, currentItemRequired } = this[state];
if (items && target instanceof Node) {
const targetIndex = indexOfItemContainingTarget(items, target);
const item = targetIndex >= 0 ? items[targetIndex] : null;
if ((item && !item.disabled) || (!item && !currentItemRequired)) {
this[setState]({
currentIndex: targetIndex,
});
event.stopPropagation();
}
}
}
};
}
|
import { actionTypes } from 'redux-resource';
import { normalize, schema } from 'normalizr';
import { includedResources } from '../../src';
describe('includedResources', function() {
it('does nothing for non-successful reads', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_PENDING,
resourceName: 'authors',
resources: [10, 200],
includedResources: {
books: {
23: {
id: 23,
name: 'Book23',
},
},
},
};
const result = reducer(state, action);
expect(result).to.equal(state);
});
it('does nothing when there is no `includedResources` attribute on the action', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
};
const result = reducer(state, action);
expect(result).to.equal(state);
});
it('does nothing when there is no matching `includedResources`', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
includedResources: {
sandwiches: [{ id: 2 }, { id: 4 }],
},
};
const result = reducer(state, action);
expect(result).to.equal(state);
});
it('should add included resources when passed as an object with READ_RESOURCES_SUCCEEDED', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
23: { id: 23, color: 'blue' },
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
23: { oinky: false },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
includedResources: {
books: {
23: {
id: 23,
name: 'Book23',
},
},
},
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
23: { id: 23, name: 'Book23', color: 'blue' },
},
meta: {
23: { readStatus: 'SUCCEEDED', oinky: false },
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('should add included resources when passed as an object with CREATE_RESOURCES_SUCCEEDED', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
23: { id: 23, color: 'blue' },
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
23: { oinky: false },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.CREATE_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
includedResources: {
books: {
23: {
id: 23,
name: 'Book23',
},
},
},
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
23: { id: 23, name: 'Book23', color: 'blue' },
},
meta: {
23: {
readStatus: 'SUCCEEDED',
createStatus: 'SUCCEEDED',
oinky: false,
},
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('should add included resources when passed as an object with UPDATE_RESOURCES_SUCCEEDED', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
23: { id: 23, color: 'blue' },
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
23: { oinky: false },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.UPDATE_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
includedResources: {
books: {
23: {
id: 23,
name: 'Book23',
},
},
},
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
23: { id: 23, name: 'Book23', color: 'blue' },
},
meta: {
23: {
readStatus: 'SUCCEEDED',
updateStatus: 'SUCCEEDED',
oinky: false,
},
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('should not merge meta with mergeMeta: false', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
23: { oinky: false },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
mergeMeta: false,
includedResources: {
books: {
23: {
id: 23,
name: 'Book23',
},
},
},
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
23: { id: 23, name: 'Book23' },
},
meta: {
23: { readStatus: 'SUCCEEDED' },
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('should not merge resources with mergeResources: false', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
23: { id: 23, color: 'blue' },
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
mergeResources: false,
includedResources: {
books: {
23: {
id: 23,
name: 'Book23',
},
},
},
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
23: { id: 23, name: 'Book23' },
},
meta: {
23: { readStatus: 'SUCCEEDED' },
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('should add included resources when passed as an Array', () => {
const reducer = includedResources('books');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: 'authors',
resources: [10, 200],
includedResources: {
books: [
{
id: 23,
name: 'Book23',
},
],
},
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'Book24' },
23: { id: 23, name: 'Book23' },
},
meta: {
23: { readStatus: 'SUCCEEDED' },
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('integrates with normalizr; included resources', () => {
const reducer = includedResources('comments');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'comment24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const user = new schema.Entity('users');
const comment = new schema.Entity('comments', {
commenter: user,
});
const article = new schema.Entity('articles', {
author: user,
comments: [comment],
});
const originalData = [
{
id: '123',
author: {
id: '1',
name: 'Paul',
},
title: 'My awesome blog post',
comments: [
{
id: '324',
commenter: {
id: '2',
name: 'Nicole',
},
},
],
},
];
const normalizedData = normalize(originalData, [article]);
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: article.key,
resources: normalizedData.result,
includedResources: normalizedData.entities,
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'comment24' },
324: { id: '324', commenter: '2' },
},
meta: {
324: { readStatus: 'SUCCEEDED' },
24: { oinky: true },
},
lists: {},
requests: {},
});
});
it('integrates with normalizr; primary resource', () => {
const reducer = includedResources('articles');
const state = {
selectedIds: [24],
resources: {
24: { id: 24, name: 'comment24' },
},
meta: {
24: { oinky: true },
},
lists: {},
requests: {},
};
const user = new schema.Entity('users');
const comment = new schema.Entity('comments', {
commenter: user,
});
const article = new schema.Entity('articles', {
author: user,
comments: [comment],
});
const originalData = [
{
id: '123',
author: {
id: '1',
name: 'Paul',
},
title: 'My awesome blog post',
comments: [
{
id: '324',
commenter: {
id: '2',
name: 'Nicole',
},
},
],
},
];
const normalizedData = normalize(originalData, [article]);
const action = {
type: actionTypes.READ_RESOURCES_SUCCEEDED,
resourceName: article.key,
resources: normalizedData.result,
includedResources: normalizedData.entities,
};
const result = reducer(state, action);
expect(result).to.deep.equal({
selectedIds: [24],
resources: {
24: { id: 24, name: 'comment24' },
123: {
id: '123',
author: '1',
title: 'My awesome blog post',
comments: ['324'],
},
},
meta: {
123: { readStatus: 'SUCCEEDED' },
24: { oinky: true },
},
lists: {},
requests: {},
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.