code stringlengths 2 1.05M |
|---|
var chai = require('chai');
var assert = chai.assert;
var mockery = require('mockery');
var sinon = require('sinon');
var travelScraperTestModule = '../../../server/webscrapers/travelScraper';
var lonelyPlanetUrl = "http://www.lonelyplanet.com";
var cheerioModuleStub = { load: function(){ } };
var cheerioDollarStub;
var cheerioDomManipulatorStub = { text: function(){},
attr: function(){}
}
describe('travel scraper', function() {
beforeEach(function(){
callbackStub = sinon.stub();
cheerioDollarStub = sinon.stub();
cheerioDollarStub.returns(cheerioDomManipulatorStub);
// stub all of the methods which allow movement between html nodes
cheerioTextMethodStub = sinon.stub(cheerioDomManipulatorStub, 'text');
cheerioAttrMethodStub = sinon.stub(cheerioDomManipulatorStub, 'attr');
requestModuleStub = sinon.stub();
error = null;
response = null;
html = "<p></p>"
// requestModuleStub.withArgs(imdbUrl+"/country/").yields(error, response, html);
// return the cheerio $ from load method
cheerioLoadSpy = sinon.stub(cheerioModuleStub, "load");
cheerioLoadSpy.returns(cheerioDollarStub);
mockery.registerAllowable(travelScraperTestModule);
// set up mocks for the 'required' modules using mockery
mockery.registerMock("request", requestModuleStub);
mockery.registerMock("cheerio", cheerioModuleStub);
mockery.enable({
useCleanCache: true,
warnOnUnregistered: false
});
});
afterEach(function(){
mockery.disable();
mockery.deregisterAll();
requestModuleStub.reset();
cheerioLoadSpy.restore();
cheerioTextMethodStub.restore();
cheerioAttrMethodStub.restore();
});
after(function(){
mockery.disable();
mockery.deregisterAll();
});
it("should request the sights page for the country", function(){
var travelScraper = require(travelScraperTestModule);
var dR = "dominican republic";
var dRNoSpace = "dominican-republic";
// when
travelScraper(dR, callbackStub);
// then
assert(requestModuleStub.calledWith(lonelyPlanetUrl+'/'+dRNoSpace+"/sights"), "the correct url should be used in request");
});
it("should setup cheerio", function(){
var travelScraper = require(travelScraperTestModule);
requestModuleStub.yields(error, response, html);
travelScraper("dominican republic", callbackStub);
assert(cheerioLoadSpy.called, "load method must be called to setup cheerio");
});
it("should populate the callback object with the correct values", function(){
var travelScraper = require(travelScraperTestModule);
requestModuleStub.yields(error, response, html);
// given
cheerioDollarStub.withArgs('article', cheerioDomManipulatorStub).returns(['1st article']);
var articleId = '123fg';
cheerioAttrMethodStub.withArgs('href').returns(articleId);
var imgUrl = "www.travel-image.com/sight.jpg";
cheerioAttrMethodStub.withArgs('src').returns(imgUrl);
var category = "Art";
cheerioTextMethodStub.onCall(0).returns(category);
var sightName = "Tate Modern";
cheerioTextMethodStub.onCall(1).returns(sightName);
var sightDescription = "Modern art gallery";
cheerioTextMethodStub.onCall(2).returns(sightDescription);
// when
travelScraper("", callbackStub);
// then callback should return object
assert(callbackStub.calledWithMatch({url: lonelyPlanetUrl+articleId}), "should append recipe onto url");
assert(callbackStub.calledWithMatch({img: imgUrl}), "should have correct image link");
assert(callbackStub.calledWithMatch({travelCategory: category}), "should have correct category");
assert(callbackStub.calledWithMatch({sightName: sightName}), "sight should have correct name");
assert(callbackStub.calledWithMatch({sightDescription: sightDescription}), "sight should have correct description");
});
}) |
'use strict';
var Hoek = require('hoek');
// Declare internals
var internals = {};
internals.defaults = {};
exports = module.exports = internals.Connection = function(options) {
Hoek.assert(this.constructor === internals.Connection, 'No-op cache client must be instantiated using new');
this.settings = Hoek.applyToDefaults(internals.defaults, options);
this.ready = false;
return this;
};
internals.Connection.prototype.start = function(callback) {
var self = this;
self.ready = true;
return callback();
};
internals.Connection.prototype.stop = function() {
this.ready = false;
};
internals.Connection.prototype.isReady = function() {
return this.ready;
};
internals.Connection.prototype.validateSegmentName = function(name) {
return null;
};
internals.Connection.prototype.get = function(key, callback) {
return callback(null);
};
internals.Connection.prototype.set = function(key, value, ttl, callback) {
return callback(null);
};
internals.Connection.prototype.drop = function(key, callback) {
return callback();
};
|
import { isCompanionAd } from './companion_ad';
import { isCreativeLinear } from './creative/creative_linear';
import { EventEmitter } from './util/event_emitter';
import { isNonLinearAd } from './non_linear_ad';
import { util } from './util/util';
/**
* The default skip delay used in case a custom one is not provided
* @constant
* @type {Number}
*/
const DEFAULT_SKIP_DELAY = -1;
/**
* This class provides methods to track an ad execution.
*
* @export
* @class VASTTracker
* @extends EventEmitter
*/
export class VASTTracker extends EventEmitter {
/**
* Creates an instance of VASTTracker.
*
* @param {VASTClient} client - An instance of VASTClient that can be updated by the tracker. [optional]
* @param {Ad} ad - The ad to track.
* @param {Creative} creative - The creative to track.
* @param {Object} [variation=null] - An optional variation of the creative.
* @constructor
*/
constructor(client, ad, creative, variation = null) {
super();
this.ad = ad;
this.creative = creative;
this.variation = variation;
this.muted = false;
this.impressed = false;
this.skippable = false;
this.trackingEvents = {};
// We need to keep the last percentage of the tracker in order to
// calculate to trigger the events when the VAST duration is short
this.lastPercentage = 0;
this._alreadyTriggeredQuartiles = {};
// Tracker listeners should be notified with some events
// no matter if there is a tracking URL or not
this.emitAlwaysEvents = [
'creativeView',
'start',
'firstQuartile',
'midpoint',
'thirdQuartile',
'complete',
'resume',
'pause',
'rewind',
'skip',
'closeLinear',
'close',
];
// Duplicate the creative's trackingEvents property so we can alter it
for (const eventName in this.creative.trackingEvents) {
const events = this.creative.trackingEvents[eventName];
this.trackingEvents[eventName] = events.slice(0);
}
// Nonlinear and companion creatives provide some tracking information at a variation level
// While linear creatives provided that at a creative level. That's why we need to
// differentiate how we retrieve some tracking information.
if (isCreativeLinear(this.creative)) {
this._initLinearTracking();
} else {
this._initVariationTracking();
}
// If the tracker is associated with a client we add a listener to the start event
// to update the lastSuccessfulAd property.
if (client) {
this.on('start', () => {
client.lastSuccessfulAd = Date.now();
});
}
}
/**
* Init the custom tracking options for linear creatives.
*
* @return {void}
*/
_initLinearTracking() {
this.linear = true;
this.skipDelay = this.creative.skipDelay;
this.setDuration(this.creative.duration);
this.clickThroughURLTemplate = this.creative.videoClickThroughURLTemplate;
this.clickTrackingURLTemplates =
this.creative.videoClickTrackingURLTemplates;
}
/**
* Init the custom tracking options for nonlinear and companion creatives.
* These options are provided in the variation Object.
*
* @return {void}
*/
_initVariationTracking() {
this.linear = false;
this.skipDelay = DEFAULT_SKIP_DELAY;
// If no variation has been provided there's nothing else to set
if (!this.variation) {
return;
}
// Duplicate the variation's trackingEvents property so we can alter it
for (const eventName in this.variation.trackingEvents) {
const events = this.variation.trackingEvents[eventName];
// If for the given eventName we already had some trackingEvents provided by the creative
// we want to keep both the creative trackingEvents and the variation ones
if (this.trackingEvents[eventName]) {
this.trackingEvents[eventName] = this.trackingEvents[eventName].concat(
events.slice(0)
);
} else {
this.trackingEvents[eventName] = events.slice(0);
}
}
if (isNonLinearAd(this.variation)) {
this.clickThroughURLTemplate =
this.variation.nonlinearClickThroughURLTemplate;
this.clickTrackingURLTemplates =
this.variation.nonlinearClickTrackingURLTemplates;
this.setDuration(this.variation.minSuggestedDuration);
} else if (isCompanionAd(this.variation)) {
this.clickThroughURLTemplate =
this.variation.companionClickThroughURLTemplate;
this.clickTrackingURLTemplates =
this.variation.companionClickTrackingURLTemplates;
}
}
/**
* Sets the duration of the ad and updates the quartiles based on that.
*
* @param {Number} duration - The duration of the ad.
*/
setDuration(duration) {
this.assetDuration = duration;
// beware of key names, theses are also used as event names
this.quartiles = {
firstQuartile: Math.round(25 * this.assetDuration) / 100,
midpoint: Math.round(50 * this.assetDuration) / 100,
thirdQuartile: Math.round(75 * this.assetDuration) / 100,
};
}
/**
* Sets the duration of the ad and updates the quartiles based on that.
* This is required for tracking time related events.
*
* @param {Number} progress - Current playback time in seconds.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#start
* @emits VASTTracker#skip-countdown
* @emits VASTTracker#progress-[0-100]%
* @emits VASTTracker#progress-[currentTime]
* @emits VASTTracker#rewind
* @emits VASTTracker#firstQuartile
* @emits VASTTracker#midpoint
* @emits VASTTracker#thirdQuartile
*/
setProgress(progress, macros = {}) {
const skipDelay = this.skipDelay || DEFAULT_SKIP_DELAY;
if (skipDelay !== -1 && !this.skippable) {
if (skipDelay > progress) {
this.emit('skip-countdown', skipDelay - progress);
} else {
this.skippable = true;
this.emit('skip-countdown', 0);
}
}
if (this.assetDuration > 0) {
const percent = Math.round((progress / this.assetDuration) * 100);
const events = [];
if (progress > 0) {
events.push('start');
for (let i = this.lastPercentage; i < percent; i++) {
events.push(`progress-${i + 1}%`);
}
events.push(`progress-${Math.round(progress)}`);
for (const quartile in this.quartiles) {
if (
this.isQuartileReached(quartile, this.quartiles[quartile], progress)
) {
events.push(quartile);
this._alreadyTriggeredQuartiles[quartile] = true;
}
}
this.lastPercentage = percent;
}
events.forEach((eventName) => {
this.track(eventName, { macros, once: true });
});
if (progress < this.progress) {
this.track('rewind', { macros });
}
}
this.progress = progress;
}
/**
* Checks if a quartile has been reached without have being triggered already.
*
* @param {String} quartile - Quartile name
* @param {Number} time - Time offset, when this quartile is reached in seconds.
* @param {Number} progress - Current progress of the ads in seconds.
*
* @return {Boolean}
*/
isQuartileReached(quartile, time, progress) {
let quartileReached = false;
// if quartile time already reached and never triggered
if (time <= progress && !this._alreadyTriggeredQuartiles[quartile]) {
quartileReached = true;
}
return quartileReached;
}
/**
* Updates the mute state and calls the mute/unmute tracking URLs.
*
* @param {Boolean} muted - Indicates if the video is muted or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#mute
* @emits VASTTracker#unmute
*/
setMuted(muted, macros = {}) {
if (this.muted !== muted) {
this.track(muted ? 'mute' : 'unmute', { macros });
}
this.muted = muted;
}
/**
* Update the pause state and call the resume/pause tracking URLs.
*
* @param {Boolean} paused - Indicates if the video is paused or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#pause
* @emits VASTTracker#resume
*/
setPaused(paused, macros = {}) {
if (this.paused !== paused) {
this.track(paused ? 'pause' : 'resume', { macros });
}
this.paused = paused;
}
/**
* Updates the fullscreen state and calls the fullscreen tracking URLs.
*
* @param {Boolean} fullscreen - Indicates if the video is in fulscreen mode or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#fullscreen
* @emits VASTTracker#exitFullscreen
*/
setFullscreen(fullscreen, macros = {}) {
if (this.fullscreen !== fullscreen) {
this.track(fullscreen ? 'fullscreen' : 'exitFullscreen', { macros });
}
this.fullscreen = fullscreen;
}
/**
* Updates the expand state and calls the expand/collapse tracking URLs.
*
* @param {Boolean} expanded - Indicates if the video is expanded or not.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#expand
* @emits VASTTracker#playerExpand
* @emits VASTTracker#collapse
* @emits VASTTracker#playerCollapse
*/
setExpand(expanded, macros = {}) {
if (this.expanded !== expanded) {
this.track(expanded ? 'expand' : 'collapse', { macros });
this.track(expanded ? 'playerExpand' : 'playerCollapse', { macros });
}
this.expanded = expanded;
}
/**
* Must be called if you want to overwrite the <Linear> Skipoffset value.
* This will init the skip countdown duration. Then, every time setProgress() is called,
* it will decrease the countdown and emit a skip-countdown event with the remaining time.
* Do not call this method if you want to keep the original Skipoffset value.
*
* @param {Number} duration - The time in seconds until the skip button is displayed.
*/
setSkipDelay(duration) {
if (typeof duration === 'number') {
this.skipDelay = duration;
}
}
/**
* Tracks an impression (can be called only once).
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#creativeView
*/
trackImpression(macros = {}) {
if (!this.impressed) {
this.impressed = true;
this.trackURLs(this.ad.impressionURLTemplates, macros);
this.track('creativeView', { macros });
}
}
/**
* Send a request to the URI provided by the VAST <Error> element.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code.
*/
error(macros = {}, isCustomCode = false) {
this.trackURLs(this.ad.errorURLTemplates, macros, { isCustomCode });
}
/**
* Send a request to the URI provided by the VAST <Error> element.
* If an [ERRORCODE] macro is included, it will be substitute with errorCode.
* @deprecated
* @param {String} errorCode - Replaces [ERRORCODE] macro. [ERRORCODE] values are listed in the VAST specification.
* @param {Boolean} [isCustomCode=false] - Flag to allow custom values on error code.
*/
errorWithCode(errorCode, isCustomCode = false) {
this.error({ ERRORCODE: errorCode }, isCustomCode);
//eslint-disable-next-line
console.log(
'The method errorWithCode is deprecated, please use vast tracker error method instead'
);
}
/**
* Must be called when the user watched the linear creative until its end.
* Calls the complete tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#complete
*/
complete(macros = {}) {
this.track('complete', { macros });
}
/**
* Must be called if the ad was not and will not be played
* This is a terminal event; no other tracking events should be sent when this is used.
* Calls the notUsed tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#notUsed
*/
notUsed(macros = {}) {
this.track('notUsed', { macros });
this.trackingEvents = [];
}
/**
* An optional metric that can capture all other user interactions
* under one metric such as hover-overs, or custom clicks. It should NOT replace
* clickthrough events or other existing events like mute, unmute, pause, etc.
* Calls the otherAdInteraction tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#otherAdInteraction
*/
otherAdInteraction(macros = {}) {
this.track('otherAdInteraction', { macros });
}
/**
* Must be called if the user clicked or otherwise activated a control used to
* pause streaming content,* which either expands the ad within the player’s
* viewable area or “takes-over” the streaming content area by launching
* additional portion of the ad.
* Calls the acceptInvitation tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#acceptInvitation
*/
acceptInvitation(macros = {}) {
this.track('acceptInvitation', { macros });
}
/**
* Must be called if user activated a control to expand the creative.
* Calls the adExpand tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#adExpand
*/
adExpand(macros = {}) {
this.track('adExpand', { macros });
}
/**
* Must be called when the user activated a control to reduce the creative to its original dimensions.
* Calls the adCollapse tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#adCollapse
*/
adCollapse(macros = {}) {
this.track('adCollapse', { macros });
}
/**
* Must be called if the user clicked or otherwise activated a control used to minimize the ad.
* Calls the minimize tracking URLs.
*
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#minimize
*/
minimize(macros = {}) {
this.track('minimize', { macros });
}
/**
* Must be called if the player did not or was not able to execute the provided
* verification code.The [REASON] macro must be filled with reason code
* Calls the verificationNotExecuted tracking URL of associated verification vendor.
*
* @param {String} vendor - An identifier for the verification vendor. The recommended format is [domain]-[useCase], to avoid name collisions. For example, "company.com-omid".
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#verificationNotExecuted
*/
verificationNotExecuted(vendor, macros = {}) {
if (
!this.ad ||
!this.ad.adVerifications ||
!this.ad.adVerifications.length
) {
throw new Error('No adVerifications provided');
}
if (!vendor) {
throw new Error(
'No vendor provided, unable to find associated verificationNotExecuted'
);
}
const vendorVerification = this.ad.adVerifications.find(
(verifications) => verifications.vendor === vendor
);
if (!vendorVerification) {
throw new Error(
`No associated verification element found for vendor: ${vendor}`
);
}
const vendorTracking = vendorVerification.trackingEvents;
if (vendorTracking && vendorTracking.verificationNotExecuted) {
const verifsNotExecuted = vendorTracking.verificationNotExecuted;
this.trackURLs(verifsNotExecuted, macros);
this.emit('verificationNotExecuted', {
trackingURLTemplates: verifsNotExecuted,
});
}
}
/**
* The time that the initial ad is displayed. This time is based on
* the time between the impression and either the completed length of display based
* on the agreement between transactional parties or a close, minimize, or accept
* invitation event.
* The time will be passed using [ADPLAYHEAD] macros for VAST 4.1
* Calls the overlayViewDuration tracking URLs.
*
* @param {String} duration - The time that the initial ad is displayed.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#overlayViewDuration
*/
overlayViewDuration(duration, macros = {}) {
macros['ADPLAYHEAD'] = duration;
this.track('overlayViewDuration', { macros });
}
/**
* Must be called when the player or the window is closed during the ad.
* Calls the `closeLinear` (in VAST 3.0 and 4.1) and `close` tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#closeLinear
* @emits VASTTracker#close
*/
close(macros = {}) {
this.track(this.linear ? 'closeLinear' : 'close', { macros });
}
/**
* Must be called when the skip button is clicked. Calls the skip tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#skip
*/
skip(macros = {}) {
this.track('skip', { macros });
}
/**
* Must be called then loaded and buffered the creative’s media and assets either fully
* or to the extent that it is ready to play the media
* Calls the loaded tracking URLs.
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
*
* @emits VASTTracker#loaded
*/
load(macros = {}) {
this.track('loaded', { macros });
}
/**
* Must be called when the user clicks on the creative.
* It calls the tracking URLs and emits a 'clickthrough' event with the resolved
* clickthrough URL when done.
*
* @param {String} [fallbackClickThroughURL=null] - an optional clickThroughURL template that could be used as a fallback
* @param {Object} [macros={}] - An optional Object containing macros and their values to be used and replaced in the tracking calls.
* @emits VASTTracker#clickthrough
*/
click(fallbackClickThroughURL = null, macros = {}) {
if (
this.clickTrackingURLTemplates &&
this.clickTrackingURLTemplates.length
) {
this.trackURLs(this.clickTrackingURLTemplates, macros);
}
// Use the provided fallbackClickThroughURL as a fallback
const clickThroughURLTemplate =
this.clickThroughURLTemplate || fallbackClickThroughURL;
// clone second usage of macros, which get mutated inside resolveURLTemplates
const clonedMacros = { ...macros };
if (clickThroughURLTemplate) {
if (this.progress) {
clonedMacros['ADPLAYHEAD'] = this.progressFormatted();
}
const clickThroughURL = util.resolveURLTemplates(
[clickThroughURLTemplate],
clonedMacros
)[0];
this.emit('clickthrough', clickThroughURL);
}
}
/**
* Calls the tracking URLs for the given eventName and emits the event.
*
* @param {String} eventName - The name of the event.
* @param {Object} [macros={}] - An optional Object of parameters(vast macros) to be used in the tracking calls.
* @param {Boolean} [once=false] - Boolean to define if the event has to be tracked only once.
*
*/
track(eventName, { macros = {}, once = false } = {}) {
// closeLinear event was introduced in VAST 3.0
// Fallback to vast 2.0 close event if necessary
if (
eventName === 'closeLinear' &&
!this.trackingEvents[eventName] &&
this.trackingEvents['close']
) {
eventName = 'close';
}
const trackingURLTemplates = this.trackingEvents[eventName];
const isAlwaysEmitEvent = this.emitAlwaysEvents.indexOf(eventName) > -1;
if (trackingURLTemplates) {
this.emit(eventName, { trackingURLTemplates });
this.trackURLs(trackingURLTemplates, macros);
} else if (isAlwaysEmitEvent) {
this.emit(eventName, null);
}
if (once) {
delete this.trackingEvents[eventName];
if (isAlwaysEmitEvent) {
this.emitAlwaysEvents.splice(
this.emitAlwaysEvents.indexOf(eventName),
1
);
}
}
}
/**
* Calls the tracking urls templates with the given macros .
*
* @param {Array} URLTemplates - An array of tracking url templates.
* @param {Object} [macros ={}] - An optional Object of parameters to be used in the tracking calls.
* @param {Object} [options={}] - An optional Object of options to be used in the tracking calls.
*/
trackURLs(URLTemplates, macros = {}, options = {}) {
//Avoid mutating the object received in parameters.
const givenMacros = { ...macros };
if (this.linear) {
if (
this.creative &&
this.creative.mediaFiles &&
this.creative.mediaFiles[0] &&
this.creative.mediaFiles[0].fileURL
) {
givenMacros['ASSETURI'] = this.creative.mediaFiles[0].fileURL;
}
if (this.progress) {
givenMacros['ADPLAYHEAD'] = this.progressFormatted();
}
}
if (this.creative?.universalAdIds?.length) {
givenMacros['UNIVERSALADID'] = this.creative.universalAdIds
.map((universalAdId) =>
universalAdId.idRegistry.concat(' ', universalAdId.value)
)
.join(',');
}
if (this.ad) {
if (this.ad.sequence) {
givenMacros['PODSEQUENCE'] = this.ad.sequence;
}
if (this.ad.adType) {
givenMacros['ADTYPE'] = this.ad.adType;
}
if (this.ad.adServingId) {
givenMacros['ADSERVINGID'] = this.ad.adServingId;
}
if (this.ad.categories && this.ad.categories.length) {
givenMacros['ADCATEGORIES'] = this.ad.categories
.map((category) => category.value)
.join(',');
}
if (this.ad.blockedAdCategories && this.ad.blockedAdCategories.length) {
givenMacros['BLOCKEDADCATEGORIES'] = this.ad.blockedAdCategories;
}
}
util.track(URLTemplates, givenMacros, options);
}
/**
* Formats time in seconds to VAST timecode (e.g. 00:00:10.000)
*
* @param {Number} timeInSeconds - Number in seconds
* @return {String}
*/
convertToTimecode(timeInSeconds) {
const progress = timeInSeconds * 1000;
const hours = Math.floor(progress / (60 * 60 * 1000));
const minutes = Math.floor((progress / (60 * 1000)) % 60);
const seconds = Math.floor((progress / 1000) % 60);
const milliseconds = Math.floor(progress % 1000);
return `${util.leftpad(hours, 2)}:${util.leftpad(
minutes,
2
)}:${util.leftpad(seconds, 2)}.${util.leftpad(milliseconds, 3)}`;
}
/**
* Formats time progress in a readable string.
*
* @return {String}
*/
progressFormatted() {
return this.convertToTimecode(this.progress);
}
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M22 6H12l-2-2H2v16h20V6zm-9 7v4h-2v-4H8l4.01-4L16 13h-3z" />
, 'DriveFolderUploadSharp');
|
import types from '../constants/actionTypes'
const initialState = {
isNavDrawerOpen: false,
snack: null,
}
export default function global(state = initialState, action) {
switch (action.type) {
case types.OPEN_NAVIGATION_DRAWER:
return {
...state,
isNavDrawerOpen: true,
}
case types.CLOSE_NAVIGATION_DRAWER:
return {
...state,
isNavDrawerOpen: false,
}
case types.READ_SUBTITLE_FAILED:
return {
...state,
snack: 'A feliratfájl felolvasása meghiúsult.',
}
case types.PARSE_SUBTITLE_FAILED:
return {
...state,
snack: 'A feliratfájl feldolgozása meghiúsult.',
}
case types.DELETE_SNACK:
return {
...state,
snack: null,
}
default:
return state
}
}
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import startApp from '../../helpers/start-app';
import hbs from 'htmlbars-inline-precompile';
var App;
moduleForComponent('advanced-form/simple-select', {
integration: true,
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
}
});
test('Renders correctly component with default values', function(assert){
this.set('countryList', ["Poland", "United Kingdom"]);
this.render(
hbs`{{advanced-form/simple-select list=countryList}}`
);
assert.equal(this.$('.select > ul > li > a').text(), '--------', 'Selected starts as --------');
});
test('Can change country', function(assert) {
var countryList;
countryList = ["Poland", "United Kingdom"];
this.set('countryList', countryList);
this.set('defaultValue', "United Kingdom");
this.render(
hbs`{{advanced-form/simple-select list=countryList selectedValue=defaultValue}}`
);
assert.equal(this.$('.select > ul > li > a').text(), 'United Kingdom', 'set correct default user setting');
click(this.$('.select'));
andThen(function(){
assert.equal(this.$('.select').hasClass('active'), true, "List opened");
});
click(this.$('.select > ul > li > ul > li:nth-child(1) > a'));
andThen(function(){
assert.equal(this.$('.select > ul > li > a').text(), 'Poland', 'Change selected country after click');
assert.equal(this.$('.select').hasClass('active'), false, "List closed");
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:d53a6e874df25ed2040564e60e6f16986b67feb1c62169e6bfa79a7867e35d2a
size 119661
|
const nodemailer = require('nodemailer'),
credentials = require('./credentials/Credentials'),
logger = require('./logger')
const EmailManager = {
// formatting shld be done prior to this
// returns false if not sent, true if sent
sendEmail: (subject, messageObject, formatter, callback) => {
const transporter = nodemailer.createTransport(credentials.email);
const emailText = formatter
? formatter(messageObject)
: messageObject;
const mailOptions = {
from: credentials.email.auth.user,
to: credentials.myEmail,
subject: subject,
text: emailText
}
logger.info(`Sending email.
Contents: ${emailText}`);
transporter.sendMail(mailOptions, callback);
},
// helper function to format email
// Schema shld be as follows:
// {
// name:
// email:
// phone:
// message:
// }
formatContactMe: message => {
const emailMessageFormatted =
'Name: ' + message.name + '\n' +
'Email: ' + message.email + '\n' +
'Phone: ' + message.phone + '\n' +
'Message: ' + message.message;
return emailMessageFormatted;
}
}
module.exports = EmailManager;
|
// export individual components
import HelloWorld from './HelloWorld';
export {
HelloWorld
};
|
/**
* validate user account
*
* Password can NOT be tested at the server side,
* since it be sent with encrypted format.
*
*/
var checkUsername = function(value) {
var regex = /^[a-z0-9]+$/i;
if (! regex.test(value)) {
throw new Meteor.Error(ERROR_CODE_MATCH, 'error_invalid_type');
}
};
var checkPassword = function(value) {
var regex = /^[A-Za-z0-9!@#$%^&*()_]+$/;
if (! regex.test(value)) {
throw new Meteor.Error(ERROR_CODE_MATCH, 'error_invalid_type');
}
};
var checkEmail = function(value) {
var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (! regex.test(value)) {
throw new Meteor.Error(ERROR_CODE_MATCH, 'error_invalid_type');
}
};
AccountValidator = {
schema: {
username: {
type: 'string',
required: false,
minLength: 3,
maxLength: 18,
custom: checkUsername
},
email: {
type: 'string',
required: true,
custom: checkEmail
},
password: {
type: 'string',
required: true,
minLength: 3,
maxLength: 18,
custom: checkPassword
}
},
validateInsert: function(object) {
var validator = new Validator(this.schema);
validator.validate(object, ['email', 'password']);
return validator;
},
validateInsertServer: function(object) {
var validator = new Validator(this.schema);
validator.validate(object, ['email']);
return validator;
},
validateUpdate: function(object) {
var validator = new Validator(this.schema);
validator.validate(object, ['email']);
return validator;
}
};
matchAccountUpdate = function(object) {
var validation = AccountValidator.validateUpdate(object);
return _.isEmpty(validation.errors());
};
|
const mysql = require('../utils/mysql_db.js');
const util = require('../utils');
/**
* 根据栏目分类ID查询栏目信息
*/
exports.queryCateById = function (id) {
return mysql.queryOne('select * from cms_category where id=?', [id]);
};
/**
* 根据栏目分类ID查询子栏目分类信息
*/
exports.queryChildrenCateById = function (id) {
return mysql.query('select * from cms_category where parent_id=?', [id]);
};
/**
* 根据栏目分类ID和站点ID查询
*/
exports.queryMaxSortByCateIdAndSiteId = async function (pId,siteId) {
let result = await mysql.queryOne('select max(sort) as sort from cms_category where parent_id=? and site_id=?', [pId,siteId]);
return result.sort;
};
/**
* 根据栏目分类ID删除一个栏目分类信息
*/
exports.delCateById = function (id) {
return mysql.update(`
update cms_category set del_flag='1' where id=? or parent_ids like '%${id}%'
`, [id]);
};
/**
* 递归查询分类信息
*/
exports.queryCmsCateForRecursion = async function (siteId) {
let cates = await mysql.query("select * from cms_category where del_flag='0' and site_id=? order by sort asc", [siteId]);
return util.jsonToTreeJson(cates,'0');
};
/**
* 根据站点ID和所属分类module,递归查询该
*/
exports.queryCmsCateForRecursionByModuleAndSiteId = async function (siteId,module) {
let cates = await mysql.query("select * from cms_category where del_flag='0' and site_id=? order by sort asc", [siteId]);
let cate = await mysql.queryOne("select * from cms_category where del_flag='0' and site_id=? and module=? order by sort asc", [siteId,module]);
cate.children = util.jsonToTreeJson(cates,cate.id);
return cate;
};
/**
* 插入一条栏目分类信息
*/
exports.saveCate = async function (parent_id, site_id,module,name,image,href,target,description,sort,in_menu,in_list,remarks,image_format,image_show_format,field_json,is_msg,req) {
// 取得用户信息
let user = req.session.user;
let id = util.uuid();
// 根据父亲ID查询父亲栏目信息
let parentCate = await mysql.queryOne('select * from cms_category where id =? ',[parent_id]);
if (!parentCate){
parentCate = {
id:0,
parent_ids:''
};
}
return mysql.update(`insert into cms_category(id,parent_id,parent_ids,site_id,office_id,module,name,image,href,target,description,sort,in_menu,
in_list,create_by,create_date,update_by,update_date,remarks,del_flag,image_format,image_show_format,field_json,is_msg)
values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,now(),?,now(),?,'0',?,?,?,?)`,
[id, parent_id, parentCate.parent_ids + parentCate.id + ',', site_id, user.office_id, module,name,image,href,target,
description,sort,in_menu,in_list,user.id,user.id, remarks,image_format,image_show_format,field_json,is_msg]);
};
/**
* 修改一条栏目分类信息
*/
exports.updateCate = function (req) {
// 需要修改的字符串集
let sets = '';
if (req.body.parent_id) {
sets += ",parent_id='" + req.body.parent_id + "'";
}
if (req.body.site_id) {
sets += ",site_id='" + req.body.site_id + "'";
}
if (req.body.module) {
sets += ",module='" + req.body.module + "'";
}
if (req.body.name) {
sets += ",name='" + req.body.name + "'";
}
if (req.body.image) {
sets += ",image='" + req.body.image + "'";
}
if (req.body.href) {
sets += ",href='" + req.body.href + "'";
}
if (req.body.target) {
sets += ",target='" + req.body.target + "'";
}
if (req.body.description) {
sets += ",description='" + req.body.description + "'";
}
if (req.body.keywords) {
sets += ",keywords='" + req.body.keywords + "'";
}
if (req.body.sort) {
sets += ',sort=' + req.body.sort;
}
if (req.body.in_menu) {
sets += ",in_menu='" + req.body.in_menu + "'";
}
if (req.body.in_list) {
sets += ',in_list=' + req.body.in_list;
}
if (req.body.remarks) {
sets += ",remarks='" + req.body.remarks + "'";
}
if (req.body.image_format) {
sets += ",image_format='" + req.body.image_format + "'";
}
if (req.body.image_show_format) {
sets += ",image_show_format='" + req.body.image_show_format + "'";
}
if (req.body.field_json) {
sets += ",field_json='" + req.body.field_json + "'";
}
if (req.body.is_msg) {
sets += ",is_msg='" + req.body.is_msg + "'";
}
return mysql.update('update cms_category set update_date=now() ' + sets + ' where id=' + mysql.getMysql().escape(req.body.id));
};
/**
* 根据站点ID查询该站点下的所有有效的栏目分类信息
*/
exports.queryCateBySiteId = function (siteId) {
return mysql.query(`
select * from cms_category where site_id=? and del_flag='0' order by sort asc
`,siteId);
}; |
module.exports = require("./lib/Device");
|
// Generated on 2014-12-31 using generator-angular 0.10.0
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
sass: {
src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}bower_components\//
}
},
// Compiles Sass to CSS and generates necessary files if requested
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
generatedImagesDir: '.tmp/images/generated',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: './bower_components',
httpImagesPath: '/images',
httpGeneratedImagesPath: '/images/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false,
assetCacheBuster: false,
raw: 'Sass::Script::Number.precision = 10\n'
},
dist: {
options: {
generatedImagesDir: '<%= yeoman.dist %>/images/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: ['*.js', '!oldieshim.js'],
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: '.',
src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'compass:server'
],
test: [
'compass'
],
dist: [
'compass:dist',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const autoIncrement = require('mongoose-auto-increment');
/**
* 小说章节。
*/
let chapterSchema = new Schema({
id: Number,
// 章节序号
serial: Number,
// 章节题目
title: String,
// 作者
author: String,
// 创建时间
createdAt: {
type: Date,
default: Date.now()
},
// 最后更新时间
updatedAt: Date,
// 章节内容
content: String
});
chapterSchema.plugin(autoIncrement.plugin, {
model: 'chapter',
field: 'id',
startAt: 15000,
incrementBy: 1
});
chapterSchema.pre('save', function(next) {
if (this.isNew) {
this.createdAt = this.updatedAt = Date.now()
} else {
this.updatedAt = Date.now()
}
next()
});
mongoose.model('chapter', chapterSchema);
|
var _ = require('lodash'),
utils = require('../utils');
var dataPrefix = '<tr><td><input type="checkbox" name="checkCtrl"></td>';
/**
* formats response data for client.
*/
// get the wanted fields values
function filterFields(values,fields){
var filterValues=[];
if(_.isArray(values)){
var length = values.length;
for(var i=0;i<length;i++){
if(_.isObject(values[i])){
var filterValue = utils.filters.filterObject(values[i],fields);
if(filterValue){
filterValues.push(filterValue);
}
}
}
}else if(_.isObject(values)){
filterValues = utils.filters.filterObject(values,fields);
}
return filterValues;
}
function replyWithData(values,fields){
var data = filterFields(values,fields);
if(data){
return {err:false,data:data};
}
return fail();
}
function replyWithPageData(values,fields,reqBody){
var pageNum = reqBody.currentPage;
var pageRecordsNum = reqBody.numPerPage;
var fieldLength = fields.length;
var totalPages = 0;
var tableData = "";
if(_.isArray(values)){
var length = values.length;
totalPages = (length%pageRecordsNum) == 0 ? length/pageRecordsNum :parseInt(length/pageRecordsNum)+1;
if (pageNum <= totalPages||pageNum==-1) {
var subValues;
if(pageNum == -1||pageNum==totalPages-1){
subValues = _.slice(values, (totalPages - 1) * pageRecordsNum,length);
}
else{
//截取一页的数据
subValues = _.slice(values, pageNum * pageRecordsNum, pageNum * pageRecordsNum + pageRecordsNum);
}
var filteredSubValues = filterFields(subValues, fields);
if (filteredSubValues) {
dataPrefix = reqBody.containCheckbox ? dataPrefix : "<tr>";
pageRecordsNum = pageRecordsNum<length ? pageRecordsNum:length;
for (var i = 0; i < pageRecordsNum; i++) {
tableData += dataPrefix;
for (var j = 0; j < fieldLength; j++) {
if(filteredSubValues[i][j]){
tableData += "<td>" + filteredSubValues[i][j] + "</td>";
}
else{
tableData += "<td>" + "" + "</td>";
}
}
tableData += "</tr>";
}
return {err: false, data: {tableData: tableData, totalCount: length},contentID:reqBody.contentID};
}
}
}
return {err:false,data:{tableData:'',totalCount:0}};
}
function fail(){
return {err:true};
}
module.exports = {
replyWithData:replyWithData,
replyWithPageData:replyWithPageData
};
|
import postcss from 'postcss';
const myPlugin = postcss.plugin('myPlugin', options => {
return css => {
css.walkDecls(decl => {
if (decl.prop === 'custom-background') {
decl.prop = 'background';
decl.value = decl.value.replace('💩','#7F4A1E');
const comment = postcss.comment({text: 'converted from custom-background'});
comment.moveBefore(decl);
comment.prev().remove();
}
});
};
});
export default myPlugin;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .
|
const Firebase = require('firebase');
const crypto = require('crypto');
const _ = require('lodash');
const mailer = require('./../mailer');
const config = require('./../config');
const fb = new Firebase(config.FB_DB);
const getDomainFromEmail = (email) => {
const email_string_array = email.split("@");
return '@' + email_string_array[email_string_array.length - 1];
};
const generateUniqueCode = () => {
const chars = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
const howMany = 5;
const rnd = crypto.randomBytes(howMany),
value = new Array(howMany),
len = chars.length;
for (var i = 0; i < howMany; i++) {
value[i] = chars[rnd[i] % len];
}
return value.join('');
};
const startProcess = (whiteListDomains) => {
const domains = whiteListDomains.split(';');
fb.authWithCustomToken(config.FB_MASTER_SECRET).then((authData) => {
// listen for child_added event in the users
fb.child('users').on('child_added', (snapShot) => {
// check if we have a corresponding verification entry
const uid = snapShot.val().uid;
const email = snapShot.val().email;
// verify if the supplied email/domain is in our white List
if (_.includes(domains, getDomainFromEmail(email))) {
fb.child(`meta/users/${uid}`).once('value').then((metaSnapShot) => {
// if the node does not exists then create one
if (metaSnapShot.val() === null) {
const generatedCode = generateUniqueCode();
// we ought to create it
fb.child(`meta/users/${uid}`).set({
verified: false,
code: generatedCode
}).then(() => mailer.sendEmailVerification(generatedCode, email));
}
});
} else {
// what should we do ?
console.warn(`An email ${email} that is not whiteListed was used ..`);
}
});
// listen for child_added event in code_verifier/users
fb.child('code_verifier').on('child_added', (snapShot) => {
// compare the code with the one that we sent out earlier
const supplied_code_value = snapShot.val().code;
const entryKey = snapShot.key();
fb.child(`meta/users/${entryKey}`).once('value').then((metaSnapShot) => {
const generated_code_value = metaSnapShot.val().code;
if (supplied_code_value === generated_code_value) {
// set verified to true
fb.child(`meta/users/${entryKey}`).set({
verified: true
})
.then(() => fb.child(`users/${entryKey}/verified`).set(true))
.then(() => fb.child(`users/${entryKey}/verification_in_progress`).set(false));
// destroy the code_verifier node
fb.child(`code_verifier/${entryKey}`).remove();
} else {
// destroy the code_verifier node
fb.child(`code_verifier/${entryKey}`).remove();
// set the progress to false
fb.child(`users/${entryKey}/verification_in_progress`).set(false);
}
});
});
});
};
fb.authWithCustomToken(config.FB_MASTER_SECRET).then((authData) => {
fb.child('meta/app').once('value').then((appSnapShot) => {
const requireEmailVerification = appSnapShot.val().requireEmailVerification;
if (requireEmailVerification) {
console.info('Starting the worker ...');
startProcess(appSnapShot.val().whiteListDomains);
} else {
// we do not need really need this worker
console.info('Email verification is not required !');
process.exit(0);
}
});
});
|
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("standalone.unit.controller.BaseController", {
/**
* Convenience method for accessing the router.
* @public
* @returns {sap.ui.core.routing.Router} the router for this component
*/
getRouter : function () {
return sap.ui.core.UIComponent.getRouterFor(this);
},
/**
* Convenience method for getting the view model by name.
* @public
* @param {string} [sName] the model name
* @returns {sap.ui.model.Model} the model instance
*/
getModel : function (sName) {
return this.getView().getModel(sName);
},
/**
* Convenience method for setting the view model.
* @public
* @param {sap.ui.model.Model} oModel the model instance
* @param {string} sName the model name
* @returns {sap.ui.mvc.View} the view instance
*/
setModel : function (oModel, sName) {
return this.getView().setModel(oModel, sName);
},
/**
* Getter for the resource bundle.
* @public
* @returns {sap.ui.model.resource.ResourceModel} the resourceModel of the component
*/
getResourceBundle : function () {
return this.getOwnerComponent().getModel("i18n").getResourceBundle();
},
/**
* Event handler when the share by E-Mail button has been clicked
* @public
*/
onShareEmailPress : function () {
var oViewModel = (this.getModel("objectView") || this.getModel("worklistView"));
sap.m.URLHelper.triggerEmail(
null,
oViewModel.getProperty("/shareSendEmailSubject"),
oViewModel.getProperty("/shareSendEmailMessage")
);
}
});
}
); |
describe("About Functions", function() {
it("should declare functions", function() {
function add(a, b) {
return a + b;
}
expect(add(1, 2)).toBe(3);
});
it("should know internal variables override outer variables", function () {
var message = "Outer";
function getMessage() {
return message;
}
function overrideMessage() {
var message = "Inner";
return message;
}
expect(getMessage()).toBe('Outer');
expect(overrideMessage()).toBe('Inner');
expect(message).toBe('Outer');
});
it("should have lexical scoping", function () {
var variable = "top-level";
function parentfunction() {
var variable = "local";
function childfunction() {
return variable;
}
return childfunction();
}
expect(parentfunction()).toBe("local");
});
it("should use lexical scoping to synthesise functions", function () {
///3
///5
function makeMysteryFunction(makerValue){
// 3 //10
// 5 //5
var newFunction = function doMysteriousThing(param) {
//3 + 10 = 13
//5 + 5 = 10
return makerValue + param;
};
return newFunction;
}
// passing 3 to make
var mysteryFunction3 = makeMysteryFunction(3);
// passing 5 to make
var mysteryFunction5 = makeMysteryFunction(5);
// passing 10 to doMyst // passing 5 to doMyst
expect(mysteryFunction3(10) + mysteryFunction5(5)).toBe(23);
});
it("should allow extra function arguments", function () {
function returnFirstArg(firstArg) {
return firstArg;
}
/////////////////////
expect(returnFirstArg("first", "second", "third")).toBe('first');
function returnSecondArg(firstArg, secondArg) {
return secondArg;
}
//no second argument defined
expect(returnSecondArg("only give first arg")).toBe(undefined);
//////////////////////
function returnAllArgs() {
var argsArray = [];
// i= index 0 less than the length of array ; count up
for (var i = 0; i < arguments.length; i += 1) {
// pushing arguments into each index of the array, also defining arguments[i]= value of that index
argsArray.push(arguments[i]);
}
// turning array into a string (separator is provided even though default is comma)
return argsArray.join(",");
}
// passing strings as the arguments, function called pushes into each index of argsArray
expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
});
///////////////
it("should pass functions as values", function () {
var appendRules = function (name) {
return name + " rules!";
};
var appendDoubleRules = function (name) {
return name + " totally rules!";
};
//METHOD
var praiseSinger = { givePraise: appendRules };
// targeting property of object which is a method
expect(praiseSinger.givePraise("John")).toBe("John rules!");
praiseSinger.givePraise = appendDoubleRules;
expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");
});
});
|
'use strict';
var res = require('../lib/response');
var control = require('../Controls/controller');
var util = require('../lib/util');
var fs = require("fs");
var path = require('path');
var log4js = require('../config/log');
var args,slice = Array.prototype.slice;
var middleware = {};
var router = module.exports = function(){
return util.mix(router,middleware)
}
middleware.router = function(){
args = slice.call(arguments);
res = util.extend(args[1],res);
res.set({
'Access-Control-Allow-Origin' : "*",
'Access-Control-Allow-Headers' : '*',
'X-Powered-By' : 'node/4.0.0',
'Access-Control-Allow-Methods' : 'PUT,POST,GET,DELETE,OPTIONS'
})
control.call(this,args[0],res,args[2]);
}
middleware.pageErr = function(){
var err ='File is Not Found';
log4js.logger_e.error(err);
return res.status(404).end(err);
}
middleware.serverErr = function(err){
var err = err || 'The request is invalid';
log4js.logger_e.error(err);
return res.status(500).end(err);
}
|
var AuthorSource = {
getAuthor:function(page=1,limit=10,params={}){
return new Promise(function(resolve,reject){
var url = "/api/author";
var param = {
"page": page,
"limit": limit,
"query": params
};
$.get(url, param).done(resolve).fail(reject);
})
},
updateAuthor:function(author={}){
return new Promise(function(resolve,reject){
var url = "/api/updateAuthor";
$.post(url, author).done(resolve).fail(reject);
})
}
}
export default AuthorSource; |
version https://git-lfs.github.com/spec/v1
oid sha256:8caff3f49234bae4d9109d6723197472b536f316a9299e6b96ac9b043ea37e7a
size 2785
|
version https://git-lfs.github.com/spec/v1
oid sha256:4e76245bf70b70d6a88d24e7857f76942daba172e8b9d83c5dfb9cee1d26eb09
size 962996
|
"use strict";
module.exports = function (grunt, options) {
return {
prod: { // Target
options: { // Target options
removeComments: true,
collapseWhitespace: true
},
files: [{
cwd: '<%= config.paths.build.dev_htdocs %>',
src: ['**/*.html'],
dest: '<%= config.paths.build.dev_htdocs %>',
expand: true,
ext: '.html'
}]
}
}
} |
// used as common object for all validators
export default (valid, message = '') => ({ valid, message });
|
jQuery(document).ready(function($) {
if (jQuery('#newsletter-dataTable').length > 0) {
var oTable;
// Add the events etc before DataTables hides a column
jQuery("thead input").keyup(function() {
//Filter on the column (the index) of this element
oTable.fnFilter(this.value, oTable.oApi._fnVisibleToColumnIndex(
oTable.fnSettings(), $("thead input").index(this)));
});
oTable = jQuery('#newsletter-dataTable').dataTable({
"aaSorting": []
});
}
}); |
/**
* This unit test file was auto generated via a gulp task.
* Any formatting issues can be ignored
*/
'use strict';
var _ = require('lodash'),
expect = require('must'),
lodashCollectionHelpers = require('./lodash-collection-helpers'),
bankUserInfoData = require('../test/bankUserInfo'),
userInfoData = require('../test/userInfo'),
fullNameInfoData = require('../test/fullNameInfo'),
workInfoData = require('../test/workInfo');
var helpers = lodashCollectionHelpers.getCollectionHelpers();
describe('Testing Lodash Collection Helpers as plain Object fetched via getCollectionHelpers', function() {
describe('Testing Lodash Collection Helpers in release 1.0.0', function() {
describe('Testing isCollection', function() {
it('with undefined value', function() {
expect(helpers.isCollection()).to.be(false);
});
it('with null value', function() {
expect(helpers.isCollection(null)).to.be(false);
});
it('with string value', function() {
expect(helpers.isCollection('should return false')).to.be(false);
});
it('with number value', function() {
expect(helpers.isCollection(111)).to.be(false);
});
it('with plain object value', function() {
expect(helpers.isCollection({
shouldReturnFalse: true
})).to.be(false);
});
it('with with empty array value', function() {
expect(helpers.isCollection([])).to.be(true);
});
it('with array of strings value', function() {
expect(helpers.isCollection(['should return false'])).to.be(false);
});
it('with array of numbers value', function() {
expect(helpers.isCollection([111])).to.be(false);
});
it('with array of plain objects value', function() {
expect(helpers.isCollection([{
shouldReturnTrue: true
}])).to.be(true);
});
});
describe('Testing pickAs', function() {
var workInfo;
beforeEach(function() {
workInfo = workInfoData;
});
it('With plain object and undefined source map returns empty object', function() {
var data = workInfo[0];
var selectedData = helpers.pickAs(data);
expect(_.isPlainObject(selectedData)).to.be(true);
expect(_.isEmpty(selectedData)).to.be(true);
});
it('With plain object and array source map to return what _.pick would return', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = helpers.pickAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
});
it('With String source and object source map to return String source', function() {
var data = "Invalid";
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.pickAs(data, sourceMap);
expect(_.isString(data)).to.be(true);
expect(selectedData).to.equal(data);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.pickAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = helpers.pickAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(4);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.pickAs(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(3);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
});
});
});
describe('Testing pickAllAs', function() {
var bankUserInfo,
userInfo,
fullNameInfo,
workInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = fullNameInfoData;
workInfo = workInfoData;
});
it('With plain object and undefined source map returns original object', function() {
var data = workInfo[0];
var selectedData = helpers.pickAllAs(data);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and array source map returns original object', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = helpers.pickAllAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.pickAllAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = helpers.pickAllAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(8);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.pickAllAs(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(6);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
expect(item.email).to.equal(original.email);
expect(item.phone).to.equal(original.phone);
expect(item.details.greeting).to.equal(original.details.greeting);
expect(item.details.other).to.equal(original.details.other);
});
});
});
describe('Testing select', function() {
var workInfo;
beforeEach(function() {
workInfo = workInfoData;
});
it('With plain object and undefined source map returns empty object', function() {
var data = workInfo[0];
var selectedData = helpers.select(data);
expect(_.isPlainObject(selectedData)).to.be(true);
expect(_.isEmpty(selectedData)).to.be(true);
});
it('With plain object and array source map to return what _.pick would return', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = helpers.select(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.select(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = helpers.select(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(4);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.select(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(3);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
});
});
});
describe('Testing selectAll', function() {
var workInfo;
beforeEach(function() {
workInfo = workInfoData;
});
it('With plain object and undefined source map returns original object', function() {
var data = workInfo[0];
var selectedData = helpers.selectAll(data);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and array source map returns original object', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = helpers.selectAll(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.selectAll(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = helpers.selectAll(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(8);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = helpers.selectAll(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(6);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
expect(item.email).to.equal(original.email);
expect(item.phone).to.equal(original.phone);
expect(item.details.greeting).to.equal(original.details.greeting);
expect(item.details.other).to.equal(original.details.other);
});
});
});
describe('Testing joinOn', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have nested Id attributes', function() {
var joinedCollection = helpers.leftJoin([{
ids: {
id: 1
},
value: 'Value One'
}], [{
uids: {
uid: 1
},
value: 'Value One other'
}], 'ids.id', 'uids.uid');
expect(joinedCollection[0].ids.id).to.equal(1);
expect(joinedCollection[0].uids.uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = helpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With invalid collections returns empty array', function() {
var joinedCollection = helpers.joinOn("userInfo", "fullNameInfo", 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With same named match key', function() {
var joinedCollection = helpers.joinOn(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = helpers.joinOn(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With differently named keys', function() {
var joinedCollection = helpers.joinOn(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
var joinedCollection = helpers.joinOn(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
expect(_.keys(item).length).to.equal(6);
}
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
});
describe('Testing leftJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = helpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With same named match key', function() {
var joinedCollection = helpers.leftJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = helpers.leftJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With differently named keys', function() {
var joinedCollection = helpers.leftJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
var joinedCollection = helpers.leftJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
expect(_.keys(item).length).to.equal(6);
}
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
});
describe('Testing rightJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from right side collection', function() {
var joinedCollection = helpers.rightJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One other');
});
it('With same named match key', function() {
var joinedCollection = helpers.rightJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = helpers.rightJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(_.keys(item).length).to.equal(4);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.name).to.equal(originalBankUserInfo.name);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently named keys', function() {
var joinedCollection = helpers.rightJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
var joinedCollection = helpers.rightJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(10);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
var originalUserInfo = _.find(userInfo, {
uid: item.customerId
});
if (_.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
} else {
expect(_.keys(item).length).to.equal(4);
}
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
});
describe('Testing innerJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = helpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With same named match key', function() {
var joinedCollection = helpers.innerJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = helpers.innerJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With differently named keys', function() {
var joinedCollection = helpers.innerJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
userInfo = _.takeRight(userInfo, 15);
var joinedCollection = helpers.innerJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(5);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
});
describe('Testing fullJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = helpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With invalid collections returns empty array', function() {
var joinedCollection = helpers.fullJoin('userInfo', 'fullNameInfo', 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With invalid dest collection returns empty array', function() {
var joinedCollection = helpers.fullJoin('userInfo', fullNameInfo, 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With invalid source collection returns empty array', function() {
var joinedCollection = helpers.fullJoin(userInfo, 'fullNameInfo', 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With same named match key', function() {
var joinedCollection = helpers.fullJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = helpers.fullJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(40);
_.each(joinedCollection, function(item) {
if (_.keys(item).length === 4) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else if (_.keys(item).length === 6) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
}
});
});
it('With differently named keys', function() {
var joinedCollection = helpers.fullJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo) && _.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(4);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else if (_.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
}
}
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
userInfo = _.takeRight(userInfo, 15);
var joinedCollection = helpers.fullJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo) && _.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(4);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else if (_.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
}
}
});
});
});
describe('Testing leftAntiJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('With same named match key', function() {
fullNameInfo = _.takeRight(fullNameInfo, 5);
var joinedCollection = helpers.leftAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With same named match key & should not have any data to anti join', function() {
var joinedCollection = helpers.leftAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With same named match key & all data to anti join', function() {
var joinedCollection = helpers.leftAntiJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With differently named keys', function() {
bankUserInfo = _.takeRight(bankUserInfo, 5);
var joinedCollection = helpers.leftAntiJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
});
describe('Testing rightAntiJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('With same named match key', function() {
userInfo = _.takeRight(userInfo, 5);
var joinedCollection = helpers.rightAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(2);
expect(item.uid).to.equal(originalFullNameInfo.uid);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to anti join', function() {
var joinedCollection = helpers.rightAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With same named match key & all data to anti join', function() {
var joinedCollection = helpers.rightAntiJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(4);
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.name).to.equal(originalBankUserInfo.name);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently named keys', function() {
userInfo = _.takeRight(userInfo, 5);
var joinedCollection = helpers.rightAntiJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(4);
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.name).to.equal(originalBankUserInfo.name);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
});
describe('Testing fullAntiJoin', function() {
var leftCollection,
rightCollection1,
rightCollection2,
rightCollection3,
userInfo,
fullNameInfo;
beforeEach(function() {
leftCollection = [{
uid: 1,
value: 'only on left'
}, {
uid: 2,
value: 'sharedLeft'
}];
rightCollection1 = [{
uid: 3,
value: 'only on right'
}, {
uid: 2,
value: 'sharedRight'
}];
rightCollection2 = [{
id: 3,
value: 'only on right'
}, {
id: 2,
value: 'sharedRight'
}];
rightCollection3 = [{
uid: 3,
value: 'only on right1'
}, {
uid: 4,
value: 'sharedRight2'
}];
userInfo = userInfoData;
fullNameInfo = helpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('With same named match key', function() {
var joinedCollection = helpers.fullAntiJoin(leftCollection, rightCollection1, 'uid');
expect(joinedCollection.length).to.equal(2);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(2);
if (item.uid === 1) {
expect(item.uid).to.equal(leftCollection[0].uid);
expect(item.value).to.equal(leftCollection[0].value);
} else {
expect(item.uid).to.equal(rightCollection1[0].uid);
expect(item.value).to.equal(rightCollection1[0].value);
}
});
});
it('With same named match key & should not have any data to anti join', function() {
var joinedCollection = helpers.fullAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With same named match key & all data to anti join', function() {
var joinedCollection = helpers.fullAntiJoin(leftCollection, rightCollection3, 'uid');
expect(joinedCollection.length).to.equal(4);
_.each(joinedCollection, function(item, index) {
expect(_.keys(item).length).to.equal(2);
if (item.uid === 1 || item.uid === 2) {
expect(item.uid).to.equal(leftCollection[index].uid);
expect(item.value).to.equal(leftCollection[index].value);
} else {
expect(item.uid).to.equal(rightCollection3[index - 2].uid);
expect(item.value).to.equal(rightCollection3[index - 2].value);
}
});
});
it('With differently named keys', function() {
var joinedCollection = helpers.fullAntiJoin(leftCollection, rightCollection2, 'uid', 'id');
expect(joinedCollection.length).to.equal(2);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(2);
if (item.uid === 1) {
expect(item.uid).to.equal(leftCollection[0].uid);
expect(item.value).to.equal(leftCollection[0].value);
} else {
expect(item.uid).to.equal(rightCollection2[0].uid);
expect(item.value).to.equal(rightCollection2[0].value);
}
});
});
});
});
describe('Testing Lodash Collection Helpers in release 1.1.0', function() {
describe('Testing indexBy', function() {
var collection;
beforeEach(function() {
collection = _.map(_.range(4), function(value) {
return {
uid: value,
test: 'test ' + value,
static: 'static-value',
data: {
list: _.range(value * 2)
}
};
});
});
it('Call with non-collection returns an empty plain Object', function() {
var indexedCollection = helpers.indexBy('non collection', 'uid');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(true);
});
it('Call with missing iteree returns indexed on collection index number', function() {
var indexedCollection = helpers.indexBy(collection);
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = collection[_.parseInt(uidKey)];
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Non-String Index value returns indexed on collection index number', function() {
var indexedCollection = helpers.indexBy(collection, 'data.list');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = collection[_.parseInt(uidKey)];
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Index by uid string key', function() {
var indexedCollection = helpers.indexBy(collection, 'uid');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = _.find(collection, {
uid: _.parseInt(uidKey)
});
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Index by function', function() {
var indexedCollection = helpers.indexBy(collection, function(item) {
return _.get(item, 'uid');
});
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = _.find(collection, {
uid: _.parseInt(uidKey)
});
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Index by static value', function() {
var indexedCollection = helpers.indexBy(collection, 'static');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, key) {
var originalItem = _.find(collection, {
uid: _.parseInt(item.uid)
});
var expectedKey = 'static-value';
if (item.uid > 0) {
expectedKey = expectedKey + '(' + item.uid + ')';
}
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem) && expectedKey === key;
})).to.be(true);
});
});
describe('Testing uniqify', function() {
var collection;
beforeEach(function() {
collection = _.map(_.range(4), function(value) {
return {
test: 'test ' + value,
static: 'static-value',
data: {
list: _.range(value * 2)
}
};
});
});
it('Call with non-collection returns original input value', function() {
var uniqifiedCollection = helpers.uniqify('non collection');
expect(_.isString(uniqifiedCollection)).to.be(true);
expect(uniqifiedCollection).to.equal('non collection');
});
it('Base uniqification', function() {
var idKey = 'uuid';
var uniqifiedCollection = helpers.uniqify(collection);
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with "" id key', function() {
var idKey = 'uuid';
var uniqifiedCollection = helpers.uniqify(collection, "");
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with null id key', function() {
var idKey = 'uuid';
var uniqifiedCollection = helpers.uniqify(collection, null);
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with non-string id key', function() {
var idKey = 'uuid';
var uniqifiedCollection = helpers.uniqify(collection, {
test: 'test'
});
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined id key', function() {
var idKey = 'uid';
var uniqifiedCollection = helpers.uniqify(collection, idKey);
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined function', function() {
var idKey = 'uid';
var uniqifiedCollection = helpers.uniqify(collection, idKey, function(item) {
return _.get(item, 'test');
});
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined function that returns static value', function() {
var idKey = 'uid';
var uniqifiedCollection = helpers.uniqify(collection, idKey, function(item) {
return _.get(item, 'static');
});
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined function that returns non-string value', function() {
var idKey = 'uid';
var uniqifiedCollection = helpers.uniqify(collection, idKey, function(item) {
return _.get(item, 'data.list');
});
expect(helpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
});
});
}); |
(function (window, factory) {
if (typeof define === 'function' && define.amd) {
define(['angular'], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('angular'));
} else {
window.ngRequiredParams = factory(window.angular);
}
}(window, (angular) => {
return angular.module('ng-required-params', [])
.factory('ngRequired', () => {
return (param) => {
throw new Error(`Missing required parameter: ${param}`);
};
});
}));
|
const Realtime = require('../src/realtime')
const assert = require('assert')
describe('push', () => {
describe('registerWatch', () => {
it('should return the appropriate object containing the URL array and custom callback', () => {
let watchObj = Realtime.push.registerWatch('watch me!', ['url1', 'url2'], () => { console.log('hello world!') })
assert.deepEqual(['url1', 'url2'], watchObj.pushUrls)
assert.equal('() => { console.log(\'hello world!\') }', watchObj.customCb)
})
it('should return errors when incompatible types are passed to the function', () => {
let watchObj = Realtime.push.registerWatch(['array'], ['string'], () => { console.log('hello world!') })
assert.equal('TypeError', watchObj.name)
assert.equal('Incompatible type: string for array - param: 1', watchObj.message)
watchObj = Realtime.push.registerWatch('watch me!', 'string', () => { console.log('hello world!') })
assert.equal('TypeError', watchObj.name)
assert.equal('Incompatible type: array for string - param: 2', watchObj.message)
watchObj = Realtime.push.registerWatch('watch me!', [1], () => { console.log('hello world!') })
assert.equal('TypeError', watchObj.name)
assert.equal('Incompatible type: string for 1 - param: 2', watchObj.message)
watchObj = Realtime.push.registerWatch('watch me!', ['string'], 'string')
assert.equal('TypeError', watchObj.name)
assert.equal('Incompatible type: function for string - param: 3', watchObj.message)
})
})
describe('addWatchUrls', () => {
})
describe('removeWatchUrls', () => {
})
describe('replaceWatchFn', () => {
})
}) |
import IssuableFilteredSearchTokenKeys from 'ee_else_ce/filtered_search/issuable_filtered_search_token_keys';
import initIssuablesList from '~/issuables_list';
import projectSelect from '~/project_select';
import initFilteredSearch from '~/pages/search/init_filtered_search';
import issuableInitBulkUpdateSidebar from '~/issuable_init_bulk_update_sidebar';
import { FILTERED_SEARCH } from '~/pages/constants';
import initManualOrdering from '~/manual_ordering';
const ISSUE_BULK_UPDATE_PREFIX = 'issue_';
document.addEventListener('DOMContentLoaded', () => {
IssuableFilteredSearchTokenKeys.addExtraTokensForIssues();
issuableInitBulkUpdateSidebar.init(ISSUE_BULK_UPDATE_PREFIX);
initIssuablesList();
initFilteredSearch({
page: FILTERED_SEARCH.ISSUES,
isGroupDecendent: true,
useDefaultState: true,
filteredSearchTokenKeys: IssuableFilteredSearchTokenKeys,
});
projectSelect();
initManualOrdering();
});
|
import { createAction } from 'bouchon';
/**
* Actions
*/
const actions = {
get: createAction(),
};
/**
* Selectors
*/
export const selectors = {};
selectors.authors = () => state => state.library.paris.authors;
/**
* Specs
*/
export default {
name: 'authors',
endpoint: 'authors',
data: require('./data.json'),
reducer: {
[actions.get]: state => state,
},
routes: {
'GET /': {
action: actions.get,
selector: selectors.authors,
status: 200,
},
},
};
|
/*
* Copyright (c) 2008-2011 Hasso Plattner Institute
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
module('lively.ast.Interpreter').requires('lively.ast.Parser', 'lively.ast.Rewriting').toRun(function() {
Object.subclass('lively.ast.Interpreter.Frame',
'initialization', {
initialize: function(func, mapping) {
this.func = func;
this.mapping = mapping || {};
this.returnTriggered = false;
this.breakTriggered = false;
this.continueTriggered = false;
this.findSetterMode = false;
this.breakAtCalls = false;
this.pc = null; // "program counter", actually an AST node
this.bp = null; // "break point", actually an AST node
this.values = {}; // stores the results of computed expressions and statements
},
newScope: function(func, mapping) {
var newFrame = new lively.ast.Interpreter.Frame(func, mapping);
newFrame.setContainingScope(this);
return newFrame;
},
breakAtFirstStatement: function() {
this.bp = this.func.ast().firstStatement();
}
},
'accessing', {
setContainingScope: function(frame) {
return this.containingScope = frame;
},
getContainingScope: function() {
return this.containingScope;
},
getCaller: function() {
return this.caller;
},
setCaller: function(caller) {
if (!caller) return;
this.caller = caller;
caller.callee = this;
if (caller.breakAtCalls) this.breakAtFirstStatement();
},
setThis: function(thisObj) {
this.addToMapping('this', thisObj);
return thisObj;
},
getThis: function() {
return this.mapping["this"] ? this.mapping["this"] : Global;
},
setArguments: function(argValues) {
var argNames = this.func.ast().argNames();
for (var i = 0; i < argNames.length; i++) {
this.addToMapping(argNames[i], argValues[i]);
}
return this.arguments = argValues;
},
getArguments: function(args) {
return this.arguments;
},
getFuncName: function() {
return this.func ?
this.func.getOriginal().qualifiedMethodName() :
'frame has no function!';
},
getFuncSource: function() {
return this.func ?
this.func.getOriginal().toSource() :
'frame has no function!';
},
findFrame: function(name) {
if (this.mapping.hasOwnProperty(name)) {
return {val: this.mapping[name], frame: this};
}
if (this.mapping === Global) { // reached global scope
throw new ReferenceError(name + " is not defined");
}
// lookup in my current function
var mapping = this.func.getVarMapping();
if (mapping) {
if (mapping.hasOwnProperty(name)) {
return {val: mapping[name], frame: this};
}
}
var containingScope = this.getContainingScope();
return containingScope ? containingScope.findFrame(name) : null;
},
lookup: function(name) {
if (name === 'undefined') return undefined;
if (name === 'null') return null;
if (name === 'true') return true;
if (name === 'false') return false;
if (name === 'NaN') return NaN;
if (name === 'arguments') return this.getArguments();
var frame = this.findFrame(name);
if (frame) return frame.val;
return undefined;
},
addToMapping: function(name, value) {
return this.mapping[name] = value;
},
addAllToMapping: function(otherMapping) {
for (var name in otherMapping) {
if (!otherMapping.hasOwnProperty(name)) continue;
this.mapping[name] = otherMapping[name];
}
},
triggerReturn: function() {
this.returnTriggered = true
},
triggerBreak: function() {
this.breakTriggered = true
},
stopBreak: function() {
this.breakTriggered = false
},
triggerContinue: function() {
this.continueTriggered = true
},
stopContinue: function() {
this.continueTriggered = false
}
},
'accessing for UI', {
listItemsForIntrospection: function() {
var items = Properties.forEachOwn(this.mapping, function(name, value) {
return {
isListItem: true,
string: name + ': ' + String(value).truncate(50),
value: value
};
});
if (this.containingScope) {
items.push({isListItem: true, string: '[[containing scope]]'});
items.pushAll(this.containingScope.listItemsForIntrospection());
}
return items;
}
},
'program counter', {
halt: function() {
this.unbreak();
if (lively.ast.halt(this)) {
throw {
isUnwindException: true,
topFrame: this,
toString: function() {return "Debugger"}
};
}
},
haltAtNextStatement: function(breakAtCalls) {
if (this.pc === this.func.ast()) {
var caller = this.getCaller();
if (caller && caller.isResuming()) {
caller.haltAtNextStatement();
}
} else {
var nextStmt = this.pc.nextStatement();
this.bp = nextStmt ? nextStmt : this.func.ast();
}
},
stepToNextStatement: function(breakAtCalls) {
this.haltAtNextStatement();
return this.resume(breakAtCalls);
},
hasNextStatement: function() {
return this.pc.nextStatement() != null;
},
restart: function() {
this.initialize(this.func, this.mapping);
this.breakAtFirstStatement();
this.resume();
}
},
'resuming', {
isResuming: function() {
return this.pc !== null || this.bp !== null;
},
resumesNow: function() {
this.pc = null;
},
isBreakingAt: function(node) {
if (this.bp === null) return false;
if (this.bp === node) return true;
if (this.bp == node.nextStatement()) return false;
return node.isAfter(this.bp);
},
findPC: function() {
if (Object.isEmpty(this.values)) return;
// find the last computed value
var last = Object.keys(this.values).max(function(k) {
var fromTo = k.split('-');
return (+fromTo[1]) << 23 - (+fromTo[0]);
});
// find the node corresponding to this value
var node = this.func.ast().nodesMatching(function(node) {
return last == node.position();
})[0];
// if the node is a debugger just use it as PC
if (node.isDebugger) return this.pc = node;
// the pc should be the next MODIFYING node right after the last one
var pc = null;
var foundNode = false;
this.func.ast().withAllChildNodesDoPostOrder(function(n) {
if (!foundNode) {
if (n === node) foundNode = true;
} else {
if (n.isCall || n.isSend || n.isSet || n.isModifyingSet || n.isPreOp || n.isPostOp) {
pc = n;
return false
}
}
return true;
});
this.pc = pc || this.func.ast();
},
setPC: function(node) {
this.pc = node.isFunction ? node : node.firstStatement();
if (this.isBreakingAt(node)) this.halt();
},
getValue: function(node) {
var value = this.values[node.position()];
// if no value was cached, set PC and compute normally
return value ? value : this.setPC(node);
},
putValue: function(node, value) {
return this.values[node.position()] = {
val: value
};
},
removeValue: function(node) {
var that = this;
node.withAllChildNodesDo(function(child){
delete that.values[child.position()];
return true;
});
},
resume: function(breakAtCalls) {
this.breakAtCalls = breakAtCalls ? true : false;
var result = this.func.ast().resume(this);
if (this.getCaller() && this.getCaller().isResuming()) {
this.getCaller().putValue(this.getCaller().pc, result);
}
// break right after the last statement
this.setPC(this.func.ast());
if (this.getCaller() && this.getCaller().isResuming()) {
return this.getCaller().resume(breakAtCalls);
}
return result;
},
unbreak: function() {
// remove all previous breakpoints in this and caller frames
this.bp = null;
if (this.getCaller()) {
this.getCaller().unbreak();
}
}
},
'debugging', {
toString: function() {
var mappings = [];
for (var name in this.mapping) {
if (this.mapping.hasOwnProperty(name)) {
mappings.push(name + ': ' + this.mapping[name]);
}
}
var mappingString = '{' + mappings.join(',') + '}';
return 'Frame(' + mappingString + ')';
}
});
Object.extend(lively.ast.Interpreter.Frame, {
create: function(func, mapping) {
return new lively.ast.Interpreter.Frame(func, mapping || {});
},
global: function() {
return this.create(null, Global);
},
fromTraceNode: function(trace) {
var frame;
if (trace.frame) {
frame = trace.frame;
} else {
frame = lively.ast.Interpreter.Frame.create(trace.method);
frame.setThis(trace.itsThis);
frame.setArguments(trace.args);
}
if (trace.caller && !trace.caller.isRoot) {
frame.setCaller(lively.ast.Interpreter.Frame.fromTraceNode(trace.caller));
}
return frame;
},
fromScope: function(scope, callstack) {
if (scope === Global) return lively.ast.Interpreter.Frame.global();
var ast = lively.ast.Rewriting.table[scope[2]],
frame = new lively.ast.Interpreter.Frame(ast.asFunction(), scope[1]),
parent = lively.ast.Interpreter.Frame.fromScope(scope[3], callstack);
if (callstack) {
frame.values = scope[0];
frame.findPC();
if (scope[3] !== Global) frame.setCaller(parent);
if (scope[4] !== Global) frame.setContainingScope(
lively.ast.Interpreter.Frame.fromScope(scope[4]));
} else {
frame.setContainingScope(parent);
}
return frame;
}
});
lively.ast.Visitor.subclass('lively.ast.InterpreterVisitor',
'interface', {
run: function(node, optMapping) {
return this.runWithFrame(node, lively.ast.Interpreter.Frame.create(null, optMapping));
},
runWithFrame: function(node, frame) {
this.currentFrame = frame;
return this.visit(node);
}
},
'invoking', {
isNative: function(func) {
if (!this._nativeFuncRegex) this._nativeFuncRegex = /\{\s+\[native\scode\]\s+\}$/;
return this._nativeFuncRegex.test(func.toString())
},
shouldInterpret: function(frame, func) {
if (this.isNative(func)) return false;
return func.hasOwnProperty("forInterpretation")
|| frame.breakAtCalls
|| func.containsDebugger();
},
invoke: function(node, recv, func, argValues) {
var isNew = node._parent && node._parent.isNew;
this.currentFrame.setPC(node);
// if we send apply to a function (recv) we want to interpret it
// although apply is a native function
if (recv && Object.isFunction(recv) && func === Function.prototype.apply) {
func = recv; // The function object is what we want to run
recv = argValues.shift(); // thisObj is first parameter
argValues = argValues[0]; // the second arg are the arguments (as an array)
}
if (this.shouldInterpret(this.currentFrame, func)) {
func = func.forInterpretation();
}
if (isNew) {
if (this.isNative(func)) return new func();
recv = this.newObject(func)
}
var result = func.apply(recv, argValues);
if (isNew) {// && !Object.isObject(result)) {
//FIXME: Cannot distinguish real result from (accidental) last result
// which might also be an object but which should not be returned
// 13.2.2 ECMA-262 3rd. Ediion Specification:
return recv;
}
return result;
},
newObject: function(func) {
var proto = func.prototype;
function constructor() {};
constructor.prototype = proto;
var newObj = new constructor();
newObj.constructor = func;
return newObj;
}
},
'visiting', {
visit: function(node) {
var value = this.currentFrame.getValue(node);
if (!value) {
value = this.currentFrame.putValue(node, node.accept(this));
}
return value.val;
},
visitSequence: function(node) {
var result, frame = this.currentFrame;
for (var i = 0; i < node.children.length; i++) {
result = this.visit(node.children[i]);
if (frame.returnTriggered || frame.breakTriggered || frame.continueTriggered) {
return result;
}
}
return result;
},
visitNumber: function(node) {
return node.value;
},
visitString: function(node) {
return node.value;
},
visitCond: function(node) {
var frame = this.currentFrame,
condVal = this.visit(node.condExpr);
return condVal ? this.visit(node.trueExpr) : this.visit(node.falseExpr);
},
visitIf: function(node) {
return this.visitCond(node);
},
visitWhile: function(node) {
var result, frame = this.currentFrame;
while (this.visit(node.condExpr)) {
result = this.visit(node.body);
if (frame.continueTriggered) {
frame.stopContinue()
};
if (frame.breakTriggered) {
frame.stopBreak();
break
};
if (frame.returnTriggered) {
return result
};
frame.removeValue(node.condExpr);
frame.removeValue(node.body);
}
return result;
},
visitDoWhile: function(node) {
var frame = this.currentFrame, result, condResult;
do {
frame.removeValue(node.condExpr);
result = this.visit(node.body);
if (frame.continueTriggered) {
frame.stopContinue()
};
if (frame.breakTriggered) {
frame.stopBreak();
break
};
if (frame.returnTriggered) {
return result
};
condResult = this.visit(node.condExpr);
frame.removeValue(node.body);
} while (condResult);
return result;
},
visitFor: function(node) {
var frame = this.currentFrame, result;
this.visit(node.init);
while (this.visit(node.condExpr)) {
result = this.visit(node.body);
if (frame.continueTriggered) {
frame.stopContinue();
};
if (frame.breakTriggered) {
frame.stopBreak();
break;
};
if (frame.returnTriggered) {
return result;
};
this.visit(node.upd);
frame.removeValue(node.condExpr);
frame.removeValue(node.body);
frame.removeValue(node.upd);
}
return result;
},
visitForIn: function(node) {
var frame = this.currentFrame,
varPart = node.name,
obj = this.visit(node.obj),
result;
if (varPart.isVarDeclaration) {
varPart.val.name = varPart.name;
}
for (var name in obj) {
frame.addToMapping(varPart.name, name);
result = this.visit(node.body);
if (frame.continueTriggered) {
frame.stopContinue();
};
if (frame.breakTriggered) {
frame.stopBreak();
break;
};
if (frame.returnTriggered) {
return result;
};
frame.removeValue(node.body);
}
return result;
},
visitSet: function(node) {
var frame = this.currentFrame;
return node.left.set(this.visit(node.right), frame, this);
},
visitModifyingSet: function(node) {
var frame = this.currentFrame,
op = node.name + '=',
oldValue = this.visit(node.left),
newValue;
switch (op) {
case '+=':
newValue = oldValue + this.visit(node.right);
break;
case '-=':
newValue = oldValue - this.visit(node.right);
break;
case '*=':
newValue = oldValue * this.visit(node.right);
break;
case '/=':
newValue = oldValue / this.visit(node.right);
break;
case '>>=':
newValue = oldValue >>= this.visit(node.right);
break;
case '<<=':
newValue = oldValue <<= this.visit(node.right);
break;
case '>>>=':
newValue = oldValue >>> this.visit(node.right);
break;
case '&=':
newValue = oldValue & this.visit(node.right);
break;
case '|=':
newValue = oldValue | this.visit(node.right);
break;
case '&=':
newValue = oldValue & this.visit(node.right);
break;
case '^=':
newValue = oldValue ^ this.visit(node.right);
break;
case '||=':
newValue = oldValue || this.visit(node.right);
break;
case '&&=':
newValue = oldValue && this.visit(node.right);
break;
default:
throw new Error('Modifying set has unknown operation ' + op);
}
return node.left.set(newValue, frame, this);
},
visitBinaryOp: function(node) {
var frame = this.currentFrame,
leftVal = this.visit(node.left);
switch (node.name) {
case '||':
return leftVal || this.visit(node.right);
case '&&':
return leftVal && this.visit(node.right);
}
var rightVal = this.visit(node.right);
switch (node.name) {
case '+':
return leftVal + rightVal;
case '-':
return leftVal - rightVal;
case '*':
return leftVal * rightVal;
case '/':
return leftVal / rightVal;
case '%':
return leftVal % rightVal;
case '<':
return leftVal < rightVal;
case '<=':
return leftVal <= rightVal;
case '>':
return leftVal > rightVal;
case '>=':
return leftVal >= rightVal;
case '==':
return leftVal == rightVal;
case '===':
return leftVal === rightVal;
case '!=':
return leftVal != rightVal;
case '!==':
return leftVal !== rightVal;
case '&':
return leftVal & rightVal;
case '|':
return leftVal | rightVal;
case '^':
return leftVal ^ rightVal;
case '>>':
return leftVal >> rightVal;
case '<<':
return leftVal << rightVal;
case '>>>':
return leftVal >>> rightVal;
case 'in':
return leftVal in rightVal;
case 'instanceof':
return leftVal instanceof rightVal;
default:
throw new Error('No semantics for binary op ' + node.name)
}
},
visitUnaryOp: function(node) {
var frame = this.currentFrame,
val = this.visit(node.expr);
switch (node.name) {
case '-':
return -val;
case '!':
return !val;
case '~':
return~val;
case 'typeof':
return typeof val;
default:
throw new Error('No semantics for unary op ' + node.name)
}
},
visitPreOp: function(node) {
var frame = this.currentFrame,
setExpr = node.expr;
if (!setExpr.isVariable && !setExpr.isGetSlot) {
throw new Error('Invalid expr in pre op ' + setExpr);
}
var value = this.visit(setExpr),
newValue;
switch (node.name) {
case '++':
newValue = value + 1;
break;
case '--':
newValue = value - 1;
break;
default:
throw new Error('No semantics for pre op ' + node.name)
}
setExpr.set(newValue, frame, this);
return newValue;
},
visitPostOp: function(node) {
var frame = this.currentFrame,
setExpr = node.expr;
if (!setExpr.isVariable && !setExpr.isGetSlot) {
throw dbgOn(new Error('Invalid expr in post op ' + setExpr));
}
var value = this.visit(setExpr), newValue;
switch (node.name) {
case '++':
newValue = value + 1;
break;
case '--':
newValue = value - 1;
break;
default:
throw new Error('No semantics for post op ' + node.name)
}
setExpr.set(newValue, frame, this);
return value;
},
visitThis: function(node) {
return this.currentFrame.getThis();
},
visitVariable: function(node) {
return this.currentFrame.lookup(node.name);
},
visitGetSlot: function(node) {
var obj = this.visit(node.obj),
name = this.visit(node.slotName),
value = obj[name];
return value;
},
visitBreak: function(node) {
this.currentFrame.triggerBreak();
},
visitContinue: function(node) {
this.currentFrame.triggerContinue();
},
visitDebugger: function($super, node) {
this.currentFrame.putValue(node, 1); // mark this 'debugger' as visited
this.currentFrame.halt(node, true);
},
visitArrayLiteral: function(node) {
var result = new Array(node.elements.length);
for (var i = 0; i < node.elements.length; i++) {
result[i] = this.visit(node.elements[i]);
}
return result;
},
visitReturn: function(node) {
var frame = this.currentFrame,
val = this.visit(node.expr);
frame.triggerReturn();
return val;
},
visitWith: function(node) {
throw new Error('with statement not yet supported');
},
visitSend: function(node) {
var recv = this.visit(node.recv),
property = this.visit(node.property),
argValues = node.args.collect(function(ea) { return this.visit(ea) }, this);
return this.invoke(node, recv, recv[property], argValues);
},
visitCall: function(node) {
var func = this.visit(node.fn),
argValues = node.args.collect(function(ea) { return this.visit(ea) }, this);
return this.invoke(node, undefined, func, argValues);
},
visitNew: function(node) {
// No need to do anything because Send and Call
// will look up _parent for New
return this.visit(node.clsExpr);
},
visitVarDeclaration: function(node) {
var frame = this.currentFrame,
val = this.visit(node.val);
frame.addToMapping(node.name, val);
return val;
},
visitThrow: function(node) {
var frame = this.currentFrame,
exceptionObj = this.visit(node.expr);
throw exceptionObj;
},
visitTryCatchFinally: function(node) {
var frame = this.currentFrame, result;
try {
result = this.visit(node.trySeq);
} catch(e) {
frame.addToMapping(node.err.name, e);
result = this.visit(node.catchSeq);
} finally {
if (node.finallySeq.isVariable && node.finallySeq.name == 'undefined') {
// do nothing, no finally block
} else {
result = this.visit(node.finallySeq);
}
}
return result;
},
visitFunction: function(node) {
var frame = this.currentFrame;
if (Object.isString(node.name)) frame.addToMapping(node.name, node);
if (!node.prototype) node.prototype = {};
node.lexicalScope = frame;
return node.asFunction();
},
visitObjectLiteral: function(node) {
var frame = this.currentFrame, obj = {};
for (var i = 0; i < node.properties.length; i++) {
var name = node.properties[i].name,
prop = this.visit(node.properties[i].property);
obj[name] = prop;
}
return obj;
},
visitObjProperty: function(node) {
throw new Error('?????');
},
visitSwitch: function(node) {
var frame = this.currentFrame,
val = this.visit(node.expr),
caseMatched = false, result;
for (var i = 0; i < node.cases.length; i++) {
node.cases[i].prevCaseMatched = caseMatched;
node.cases[i].switchValue = val;
result = this.visit(node.cases[i]);
caseMatched = result !== undefined; // FIXME what when case returns undefined?
if (frame.breakTriggered) {
frame.stopBreak();
break;
};
}
return result;
},
visitCase: function(node) {
return node.prevCaseMatched || node.switchValue == this.visit(node.condExpr) ?
this.visit(node.thenExpr) : undefined;
},
visitDefault: function(node) {
return node.prevCaseMatched ? undefined : this.visit(node.defaultExpr);
},
visitRegex: function(node) {
return new RegExp(node.exprString, node.flags);
}
});
lively.ast.Node.addMethods('interpretation', {
startInterpretation: function(optMapping) {
var interpreter = new lively.ast.InterpreterVisitor();
return interpreter.run(this, optMapping);
},
toSource: function() { return this.toString(); },
parentSource: function() {
if (this.source) return this.source;
if (this.hasParent()) return this.getParent().parentSource();
return this.toSource();
}
});
lively.ast.Variable.addMethods('interpretation', {
set: function(value, frame, interpreter) {
var search = frame.findFrame(this.name),
scope = search ? search.frame : lively.ast.Interpreter.Frame.global();
return scope.addToMapping(this.name, value);
}
});
lively.ast.GetSlot.addMethods('interpretation', {
set: function(value, frame, interpreter) {
var obj = interpreter.visit(this.obj),
name = interpreter.visit(this.slotName);
return obj[name] = value;
}
});
lively.ast.Function.addMethods('interpretation', {
position: function() {
return this.pos[0] + "-" + this.pos[1];
},
basicApply: function(frame) {
var interpreter = new lively.ast.InterpreterVisitor();
try {
lively.ast.Interpreter.Frame.top = frame;
// important: lively.ast.Interpreter.Frame.top is only valid
// during the native VM-execution time. When the execution
// of the interpreter is stopped, there is no top frame anymore.
return interpreter.runWithFrame(this.body, frame);
} finally {
lively.ast.Interpreter.Frame.top = null;
}
},
apply: function(thisObj, argValues, startHalted) {
var calledFunction = this.asFunction(),
mapping = Object.extend({}, calledFunction.getVarMapping()),
argNames = this.argNames();
// work-around for $super
if (mapping["$super"] && argNames[0] == "$super") {
argValues.unshift(mapping["$super"]);
}
var scope = this.lexicalScope ? this.lexicalScope : lively.ast.Interpreter.Frame.global(),
newFrame = scope.newScope(calledFunction, mapping);
if (thisObj !== undefined) newFrame.setThis(thisObj);
newFrame.setArguments(argValues);
newFrame.setCaller(lively.ast.Interpreter.Frame.top);
if (startHalted) newFrame.breakAtFirstStatement();
return this.basicApply(newFrame);
},
asFunction: function(optFunc) {
if (this._cachedFunction) return this._cachedFunction;
var that = this;
function fn(/*args*/) {
return that.apply(this, Array.from(arguments));
};
fn.methodName = this.name();
fn.forInterpretation = function() { return fn; };
fn.ast = function() { return that; };
fn.startHalted = function() {
return function(/*args*/) { return that.apply(this, Array.from(arguments), true); }
};
fn.evaluatedSource = function() { return that.parentSource(); };
if (optFunc) {
fn.source = optFunc.toSource();
fn.varMapping = optFunc.getVarMapping();
fn.prototype = optFunc.prototype;
if (optFunc.declaredClass) fn.declaredClass = optFunc.declaredClass;
if (optFunc.methodName) fn.methodName = optFunc.methodName;
if (optFunc.sourceModule) fn.sourceModule = optFunc.sourceModule;
if (optFunc.declaredObject) fn.declaredObject = optFunc.declaredObject;
if (optFunc.name) fn.methodName = optFunc.name;
}
return this._cachedFunction = fn;
}
},
'continued interpretation', {
resume: function(frame) {
return this.basicApply(frame);
}
});
Object.extend(lively.ast, {
halt: lively.ast.halt || function(frame) {
// overwrite this function, e.g. to open a debugger
return false; // return true to actually stop execution
},
doWithHalt: function(func, halt) {
var oldHalt = lively.ast.halt;
lively.ast.halt = halt || Functions.True;
try {
func();
} finally { lively.ast.halt = oldHalt; }
}
});
lively.ast.Visitor.subclass('lively.ast.ContainsDebuggerVisitor',
'visiting', {
visitSequence: function(node) {
for (var i = 0; i < node.children.length; i++) {
if (this.visit(node.children[i])) {
return true;
}
}
return false;
},
visitNumber: function(node) {
return false;
},
visitString: function(node) {
return false;
},
visitCond: function(node) {
return this.visit(node.condExpr) || this.visit(node.trueExpr) || this.visit(node.falseExpr);
},
visitIf: function(node) {
return this.visitCond(node);
},
visitWhile: function(node) {
return this.visit(node.condExpr) || this.visit(node.body);
},
visitDoWhile: function(node) {
return this.visit(node.body) || this.visit(node.condExpr);
},
visitFor: function(node) {
return this.visit(node.init) || this.visit(node.condExpr) || this.visit(node.body) || this.visit(node.upd);
},
visitForIn: function(node) {
return this.visit(node.obj) || this.visit(node.body);
},
visitSet: function(node) {
return this.visit(node.left) || this.visit(node.right);
},
visitModifyingSet: function(node) {
return this.visit(node.left) || this.visit(node.right);
},
visitBinaryOp: function(node) {
return this.visit(node.left) || this.visit(node.right);
},
visitUnaryOp: function(node) {
return this.visit(node.expr);
},
visitPreOp: function(node) {
return this.visit(node.expr);
},
visitPostOp: function(node) {
return this.visit(node.expr);
},
visitThis: function(node) {
return false;
},
visitVariable: function(node) {
return false;
},
visitGetSlot: function(node) {
return false;
},
visitBreak: function(node) {
return false;
},
visitDebugger: function(node) {
return true;
},
visitContinue: function(node) {
return false;
},
visitArrayLiteral: function(node) {
for (var i = 0; i < node.elements.length; i++) {
if (this.visit(node.elements[i])) {
return true;
}
}
return false;
},
visitReturn: function(node) {
return this.visit(node.expr);
},
visitWith: function(node) {
throw new Error('with statement not yet supported');
},
visitSend: function(node) {
if (this.visit(node.recv)) return true;
for (var i = 0; i < node.args.length; i++) {
if (this.visit(node.args[i])) {
return true;
}
}
return false;
},
visitCall: function(node) {
if (this.visit(node.fn)) return true;
for (var i = 0; i < node.args.length; i++) {
if (this.visit(node.args[i])) {
return true;
}
}
return false;
},
visitNew: function(node) {
return this.visit(node.clsExpr);
},
visitVarDeclaration: function(node) {
return this.visit(node.val);
},
visitThrow: function(node) {
return this.visit(node.expr);
},
visitTryCatchFinally: function(node) {
return this.visit(node.trySeq) || this.visit(node.catchSeq) || this.visit(node.finallySeq);
},
visitFunction: function(node) {
return this.visit(node.body);
},
visitObjectLiteral: function(node) {
for (var i = 0; i < node.properties.length; i++) {
if (this.visit(node.properties[i].property)) {
return true;
}
}
return false;
},
visitObjProperty: function(node) {
return false;
},
visitSwitch: function(node) {
if (this.visit(node.expr)) {
return true;
}
for (var i = 0; i < node.cases.length; i++) {
if (this.visit(node.cases[i])) {
return true;
}
}
return false;
},
visitCase: function(node) {
return this.visit(node.condExpr) || this.visit(node.thenExpr);
},
visitDefault: function(node) {
return this.visit(node.defaultExpr);
},
visitRegex: function(node) {
return false;
}
});
Function.addMethods(
'ast', {
evaluatedSource: function() {
return this.toSource();
},
ast: function() {
if (this._cachedAst) return this._cachedAst;
var parseResult = lively.ast.Parser.parse(this.toSource(), 'topLevel');
if (!parseResult || Object.isString(parseResult)) return parseResult;
parseResult = parseResult.children[0];
if (parseResult.isVarDeclaration && parseResult.val.isFunction) {
return this._cachedAst = parseResult.val;
}
return this._cachedAst = parseResult;
}
},
'debugging', {
forInterpretation: function(optMapping) {
var funcAst = this.ast();
if (!funcAst.lexicalScope && this._cachedScope) {
funcAst.lexicalScope = lively.ast.Interpreter.Frame.fromScope(this._cachedScope);
}
return funcAst.asFunction(this);
},
containsDebugger: function() {
return new lively.ast.ContainsDebuggerVisitor().visit(this.ast());
}
},
'meta programming interface', {
toSource: function() {
if (!this.source) {
var name = this.methodName || this.name || "anonymous";
this.source = this.toString()
.replace(/^function[^\(]*/, "function " + name);
}
return this.source;
},
browse: function() {
if (this.sourceModule && this.methodName && this.declaredClass) {
require('lively.ide.SystemCodeBrowser').toRun(function() {
return lively.ide.browse(
this.declaredClass,
this.methodName,
this.sourceModule.name());
}.bind(this));
}
//TODO: Add browse implementation for Morphic scripts with ObjectEditor
throw new Error('Cannot browse anonymous function ' + this);
},
});
}); // end of module
|
import expect from 'expect';
import db from '../../app/models';
import helper from '../helper/test-helper';
describe('ROLE', () => {
let guestRole;
describe('Create Role', () => {
it('should create a role', (done) => {
db.Role.create(helper.guestRole)
.then((role) => {
guestRole = role.dataValues;
expect(role.dataValues.title).toEqual(helper.guestRole.title);
done();
});
});
it('should fail when role title already exist', (done) => {
const newRole = { title: 'guest' };
db.Role.create(newRole)
.then()
.catch((error) => {
expect(error.errors[0].message).toEqual('role already exist');
expect(error.errors[0].type).toEqual('unique violation');
expect(error.errors[0].path).toEqual('title');
expect(error.errors[0].value).toEqual('guest');
done();
});
});
});
describe('NOT NULL violation', () => {
it('should fail when title of a role is null', (done) => {
const nullTitle = { title: null };
db.Role.create(nullTitle)
.then()
.catch((error) => {
expect(error.errors[0].message).toEqual('title cannot be null');
expect(error.errors[0].type).toEqual('notNull Violation');
expect(error.errors[0].value).toEqual(null);
done();
});
});
});
describe('EMPTY String violation', () => {
it('should fail for empty string title', (done) => {
const emptyTitle = { title: ' ' };
db.Role.create(emptyTitle)
.then()
.catch((error) => {
expect(error.errors[0].message).toEqual('Input a valid title');
expect(error.errors[0].type).toEqual('Validation error');
expect(error.errors[1].message)
.toEqual('This field cannot be empty');
done();
});
});
});
describe('Update Role', () => {
let newRole;
before((done) => {
db.Role.findById(guestRole.id)
.then((role) => {
role.update({ title: 'fellow' })
.then((updatedRole) => {
newRole = updatedRole;
done();
});
});
});
it('should update a role', (done) => {
db.Role.findById(newRole.id)
.then((role) => {
expect(role.dataValues.id).toEqual(guestRole.id);
expect(role.dataValues.title).toNotEqual(guestRole.title);
expect(role.dataValues.title).toEqual('fellow');
done();
});
});
});
describe('DELETE role', () => {
it('should delete a role', (done) => {
db.Role.destroy({ where: { id: guestRole.id } })
.then(() => {
db.Role.findById(guestRole.id)
.then((res) => {
expect(res).toEqual(null);
done();
});
});
});
});
});
|
const Keeper = require('../models/Keeper');
const User = require('../models/User');
const async = require('async');
exports.getKeepersPage = (req, res) => {
let myModel = [];
let keeperMax = 0;
User.find({}).exec((err, users) => {
myModel = users;
let numRunningQueries = 0;
myModel.forEach((u) => {
++numRunningQueries;
Keeper.find({ ownerId: u._id})
.exec((err, keepers) => {
u.keepers = keepers;
if (req.user._id && req.user._id.toString() === u._id.toString()) {
keeperMax = u.keepers.length;
}
--numRunningQueries;
if (numRunningQueries === 0) {
res.render('keeper', { users: myModel, keeperMax: keeperMax });
}
});
});
});
}
exports.addKeeper = (req, res, next) => {
if (!req.body.firstName || !req.body.lastName || !req.body.round) {
req.flash('errors', { msg: 'First Name, Last Name, and Round cannot be blank.' });
res.redirect('/keeper');
} else {
const newKeeper = new Keeper({
firstName: req.body.firstName,
lastName: req.body.lastName,
round: req.body.round,
ownerId: req.user._id,
ownerName: req.user.profile.name
});
newKeeper.save((err, saved) => {
if (err) { return next(err); }
req.flash('success', { msg: 'Success! You added your keeper.' });
res.redirect('/keeper');
});
}
}
exports.deleteKeeper = (req, res) => {
Keeper.findOne({ _id: req.params.id }).exec((err, keeper) => {
if (err) {
res.status(500).send(err);
}
console.log(keeper);
if (keeper.ownerId.toString() === req.user._id.toString()) {
keeper.remove(() => {
req.flash('info', { msg: 'You have successfully deleted your keeper.' });
res.redirect('/keeper');
});
} else {
req.flash('errors', { msg: 'You do not have permission to delete this keeper.' });
res.redirect('/keeper');
}
});
} |
define(function(require) {
var app = require('app');
var $ = require('jquery');
app.controller('AdminIndexController', function ($rootScope, $scope, $location,$anchorScroll) {
console.log('AdminIndexController');
});
}); |
// @flow
/**
* This file provides support to buildMathML.js and buildHTML.js
* for stretchy wide elements rendered from SVG files
* and other CSS trickery.
*/
import {LineNode, PathNode, SvgNode} from "./domTree";
import buildCommon from "./buildCommon";
import mathMLTree from "./mathMLTree";
import utils from "./utils";
import {makeEm} from "./units";
import type Options from "./Options";
import type {ParseNode, AnyParseNode} from "./parseNode";
import type {DomSpan, HtmlDomNode, SvgSpan} from "./domTree";
const stretchyCodePoint: {[string]: string} = {
widehat: "^",
widecheck: "ˇ",
widetilde: "~",
utilde: "~",
overleftarrow: "\u2190",
underleftarrow: "\u2190",
xleftarrow: "\u2190",
overrightarrow: "\u2192",
underrightarrow: "\u2192",
xrightarrow: "\u2192",
underbrace: "\u23df",
overbrace: "\u23de",
overgroup: "\u23e0",
undergroup: "\u23e1",
overleftrightarrow: "\u2194",
underleftrightarrow: "\u2194",
xleftrightarrow: "\u2194",
Overrightarrow: "\u21d2",
xRightarrow: "\u21d2",
overleftharpoon: "\u21bc",
xleftharpoonup: "\u21bc",
overrightharpoon: "\u21c0",
xrightharpoonup: "\u21c0",
xLeftarrow: "\u21d0",
xLeftrightarrow: "\u21d4",
xhookleftarrow: "\u21a9",
xhookrightarrow: "\u21aa",
xmapsto: "\u21a6",
xrightharpoondown: "\u21c1",
xleftharpoondown: "\u21bd",
xrightleftharpoons: "\u21cc",
xleftrightharpoons: "\u21cb",
xtwoheadleftarrow: "\u219e",
xtwoheadrightarrow: "\u21a0",
xlongequal: "=",
xtofrom: "\u21c4",
xrightleftarrows: "\u21c4",
xrightequilibrium: "\u21cc", // Not a perfect match.
xleftequilibrium: "\u21cb", // None better available.
"\\cdrightarrow": "\u2192",
"\\cdleftarrow": "\u2190",
"\\cdlongequal": "=",
};
const mathMLnode = function(label: string): mathMLTree.MathNode {
const node = new mathMLTree.MathNode(
"mo",
[new mathMLTree.TextNode(stretchyCodePoint[label.replace(/^\\/, '')])],
);
node.setAttribute("stretchy", "true");
return node;
};
// Many of the KaTeX SVG images have been adapted from glyphs in KaTeX fonts.
// Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
// Copyright (c) 2014-2017 Khan Academy (<www.khanacademy.org>)
// Licensed under the SIL Open Font License, Version 1.1.
// See \nhttp://scripts.sil.org/OFL
// Very Long SVGs
// Many of the KaTeX stretchy wide elements use a long SVG image and an
// overflow: hidden tactic to achieve a stretchy image while avoiding
// distortion of arrowheads or brace corners.
// The SVG typically contains a very long (400 em) arrow.
// The SVG is in a container span that has overflow: hidden, so the span
// acts like a window that exposes only part of the SVG.
// The SVG always has a longer, thinner aspect ratio than the container span.
// After the SVG fills 100% of the height of the container span,
// there is a long arrow shaft left over. That left-over shaft is not shown.
// Instead, it is sliced off because the span's CSS has overflow: hidden.
// Thus, the reader sees an arrow that matches the subject matter width
// without distortion.
// Some functions, such as \cancel, need to vary their aspect ratio. These
// functions do not get the overflow SVG treatment.
// Second Brush Stroke
// Low resolution monitors struggle to display images in fine detail.
// So browsers apply anti-aliasing. A long straight arrow shaft therefore
// will sometimes appear as if it has a blurred edge.
// To mitigate this, these SVG files contain a second "brush-stroke" on the
// arrow shafts. That is, a second long thin rectangular SVG path has been
// written directly on top of each arrow shaft. This reinforcement causes
// some of the screen pixels to display as black instead of the anti-aliased
// gray pixel that a single path would generate. So we get arrow shafts
// whose edges appear to be sharper.
// In the katexImagesData object just below, the dimensions all
// correspond to path geometry inside the relevant SVG.
// For example, \overrightarrow uses the same arrowhead as glyph U+2192
// from the KaTeX Main font. The scaling factor is 1000.
// That is, inside the font, that arrowhead is 522 units tall, which
// corresponds to 0.522 em inside the document.
const katexImagesData: {
[string]: ([string[], number, number] | [[string], number, number, string])
} = {
// path(s), minWidth, height, align
overrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
overleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
underrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
underleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
xrightarrow: [["rightarrow"], 1.469, 522, "xMaxYMin"],
"\\cdrightarrow": [["rightarrow"], 3.0, 522, "xMaxYMin"], // CD minwwidth2.5pc
xleftarrow: [["leftarrow"], 1.469, 522, "xMinYMin"],
"\\cdleftarrow": [["leftarrow"], 3.0, 522, "xMinYMin"],
Overrightarrow: [["doublerightarrow"], 0.888, 560, "xMaxYMin"],
xRightarrow: [["doublerightarrow"], 1.526, 560, "xMaxYMin"],
xLeftarrow: [["doubleleftarrow"], 1.526, 560, "xMinYMin"],
overleftharpoon: [["leftharpoon"], 0.888, 522, "xMinYMin"],
xleftharpoonup: [["leftharpoon"], 0.888, 522, "xMinYMin"],
xleftharpoondown: [["leftharpoondown"], 0.888, 522, "xMinYMin"],
overrightharpoon: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
xrightharpoonup: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
xrightharpoondown: [["rightharpoondown"], 0.888, 522, "xMaxYMin"],
xlongequal: [["longequal"], 0.888, 334, "xMinYMin"],
"\\cdlongequal": [["longequal"], 3.0, 334, "xMinYMin"],
xtwoheadleftarrow: [["twoheadleftarrow"], 0.888, 334, "xMinYMin"],
xtwoheadrightarrow: [["twoheadrightarrow"], 0.888, 334, "xMaxYMin"],
overleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
overbrace: [["leftbrace", "midbrace", "rightbrace"], 1.6, 548],
underbrace: [["leftbraceunder", "midbraceunder", "rightbraceunder"],
1.6, 548],
underleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
xleftrightarrow: [["leftarrow", "rightarrow"], 1.75, 522],
xLeftrightarrow: [["doubleleftarrow", "doublerightarrow"], 1.75, 560],
xrightleftharpoons: [["leftharpoondownplus", "rightharpoonplus"], 1.75, 716],
xleftrightharpoons: [["leftharpoonplus", "rightharpoondownplus"],
1.75, 716],
xhookleftarrow: [["leftarrow", "righthook"], 1.08, 522],
xhookrightarrow: [["lefthook", "rightarrow"], 1.08, 522],
overlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
underlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
overgroup: [["leftgroup", "rightgroup"], 0.888, 342],
undergroup: [["leftgroupunder", "rightgroupunder"], 0.888, 342],
xmapsto: [["leftmapsto", "rightarrow"], 1.5, 522],
xtofrom: [["leftToFrom", "rightToFrom"], 1.75, 528],
// The next three arrows are from the mhchem package.
// In mhchem.sty, min-length is 2.0em. But these arrows might appear in the
// document as \xrightarrow or \xrightleftharpoons. Those have
// min-length = 1.75em, so we set min-length on these next three to match.
xrightleftarrows: [["baraboveleftarrow", "rightarrowabovebar"], 1.75, 901],
xrightequilibrium: [["baraboveshortleftharpoon",
"rightharpoonaboveshortbar"], 1.75, 716],
xleftequilibrium: [["shortbaraboveleftharpoon",
"shortrightharpoonabovebar"], 1.75, 716],
};
const groupLength = function(arg: AnyParseNode): number {
if (arg.type === "ordgroup") {
return arg.body.length;
} else {
return 1;
}
};
const svgSpan = function(
group: ParseNode<"accent"> | ParseNode<"accentUnder"> | ParseNode<"xArrow">
| ParseNode<"horizBrace">,
options: Options,
): DomSpan | SvgSpan {
// Create a span with inline SVG for the element.
function buildSvgSpan_(): {
span: DomSpan | SvgSpan,
minWidth: number,
height: number,
} {
let viewBoxWidth = 400000; // default
const label = group.label.substr(1);
if (utils.contains(["widehat", "widecheck", "widetilde", "utilde"],
label)) {
// Each type in the `if` statement corresponds to one of the ParseNode
// types below. This narrowing is required to access `grp.base`.
// $FlowFixMe
const grp: ParseNode<"accent"> | ParseNode<"accentUnder"> = group;
// There are four SVG images available for each function.
// Choose a taller image when there are more characters.
const numChars = groupLength(grp.base);
let viewBoxHeight;
let pathName;
let height;
if (numChars > 5) {
if (label === "widehat" || label === "widecheck") {
viewBoxHeight = 420;
viewBoxWidth = 2364;
height = 0.42;
pathName = label + "4";
} else {
viewBoxHeight = 312;
viewBoxWidth = 2340;
height = 0.34;
pathName = "tilde4";
}
} else {
const imgIndex = [1, 1, 2, 2, 3, 3][numChars];
if (label === "widehat" || label === "widecheck") {
viewBoxWidth = [0, 1062, 2364, 2364, 2364][imgIndex];
viewBoxHeight = [0, 239, 300, 360, 420][imgIndex];
height = [0, 0.24, 0.3, 0.3, 0.36, 0.42][imgIndex];
pathName = label + imgIndex;
} else {
viewBoxWidth = [0, 600, 1033, 2339, 2340][imgIndex];
viewBoxHeight = [0, 260, 286, 306, 312][imgIndex];
height = [0, 0.26, 0.286, 0.3, 0.306, 0.34][imgIndex];
pathName = "tilde" + imgIndex;
}
}
const path = new PathNode(pathName);
const svgNode = new SvgNode([path], {
"width": "100%",
"height": makeEm(height),
"viewBox": `0 0 ${viewBoxWidth} ${viewBoxHeight}`,
"preserveAspectRatio": "none",
});
return {
span: buildCommon.makeSvgSpan([], [svgNode], options),
minWidth: 0,
height,
};
} else {
const spans = [];
const data = katexImagesData[label];
const [paths, minWidth, viewBoxHeight] = data;
const height = viewBoxHeight / 1000;
const numSvgChildren = paths.length;
let widthClasses;
let aligns;
if (numSvgChildren === 1) {
// $FlowFixMe: All these cases must be of the 4-tuple type.
const align1: string = data[3];
widthClasses = ["hide-tail"];
aligns = [align1];
} else if (numSvgChildren === 2) {
widthClasses = ["halfarrow-left", "halfarrow-right"];
aligns = ["xMinYMin", "xMaxYMin"];
} else if (numSvgChildren === 3) {
widthClasses = ["brace-left", "brace-center", "brace-right"];
aligns = ["xMinYMin", "xMidYMin", "xMaxYMin"];
} else {
throw new Error(
`Correct katexImagesData or update code here to support
${numSvgChildren} children.`);
}
for (let i = 0; i < numSvgChildren; i++) {
const path = new PathNode(paths[i]);
const svgNode = new SvgNode([path], {
"width": "400em",
"height": makeEm(height),
"viewBox": `0 0 ${viewBoxWidth} ${viewBoxHeight}`,
"preserveAspectRatio": aligns[i] + " slice",
});
const span = buildCommon.makeSvgSpan(
[widthClasses[i]], [svgNode], options);
if (numSvgChildren === 1) {
return {span, minWidth, height};
} else {
span.style.height = makeEm(height);
spans.push(span);
}
}
return {
span: buildCommon.makeSpan(["stretchy"], spans, options),
minWidth,
height,
};
}
} // buildSvgSpan_()
const {span, minWidth, height} = buildSvgSpan_();
// Note that we are returning span.depth = 0.
// Any adjustments relative to the baseline must be done in buildHTML.
span.height = height;
span.style.height = makeEm(height);
if (minWidth > 0) {
span.style.minWidth = makeEm(minWidth);
}
return span;
};
const encloseSpan = function(
inner: HtmlDomNode,
label: string,
topPad: number,
bottomPad: number,
options: Options,
): DomSpan | SvgSpan {
// Return an image span for \cancel, \bcancel, \xcancel, \fbox, or \angl
let img;
const totalHeight = inner.height + inner.depth + topPad + bottomPad;
if (/fbox|color|angl/.test(label)) {
img = buildCommon.makeSpan(["stretchy", label], [], options);
if (label === "fbox") {
const color = options.color && options.getColor();
if (color) {
img.style.borderColor = color;
}
}
} else {
// \cancel, \bcancel, or \xcancel
// Since \cancel's SVG is inline and it omits the viewBox attribute,
// its stroke-width will not vary with span area.
const lines = [];
if (/^[bx]cancel$/.test(label)) {
lines.push(new LineNode({
"x1": "0",
"y1": "0",
"x2": "100%",
"y2": "100%",
"stroke-width": "0.046em",
}));
}
if (/^x?cancel$/.test(label)) {
lines.push(new LineNode({
"x1": "0",
"y1": "100%",
"x2": "100%",
"y2": "0",
"stroke-width": "0.046em",
}));
}
const svgNode = new SvgNode(lines, {
"width": "100%",
"height": makeEm(totalHeight),
});
img = buildCommon.makeSvgSpan([], [svgNode], options);
}
img.height = totalHeight;
img.style.height = makeEm(totalHeight);
return img;
};
export default {
encloseSpan,
mathMLnode,
svgSpan,
};
|
import React, { PropTypes } from 'react'
import classnames from 'classnames'
import { ListGroupItem, Button } from 'react-bootstrap'
import { FilePlayer } from 'voicebase-player-v2';
export default class UploadPreviewItem extends React.Component {
static propTypes = {
file: PropTypes.object.isRequired,
fileId: PropTypes.string.isRequired,
actions: PropTypes.object.isRequired
};
onRemove = () => {
const { fileId, actions } = this.props;
actions.removeFile(fileId);
};
render () {
const { file, fileId } = this.props;
const itemClasses = classnames({
'preview-player-item--video': file.type === 'video',
'preview-player-item--audio': file.type === 'audio'
});
return (
<ListGroupItem key={'preview' + fileId} className={itemClasses}>
<h4>{file.file.name}</h4>
<div className="preview-player-row">
<div className="player-wrapper">
<FilePlayer
fileId={fileId}
file={file}
/>
</div>
<Button bsStyle="danger" className="btn-delete" onClick={this.onRemove}>
<i className="fa fa-fw fa-times" />
</Button>
</div>
</ListGroupItem>
)
}
}
|
/**
* Created with JetBrains RubyMine.
* User: teamco
* Date: 11/24/12
* Time: 10:12 PM
* To change this template use File | Settings | File Templates.
*/
import {BaseElement} from '../../../modules/Element';
/**
* @extends BaseElement
* @class PageElement
* @type {PageElement}
*/
export class PageElement extends BaseElement {
/**
* @param {PageView} view
* @param opts
* @constructor
*/
constructor(view, opts) {
super('PageElement', view);
this._config(view, opts, '<page />').build(opts);
}
/**
* Set page padding
* @param padding
* @memberOf PageElement
*/
setPadding(padding) {
this.view.elements.$widgets.$.css({
paddingTop: padding.top,
paddingRight: padding.right,
paddingBottom: padding.bottom,
paddingLeft: padding.left
});
}
/**
* Define height
* @memberOf PageElement
*/
updateDimensions() {
/**
* Fetch page
* @type {Page}
*/
const scope = this.view.scope;
this.$.removeClass('height-auto');
/**
* Get widget
* @type {Widget}
*/
const widget = scope.model.getCurrentItem();
if (!widget) {
scope.logger.debug('Widget should be defined', widget);
return false;
}
if (!widget.view) {
scope.logger.debug('Unable to set page height: Page without items (default 100%)');
return false;
}
if (!widget.view.get$item()) {
scope.logger.debug('Unable to set page height: Initial state (default 100%)');
return false;
}
/**
* Calculate last occupied row
* @type {*|number}
*/
const lastOccupiedRow = widget.map.getLastOccupiedRow();
/**
* Get layout
* @type {*|Layout}
*/
const layout = scope.controller.getLayout();
let height = lastOccupiedRow * layout.controller.minCellWidth() + (lastOccupiedRow + 1) * layout.config.grid.margin;
const header = this.view.elements.$header,
footer = this.view.elements.$footer,
containerHeight = this.getRootContainer().height();
const headerHeight = header.$ ? header.$.height() : 0,
footerHeight = footer.$ ? footer.$.height() : 0,
outerHeight = headerHeight + footerHeight;
height = height ? height : containerHeight;
if (height < containerHeight) {
height = containerHeight;
}
const pageScrollHeight = parseInt(scope.model.getConfig('preferences').pageScrollHeight, 10) || 0;
let delta = height + outerHeight;
if (pageScrollHeight > delta) {
delta += (pageScrollHeight - delta);
}
this.setHeight(delta);
}
/**
* Define page visibility
* @memberOf PageElement
* @param {boolean} visible
*/
setVisibility(visible) {
this.$[(visible ? 'add' : 'remove') + 'Class']('current-page');
}
} |
/**
* matter-js 0.14.2 by @liabru 2018-06-11
* http://brm.io/matter-js/
* License MIT
*/
/**
* The MIT License (MIT)
*
* Copyright (c) Liam Brummitt and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (f) {
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f()
} else if (typeof define === "function" && define.amd) {
define([], f)
} else {
var g;
if (typeof window !== "undefined") {
g = window
} else if (typeof global !== "undefined") {
g = global
} else if (typeof self !== "undefined") {
g = self
} else {
g = this
}
g.Matter = f()
}
})(function () {
var define, module, exports;
return (function () {
function r(e, n, t) {
function o(i, f) {
if (!n[i]) {
if (!e[i]) {
var c = "function" == typeof require && require;
if (!f && c) return c(i, !0);
if (u) return u(i, !0);
var a = new Error("Cannot find module '" + i + "'");
throw a.code = "MODULE_NOT_FOUND", a
}
var p = n[i] = {
exports: {}
};
e[i][0].call(p.exports, function (r) {
var n = e[i][1][r];
return o(n || r)
}, p, p.exports, r, e, n, t)
}
return n[i].exports
}
for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) o(t[i]);
return o
}
return r
})()({
1: [function (_dereq_, module, exports) {
/**
* The `Matter.Body` module contains methods for creating and manipulating body models.
* A `Matter.Body` is a rigid body that can be simulated by a `Matter.Engine`.
* Factories for commonly used body configurations (such as rectangles, circles and other polygons) can be found in the module `Matter.Bodies`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
* @class Body
*/
var Body = {};
module.exports = Body;
var Vertices = _dereq_('../geometry/Vertices');
var Vector = _dereq_('../geometry/Vector');
var Sleeping = _dereq_('../core/Sleeping');
var Render = _dereq_('../render/Render');
var Common = _dereq_('../core/Common');
var Bounds = _dereq_('../geometry/Bounds');
var Axes = _dereq_('../geometry/Axes');
(function () {
Body._inertiaScale = 4;
Body._nextCollidingGroupId = 1;
Body._nextNonCollidingGroupId = -1;
Body._nextCategory = 0x0001;
/**
* Creates a new rigid body model. The options parameter is an object that specifies any properties you wish to override the defaults.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* Vertices must be specified in clockwise order.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {} options
* @return {body} body
*/
Body.create = function (options) {
var defaults = {
id: Common.nextId(),
type: 'body',
label: 'Body',
parts: [],
plugin: {},
angle: 0,
vertices: Vertices.fromPath('L 0 0 L 40 0 L 40 40 L 0 40'),
position: {
x: 0,
y: 0
},
force: {
x: 0,
y: 0
},
torque: 0,
positionImpulse: {
x: 0,
y: 0
},
constraintImpulse: {
x: 0,
y: 0,
angle: 0
},
totalContacts: 0,
speed: 0,
angularSpeed: 0,
velocity: {
x: 0,
y: 0
},
angularVelocity: 0,
isSensor: false,
isStatic: false,
isSleeping: false,
motion: 0,
sleepThreshold: 60,
density: 0.001,
restitution: 0,
friction: 0.1,
frictionStatic: 0.5,
frictionAir: 0.01,
collisionFilter: {
category: 0x0001,
mask: 0xFFFFFFFF,
group: 0
},
slop: 0.05,
timeScale: 1,
render: {
visible: true,
opacity: 1,
sprite: {
xScale: 1,
yScale: 1,
xOffset: 0,
yOffset: 0
},
lineWidth: 0
}
};
var body = Common.extend(defaults, options);
_initProperties(body, options);
return body;
};
/**
* Returns the next unique group index for which bodies will collide.
* If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide.
* See `body.collisionFilter` for more information.
* @method nextGroup
* @param {bool} [isNonColliding=false]
* @return {Number} Unique group index
*/
Body.nextGroup = function (isNonColliding) {
if (isNonColliding)
return Body._nextNonCollidingGroupId--;
return Body._nextCollidingGroupId++;
};
/**
* Returns the next unique category bitfield (starting after the initial default category `0x0001`).
* There are 32 available. See `body.collisionFilter` for more information.
* @method nextCategory
* @return {Number} Unique category bitfield
*/
Body.nextCategory = function () {
Body._nextCategory = Body._nextCategory << 1;
return Body._nextCategory;
};
/**
* Initialises body properties.
* @method _initProperties
* @private
* @param {body} body
* @param {} [options]
*/
var _initProperties = function (body, options) {
options = options || {};
// init required properties (order is important)
Body.set(body, {
bounds: body.bounds || Bounds.create(body.vertices),
positionPrev: body.positionPrev || Vector.clone(body.position),
anglePrev: body.anglePrev || body.angle,
vertices: body.vertices,
parts: body.parts || [body],
isStatic: body.isStatic,
isSleeping: body.isSleeping,
parent: body.parent || body
});
Vertices.rotate(body.vertices, body.angle, body.position);
Axes.rotate(body.axes, body.angle);
Bounds.update(body.bounds, body.vertices, body.velocity);
// allow options to override the automatically calculated properties
Body.set(body, {
axes: options.axes || body.axes,
area: options.area || body.area,
mass: options.mass || body.mass,
inertia: options.inertia || body.inertia
});
// render properties
var defaultFillStyle = (body.isStatic ? '#2e2b44' : Common.choose(['#006BA6', '#0496FF', '#FFBC42', '#D81159', '#8F2D56'])),
defaultStrokeStyle = '#000';
body.render.fillStyle = body.render.fillStyle || defaultFillStyle;
body.render.strokeStyle = body.render.strokeStyle || defaultStrokeStyle;
body.render.sprite.xOffset += -(body.bounds.min.x - body.position.x) / (body.bounds.max.x - body.bounds.min.x);
body.render.sprite.yOffset += -(body.bounds.min.y - body.position.y) / (body.bounds.max.y - body.bounds.min.y);
};
/**
* Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist.
* Prefer to use the actual setter functions in performance critical situations.
* @method set
* @param {body} body
* @param {} settings A property name (or map of properties and values) to set on the body.
* @param {} value The value to set if `settings` is a single property name.
*/
Body.set = function (body, settings, value) {
var property;
if (typeof settings === 'string') {
property = settings;
settings = {};
settings[property] = value;
}
for (property in settings) {
value = settings[property];
if (!settings.hasOwnProperty(property))
continue;
switch (property) {
case 'isStatic':
Body.setStatic(body, value);
break;
case 'isSleeping':
Sleeping.set(body, value);
break;
case 'mass':
Body.setMass(body, value);
break;
case 'density':
Body.setDensity(body, value);
break;
case 'inertia':
Body.setInertia(body, value);
break;
case 'vertices':
Body.setVertices(body, value);
break;
case 'position':
Body.setPosition(body, value);
break;
case 'angle':
Body.setAngle(body, value);
break;
case 'velocity':
Body.setVelocity(body, value);
break;
case 'angularVelocity':
Body.setAngularVelocity(body, value);
break;
case 'parts':
Body.setParts(body, value);
break;
default:
body[property] = value;
}
}
};
/**
* Sets the body as static, including isStatic flag and setting mass and inertia to Infinity.
* @method setStatic
* @param {body} body
* @param {bool} isStatic
*/
Body.setStatic = function (body, isStatic) {
for (var i = 0; i < body.parts.length; i++) {
var part = body.parts[i];
part.isStatic = isStatic;
if (isStatic) {
part._original = {
restitution: part.restitution,
friction: part.friction,
mass: part.mass,
inertia: part.inertia,
density: part.density,
inverseMass: part.inverseMass,
inverseInertia: part.inverseInertia
};
part.restitution = 0;
part.friction = 1;
part.mass = part.inertia = part.density = Infinity;
part.inverseMass = part.inverseInertia = 0;
part.positionPrev.x = part.position.x;
part.positionPrev.y = part.position.y;
part.anglePrev = part.angle;
part.angularVelocity = 0;
part.speed = 0;
part.angularSpeed = 0;
part.motion = 0;
} else if (part._original) {
part.restitution = part._original.restitution;
part.friction = part._original.friction;
part.mass = part._original.mass;
part.inertia = part._original.inertia;
part.density = part._original.density;
part.inverseMass = part._original.inverseMass;
part.inverseInertia = part._original.inverseInertia;
delete part._original;
}
}
};
/**
* Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change.
* @method setMass
* @param {body} body
* @param {number} mass
*/
Body.setMass = function (body, mass) {
var moment = body.inertia / (body.mass / 6);
body.inertia = moment * (mass / 6);
body.inverseInertia = 1 / body.inertia;
body.mass = mass;
body.inverseMass = 1 / body.mass;
body.density = body.mass / body.area;
};
/**
* Sets the density of the body. Mass and inertia are automatically updated to reflect the change.
* @method setDensity
* @param {body} body
* @param {number} density
*/
Body.setDensity = function (body, density) {
Body.setMass(body, density * body.area);
body.density = density;
};
/**
* Sets the moment of inertia (i.e. second moment of area) of the body of the body.
* Inverse inertia is automatically updated to reflect the change. Mass is not changed.
* @method setInertia
* @param {body} body
* @param {number} inertia
*/
Body.setInertia = function (body, inertia) {
body.inertia = inertia;
body.inverseInertia = 1 / body.inertia;
};
/**
* Sets the body's vertices and updates body properties accordingly, including inertia, area and mass (with respect to `body.density`).
* Vertices will be automatically transformed to be orientated around their centre of mass as the origin.
* They are then automatically translated to world space based on `body.position`.
*
* The `vertices` argument should be passed as an array of `Matter.Vector` points (or a `Matter.Vertices` array).
* Vertices must form a convex hull, concave hulls are not supported.
*
* @method setVertices
* @param {body} body
* @param {vector[]} vertices
*/
Body.setVertices = function (body, vertices) {
// change vertices
if (vertices[0].body === body) {
body.vertices = vertices;
} else {
body.vertices = Vertices.create(vertices, body);
}
// update properties
body.axes = Axes.fromVertices(body.vertices);
body.area = Vertices.area(body.vertices);
Body.setMass(body, body.density * body.area);
// orient vertices around the centre of mass at origin (0, 0)
var centre = Vertices.centre(body.vertices);
Vertices.translate(body.vertices, centre, -1);
// update inertia while vertices are at origin (0, 0)
Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass));
// update geometry
Vertices.translate(body.vertices, body.position);
Bounds.update(body.bounds, body.vertices, body.velocity);
};
/**
* Sets the parts of the `body` and updates mass, inertia and centroid.
* Each part will have its parent set to `body`.
* By default the convex hull will be automatically computed and set on `body`, unless `autoHull` is set to `false.`
* Note that this method will ensure that the first part in `body.parts` will always be the `body`.
* @method setParts
* @param {body} body
* @param [body] parts
* @param {bool} [autoHull=true]
*/
Body.setParts = function (body, parts, autoHull) {
var i;
// add all the parts, ensuring that the first part is always the parent body
parts = parts.slice(0);
body.parts.length = 0;
body.parts.push(body);
body.parent = body;
for (i = 0; i < parts.length; i++) {
var part = parts[i];
if (part !== body) {
part.parent = body;
body.parts.push(part);
}
}
if (body.parts.length === 1)
return;
autoHull = typeof autoHull !== 'undefined' ? autoHull : true;
// find the convex hull of all parts to set on the parent body
if (autoHull) {
var vertices = [];
for (i = 0; i < parts.length; i++) {
vertices = vertices.concat(parts[i].vertices);
}
Vertices.clockwiseSort(vertices);
var hull = Vertices.hull(vertices),
hullCentre = Vertices.centre(hull);
Body.setVertices(body, hull);
Vertices.translate(body.vertices, hullCentre);
}
// sum the properties of all compound parts of the parent body
var total = Body._totalProperties(body);
body.area = total.area;
body.parent = body;
body.position.x = total.centre.x;
body.position.y = total.centre.y;
body.positionPrev.x = total.centre.x;
body.positionPrev.y = total.centre.y;
Body.setMass(body, total.mass);
Body.setInertia(body, total.inertia);
Body.setPosition(body, total.centre);
};
/**
* Sets the position of the body instantly. Velocity, angle, force etc. are unchanged.
* @method setPosition
* @param {body} body
* @param {vector} position
*/
Body.setPosition = function (body, position) {
var delta = Vector.sub(position, body.position);
body.positionPrev.x += delta.x;
body.positionPrev.y += delta.y;
for (var i = 0; i < body.parts.length; i++) {
var part = body.parts[i];
part.position.x += delta.x;
part.position.y += delta.y;
Vertices.translate(part.vertices, delta);
Bounds.update(part.bounds, part.vertices, body.velocity);
}
};
/**
* Sets the angle of the body instantly. Angular velocity, position, force etc. are unchanged.
* @method setAngle
* @param {body} body
* @param {number} angle
*/
Body.setAngle = function (body, angle) {
var delta = angle - body.angle;
body.anglePrev += delta;
for (var i = 0; i < body.parts.length; i++) {
var part = body.parts[i];
part.angle += delta;
Vertices.rotate(part.vertices, delta, body.position);
Axes.rotate(part.axes, delta);
Bounds.update(part.bounds, part.vertices, body.velocity);
if (i > 0) {
Vector.rotateAbout(part.position, delta, body.position, part.position);
}
}
};
/**
* Sets the linear velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`.
* @method setVelocity
* @param {body} body
* @param {vector} velocity
*/
Body.setVelocity = function (body, velocity) {
body.positionPrev.x = body.position.x - velocity.x;
body.positionPrev.y = body.position.y - velocity.y;
body.velocity.x = velocity.x;
body.velocity.y = velocity.y;
body.speed = Vector.magnitude(body.velocity);
};
/**
* Sets the angular velocity of the body instantly. Position, angle, force etc. are unchanged. See also `Body.applyForce`.
* @method setAngularVelocity
* @param {body} body
* @param {number} velocity
*/
Body.setAngularVelocity = function (body, velocity) {
body.anglePrev = body.angle - velocity;
body.angularVelocity = velocity;
body.angularSpeed = Math.abs(body.angularVelocity);
};
/**
* Moves a body by a given vector relative to its current position, without imparting any velocity.
* @method translate
* @param {body} body
* @param {vector} translation
*/
Body.translate = function (body, translation) {
Body.setPosition(body, Vector.add(body.position, translation));
};
/**
* Rotates a body by a given angle relative to its current angle, without imparting any angular velocity.
* @method rotate
* @param {body} body
* @param {number} rotation
* @param {vector} [point]
*/
Body.rotate = function (body, rotation, point) {
if (!point) {
Body.setAngle(body, body.angle + rotation);
} else {
var cos = Math.cos(rotation),
sin = Math.sin(rotation),
dx = body.position.x - point.x,
dy = body.position.y - point.y;
Body.setPosition(body, {
x: point.x + (dx * cos - dy * sin),
y: point.y + (dx * sin + dy * cos)
});
Body.setAngle(body, body.angle + rotation);
}
};
/**
* Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre).
* @method scale
* @param {body} body
* @param {number} scaleX
* @param {number} scaleY
* @param {vector} [point]
*/
Body.scale = function (body, scaleX, scaleY, point) {
var totalArea = 0,
totalInertia = 0;
point = point || body.position;
for (var i = 0; i < body.parts.length; i++) {
var part = body.parts[i];
// scale vertices
Vertices.scale(part.vertices, scaleX, scaleY, point);
// update properties
part.axes = Axes.fromVertices(part.vertices);
part.area = Vertices.area(part.vertices);
Body.setMass(part, body.density * part.area);
// update inertia (requires vertices to be at origin)
Vertices.translate(part.vertices, {
x: -part.position.x,
y: -part.position.y
});
Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass));
Vertices.translate(part.vertices, {
x: part.position.x,
y: part.position.y
});
if (i > 0) {
totalArea += part.area;
totalInertia += part.inertia;
}
// scale position
part.position.x = point.x + (part.position.x - point.x) * scaleX;
part.position.y = point.y + (part.position.y - point.y) * scaleY;
// update bounds
Bounds.update(part.bounds, part.vertices, body.velocity);
}
// handle parent body
if (body.parts.length > 1) {
body.area = totalArea;
if (!body.isStatic) {
Body.setMass(body, body.density * totalArea);
Body.setInertia(body, totalInertia);
}
}
// handle circles
if (body.circleRadius) {
if (scaleX === scaleY) {
body.circleRadius *= scaleX;
} else {
// body is no longer a circle
body.circleRadius = null;
}
}
};
/**
* Performs a simulation step for the given `body`, including updating position and angle using Verlet integration.
* @method update
* @param {body} body
* @param {number} deltaTime
* @param {number} timeScale
* @param {number} correction
*/
Body.update = function (body, deltaTime, timeScale, correction) {
var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2);
// from the previous step
var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale,
velocityPrevX = body.position.x - body.positionPrev.x,
velocityPrevY = body.position.y - body.positionPrev.y;
// update velocity with Verlet integration
body.velocity.x = (velocityPrevX * frictionAir * correction) + (body.force.x / body.mass) * deltaTimeSquared;
body.velocity.y = (velocityPrevY * frictionAir * correction) + (body.force.y / body.mass) * deltaTimeSquared;
body.positionPrev.x = body.position.x;
body.positionPrev.y = body.position.y;
body.position.x += body.velocity.x;
body.position.y += body.velocity.y;
// update angular velocity with Verlet integration
body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared;
body.anglePrev = body.angle;
body.angle += body.angularVelocity;
// track speed and acceleration
body.speed = Vector.magnitude(body.velocity);
body.angularSpeed = Math.abs(body.angularVelocity);
// transform the body geometry
for (var i = 0; i < body.parts.length; i++) {
var part = body.parts[i];
Vertices.translate(part.vertices, body.velocity);
if (i > 0) {
part.position.x += body.velocity.x;
part.position.y += body.velocity.y;
}
if (body.angularVelocity !== 0) {
Vertices.rotate(part.vertices, body.angularVelocity, body.position);
Axes.rotate(part.axes, body.angularVelocity);
if (i > 0) {
Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position);
}
}
Bounds.update(part.bounds, part.vertices, body.velocity);
}
};
/**
* Applies a force to a body from a given world-space position, including resulting torque.
* @method applyForce
* @param {body} body
* @param {vector} position
* @param {vector} force
*/
Body.applyForce = function (body, position, force) {
body.force.x += force.x;
body.force.y += force.y;
var offset = {
x: position.x - body.position.x,
y: position.y - body.position.y
};
body.torque += offset.x * force.y - offset.y * force.x;
};
/**
* Returns the sums of the properties of all compound parts of the parent body.
* @method _totalProperties
* @private
* @param {body} body
* @return {}
*/
Body._totalProperties = function (body) {
// from equations at:
// https://ecourses.ou.edu/cgi-bin/ebook.cgi?doc=&topic=st&chap_sec=07.2&page=theory
// http://output.to/sideway/default.asp?qno=121100087
var properties = {
mass: 0,
area: 0,
inertia: 0,
centre: {
x: 0,
y: 0
}
};
// sum the properties of all compound parts of the parent body
for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) {
var part = body.parts[i],
mass = part.mass !== Infinity ? part.mass : 1;
properties.mass += mass;
properties.area += part.area;
properties.inertia += part.inertia;
properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass));
}
properties.centre = Vector.div(properties.centre, properties.mass);
return properties;
};
/*
*
* Events Documentation
*
*/
/**
* Fired when a body starts sleeping (where `this` is the body).
*
* @event sleepStart
* @this {body} The body that has started sleeping
* @param {} event An event object
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when a body ends sleeping (where `this` is the body).
*
* @event sleepEnd
* @this {body} The body that has ended sleeping
* @param {} event An event object
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/*
*
* Properties Documentation
*
*/
/**
* An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`.
*
* @property id
* @type number
*/
/**
* A `String` denoting the type of object.
*
* @property type
* @type string
* @default "body"
* @readOnly
*/
/**
* An arbitrary `String` name to help the user identify and manage bodies.
*
* @property label
* @type string
* @default "Body"
*/
/**
* An array of bodies that make up this body.
* The first body in the array must always be a self reference to the current body instance.
* All bodies in the `parts` array together form a single rigid compound body.
* Parts are allowed to overlap, have gaps or holes or even form concave bodies.
* Parts themselves should never be added to a `World`, only the parent body should be.
* Use `Body.setParts` when setting parts to ensure correct updates of all properties.
*
* @property parts
* @type body[]
*/
/**
* An object reserved for storing plugin-specific properties.
*
* @property plugin
* @type {}
*/
/**
* A self reference if the body is _not_ a part of another body.
* Otherwise this is a reference to the body that this is a part of.
* See `body.parts`.
*
* @property parent
* @type body
*/
/**
* A `Number` specifying the angle of the body, in radians.
*
* @property angle
* @type number
* @default 0
*/
/**
* An array of `Vector` objects that specify the convex hull of the rigid body.
* These should be provided about the origin `(0, 0)`. E.g.
*
* [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]
*
* When passed via `Body.create`, the vertices are translated relative to `body.position` (i.e. world-space, and constantly updated by `Body.update` during simulation).
* The `Vector` objects are also augmented with additional properties required for efficient collision detection.
*
* Other properties such as `inertia` and `bounds` are automatically calculated from the passed vertices (unless provided via `options`).
* Concave hulls are not currently supported. The module `Matter.Vertices` contains useful methods for working with vertices.
*
* @property vertices
* @type vector[]
*/
/**
* A `Vector` that specifies the current world-space position of the body.
*
* @property position
* @type vector
* @default { x: 0, y: 0 }
*/
/**
* A `Vector` that specifies the force to apply in the current step. It is zeroed after every `Body.update`. See also `Body.applyForce`.
*
* @property force
* @type vector
* @default { x: 0, y: 0 }
*/
/**
* A `Number` that specifies the torque (turning force) to apply in the current step. It is zeroed after every `Body.update`.
*
* @property torque
* @type number
* @default 0
*/
/**
* A `Number` that _measures_ the current speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.velocity`).
*
* @readOnly
* @property speed
* @type number
* @default 0
*/
/**
* A `Number` that _measures_ the current angular speed of the body after the last `Body.update`. It is read-only and always positive (it's the magnitude of `body.angularVelocity`).
*
* @readOnly
* @property angularSpeed
* @type number
* @default 0
*/
/**
* A `Vector` that _measures_ the current velocity of the body after the last `Body.update`. It is read-only.
* If you need to modify a body's velocity directly, you should either apply a force or simply change the body's `position` (as the engine uses position-Verlet integration).
*
* @readOnly
* @property velocity
* @type vector
* @default { x: 0, y: 0 }
*/
/**
* A `Number` that _measures_ the current angular velocity of the body after the last `Body.update`. It is read-only.
* If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's `angle` (as the engine uses position-Verlet integration).
*
* @readOnly
* @property angularVelocity
* @type number
* @default 0
*/
/**
* A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed.
* If you need to set a body as static after its creation, you should use `Body.setStatic` as this requires more than just setting this flag.
*
* @property isStatic
* @type boolean
* @default false
*/
/**
* A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically.
*
* @property isSensor
* @type boolean
* @default false
*/
/**
* A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken.
* If you need to set a body as sleeping, you should use `Sleeping.set` as this requires more than just setting this flag.
*
* @property isSleeping
* @type boolean
* @default false
*/
/**
* A `Number` that _measures_ the amount of movement a body currently has (a combination of `speed` and `angularSpeed`). It is read-only and always positive.
* It is used and updated by the `Matter.Sleeping` module during simulation to decide if a body has come to rest.
*
* @readOnly
* @property motion
* @type number
* @default 0
*/
/**
* A `Number` that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine).
*
* @property sleepThreshold
* @type number
* @default 60
*/
/**
* A `Number` that defines the density of the body, that is its mass per unit area.
* If you pass the density via `Body.create` the `mass` property is automatically calculated for you based on the size (area) of the object.
* This is generally preferable to simply setting mass and allows for more intuitive definition of materials (e.g. rock has a higher density than wood).
*
* @property density
* @type number
* @default 0.001
*/
/**
* A `Number` that defines the mass of the body, although it may be more appropriate to specify the `density` property instead.
* If you modify this value, you must also modify the `body.inverseMass` property (`1 / mass`).
*
* @property mass
* @type number
*/
/**
* A `Number` that defines the inverse mass of the body (`1 / mass`).
* If you modify this value, you must also modify the `body.mass` property.
*
* @property inverseMass
* @type number
*/
/**
* A `Number` that defines the moment of inertia (i.e. second moment of area) of the body.
* It is automatically calculated from the given convex hull (`vertices` array) and density in `Body.create`.
* If you modify this value, you must also modify the `body.inverseInertia` property (`1 / inertia`).
*
* @property inertia
* @type number
*/
/**
* A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`).
* If you modify this value, you must also modify the `body.inertia` property.
*
* @property inverseInertia
* @type number
*/
/**
* A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`.
* A value of `0` means collisions may be perfectly inelastic and no bouncing may occur.
* A value of `0.8` means the body may bounce back with approximately 80% of its kinetic energy.
* Note that collision response is based on _pairs_ of bodies, and that `restitution` values are _combined_ with the following formula:
*
* Math.max(bodyA.restitution, bodyB.restitution)
*
* @property restitution
* @type number
* @default 0
*/
/**
* A `Number` that defines the friction of the body. The value is always positive and is in the range `(0, 1)`.
* A value of `0` means that the body may slide indefinitely.
* A value of `1` means the body may come to a stop almost instantly after a force is applied.
*
* The effects of the value may be non-linear.
* High values may be unstable depending on the body.
* The engine uses a Coulomb friction model including static and kinetic friction.
* Note that collision response is based on _pairs_ of bodies, and that `friction` values are _combined_ with the following formula:
*
* Math.min(bodyA.friction, bodyB.friction)
*
* @property friction
* @type number
* @default 0.1
*/
/**
* A `Number` that defines the static friction of the body (in the Coulomb friction model).
* A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used.
* The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary.
* This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction.
*
* @property frictionStatic
* @type number
* @default 0.5
*/
/**
* A `Number` that defines the air friction of the body (air resistance).
* A value of `0` means the body will never slow as it moves through space.
* The higher the value, the faster a body slows when moving through space.
* The effects of the value are non-linear.
*
* @property frictionAir
* @type number
* @default 0.01
*/
/**
* An `Object` that specifies the collision filtering properties of this body.
*
* Collisions between two bodies will obey the following rules:
* - If the two bodies have the same non-zero value of `collisionFilter.group`,
* they will always collide if the value is positive, and they will never collide
* if the value is negative.
* - If the two bodies have different values of `collisionFilter.group` or if one
* (or both) of the bodies has a value of 0, then the category/mask rules apply as follows:
*
* Each body belongs to a collision category, given by `collisionFilter.category`. This
* value is used as a bit field and the category should have only one bit set, meaning that
* the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32
* different collision categories available.
*
* Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies
* the categories it collides with (the value is the bitwise AND value of all these categories).
*
* Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's
* category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0`
* are both true.
*
* @property collisionFilter
* @type object
*/
/**
* An Integer `Number`, that specifies the collision group this body belongs to.
* See `body.collisionFilter` for more information.
*
* @property collisionFilter.group
* @type object
* @default 0
*/
/**
* A bit field that specifies the collision category this body belongs to.
* The category value should have only one bit set, for example `0x0001`.
* This means there are up to 32 unique collision categories available.
* See `body.collisionFilter` for more information.
*
* @property collisionFilter.category
* @type object
* @default 1
*/
/**
* A bit mask that specifies the collision categories this body may collide with.
* See `body.collisionFilter` for more information.
*
* @property collisionFilter.mask
* @type object
* @default -1
*/
/**
* A `Number` that specifies a tolerance on how far a body is allowed to 'sink' or rotate into other bodies.
* Avoid changing this value unless you understand the purpose of `slop` in physics engines.
* The default should generally suffice, although very large bodies may require larger values for stable stacking.
*
* @property slop
* @type number
* @default 0.05
*/
/**
* A `Number` that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed.
*
* @property timeScale
* @type number
* @default 1
*/
/**
* An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.
*
* @property render
* @type object
*/
/**
* A flag that indicates if the body should be rendered.
*
* @property render.visible
* @type boolean
* @default true
*/
/**
* Sets the opacity to use when rendering.
*
* @property render.opacity
* @type number
* @default 1
*/
/**
* An `Object` that defines the sprite properties to use when rendering, if any.
*
* @property render.sprite
* @type object
*/
/**
* An `String` that defines the path to the image to use as the sprite texture, if any.
*
* @property render.sprite.texture
* @type string
*/
/**
* A `Number` that defines the scaling in the x-axis for the sprite, if any.
*
* @property render.sprite.xScale
* @type number
* @default 1
*/
/**
* A `Number` that defines the scaling in the y-axis for the sprite, if any.
*
* @property render.sprite.yScale
* @type number
* @default 1
*/
/**
* A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width).
*
* @property render.sprite.xOffset
* @type number
* @default 0
*/
/**
* A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height).
*
* @property render.sprite.yOffset
* @type number
* @default 0
*/
/**
* A `Number` that defines the line width to use when rendering the body outline (if a sprite is not defined).
* A value of `0` means no outline will be rendered.
*
* @property render.lineWidth
* @type number
* @default 0
*/
/**
* A `String` that defines the fill style to use when rendering the body (if a sprite is not defined).
* It is the same as when using a canvas, so it accepts CSS style property values.
*
* @property render.fillStyle
* @type string
* @default a random colour
*/
/**
* A `String` that defines the stroke style to use when rendering the body outline (if a sprite is not defined).
* It is the same as when using a canvas, so it accepts CSS style property values.
*
* @property render.strokeStyle
* @type string
* @default a random colour
*/
/**
* An array of unique axis vectors (edge normals) used for collision detection.
* These are automatically calculated from the given convex hull (`vertices` array) in `Body.create`.
* They are constantly updated by `Body.update` during the simulation.
*
* @property axes
* @type vector[]
*/
/**
* A `Number` that _measures_ the area of the body's convex hull, calculated at creation by `Body.create`.
*
* @property area
* @type string
* @default
*/
/**
* A `Bounds` object that defines the AABB region for the body.
* It is automatically calculated from the given convex hull (`vertices` array) in `Body.create` and constantly updated by `Body.update` during simulation.
*
* @property bounds
* @type bounds
*/
})();
}, {
"../core/Common": 14,
"../core/Sleeping": 22,
"../geometry/Axes": 25,
"../geometry/Bounds": 26,
"../geometry/Vector": 28,
"../geometry/Vertices": 29,
"../render/Render": 31
}],
2: [function (_dereq_, module, exports) {
/**
* The `Matter.Composite` module contains methods for creating and manipulating composite bodies.
* A composite body is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`, therefore composites form a tree structure.
* It is important to use the functions in this module to modify composites, rather than directly modifying their properties.
* Note that the `Matter.World` object is also a type of `Matter.Composite` and as such all composite methods here can also operate on a `Matter.World`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Composite
*/
var Composite = {};
module.exports = Composite;
var Events = _dereq_('../core/Events');
var Common = _dereq_('../core/Common');
var Bounds = _dereq_('../geometry/Bounds');
var Body = _dereq_('./Body');
(function () {
/**
* Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults.
* See the properites section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {} [options]
* @return {composite} A new composite
*/
Composite.create = function (options) {
return Common.extend({
id: Common.nextId(),
type: 'composite',
parent: null,
isModified: false,
bodies: [],
constraints: [],
composites: [],
label: 'Composite',
plugin: {}
}, options);
};
/**
* Sets the composite's `isModified` flag.
* If `updateParents` is true, all parents will be set (default: false).
* If `updateChildren` is true, all children will be set (default: false).
* @method setModified
* @param {composite} composite
* @param {boolean} isModified
* @param {boolean} [updateParents=false]
* @param {boolean} [updateChildren=false]
*/
Composite.setModified = function (composite, isModified, updateParents, updateChildren) {
composite.isModified = isModified;
if (updateParents && composite.parent) {
Composite.setModified(composite.parent, isModified, updateParents, updateChildren);
}
if (updateChildren) {
for (var i = 0; i < composite.composites.length; i++) {
var childComposite = composite.composites[i];
Composite.setModified(childComposite, isModified, updateParents, updateChildren);
}
}
};
/**
* Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite.
* Triggers `beforeAdd` and `afterAdd` events on the `composite`.
* @method add
* @param {composite} composite
* @param {} object
* @return {composite} The original composite with the objects added
*/
Composite.add = function (composite, object) {
var objects = [].concat(object);
Events.trigger(composite, 'beforeAdd', {
object: object
});
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
switch (obj.type) {
case 'body':
// skip adding compound parts
if (obj.parent !== obj) {
Common.warn('Composite.add: skipped adding a compound body part (you must add its parent instead)');
break;
}
Composite.addBody(composite, obj);
break;
case 'constraint':
Composite.addConstraint(composite, obj);
break;
case 'composite':
Composite.addComposite(composite, obj);
break;
case 'mouseConstraint':
Composite.addConstraint(composite, obj.constraint);
break;
}
}
Events.trigger(composite, 'afterAdd', {
object: object
});
return composite;
};
/**
* Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite.
* Optionally searching its children recursively.
* Triggers `beforeRemove` and `afterRemove` events on the `composite`.
* @method remove
* @param {composite} composite
* @param {} object
* @param {boolean} [deep=false]
* @return {composite} The original composite with the objects removed
*/
Composite.remove = function (composite, object, deep) {
var objects = [].concat(object);
Events.trigger(composite, 'beforeRemove', {
object: object
});
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
switch (obj.type) {
case 'body':
Composite.removeBody(composite, obj, deep);
break;
case 'constraint':
Composite.removeConstraint(composite, obj, deep);
break;
case 'composite':
Composite.removeComposite(composite, obj, deep);
break;
case 'mouseConstraint':
Composite.removeConstraint(composite, obj.constraint);
break;
}
}
Events.trigger(composite, 'afterRemove', {
object: object
});
return composite;
};
/**
* Adds a composite to the given composite.
* @private
* @method addComposite
* @param {composite} compositeA
* @param {composite} compositeB
* @return {composite} The original compositeA with the objects from compositeB added
*/
Composite.addComposite = function (compositeA, compositeB) {
compositeA.composites.push(compositeB);
compositeB.parent = compositeA;
Composite.setModified(compositeA, true, true, false);
return compositeA;
};
/**
* Removes a composite from the given composite, and optionally searching its children recursively.
* @private
* @method removeComposite
* @param {composite} compositeA
* @param {composite} compositeB
* @param {boolean} [deep=false]
* @return {composite} The original compositeA with the composite removed
*/
Composite.removeComposite = function (compositeA, compositeB, deep) {
var position = Common.indexOf(compositeA.composites, compositeB);
if (position !== -1) {
Composite.removeCompositeAt(compositeA, position);
Composite.setModified(compositeA, true, true, false);
}
if (deep) {
for (var i = 0; i < compositeA.composites.length; i++) {
Composite.removeComposite(compositeA.composites[i], compositeB, true);
}
}
return compositeA;
};
/**
* Removes a composite from the given composite.
* @private
* @method removeCompositeAt
* @param {composite} composite
* @param {number} position
* @return {composite} The original composite with the composite removed
*/
Composite.removeCompositeAt = function (composite, position) {
composite.composites.splice(position, 1);
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Adds a body to the given composite.
* @private
* @method addBody
* @param {composite} composite
* @param {body} body
* @return {composite} The original composite with the body added
*/
Composite.addBody = function (composite, body) {
composite.bodies.push(body);
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Removes a body from the given composite, and optionally searching its children recursively.
* @private
* @method removeBody
* @param {composite} composite
* @param {body} body
* @param {boolean} [deep=false]
* @return {composite} The original composite with the body removed
*/
Composite.removeBody = function (composite, body, deep) {
var position = Common.indexOf(composite.bodies, body);
if (position !== -1) {
Composite.removeBodyAt(composite, position);
Composite.setModified(composite, true, true, false);
}
if (deep) {
for (var i = 0; i < composite.composites.length; i++) {
Composite.removeBody(composite.composites[i], body, true);
}
}
return composite;
};
/**
* Removes a body from the given composite.
* @private
* @method removeBodyAt
* @param {composite} composite
* @param {number} position
* @return {composite} The original composite with the body removed
*/
Composite.removeBodyAt = function (composite, position) {
composite.bodies.splice(position, 1);
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Adds a constraint to the given composite.
* @private
* @method addConstraint
* @param {composite} composite
* @param {constraint} constraint
* @return {composite} The original composite with the constraint added
*/
Composite.addConstraint = function (composite, constraint) {
composite.constraints.push(constraint);
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Removes a constraint from the given composite, and optionally searching its children recursively.
* @private
* @method removeConstraint
* @param {composite} composite
* @param {constraint} constraint
* @param {boolean} [deep=false]
* @return {composite} The original composite with the constraint removed
*/
Composite.removeConstraint = function (composite, constraint, deep) {
var position = Common.indexOf(composite.constraints, constraint);
if (position !== -1) {
Composite.removeConstraintAt(composite, position);
}
if (deep) {
for (var i = 0; i < composite.composites.length; i++) {
Composite.removeConstraint(composite.composites[i], constraint, true);
}
}
return composite;
};
/**
* Removes a body from the given composite.
* @private
* @method removeConstraintAt
* @param {composite} composite
* @param {number} position
* @return {composite} The original composite with the constraint removed
*/
Composite.removeConstraintAt = function (composite, position) {
composite.constraints.splice(position, 1);
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Removes all bodies, constraints and composites from the given composite.
* Optionally clearing its children recursively.
* @method clear
* @param {composite} composite
* @param {boolean} keepStatic
* @param {boolean} [deep=false]
*/
Composite.clear = function (composite, keepStatic, deep) {
if (deep) {
for (var i = 0; i < composite.composites.length; i++) {
Composite.clear(composite.composites[i], keepStatic, true);
}
}
if (keepStatic) {
composite.bodies = composite.bodies.filter(function (body) {
return body.isStatic;
});
} else {
composite.bodies.length = 0;
}
composite.constraints.length = 0;
composite.composites.length = 0;
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Returns all bodies in the given composite, including all bodies in its children, recursively.
* @method allBodies
* @param {composite} composite
* @return {body[]} All the bodies
*/
Composite.allBodies = function (composite) {
var bodies = [].concat(composite.bodies);
for (var i = 0; i < composite.composites.length; i++)
bodies = bodies.concat(Composite.allBodies(composite.composites[i]));
return bodies;
};
/**
* Returns all constraints in the given composite, including all constraints in its children, recursively.
* @method allConstraints
* @param {composite} composite
* @return {constraint[]} All the constraints
*/
Composite.allConstraints = function (composite) {
var constraints = [].concat(composite.constraints);
for (var i = 0; i < composite.composites.length; i++)
constraints = constraints.concat(Composite.allConstraints(composite.composites[i]));
return constraints;
};
/**
* Returns all composites in the given composite, including all composites in its children, recursively.
* @method allComposites
* @param {composite} composite
* @return {composite[]} All the composites
*/
Composite.allComposites = function (composite) {
var composites = [].concat(composite.composites);
for (var i = 0; i < composite.composites.length; i++)
composites = composites.concat(Composite.allComposites(composite.composites[i]));
return composites;
};
/**
* Searches the composite recursively for an object matching the type and id supplied, null if not found.
* @method get
* @param {composite} composite
* @param {number} id
* @param {string} type
* @return {object} The requested object, if found
*/
Composite.get = function (composite, id, type) {
var objects,
object;
switch (type) {
case 'body':
objects = Composite.allBodies(composite);
break;
case 'constraint':
objects = Composite.allConstraints(composite);
break;
case 'composite':
objects = Composite.allComposites(composite).concat(composite);
break;
}
if (!objects)
return null;
object = objects.filter(function (object) {
return object.id.toString() === id.toString();
});
return object.length === 0 ? null : object[0];
};
/**
* Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add).
* @method move
* @param {compositeA} compositeA
* @param {object[]} objects
* @param {compositeB} compositeB
* @return {composite} Returns compositeA
*/
Composite.move = function (compositeA, objects, compositeB) {
Composite.remove(compositeA, objects);
Composite.add(compositeB, objects);
return compositeA;
};
/**
* Assigns new ids for all objects in the composite, recursively.
* @method rebase
* @param {composite} composite
* @return {composite} Returns composite
*/
Composite.rebase = function (composite) {
var objects = Composite.allBodies(composite)
.concat(Composite.allConstraints(composite))
.concat(Composite.allComposites(composite));
for (var i = 0; i < objects.length; i++) {
objects[i].id = Common.nextId();
}
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Translates all children in the composite by a given vector relative to their current positions,
* without imparting any velocity.
* @method translate
* @param {composite} composite
* @param {vector} translation
* @param {bool} [recursive=true]
*/
Composite.translate = function (composite, translation, recursive) {
var bodies = recursive ? Composite.allBodies(composite) : composite.bodies;
for (var i = 0; i < bodies.length; i++) {
Body.translate(bodies[i], translation);
}
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity.
* @method rotate
* @param {composite} composite
* @param {number} rotation
* @param {vector} point
* @param {bool} [recursive=true]
*/
Composite.rotate = function (composite, rotation, point, recursive) {
var cos = Math.cos(rotation),
sin = Math.sin(rotation),
bodies = recursive ? Composite.allBodies(composite) : composite.bodies;
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i],
dx = body.position.x - point.x,
dy = body.position.y - point.y;
Body.setPosition(body, {
x: point.x + (dx * cos - dy * sin),
y: point.y + (dx * sin + dy * cos)
});
Body.rotate(body, rotation);
}
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point.
* @method scale
* @param {composite} composite
* @param {number} scaleX
* @param {number} scaleY
* @param {vector} point
* @param {bool} [recursive=true]
*/
Composite.scale = function (composite, scaleX, scaleY, point, recursive) {
var bodies = recursive ? Composite.allBodies(composite) : composite.bodies;
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i],
dx = body.position.x - point.x,
dy = body.position.y - point.y;
Body.setPosition(body, {
x: point.x + dx * scaleX,
y: point.y + dy * scaleY
});
Body.scale(body, scaleX, scaleY);
}
Composite.setModified(composite, true, true, false);
return composite;
};
/**
* Returns the union of the bounds of all of the composite's bodies.
* @method bounds
* @param {composite} composite The composite.
* @returns {bounds} The composite bounds.
*/
Composite.bounds = function (composite) {
var bodies = Composite.allBodies(composite),
vertices = [];
for (var i = 0; i < bodies.length; i += 1) {
var body = bodies[i];
vertices.push(body.bounds.min, body.bounds.max);
}
return Bounds.create(vertices);
};
/*
*
* Events Documentation
*
*/
/**
* Fired when a call to `Composite.add` is made, before objects have been added.
*
* @event beforeAdd
* @param {} event An event object
* @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these)
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when a call to `Composite.add` is made, after objects have been added.
*
* @event afterAdd
* @param {} event An event object
* @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these)
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when a call to `Composite.remove` is made, before objects have been removed.
*
* @event beforeRemove
* @param {} event An event object
* @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these)
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when a call to `Composite.remove` is made, after objects have been removed.
*
* @event afterRemove
* @param {} event An event object
* @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these)
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/*
*
* Properties Documentation
*
*/
/**
* An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.
*
* @property id
* @type number
*/
/**
* A `String` denoting the type of object.
*
* @property type
* @type string
* @default "composite"
* @readOnly
*/
/**
* An arbitrary `String` name to help the user identify and manage composites.
*
* @property label
* @type string
* @default "Composite"
*/
/**
* A flag that specifies whether the composite has been modified during the current step.
* Most `Matter.Composite` methods will automatically set this flag to `true` to inform the engine of changes to be handled.
* If you need to change it manually, you should use the `Composite.setModified` method.
*
* @property isModified
* @type boolean
* @default false
*/
/**
* The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods.
*
* @property parent
* @type composite
* @default null
*/
/**
* An array of `Body` that are _direct_ children of this composite.
* To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
* If you wish to recursively find all descendants, you should use the `Composite.allBodies` method.
*
* @property bodies
* @type body[]
* @default []
*/
/**
* An array of `Constraint` that are _direct_ children of this composite.
* To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
* If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method.
*
* @property constraints
* @type constraint[]
* @default []
*/
/**
* An array of `Composite` that are _direct_ children of this composite.
* To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.
* If you wish to recursively find all descendants, you should use the `Composite.allComposites` method.
*
* @property composites
* @type composite[]
* @default []
*/
/**
* An object reserved for storing plugin-specific properties.
*
* @property plugin
* @type {}
*/
})();
}, {
"../core/Common": 14,
"../core/Events": 16,
"../geometry/Bounds": 26,
"./Body": 1
}],
3: [function (_dereq_, module, exports) {
/**
* The `Matter.World` module contains methods for creating and manipulating the world composite.
* A `Matter.World` is a `Matter.Composite` body, which is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite`.
* A `Matter.World` has a few additional properties including `gravity` and `bounds`.
* It is important to use the functions in the `Matter.Composite` module to modify the world composite, rather than directly modifying its properties.
* There are also a few methods here that alias those in `Matter.Composite` for easier readability.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class World
* @extends Composite
*/
var World = {};
module.exports = World;
var Composite = _dereq_('./Composite');
var Constraint = _dereq_('../constraint/Constraint');
var Common = _dereq_('../core/Common');
(function () {
/**
* Creates a new world composite. The options parameter is an object that specifies any properties you wish to override the defaults.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @constructor
* @param {} options
* @return {world} A new world
*/
World.create = function (options) {
var composite = Composite.create();
var defaults = {
label: 'World',
gravity: {
x: 0,
y: 1,
scale: 0.001
},
bounds: {
min: {
x: -Infinity,
y: -Infinity
},
max: {
x: Infinity,
y: Infinity
}
}
};
return Common.extend(composite, defaults, options);
};
/*
*
* Properties Documentation
*
*/
/**
* The gravity to apply on the world.
*
* @property gravity
* @type object
*/
/**
* The gravity x component.
*
* @property gravity.x
* @type object
* @default 0
*/
/**
* The gravity y component.
*
* @property gravity.y
* @type object
* @default 1
*/
/**
* The gravity scale factor.
*
* @property gravity.scale
* @type object
* @default 0.001
*/
/**
* A `Bounds` object that defines the world bounds for collision detection.
*
* @property bounds
* @type bounds
* @default { min: { x: -Infinity, y: -Infinity }, max: { x: Infinity, y: Infinity } }
*/
// World is a Composite body
// see src/module/Outro.js for these aliases:
/**
* An alias for Composite.add
* @method add
* @param {world} world
* @param {} object
* @return {composite} The original world with the objects added
*/
/**
* An alias for Composite.remove
* @method remove
* @param {world} world
* @param {} object
* @param {boolean} [deep=false]
* @return {composite} The original world with the objects removed
*/
/**
* An alias for Composite.clear
* @method clear
* @param {world} world
* @param {boolean} keepStatic
*/
/**
* An alias for Composite.addComposite
* @method addComposite
* @param {world} world
* @param {composite} composite
* @return {world} The original world with the objects from composite added
*/
/**
* An alias for Composite.addBody
* @method addBody
* @param {world} world
* @param {body} body
* @return {world} The original world with the body added
*/
/**
* An alias for Composite.addConstraint
* @method addConstraint
* @param {world} world
* @param {constraint} constraint
* @return {world} The original world with the constraint added
*/
})();
}, {
"../constraint/Constraint": 12,
"../core/Common": 14,
"./Composite": 2
}],
4: [function (_dereq_, module, exports) {
/**
* The `Matter.Contact` module contains methods for creating and manipulating collision contacts.
*
* @class Contact
*/
var Contact = {};
module.exports = Contact;
(function () {
/**
* Creates a new contact.
* @method create
* @param {vertex} vertex
* @return {contact} A new contact
*/
Contact.create = function (vertex) {
return {
id: Contact.id(vertex),
vertex: vertex,
normalImpulse: 0,
tangentImpulse: 0
};
};
/**
* Generates a contact id.
* @method id
* @param {vertex} vertex
* @return {string} Unique contactID
*/
Contact.id = function (vertex) {
return vertex.body.id + '_' + vertex.index;
};
})();
}, {}],
5: [function (_dereq_, module, exports) {
/**
* The `Matter.Detector` module contains methods for detecting collisions given a set of pairs.
*
* @class Detector
*/
// TODO: speculative contacts
var Detector = {};
module.exports = Detector;
var SAT = _dereq_('./SAT');
var Pair = _dereq_('./Pair');
var Bounds = _dereq_('../geometry/Bounds');
(function () {
/**
* Finds all collisions given a list of pairs.
* @method collisions
* @param {pair[]} broadphasePairs
* @param {engine} engine
* @return {array} collisions
*/
Detector.collisions = function (broadphasePairs, engine) {
var collisions = [],
pairsTable = engine.pairs.table;
for (var i = 0; i < broadphasePairs.length; i++) {
var bodyA = broadphasePairs[i][0],
bodyB = broadphasePairs[i][1];
if ((bodyA.isStatic || bodyA.isSleeping) && (bodyB.isStatic || bodyB.isSleeping))
continue;
if (!Detector.canCollide(bodyA.collisionFilter, bodyB.collisionFilter))
continue;
// mid phase
if (Bounds.overlaps(bodyA.bounds, bodyB.bounds)) {
for (var j = bodyA.parts.length > 1 ? 1 : 0; j < bodyA.parts.length; j++) {
var partA = bodyA.parts[j];
for (var k = bodyB.parts.length > 1 ? 1 : 0; k < bodyB.parts.length; k++) {
var partB = bodyB.parts[k];
if ((partA === bodyA && partB === bodyB) || Bounds.overlaps(partA.bounds, partB.bounds)) {
// find a previous collision we could reuse
var pairId = Pair.id(partA, partB),
pair = pairsTable[pairId],
previousCollision;
if (pair && pair.isActive) {
previousCollision = pair.collision;
} else {
previousCollision = null;
}
// narrow phase
var collision = SAT.collides(partA, partB, previousCollision);
if (collision.collided) {
collisions.push(collision);
}
}
}
}
}
}
return collisions;
};
/**
* Returns `true` if both supplied collision filters will allow a collision to occur.
* See `body.collisionFilter` for more information.
* @method canCollide
* @param {} filterA
* @param {} filterB
* @return {bool} `true` if collision can occur
*/
Detector.canCollide = function (filterA, filterB) {
if (filterA.group === filterB.group && filterA.group !== 0)
return filterA.group > 0;
return (filterA.mask & filterB.category) !== 0 && (filterB.mask & filterA.category) !== 0;
};
})();
}, {
"../geometry/Bounds": 26,
"./Pair": 7,
"./SAT": 11
}],
6: [function (_dereq_, module, exports) {
/**
* The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures.
*
* @class Grid
*/
var Grid = {};
module.exports = Grid;
var Pair = _dereq_('./Pair');
var Detector = _dereq_('./Detector');
var Common = _dereq_('../core/Common');
(function () {
/**
* Creates a new grid.
* @method create
* @param {} options
* @return {grid} A new grid
*/
Grid.create = function (options) {
var defaults = {
controller: Grid,
detector: Detector.collisions,
buckets: {},
pairs: {},
pairsList: [],
bucketWidth: 48,
bucketHeight: 48
};
return Common.extend(defaults, options);
};
/**
* The width of a single grid bucket.
*
* @property bucketWidth
* @type number
* @default 48
*/
/**
* The height of a single grid bucket.
*
* @property bucketHeight
* @type number
* @default 48
*/
/**
* Updates the grid.
* @method update
* @param {grid} grid
* @param {body[]} bodies
* @param {engine} engine
* @param {boolean} forceUpdate
*/
Grid.update = function (grid, bodies, engine, forceUpdate) {
var i, col, row,
world = engine.world,
buckets = grid.buckets,
bucket,
bucketId,
gridChanged = false;
for (i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (body.isSleeping && !forceUpdate)
continue;
// don't update out of world bodies
if (body.bounds.max.x < world.bounds.min.x || body.bounds.min.x > world.bounds.max.x ||
body.bounds.max.y < world.bounds.min.y || body.bounds.min.y > world.bounds.max.y)
continue;
var newRegion = Grid._getRegion(grid, body);
// if the body has changed grid region
if (!body.region || newRegion.id !== body.region.id || forceUpdate) {
if (!body.region || forceUpdate)
body.region = newRegion;
var union = Grid._regionUnion(newRegion, body.region);
// update grid buckets affected by region change
// iterate over the union of both regions
for (col = union.startCol; col <= union.endCol; col++) {
for (row = union.startRow; row <= union.endRow; row++) {
bucketId = Grid._getBucketId(col, row);
bucket = buckets[bucketId];
var isInsideNewRegion = (col >= newRegion.startCol && col <= newRegion.endCol &&
row >= newRegion.startRow && row <= newRegion.endRow);
var isInsideOldRegion = (col >= body.region.startCol && col <= body.region.endCol &&
row >= body.region.startRow && row <= body.region.endRow);
// remove from old region buckets
if (!isInsideNewRegion && isInsideOldRegion) {
if (isInsideOldRegion) {
if (bucket)
Grid._bucketRemoveBody(grid, bucket, body);
}
}
// add to new region buckets
if (body.region === newRegion || (isInsideNewRegion && !isInsideOldRegion) || forceUpdate) {
if (!bucket)
bucket = Grid._createBucket(buckets, bucketId);
Grid._bucketAddBody(grid, bucket, body);
}
}
}
// set the new region
body.region = newRegion;
// flag changes so we can update pairs
gridChanged = true;
}
}
// update pairs list only if pairs changed (i.e. a body changed region)
if (gridChanged)
grid.pairsList = Grid._createActivePairsList(grid);
};
/**
* Clears the grid.
* @method clear
* @param {grid} grid
*/
Grid.clear = function (grid) {
grid.buckets = {};
grid.pairs = {};
grid.pairsList = [];
};
/**
* Finds the union of two regions.
* @method _regionUnion
* @private
* @param {} regionA
* @param {} regionB
* @return {} region
*/
Grid._regionUnion = function (regionA, regionB) {
var startCol = Math.min(regionA.startCol, regionB.startCol),
endCol = Math.max(regionA.endCol, regionB.endCol),
startRow = Math.min(regionA.startRow, regionB.startRow),
endRow = Math.max(regionA.endRow, regionB.endRow);
return Grid._createRegion(startCol, endCol, startRow, endRow);
};
/**
* Gets the region a given body falls in for a given grid.
* @method _getRegion
* @private
* @param {} grid
* @param {} body
* @return {} region
*/
Grid._getRegion = function (grid, body) {
var bounds = body.bounds,
startCol = Math.floor(bounds.min.x / grid.bucketWidth),
endCol = Math.floor(bounds.max.x / grid.bucketWidth),
startRow = Math.floor(bounds.min.y / grid.bucketHeight),
endRow = Math.floor(bounds.max.y / grid.bucketHeight);
return Grid._createRegion(startCol, endCol, startRow, endRow);
};
/**
* Creates a region.
* @method _createRegion
* @private
* @param {} startCol
* @param {} endCol
* @param {} startRow
* @param {} endRow
* @return {} region
*/
Grid._createRegion = function (startCol, endCol, startRow, endRow) {
return {
id: startCol + ',' + endCol + ',' + startRow + ',' + endRow,
startCol: startCol,
endCol: endCol,
startRow: startRow,
endRow: endRow
};
};
/**
* Gets the bucket id at the given position.
* @method _getBucketId
* @private
* @param {} column
* @param {} row
* @return {string} bucket id
*/
Grid._getBucketId = function (column, row) {
return 'C' + column + 'R' + row;
};
/**
* Creates a bucket.
* @method _createBucket
* @private
* @param {} buckets
* @param {} bucketId
* @return {} bucket
*/
Grid._createBucket = function (buckets, bucketId) {
var bucket = buckets[bucketId] = [];
return bucket;
};
/**
* Adds a body to a bucket.
* @method _bucketAddBody
* @private
* @param {} grid
* @param {} bucket
* @param {} body
*/
Grid._bucketAddBody = function (grid, bucket, body) {
// add new pairs
for (var i = 0; i < bucket.length; i++) {
var bodyB = bucket[i];
if (body.id === bodyB.id || (body.isStatic && bodyB.isStatic))
continue;
// keep track of the number of buckets the pair exists in
// important for Grid.update to work
var pairId = Pair.id(body, bodyB),
pair = grid.pairs[pairId];
if (pair) {
pair[2] += 1;
} else {
grid.pairs[pairId] = [body, bodyB, 1];
}
}
// add to bodies (after pairs, otherwise pairs with self)
bucket.push(body);
};
/**
* Removes a body from a bucket.
* @method _bucketRemoveBody
* @private
* @param {} grid
* @param {} bucket
* @param {} body
*/
Grid._bucketRemoveBody = function (grid, bucket, body) {
// remove from bucket
bucket.splice(Common.indexOf(bucket, body), 1);
// update pair counts
for (var i = 0; i < bucket.length; i++) {
// keep track of the number of buckets the pair exists in
// important for _createActivePairsList to work
var bodyB = bucket[i],
pairId = Pair.id(body, bodyB),
pair = grid.pairs[pairId];
if (pair)
pair[2] -= 1;
}
};
/**
* Generates a list of the active pairs in the grid.
* @method _createActivePairsList
* @private
* @param {} grid
* @return [] pairs
*/
Grid._createActivePairsList = function (grid) {
var pairKeys,
pair,
pairs = [];
// grid.pairs is used as a hashmap
pairKeys = Common.keys(grid.pairs);
// iterate over grid.pairs
for (var k = 0; k < pairKeys.length; k++) {
pair = grid.pairs[pairKeys[k]];
// if pair exists in at least one bucket
// it is a pair that needs further collision testing so push it
if (pair[2] > 0) {
pairs.push(pair);
} else {
delete grid.pairs[pairKeys[k]];
}
}
return pairs;
};
})();
}, {
"../core/Common": 14,
"./Detector": 5,
"./Pair": 7
}],
7: [function (_dereq_, module, exports) {
/**
* The `Matter.Pair` module contains methods for creating and manipulating collision pairs.
*
* @class Pair
*/
var Pair = {};
module.exports = Pair;
var Contact = _dereq_('./Contact');
(function () {
/**
* Creates a pair.
* @method create
* @param {collision} collision
* @param {number} timestamp
* @return {pair} A new pair
*/
Pair.create = function (collision, timestamp) {
var bodyA = collision.bodyA,
bodyB = collision.bodyB,
parentA = collision.parentA,
parentB = collision.parentB;
var pair = {
id: Pair.id(bodyA, bodyB),
bodyA: bodyA,
bodyB: bodyB,
contacts: {},
activeContacts: [],
separation: 0,
isActive: true,
isSensor: bodyA.isSensor || bodyB.isSensor,
timeCreated: timestamp,
timeUpdated: timestamp,
inverseMass: parentA.inverseMass + parentB.inverseMass,
friction: Math.min(parentA.friction, parentB.friction),
frictionStatic: Math.max(parentA.frictionStatic, parentB.frictionStatic),
restitution: Math.max(parentA.restitution, parentB.restitution),
slop: Math.max(parentA.slop, parentB.slop)
};
Pair.update(pair, collision, timestamp);
return pair;
};
/**
* Updates a pair given a collision.
* @method update
* @param {pair} pair
* @param {collision} collision
* @param {number} timestamp
*/
Pair.update = function (pair, collision, timestamp) {
var contacts = pair.contacts,
supports = collision.supports,
activeContacts = pair.activeContacts,
parentA = collision.parentA,
parentB = collision.parentB;
pair.collision = collision;
pair.inverseMass = parentA.inverseMass + parentB.inverseMass;
pair.friction = Math.min(parentA.friction, parentB.friction);
pair.frictionStatic = Math.max(parentA.frictionStatic, parentB.frictionStatic);
pair.restitution = Math.max(parentA.restitution, parentB.restitution);
pair.slop = Math.max(parentA.slop, parentB.slop);
activeContacts.length = 0;
if (collision.collided) {
for (var i = 0; i < supports.length; i++) {
var support = supports[i],
contactId = Contact.id(support),
contact = contacts[contactId];
if (contact) {
activeContacts.push(contact);
} else {
activeContacts.push(contacts[contactId] = Contact.create(support));
}
}
pair.separation = collision.depth;
Pair.setActive(pair, true, timestamp);
} else {
if (pair.isActive === true)
Pair.setActive(pair, false, timestamp);
}
};
/**
* Set a pair as active or inactive.
* @method setActive
* @param {pair} pair
* @param {bool} isActive
* @param {number} timestamp
*/
Pair.setActive = function (pair, isActive, timestamp) {
if (isActive) {
pair.isActive = true;
pair.timeUpdated = timestamp;
} else {
pair.isActive = false;
pair.activeContacts.length = 0;
}
};
/**
* Get the id for the given pair.
* @method id
* @param {body} bodyA
* @param {body} bodyB
* @return {string} Unique pairId
*/
Pair.id = function (bodyA, bodyB) {
if (bodyA.id < bodyB.id) {
return 'A' + bodyA.id + 'B' + bodyB.id;
} else {
return 'A' + bodyB.id + 'B' + bodyA.id;
}
};
})();
}, {
"./Contact": 4
}],
8: [function (_dereq_, module, exports) {
/**
* The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets.
*
* @class Pairs
*/
var Pairs = {};
module.exports = Pairs;
var Pair = _dereq_('./Pair');
var Common = _dereq_('../core/Common');
(function () {
Pairs._pairMaxIdleLife = 1000;
/**
* Creates a new pairs structure.
* @method create
* @param {object} options
* @return {pairs} A new pairs structure
*/
Pairs.create = function (options) {
return Common.extend({
table: {},
list: [],
collisionStart: [],
collisionActive: [],
collisionEnd: []
}, options);
};
/**
* Updates pairs given a list of collisions.
* @method update
* @param {object} pairs
* @param {collision[]} collisions
* @param {number} timestamp
*/
Pairs.update = function (pairs, collisions, timestamp) {
var pairsList = pairs.list,
pairsTable = pairs.table,
collisionStart = pairs.collisionStart,
collisionEnd = pairs.collisionEnd,
collisionActive = pairs.collisionActive,
activePairIds = [],
collision,
pairId,
pair,
i;
// clear collision state arrays, but maintain old reference
collisionStart.length = 0;
collisionEnd.length = 0;
collisionActive.length = 0;
for (i = 0; i < collisions.length; i++) {
collision = collisions[i];
if (collision.collided) {
pairId = Pair.id(collision.bodyA, collision.bodyB);
activePairIds.push(pairId);
pair = pairsTable[pairId];
if (pair) {
// pair already exists (but may or may not be active)
if (pair.isActive) {
// pair exists and is active
collisionActive.push(pair);
} else {
// pair exists but was inactive, so a collision has just started again
collisionStart.push(pair);
}
// update the pair
Pair.update(pair, collision, timestamp);
} else {
// pair did not exist, create a new pair
pair = Pair.create(collision, timestamp);
pairsTable[pairId] = pair;
// push the new pair
collisionStart.push(pair);
pairsList.push(pair);
}
}
}
// deactivate previously active pairs that are now inactive
for (i = 0; i < pairsList.length; i++) {
pair = pairsList[i];
if (pair.isActive && Common.indexOf(activePairIds, pair.id) === -1) {
Pair.setActive(pair, false, timestamp);
collisionEnd.push(pair);
}
}
};
/**
* Finds and removes pairs that have been inactive for a set amount of time.
* @method removeOld
* @param {object} pairs
* @param {number} timestamp
*/
Pairs.removeOld = function (pairs, timestamp) {
var pairsList = pairs.list,
pairsTable = pairs.table,
indexesToRemove = [],
pair,
collision,
pairIndex,
i;
for (i = 0; i < pairsList.length; i++) {
pair = pairsList[i];
collision = pair.collision;
// never remove sleeping pairs
if (collision.bodyA.isSleeping || collision.bodyB.isSleeping) {
pair.timeUpdated = timestamp;
continue;
}
// if pair is inactive for too long, mark it to be removed
if (timestamp - pair.timeUpdated > Pairs._pairMaxIdleLife) {
indexesToRemove.push(i);
}
}
// remove marked pairs
for (i = 0; i < indexesToRemove.length; i++) {
pairIndex = indexesToRemove[i] - i;
pair = pairsList[pairIndex];
delete pairsTable[pair.id];
pairsList.splice(pairIndex, 1);
}
};
/**
* Clears the given pairs structure.
* @method clear
* @param {pairs} pairs
* @return {pairs} pairs
*/
Pairs.clear = function (pairs) {
pairs.table = {};
pairs.list.length = 0;
pairs.collisionStart.length = 0;
pairs.collisionActive.length = 0;
pairs.collisionEnd.length = 0;
return pairs;
};
})();
}, {
"../core/Common": 14,
"./Pair": 7
}],
9: [function (_dereq_, module, exports) {
/**
* The `Matter.Query` module contains methods for performing collision queries.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Query
*/
var Query = {};
module.exports = Query;
var Vector = _dereq_('../geometry/Vector');
var SAT = _dereq_('./SAT');
var Bounds = _dereq_('../geometry/Bounds');
var Bodies = _dereq_('../factory/Bodies');
var Vertices = _dereq_('../geometry/Vertices');
(function () {
/**
* Returns a list of collisions between `body` and `bodies`.
* @method collides
* @param {body} body
* @param {body[]} bodies
* @return {object[]} Collisions
*/
Query.collides = function (body, bodies) {
var collisions = [];
for (var i = 0; i < bodies.length; i++) {
var bodyA = bodies[i];
if (Bounds.overlaps(bodyA.bounds, body.bounds)) {
for (var j = bodyA.parts.length === 1 ? 0 : 1; j < bodyA.parts.length; j++) {
var part = bodyA.parts[j];
if (Bounds.overlaps(part.bounds, body.bounds)) {
var collision = SAT.collides(part, body);
if (collision.collided) {
collisions.push(collision);
break;
}
}
}
}
}
return collisions;
};
/**
* Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided.
* @method ray
* @param {body[]} bodies
* @param {vector} startPoint
* @param {vector} endPoint
* @param {number} [rayWidth]
* @return {object[]} Collisions
*/
Query.ray = function (bodies, startPoint, endPoint, rayWidth) {
rayWidth = rayWidth || 1e-100;
var rayAngle = Vector.angle(startPoint, endPoint),
rayLength = Vector.magnitude(Vector.sub(startPoint, endPoint)),
rayX = (endPoint.x + startPoint.x) * 0.5,
rayY = (endPoint.y + startPoint.y) * 0.5,
ray = Bodies.rectangle(rayX, rayY, rayLength, rayWidth, {
angle: rayAngle
}),
collisions = Query.collides(ray, bodies);
for (var i = 0; i < collisions.length; i += 1) {
var collision = collisions[i];
collision.body = collision.bodyB = collision.bodyA;
}
return collisions;
};
/**
* Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies.
* @method region
* @param {body[]} bodies
* @param {bounds} bounds
* @param {bool} [outside=false]
* @return {body[]} The bodies matching the query
*/
Query.region = function (bodies, bounds, outside) {
var result = [];
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i],
overlaps = Bounds.overlaps(body.bounds, bounds);
if ((overlaps && !outside) || (!overlaps && outside))
result.push(body);
}
return result;
};
/**
* Returns all bodies whose vertices contain the given point, from the given set of bodies.
* @method point
* @param {body[]} bodies
* @param {vector} point
* @return {body[]} The bodies matching the query
*/
Query.point = function (bodies, point) {
var result = [];
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (Bounds.contains(body.bounds, point)) {
for (var j = body.parts.length === 1 ? 0 : 1; j < body.parts.length; j++) {
var part = body.parts[j];
if (Bounds.contains(part.bounds, point) &&
Vertices.contains(part.vertices, point)) {
result.push(body);
break;
}
}
}
}
return result;
};
})();
}, {
"../factory/Bodies": 23,
"../geometry/Bounds": 26,
"../geometry/Vector": 28,
"../geometry/Vertices": 29,
"./SAT": 11
}],
10: [function (_dereq_, module, exports) {
/**
* The `Matter.Resolver` module contains methods for resolving collision pairs.
*
* @class Resolver
*/
var Resolver = {};
module.exports = Resolver;
var Vertices = _dereq_('../geometry/Vertices');
var Vector = _dereq_('../geometry/Vector');
var Common = _dereq_('../core/Common');
var Bounds = _dereq_('../geometry/Bounds');
(function () {
Resolver._restingThresh = 4;
Resolver._restingThreshTangent = 6;
Resolver._positionDampen = 0.9;
Resolver._positionWarming = 0.8;
Resolver._frictionNormalMultiplier = 5;
/**
* Prepare pairs for position solving.
* @method preSolvePosition
* @param {pair[]} pairs
*/
Resolver.preSolvePosition = function (pairs) {
var i,
pair,
activeCount;
// find total contacts on each body
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive)
continue;
activeCount = pair.activeContacts.length;
pair.collision.parentA.totalContacts += activeCount;
pair.collision.parentB.totalContacts += activeCount;
}
};
/**
* Find a solution for pair positions.
* @method solvePosition
* @param {pair[]} pairs
* @param {number} timeScale
*/
Resolver.solvePosition = function (pairs, timeScale) {
var i,
pair,
collision,
bodyA,
bodyB,
normal,
bodyBtoA,
contactShare,
positionImpulse,
contactCount = {},
tempA = Vector._temp[0],
tempB = Vector._temp[1],
tempC = Vector._temp[2],
tempD = Vector._temp[3];
// find impulses required to resolve penetration
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive || pair.isSensor)
continue;
collision = pair.collision;
bodyA = collision.parentA;
bodyB = collision.parentB;
normal = collision.normal;
// get current separation between body edges involved in collision
bodyBtoA = Vector.sub(Vector.add(bodyB.positionImpulse, bodyB.position, tempA),
Vector.add(bodyA.positionImpulse,
Vector.sub(bodyB.position, collision.penetration, tempB), tempC), tempD);
pair.separation = Vector.dot(normal, bodyBtoA);
}
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive || pair.isSensor)
continue;
collision = pair.collision;
bodyA = collision.parentA;
bodyB = collision.parentB;
normal = collision.normal;
positionImpulse = (pair.separation - pair.slop) * timeScale;
if (bodyA.isStatic || bodyB.isStatic)
positionImpulse *= 2;
if (!(bodyA.isStatic || bodyA.isSleeping)) {
contactShare = Resolver._positionDampen / bodyA.totalContacts;
bodyA.positionImpulse.x += normal.x * positionImpulse * contactShare;
bodyA.positionImpulse.y += normal.y * positionImpulse * contactShare;
}
if (!(bodyB.isStatic || bodyB.isSleeping)) {
contactShare = Resolver._positionDampen / bodyB.totalContacts;
bodyB.positionImpulse.x -= normal.x * positionImpulse * contactShare;
bodyB.positionImpulse.y -= normal.y * positionImpulse * contactShare;
}
}
};
/**
* Apply position resolution.
* @method postSolvePosition
* @param {body[]} bodies
*/
Resolver.postSolvePosition = function (bodies) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
// reset contact count
body.totalContacts = 0;
if (body.positionImpulse.x !== 0 || body.positionImpulse.y !== 0) {
// update body geometry
for (var j = 0; j < body.parts.length; j++) {
var part = body.parts[j];
Vertices.translate(part.vertices, body.positionImpulse);
Bounds.update(part.bounds, part.vertices, body.velocity);
part.position.x += body.positionImpulse.x;
part.position.y += body.positionImpulse.y;
}
// move the body without changing velocity
body.positionPrev.x += body.positionImpulse.x;
body.positionPrev.y += body.positionImpulse.y;
if (Vector.dot(body.positionImpulse, body.velocity) < 0) {
// reset cached impulse if the body has velocity along it
body.positionImpulse.x = 0;
body.positionImpulse.y = 0;
} else {
// warm the next iteration
body.positionImpulse.x *= Resolver._positionWarming;
body.positionImpulse.y *= Resolver._positionWarming;
}
}
}
};
/**
* Prepare pairs for velocity solving.
* @method preSolveVelocity
* @param {pair[]} pairs
*/
Resolver.preSolveVelocity = function (pairs) {
var i,
j,
pair,
contacts,
collision,
bodyA,
bodyB,
normal,
tangent,
contact,
contactVertex,
normalImpulse,
tangentImpulse,
offset,
impulse = Vector._temp[0],
tempA = Vector._temp[1];
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive || pair.isSensor)
continue;
contacts = pair.activeContacts;
collision = pair.collision;
bodyA = collision.parentA;
bodyB = collision.parentB;
normal = collision.normal;
tangent = collision.tangent;
// resolve each contact
for (j = 0; j < contacts.length; j++) {
contact = contacts[j];
contactVertex = contact.vertex;
normalImpulse = contact.normalImpulse;
tangentImpulse = contact.tangentImpulse;
if (normalImpulse !== 0 || tangentImpulse !== 0) {
// total impulse from contact
impulse.x = (normal.x * normalImpulse) + (tangent.x * tangentImpulse);
impulse.y = (normal.y * normalImpulse) + (tangent.y * tangentImpulse);
// apply impulse from contact
if (!(bodyA.isStatic || bodyA.isSleeping)) {
offset = Vector.sub(contactVertex, bodyA.position, tempA);
bodyA.positionPrev.x += impulse.x * bodyA.inverseMass;
bodyA.positionPrev.y += impulse.y * bodyA.inverseMass;
bodyA.anglePrev += Vector.cross(offset, impulse) * bodyA.inverseInertia;
}
if (!(bodyB.isStatic || bodyB.isSleeping)) {
offset = Vector.sub(contactVertex, bodyB.position, tempA);
bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass;
bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass;
bodyB.anglePrev -= Vector.cross(offset, impulse) * bodyB.inverseInertia;
}
}
}
}
};
/**
* Find a solution for pair velocities.
* @method solveVelocity
* @param {pair[]} pairs
* @param {number} timeScale
*/
Resolver.solveVelocity = function (pairs, timeScale) {
var timeScaleSquared = timeScale * timeScale,
impulse = Vector._temp[0],
tempA = Vector._temp[1],
tempB = Vector._temp[2],
tempC = Vector._temp[3],
tempD = Vector._temp[4],
tempE = Vector._temp[5];
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
if (!pair.isActive || pair.isSensor)
continue;
var collision = pair.collision,
bodyA = collision.parentA,
bodyB = collision.parentB,
normal = collision.normal,
tangent = collision.tangent,
contacts = pair.activeContacts,
contactShare = 1 / contacts.length;
// update body velocities
bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x;
bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y;
bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x;
bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y;
bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev;
bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev;
// resolve each contact
for (var j = 0; j < contacts.length; j++) {
var contact = contacts[j],
contactVertex = contact.vertex,
offsetA = Vector.sub(contactVertex, bodyA.position, tempA),
offsetB = Vector.sub(contactVertex, bodyB.position, tempB),
velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity), tempC),
velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity), tempD),
relativeVelocity = Vector.sub(velocityPointA, velocityPointB, tempE),
normalVelocity = Vector.dot(normal, relativeVelocity);
var tangentVelocity = Vector.dot(tangent, relativeVelocity),
tangentSpeed = Math.abs(tangentVelocity),
tangentVelocityDirection = Common.sign(tangentVelocity);
// raw impulses
var normalImpulse = (1 + pair.restitution) * normalVelocity,
normalForce = Common.clamp(pair.separation + normalVelocity, 0, 1) * Resolver._frictionNormalMultiplier;
// coulomb friction
var tangentImpulse = tangentVelocity,
maxFriction = Infinity;
if (tangentSpeed > pair.friction * pair.frictionStatic * normalForce * timeScaleSquared) {
maxFriction = tangentSpeed;
tangentImpulse = Common.clamp(
pair.friction * tangentVelocityDirection * timeScaleSquared, -maxFriction, maxFriction
);
}
// modify impulses accounting for mass, inertia and offset
var oAcN = Vector.cross(offsetA, normal),
oBcN = Vector.cross(offsetB, normal),
share = contactShare / (bodyA.inverseMass + bodyB.inverseMass + bodyA.inverseInertia * oAcN * oAcN + bodyB.inverseInertia * oBcN * oBcN);
normalImpulse *= share;
tangentImpulse *= share;
// handle high velocity and resting collisions separately
if (normalVelocity < 0 && normalVelocity * normalVelocity > Resolver._restingThresh * timeScaleSquared) {
// high normal velocity so clear cached contact normal impulse
contact.normalImpulse = 0;
} else {
// solve resting collision constraints using Erin Catto's method (GDC08)
// impulse constraint tends to 0
var contactNormalImpulse = contact.normalImpulse;
contact.normalImpulse = Math.min(contact.normalImpulse + normalImpulse, 0);
normalImpulse = contact.normalImpulse - contactNormalImpulse;
}
// handle high velocity and resting collisions separately
if (tangentVelocity * tangentVelocity > Resolver._restingThreshTangent * timeScaleSquared) {
// high tangent velocity so clear cached contact tangent impulse
contact.tangentImpulse = 0;
} else {
// solve resting collision constraints using Erin Catto's method (GDC08)
// tangent impulse tends to -tangentSpeed or +tangentSpeed
var contactTangentImpulse = contact.tangentImpulse;
contact.tangentImpulse = Common.clamp(contact.tangentImpulse + tangentImpulse, -maxFriction, maxFriction);
tangentImpulse = contact.tangentImpulse - contactTangentImpulse;
}
// total impulse from contact
impulse.x = (normal.x * normalImpulse) + (tangent.x * tangentImpulse);
impulse.y = (normal.y * normalImpulse) + (tangent.y * tangentImpulse);
// apply impulse from contact
if (!(bodyA.isStatic || bodyA.isSleeping)) {
bodyA.positionPrev.x += impulse.x * bodyA.inverseMass;
bodyA.positionPrev.y += impulse.y * bodyA.inverseMass;
bodyA.anglePrev += Vector.cross(offsetA, impulse) * bodyA.inverseInertia;
}
if (!(bodyB.isStatic || bodyB.isSleeping)) {
bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass;
bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass;
bodyB.anglePrev -= Vector.cross(offsetB, impulse) * bodyB.inverseInertia;
}
}
}
};
})();
}, {
"../core/Common": 14,
"../geometry/Bounds": 26,
"../geometry/Vector": 28,
"../geometry/Vertices": 29
}],
11: [function (_dereq_, module, exports) {
/**
* The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem.
*
* @class SAT
*/
// TODO: true circles and curves
var SAT = {};
module.exports = SAT;
var Vertices = _dereq_('../geometry/Vertices');
var Vector = _dereq_('../geometry/Vector');
(function () {
/**
* Detect collision between two bodies using the Separating Axis Theorem.
* @method collides
* @param {body} bodyA
* @param {body} bodyB
* @param {collision} previousCollision
* @return {collision} collision
*/
SAT.collides = function (bodyA, bodyB, previousCollision) {
var overlapAB,
overlapBA,
minOverlap,
collision,
canReusePrevCol = false;
if (previousCollision) {
// estimate total motion
var parentA = bodyA.parent,
parentB = bodyB.parent,
motion = parentA.speed * parentA.speed + parentA.angularSpeed * parentA.angularSpeed +
parentB.speed * parentB.speed + parentB.angularSpeed * parentB.angularSpeed;
// we may be able to (partially) reuse collision result
// but only safe if collision was resting
canReusePrevCol = previousCollision && previousCollision.collided && motion < 0.2;
// reuse collision object
collision = previousCollision;
} else {
collision = {
collided: false,
bodyA: bodyA,
bodyB: bodyB
};
}
if (previousCollision && canReusePrevCol) {
// if we can reuse the collision result
// we only need to test the previously found axis
var axisBodyA = collision.axisBody,
axisBodyB = axisBodyA === bodyA ? bodyB : bodyA,
axes = [axisBodyA.axes[previousCollision.axisNumber]];
minOverlap = SAT._overlapAxes(axisBodyA.vertices, axisBodyB.vertices, axes);
collision.reused = true;
if (minOverlap.overlap <= 0) {
collision.collided = false;
return collision;
}
} else {
// if we can't reuse a result, perform a full SAT test
overlapAB = SAT._overlapAxes(bodyA.vertices, bodyB.vertices, bodyA.axes);
if (overlapAB.overlap <= 0) {
collision.collided = false;
return collision;
}
overlapBA = SAT._overlapAxes(bodyB.vertices, bodyA.vertices, bodyB.axes);
if (overlapBA.overlap <= 0) {
collision.collided = false;
return collision;
}
if (overlapAB.overlap < overlapBA.overlap) {
minOverlap = overlapAB;
collision.axisBody = bodyA;
} else {
minOverlap = overlapBA;
collision.axisBody = bodyB;
}
// important for reuse later
collision.axisNumber = minOverlap.axisNumber;
}
collision.bodyA = bodyA.id < bodyB.id ? bodyA : bodyB;
collision.bodyB = bodyA.id < bodyB.id ? bodyB : bodyA;
collision.collided = true;
collision.depth = minOverlap.overlap;
collision.parentA = collision.bodyA.parent;
collision.parentB = collision.bodyB.parent;
bodyA = collision.bodyA;
bodyB = collision.bodyB;
// ensure normal is facing away from bodyA
if (Vector.dot(minOverlap.axis, Vector.sub(bodyB.position, bodyA.position)) < 0) {
collision.normal = {
x: minOverlap.axis.x,
y: minOverlap.axis.y
};
} else {
collision.normal = {
x: -minOverlap.axis.x,
y: -minOverlap.axis.y
};
}
collision.tangent = Vector.perp(collision.normal);
collision.penetration = collision.penetration || {};
collision.penetration.x = collision.normal.x * collision.depth;
collision.penetration.y = collision.normal.y * collision.depth;
// find support points, there is always either exactly one or two
var verticesB = SAT._findSupports(bodyA, bodyB, collision.normal),
supports = [];
// find the supports from bodyB that are inside bodyA
if (Vertices.contains(bodyA.vertices, verticesB[0]))
supports.push(verticesB[0]);
if (Vertices.contains(bodyA.vertices, verticesB[1]))
supports.push(verticesB[1]);
// find the supports from bodyA that are inside bodyB
if (supports.length < 2) {
var verticesA = SAT._findSupports(bodyB, bodyA, Vector.neg(collision.normal));
if (Vertices.contains(bodyB.vertices, verticesA[0]))
supports.push(verticesA[0]);
if (supports.length < 2 && Vertices.contains(bodyB.vertices, verticesA[1]))
supports.push(verticesA[1]);
}
// account for the edge case of overlapping but no vertex containment
if (supports.length < 1)
supports = [verticesB[0]];
collision.supports = supports;
return collision;
};
/**
* Find the overlap between two sets of vertices.
* @method _overlapAxes
* @private
* @param {} verticesA
* @param {} verticesB
* @param {} axes
* @return result
*/
SAT._overlapAxes = function (verticesA, verticesB, axes) {
var projectionA = Vector._temp[0],
projectionB = Vector._temp[1],
result = {
overlap: Number.MAX_VALUE
},
overlap,
axis;
for (var i = 0; i < axes.length; i++) {
axis = axes[i];
SAT._projectToAxis(projectionA, verticesA, axis);
SAT._projectToAxis(projectionB, verticesB, axis);
overlap = Math.min(projectionA.max - projectionB.min, projectionB.max - projectionA.min);
if (overlap <= 0) {
result.overlap = overlap;
return result;
}
if (overlap < result.overlap) {
result.overlap = overlap;
result.axis = axis;
result.axisNumber = i;
}
}
return result;
};
/**
* Projects vertices on an axis and returns an interval.
* @method _projectToAxis
* @private
* @param {} projection
* @param {} vertices
* @param {} axis
*/
SAT._projectToAxis = function (projection, vertices, axis) {
var min = Vector.dot(vertices[0], axis),
max = min;
for (var i = 1; i < vertices.length; i += 1) {
var dot = Vector.dot(vertices[i], axis);
if (dot > max) {
max = dot;
} else if (dot < min) {
min = dot;
}
}
projection.min = min;
projection.max = max;
};
/**
* Finds supporting vertices given two bodies along a given direction using hill-climbing.
* @method _findSupports
* @private
* @param {} bodyA
* @param {} bodyB
* @param {} normal
* @return [vector]
*/
SAT._findSupports = function (bodyA, bodyB, normal) {
var nearestDistance = Number.MAX_VALUE,
vertexToBody = Vector._temp[0],
vertices = bodyB.vertices,
bodyAPosition = bodyA.position,
distance,
vertex,
vertexA,
vertexB;
// find closest vertex on bodyB
for (var i = 0; i < vertices.length; i++) {
vertex = vertices[i];
vertexToBody.x = vertex.x - bodyAPosition.x;
vertexToBody.y = vertex.y - bodyAPosition.y;
distance = -Vector.dot(normal, vertexToBody);
if (distance < nearestDistance) {
nearestDistance = distance;
vertexA = vertex;
}
}
// find next closest vertex using the two connected to it
var prevIndex = vertexA.index - 1 >= 0 ? vertexA.index - 1 : vertices.length - 1;
vertex = vertices[prevIndex];
vertexToBody.x = vertex.x - bodyAPosition.x;
vertexToBody.y = vertex.y - bodyAPosition.y;
nearestDistance = -Vector.dot(normal, vertexToBody);
vertexB = vertex;
var nextIndex = (vertexA.index + 1) % vertices.length;
vertex = vertices[nextIndex];
vertexToBody.x = vertex.x - bodyAPosition.x;
vertexToBody.y = vertex.y - bodyAPosition.y;
distance = -Vector.dot(normal, vertexToBody);
if (distance < nearestDistance) {
vertexB = vertex;
}
return [vertexA, vertexB];
};
})();
}, {
"../geometry/Vector": 28,
"../geometry/Vertices": 29
}],
12: [function (_dereq_, module, exports) {
/**
* The `Matter.Constraint` module contains methods for creating and manipulating constraints.
* Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position).
* The stiffness of constraints can be modified to create springs or elastic.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Constraint
*/
var Constraint = {};
module.exports = Constraint;
var Vertices = _dereq_('../geometry/Vertices');
var Vector = _dereq_('../geometry/Vector');
var Sleeping = _dereq_('../core/Sleeping');
var Bounds = _dereq_('../geometry/Bounds');
var Axes = _dereq_('../geometry/Axes');
var Common = _dereq_('../core/Common');
(function () {
Constraint._warming = 0.4;
Constraint._torqueDampen = 1;
Constraint._minLength = 0.000001;
/**
* Creates a new constraint.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* To simulate a revolute constraint (or pin joint) set `length: 0` and a high `stiffness` value (e.g. `0.7` or above).
* If the constraint is unstable, try lowering the `stiffness` value and / or increasing `engine.constraintIterations`.
* For compound bodies, constraints must be applied to the parent body (not one of its parts).
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {} options
* @return {constraint} constraint
*/
Constraint.create = function (options) {
var constraint = options;
// if bodies defined but no points, use body centre
if (constraint.bodyA && !constraint.pointA)
constraint.pointA = {
x: 0,
y: 0
};
if (constraint.bodyB && !constraint.pointB)
constraint.pointB = {
x: 0,
y: 0
};
// calculate static length using initial world space points
var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA,
initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB,
length = Vector.magnitude(Vector.sub(initialPointA, initialPointB));
constraint.length = typeof constraint.length !== 'undefined' ? constraint.length : length;
// option defaults
constraint.id = constraint.id || Common.nextId();
constraint.label = constraint.label || 'Constraint';
constraint.type = 'constraint';
constraint.stiffness = constraint.stiffness || (constraint.length > 0 ? 1 : 0.7);
constraint.damping = constraint.damping || 0;
constraint.angularStiffness = constraint.angularStiffness || 0;
constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA;
constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB;
constraint.plugin = {};
// render
var render = {
visible: true,
lineWidth: 2,
strokeStyle: '#ffffff',
type: 'line',
anchors: true
};
if (constraint.length === 0 && constraint.stiffness > 0.1) {
render.type = 'pin';
render.anchors = false;
} else if (constraint.stiffness < 0.9) {
render.type = 'spring';
}
constraint.render = Common.extend(render, constraint.render);
return constraint;
};
/**
* Prepares for solving by constraint warming.
* @private
* @method preSolveAll
* @param {body[]} bodies
*/
Constraint.preSolveAll = function (bodies) {
for (var i = 0; i < bodies.length; i += 1) {
var body = bodies[i],
impulse = body.constraintImpulse;
if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) {
continue;
}
body.position.x += impulse.x;
body.position.y += impulse.y;
body.angle += impulse.angle;
}
};
/**
* Solves all constraints in a list of collisions.
* @private
* @method solveAll
* @param {constraint[]} constraints
* @param {number} timeScale
*/
Constraint.solveAll = function (constraints, timeScale) {
// Solve fixed constraints first.
for (var i = 0; i < constraints.length; i += 1) {
var constraint = constraints[i],
fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic),
fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic);
if (fixedA || fixedB) {
Constraint.solve(constraints[i], timeScale);
}
}
// Solve free constraints last.
for (i = 0; i < constraints.length; i += 1) {
constraint = constraints[i];
fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic);
fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic);
if (!fixedA && !fixedB) {
Constraint.solve(constraints[i], timeScale);
}
}
};
/**
* Solves a distance constraint with Gauss-Siedel method.
* @private
* @method solve
* @param {constraint} constraint
* @param {number} timeScale
*/
Constraint.solve = function (constraint, timeScale) {
var bodyA = constraint.bodyA,
bodyB = constraint.bodyB,
pointA = constraint.pointA,
pointB = constraint.pointB;
if (!bodyA && !bodyB)
return;
// update reference angle
if (bodyA && !bodyA.isStatic) {
Vector.rotate(pointA, bodyA.angle - constraint.angleA, pointA);
constraint.angleA = bodyA.angle;
}
// update reference angle
if (bodyB && !bodyB.isStatic) {
Vector.rotate(pointB, bodyB.angle - constraint.angleB, pointB);
constraint.angleB = bodyB.angle;
}
var pointAWorld = pointA,
pointBWorld = pointB;
if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA);
if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB);
if (!pointAWorld || !pointBWorld)
return;
var delta = Vector.sub(pointAWorld, pointBWorld),
currentLength = Vector.magnitude(delta);
// prevent singularity
if (currentLength < Constraint._minLength) {
currentLength = Constraint._minLength;
}
// solve distance constraint with Gauss-Siedel method
var difference = (currentLength - constraint.length) / currentLength,
stiffness = constraint.stiffness < 1 ? constraint.stiffness * timeScale : constraint.stiffness,
force = Vector.mult(delta, difference * stiffness),
massTotal = (bodyA ? bodyA.inverseMass : 0) + (bodyB ? bodyB.inverseMass : 0),
inertiaTotal = (bodyA ? bodyA.inverseInertia : 0) + (bodyB ? bodyB.inverseInertia : 0),
resistanceTotal = massTotal + inertiaTotal,
torque,
share,
normal,
normalVelocity,
relativeVelocity;
if (constraint.damping) {
var zero = Vector.create();
normal = Vector.div(delta, currentLength);
relativeVelocity = Vector.sub(
bodyB && Vector.sub(bodyB.position, bodyB.positionPrev) || zero,
bodyA && Vector.sub(bodyA.position, bodyA.positionPrev) || zero
);
normalVelocity = Vector.dot(normal, relativeVelocity);
}
if (bodyA && !bodyA.isStatic) {
share = bodyA.inverseMass / massTotal;
// keep track of applied impulses for post solving
bodyA.constraintImpulse.x -= force.x * share;
bodyA.constraintImpulse.y -= force.y * share;
// apply forces
bodyA.position.x -= force.x * share;
bodyA.position.y -= force.y * share;
// apply damping
if (constraint.damping) {
bodyA.positionPrev.x -= constraint.damping * normal.x * normalVelocity * share;
bodyA.positionPrev.y -= constraint.damping * normal.y * normalVelocity * share;
}
// apply torque
torque = (Vector.cross(pointA, force) / resistanceTotal) * Constraint._torqueDampen * bodyA.inverseInertia * (1 - constraint.angularStiffness);
bodyA.constraintImpulse.angle -= torque;
bodyA.angle -= torque;
}
if (bodyB && !bodyB.isStatic) {
share = bodyB.inverseMass / massTotal;
// keep track of applied impulses for post solving
bodyB.constraintImpulse.x += force.x * share;
bodyB.constraintImpulse.y += force.y * share;
// apply forces
bodyB.position.x += force.x * share;
bodyB.position.y += force.y * share;
// apply damping
if (constraint.damping) {
bodyB.positionPrev.x += constraint.damping * normal.x * normalVelocity * share;
bodyB.positionPrev.y += constraint.damping * normal.y * normalVelocity * share;
}
// apply torque
torque = (Vector.cross(pointB, force) / resistanceTotal) * Constraint._torqueDampen * bodyB.inverseInertia * (1 - constraint.angularStiffness);
bodyB.constraintImpulse.angle += torque;
bodyB.angle += torque;
}
};
/**
* Performs body updates required after solving constraints.
* @private
* @method postSolveAll
* @param {body[]} bodies
*/
Constraint.postSolveAll = function (bodies) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i],
impulse = body.constraintImpulse;
if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) {
continue;
}
Sleeping.set(body, false);
// update geometry and reset
for (var j = 0; j < body.parts.length; j++) {
var part = body.parts[j];
Vertices.translate(part.vertices, impulse);
if (j > 0) {
part.position.x += impulse.x;
part.position.y += impulse.y;
}
if (impulse.angle !== 0) {
Vertices.rotate(part.vertices, impulse.angle, body.position);
Axes.rotate(part.axes, impulse.angle);
if (j > 0) {
Vector.rotateAbout(part.position, impulse.angle, body.position, part.position);
}
}
Bounds.update(part.bounds, part.vertices, body.velocity);
}
// dampen the cached impulse for warming next step
impulse.angle *= Constraint._warming;
impulse.x *= Constraint._warming;
impulse.y *= Constraint._warming;
}
};
/*
*
* Properties Documentation
*
*/
/**
* An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.
*
* @property id
* @type number
*/
/**
* A `String` denoting the type of object.
*
* @property type
* @type string
* @default "constraint"
* @readOnly
*/
/**
* An arbitrary `String` name to help the user identify and manage bodies.
*
* @property label
* @type string
* @default "Constraint"
*/
/**
* An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.
*
* @property render
* @type object
*/
/**
* A flag that indicates if the constraint should be rendered.
*
* @property render.visible
* @type boolean
* @default true
*/
/**
* A `Number` that defines the line width to use when rendering the constraint outline.
* A value of `0` means no outline will be rendered.
*
* @property render.lineWidth
* @type number
* @default 2
*/
/**
* A `String` that defines the stroke style to use when rendering the constraint outline.
* It is the same as when using a canvas, so it accepts CSS style property values.
*
* @property render.strokeStyle
* @type string
* @default a random colour
*/
/**
* A `String` that defines the constraint rendering type.
* The possible values are 'line', 'pin', 'spring'.
* An appropriate render type will be automatically chosen unless one is given in options.
*
* @property render.type
* @type string
* @default 'line'
*/
/**
* A `Boolean` that defines if the constraint's anchor points should be rendered.
*
* @property render.anchors
* @type boolean
* @default true
*/
/**
* The first possible `Body` that this constraint is attached to.
*
* @property bodyA
* @type body
* @default null
*/
/**
* The second possible `Body` that this constraint is attached to.
*
* @property bodyB
* @type body
* @default null
*/
/**
* A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.
*
* @property pointA
* @type vector
* @default { x: 0, y: 0 }
*/
/**
* A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position.
*
* @property pointB
* @type vector
* @default { x: 0, y: 0 }
*/
/**
* A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`.
* A value of `1` means the constraint should be very stiff.
* A value of `0.2` means the constraint acts like a soft spring.
*
* @property stiffness
* @type number
* @default 1
*/
/**
* A `Number` that specifies the damping of the constraint,
* i.e. the amount of resistance applied to each body based on their velocities to limit the amount of oscillation.
* Damping will only be apparent when the constraint also has a very low `stiffness`.
* A value of `0.1` means the constraint will apply heavy damping, resulting in little to no oscillation.
* A value of `0` means the constraint will apply no damping.
*
* @property damping
* @type number
* @default 0
*/
/**
* A `Number` that specifies the target resting length of the constraint.
* It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`.
*
* @property length
* @type number
*/
/**
* An object reserved for storing plugin-specific properties.
*
* @property plugin
* @type {}
*/
})();
}, {
"../core/Common": 14,
"../core/Sleeping": 22,
"../geometry/Axes": 25,
"../geometry/Bounds": 26,
"../geometry/Vector": 28,
"../geometry/Vertices": 29
}],
13: [function (_dereq_, module, exports) {
/**
* The `Matter.MouseConstraint` module contains methods for creating mouse constraints.
* Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class MouseConstraint
*/
var MouseConstraint = {};
module.exports = MouseConstraint;
var Vertices = _dereq_('../geometry/Vertices');
var Sleeping = _dereq_('../core/Sleeping');
var Mouse = _dereq_('../core/Mouse');
var Events = _dereq_('../core/Events');
var Detector = _dereq_('../collision/Detector');
var Constraint = _dereq_('./Constraint');
var Composite = _dereq_('../body/Composite');
var Common = _dereq_('../core/Common');
var Bounds = _dereq_('../geometry/Bounds');
(function () {
/**
* Creates a new mouse constraint.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {engine} engine
* @param {} options
* @return {MouseConstraint} A new MouseConstraint
*/
MouseConstraint.create = function (engine, options) {
var mouse = (engine ? engine.mouse : null) || (options ? options.mouse : null);
if (!mouse) {
if (engine && engine.render && engine.render.canvas) {
mouse = Mouse.create(engine.render.canvas);
} else if (options && options.element) {
mouse = Mouse.create(options.element);
} else {
mouse = Mouse.create();
Common.warn('MouseConstraint.create: options.mouse was undefined, options.element was undefined, may not function as expected');
}
}
var constraint = Constraint.create({
label: 'Mouse Constraint',
pointA: mouse.position,
pointB: {
x: 0,
y: 0
},
length: 0.01,
stiffness: 0.1,
angularStiffness: 1,
render: {
strokeStyle: '#90EE90',
lineWidth: 3
}
});
var defaults = {
type: 'mouseConstraint',
mouse: mouse,
element: null,
body: null,
constraint: constraint,
collisionFilter: {
category: 0x0001,
mask: 0xFFFFFFFF,
group: 0
}
};
var mouseConstraint = Common.extend(defaults, options);
Events.on(engine, 'beforeUpdate', function () {
var allBodies = Composite.allBodies(engine.world);
MouseConstraint.update(mouseConstraint, allBodies);
MouseConstraint._triggerEvents(mouseConstraint);
});
return mouseConstraint;
};
/**
* Updates the given mouse constraint.
* @private
* @method update
* @param {MouseConstraint} mouseConstraint
* @param {body[]} bodies
*/
MouseConstraint.update = function (mouseConstraint, bodies) {
var mouse = mouseConstraint.mouse,
constraint = mouseConstraint.constraint,
body = mouseConstraint.body;
if (mouse.button === 0) {
if (!constraint.bodyB) {
for (var i = 0; i < bodies.length; i++) {
body = bodies[i];
if (Bounds.contains(body.bounds, mouse.position) &&
Detector.canCollide(body.collisionFilter, mouseConstraint.collisionFilter)) {
for (var j = body.parts.length > 1 ? 1 : 0; j < body.parts.length; j++) {
var part = body.parts[j];
if (Vertices.contains(part.vertices, mouse.position)) {
constraint.pointA = mouse.position;
constraint.bodyB = mouseConstraint.body = body;
constraint.pointB = {
x: mouse.position.x - body.position.x,
y: mouse.position.y - body.position.y
};
constraint.angleB = body.angle;
Sleeping.set(body, false);
Events.trigger(mouseConstraint, 'startdrag', {
mouse: mouse,
body: body
});
break;
}
}
}
}
} else {
Sleeping.set(constraint.bodyB, false);
constraint.pointA = mouse.position;
}
} else {
constraint.bodyB = mouseConstraint.body = null;
constraint.pointB = null;
if (body)
Events.trigger(mouseConstraint, 'enddrag', {
mouse: mouse,
body: body
});
}
};
/**
* Triggers mouse constraint events.
* @method _triggerEvents
* @private
* @param {mouse} mouseConstraint
*/
MouseConstraint._triggerEvents = function (mouseConstraint) {
var mouse = mouseConstraint.mouse,
mouseEvents = mouse.sourceEvents;
if (mouseEvents.mousemove)
Events.trigger(mouseConstraint, 'mousemove', {
mouse: mouse
});
if (mouseEvents.mousedown)
Events.trigger(mouseConstraint, 'mousedown', {
mouse: mouse
});
if (mouseEvents.mouseup)
Events.trigger(mouseConstraint, 'mouseup', {
mouse: mouse
});
// reset the mouse state ready for the next step
Mouse.clearSourceEvents(mouse);
};
/*
*
* Events Documentation
*
*/
/**
* Fired when the mouse has moved (or a touch moves) during the last step
*
* @event mousemove
* @param {} event An event object
* @param {mouse} event.mouse The engine's mouse instance
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when the mouse is down (or a touch has started) during the last step
*
* @event mousedown
* @param {} event An event object
* @param {mouse} event.mouse The engine's mouse instance
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when the mouse is up (or a touch has ended) during the last step
*
* @event mouseup
* @param {} event An event object
* @param {mouse} event.mouse The engine's mouse instance
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when the user starts dragging a body
*
* @event startdrag
* @param {} event An event object
* @param {mouse} event.mouse The engine's mouse instance
* @param {body} event.body The body being dragged
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired when the user ends dragging a body
*
* @event enddrag
* @param {} event An event object
* @param {mouse} event.mouse The engine's mouse instance
* @param {body} event.body The body that has stopped being dragged
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/*
*
* Properties Documentation
*
*/
/**
* A `String` denoting the type of object.
*
* @property type
* @type string
* @default "constraint"
* @readOnly
*/
/**
* The `Mouse` instance in use. If not supplied in `MouseConstraint.create`, one will be created.
*
* @property mouse
* @type mouse
* @default mouse
*/
/**
* The `Body` that is currently being moved by the user, or `null` if no body.
*
* @property body
* @type body
* @default null
*/
/**
* The `Constraint` object that is used to move the body during interaction.
*
* @property constraint
* @type constraint
*/
/**
* An `Object` that specifies the collision filter properties.
* The collision filter allows the user to define which types of body this mouse constraint can interact with.
* See `body.collisionFilter` for more information.
*
* @property collisionFilter
* @type object
*/
})();
}, {
"../body/Composite": 2,
"../collision/Detector": 5,
"../core/Common": 14,
"../core/Events": 16,
"../core/Mouse": 19,
"../core/Sleeping": 22,
"../geometry/Bounds": 26,
"../geometry/Vertices": 29,
"./Constraint": 12
}],
14: [function (_dereq_, module, exports) {
(function (global) {
/**
* The `Matter.Common` module contains utility functions that are common to all modules.
*
* @class Common
*/
var Common = {};
module.exports = Common;
(function () {
Common._nextId = 0;
Common._seed = 0;
Common._nowStartTime = +(new Date());
/**
* Extends the object in the first argument using the object in the second argument.
* @method extend
* @param {} obj
* @param {boolean} deep
* @return {} obj extended
*/
Common.extend = function (obj, deep) {
var argsStart,
args,
deepClone;
if (typeof deep === 'boolean') {
argsStart = 2;
deepClone = deep;
} else {
argsStart = 1;
deepClone = true;
}
for (var i = argsStart; i < arguments.length; i++) {
var source = arguments[i];
if (source) {
for (var prop in source) {
if (deepClone && source[prop] && source[prop].constructor === Object) {
if (!obj[prop] || obj[prop].constructor === Object) {
obj[prop] = obj[prop] || {};
Common.extend(obj[prop], deepClone, source[prop]);
} else {
obj[prop] = source[prop];
}
} else {
obj[prop] = source[prop];
}
}
}
}
return obj;
};
/**
* Creates a new clone of the object, if deep is true references will also be cloned.
* @method clone
* @param {} obj
* @param {bool} deep
* @return {} obj cloned
*/
Common.clone = function (obj, deep) {
return Common.extend({}, deep, obj);
};
/**
* Returns the list of keys for the given object.
* @method keys
* @param {} obj
* @return {string[]} keys
*/
Common.keys = function (obj) {
if (Object.keys)
return Object.keys(obj);
// avoid hasOwnProperty for performance
var keys = [];
for (var key in obj)
keys.push(key);
return keys;
};
/**
* Returns the list of values for the given object.
* @method values
* @param {} obj
* @return {array} Array of the objects property values
*/
Common.values = function (obj) {
var values = [];
if (Object.keys) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
values.push(obj[keys[i]]);
}
return values;
}
// avoid hasOwnProperty for performance
for (var key in obj)
values.push(obj[key]);
return values;
};
/**
* Gets a value from `base` relative to the `path` string.
* @method get
* @param {} obj The base object
* @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'
* @param {number} [begin] Path slice begin
* @param {number} [end] Path slice end
* @return {} The object at the given path
*/
Common.get = function (obj, path, begin, end) {
path = path.split('.').slice(begin, end);
for (var i = 0; i < path.length; i += 1) {
obj = obj[path[i]];
}
return obj;
};
/**
* Sets a value on `base` relative to the given `path` string.
* @method set
* @param {} obj The base object
* @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'
* @param {} val The value to set
* @param {number} [begin] Path slice begin
* @param {number} [end] Path slice end
* @return {} Pass through `val` for chaining
*/
Common.set = function (obj, path, val, begin, end) {
var parts = path.split('.').slice(begin, end);
Common.get(obj, path, 0, -1)[parts[parts.length - 1]] = val;
return val;
};
/**
* Shuffles the given array in-place.
* The function uses a seeded random generator.
* @method shuffle
* @param {array} array
* @return {array} array shuffled randomly
*/
Common.shuffle = function (array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Common.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
/**
* Randomly chooses a value from a list with equal probability.
* The function uses a seeded random generator.
* @method choose
* @param {array} choices
* @return {object} A random choice object from the array
*/
Common.choose = function (choices) {
return choices[Math.floor(Common.random() * choices.length)];
};
/**
* Returns true if the object is a HTMLElement, otherwise false.
* @method isElement
* @param {object} obj
* @return {boolean} True if the object is a HTMLElement, otherwise false
*/
Common.isElement = function (obj) {
if (typeof HTMLElement !== 'undefined') {
return obj instanceof HTMLElement;
}
return !!(obj && obj.nodeType && obj.nodeName);
};
/**
* Returns true if the object is an array.
* @method isArray
* @param {object} obj
* @return {boolean} True if the object is an array, otherwise false
*/
Common.isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
/**
* Returns true if the object is a function.
* @method isFunction
* @param {object} obj
* @return {boolean} True if the object is a function, otherwise false
*/
Common.isFunction = function (obj) {
return typeof obj === "function";
};
/**
* Returns true if the object is a plain object.
* @method isPlainObject
* @param {object} obj
* @return {boolean} True if the object is a plain object, otherwise false
*/
Common.isPlainObject = function (obj) {
return typeof obj === 'object' && obj.constructor === Object;
};
/**
* Returns true if the object is a string.
* @method isString
* @param {object} obj
* @return {boolean} True if the object is a string, otherwise false
*/
Common.isString = function (obj) {
return toString.call(obj) === '[object String]';
};
/**
* Returns the given value clamped between a minimum and maximum value.
* @method clamp
* @param {number} value
* @param {number} min
* @param {number} max
* @return {number} The value clamped between min and max inclusive
*/
Common.clamp = function (value, min, max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
};
/**
* Returns the sign of the given value.
* @method sign
* @param {number} value
* @return {number} -1 if negative, +1 if 0 or positive
*/
Common.sign = function (value) {
return value < 0 ? -1 : 1;
};
/**
* Returns the current timestamp since the time origin (e.g. from page load).
* The result will be high-resolution including decimal places if available.
* @method now
* @return {number} the current timestamp
*/
Common.now = function () {
if (window.performance) {
if (window.performance.now) {
return window.performance.now();
} else if (window.performance.webkitNow) {
return window.performance.webkitNow();
}
}
return (new Date()) - Common._nowStartTime;
};
/**
* Returns a random value between a minimum and a maximum value inclusive.
* The function uses a seeded random generator.
* @method random
* @param {number} min
* @param {number} max
* @return {number} A random number between min and max inclusive
*/
Common.random = function (min, max) {
min = (typeof min !== "undefined") ? min : 0;
max = (typeof max !== "undefined") ? max : 1;
return min + _seededRandom() * (max - min);
};
var _seededRandom = function () {
// https://en.wikipedia.org/wiki/Linear_congruential_generator
Common._seed = (Common._seed * 9301 + 49297) % 233280;
return Common._seed / 233280;
};
/**
* Converts a CSS hex colour string into an integer.
* @method colorToNumber
* @param {string} colorString
* @return {number} An integer representing the CSS hex string
*/
Common.colorToNumber = function (colorString) {
colorString = colorString.replace('#', '');
if (colorString.length == 3) {
colorString = colorString.charAt(0) + colorString.charAt(0) +
colorString.charAt(1) + colorString.charAt(1) +
colorString.charAt(2) + colorString.charAt(2);
}
return parseInt(colorString, 16);
};
/**
* The console logging level to use, where each level includes all levels above and excludes the levels below.
* The default level is 'debug' which shows all console messages.
*
* Possible level values are:
* - 0 = None
* - 1 = Debug
* - 2 = Info
* - 3 = Warn
* - 4 = Error
* @property Common.logLevel
* @type {Number}
* @default 1
*/
Common.logLevel = 1;
/**
* Shows a `console.log` message only if the current `Common.logLevel` allows it.
* The message will be prefixed with 'matter-js' to make it easily identifiable.
* @method log
* @param ...objs {} The objects to log.
*/
Common.log = function () {
if (console && Common.logLevel > 0 && Common.logLevel <= 3) {
console.log.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));
}
};
/**
* Shows a `console.info` message only if the current `Common.logLevel` allows it.
* The message will be prefixed with 'matter-js' to make it easily identifiable.
* @method info
* @param ...objs {} The objects to log.
*/
Common.info = function () {
if (console && Common.logLevel > 0 && Common.logLevel <= 2) {
console.info.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));
}
};
/**
* Shows a `console.warn` message only if the current `Common.logLevel` allows it.
* The message will be prefixed with 'matter-js' to make it easily identifiable.
* @method warn
* @param ...objs {} The objects to log.
*/
Common.warn = function () {
if (console && Common.logLevel > 0 && Common.logLevel <= 3) {
console.warn.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));
}
};
/**
* Returns the next unique sequential ID.
* @method nextId
* @return {Number} Unique sequential ID
*/
Common.nextId = function () {
return Common._nextId++;
};
/**
* A cross browser compatible indexOf implementation.
* @method indexOf
* @param {array} haystack
* @param {object} needle
* @return {number} The position of needle in haystack, otherwise -1.
*/
Common.indexOf = function (haystack, needle) {
if (haystack.indexOf)
return haystack.indexOf(needle);
for (var i = 0; i < haystack.length; i++) {
if (haystack[i] === needle)
return i;
}
return -1;
};
/**
* A cross browser compatible array map implementation.
* @method map
* @param {array} list
* @param {function} func
* @return {array} Values from list transformed by func.
*/
Common.map = function (list, func) {
if (list.map) {
return list.map(func);
}
var mapped = [];
for (var i = 0; i < list.length; i += 1) {
mapped.push(func(list[i]));
}
return mapped;
};
/**
* Takes a directed graph and returns the partially ordered set of vertices in topological order.
* Circular dependencies are allowed.
* @method topologicalSort
* @param {object} graph
* @return {array} Partially ordered set of vertices in topological order.
*/
Common.topologicalSort = function (graph) {
// https://github.com/mgechev/javascript-algorithms
// Copyright (c) Minko Gechev (MIT license)
// Modifications: tidy formatting and naming
var result = [],
visited = [],
temp = [];
for (var node in graph) {
if (!visited[node] && !temp[node]) {
Common._topologicalSort(node, visited, temp, graph, result);
}
}
return result;
};
Common._topologicalSort = function (node, visited, temp, graph, result) {
var neighbors = graph[node] || [];
temp[node] = true;
for (var i = 0; i < neighbors.length; i += 1) {
var neighbor = neighbors[i];
if (temp[neighbor]) {
// skip circular dependencies
continue;
}
if (!visited[neighbor]) {
Common._topologicalSort(neighbor, visited, temp, graph, result);
}
}
temp[node] = false;
visited[node] = true;
result.push(node);
};
/**
* Takes _n_ functions as arguments and returns a new function that calls them in order.
* The arguments applied when calling the new function will also be applied to every function passed.
* The value of `this` refers to the last value returned in the chain that was not `undefined`.
* Therefore if a passed function does not return a value, the previously returned value is maintained.
* After all passed functions have been called the new function returns the last returned value (if any).
* If any of the passed functions are a chain, then the chain will be flattened.
* @method chain
* @param ...funcs {function} The functions to chain.
* @return {function} A new function that calls the passed functions in order.
*/
Common.chain = function () {
var funcs = [];
for (var i = 0; i < arguments.length; i += 1) {
var func = arguments[i];
if (func._chained) {
// flatten already chained functions
funcs.push.apply(funcs, func._chained);
} else {
funcs.push(func);
}
}
var chain = function () {
// https://github.com/GoogleChrome/devtools-docs/issues/53#issuecomment-51941358
var lastResult,
args = new Array(arguments.length);
for (var i = 0, l = arguments.length; i < l; i++) {
args[i] = arguments[i];
}
for (i = 0; i < funcs.length; i += 1) {
var result = funcs[i].apply(lastResult, args);
if (typeof result !== 'undefined') {
lastResult = result;
}
}
return lastResult;
};
chain._chained = funcs;
return chain;
};
/**
* Chains a function to excute before the original function on the given `path` relative to `base`.
* See also docs for `Common.chain`.
* @method chainPathBefore
* @param {} base The base object
* @param {string} path The path relative to `base`
* @param {function} func The function to chain before the original
* @return {function} The chained function that replaced the original
*/
Common.chainPathBefore = function (base, path, func) {
return Common.set(base, path, Common.chain(
func,
Common.get(base, path)
));
};
/**
* Chains a function to excute after the original function on the given `path` relative to `base`.
* See also docs for `Common.chain`.
* @method chainPathAfter
* @param {} base The base object
* @param {string} path The path relative to `base`
* @param {function} func The function to chain after the original
* @return {function} The chained function that replaced the original
*/
Common.chainPathAfter = function (base, path, func) {
return Common.set(base, path, Common.chain(
Common.get(base, path),
func
));
};
/**
* Used to require external libraries outside of the bundle.
* It first looks for the `globalName` on the environment's global namespace.
* If the global is not found, it will fall back to using the standard `require` using the `moduleName`.
* @private
* @method _requireGlobal
* @param {string} globalName The global module name
* @param {string} moduleName The fallback CommonJS module name
* @return {} The loaded module
*/
Common._requireGlobal = function (globalName, moduleName) {
var obj = (typeof window !== 'undefined' ? window[globalName] : typeof global !== 'undefined' ? global[globalName] : null);
return obj || _dereq_(moduleName);
};
})();
}).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
}, {}],
15: [function (_dereq_, module, exports) {
/**
* The `Matter.Engine` module contains methods for creating and manipulating engines.
* An engine is a controller that manages updating the simulation of the world.
* See `Matter.Runner` for an optional game loop utility.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Engine
*/
var Engine = {};
module.exports = Engine;
var World = _dereq_('../body/World');
var Sleeping = _dereq_('./Sleeping');
var Resolver = _dereq_('../collision/Resolver');
var Render = _dereq_('../render/Render');
var Pairs = _dereq_('../collision/Pairs');
var Metrics = _dereq_('./Metrics');
var Grid = _dereq_('../collision/Grid');
var Events = _dereq_('./Events');
var Composite = _dereq_('../body/Composite');
var Constraint = _dereq_('../constraint/Constraint');
var Common = _dereq_('./Common');
var Body = _dereq_('../body/Body');
(function () {
/**
* Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {object} [options]
* @return {engine} engine
*/
Engine.create = function (element, options) {
// options may be passed as the first (and only) argument
options = Common.isElement(element) ? options : element;
element = Common.isElement(element) ? element : null;
options = options || {};
if (element || options.render) {
Common.warn('Engine.create: engine.render is deprecated (see docs)');
}
var defaults = {
positionIterations: 6,
velocityIterations: 4,
constraintIterations: 2,
enableSleeping: false,
events: [],
plugin: {},
timing: {
timestamp: 0,
timeScale: 1
},
broadphase: {
controller: Grid
}
};
var engine = Common.extend(defaults, options);
// @deprecated
if (element || engine.render) {
var renderDefaults = {
element: element,
controller: Render
};
engine.render = Common.extend(renderDefaults, engine.render);
}
// @deprecated
if (engine.render && engine.render.controller) {
engine.render = engine.render.controller.create(engine.render);
}
// @deprecated
if (engine.render) {
engine.render.engine = engine;
}
engine.world = options.world || World.create(engine.world);
engine.pairs = Pairs.create();
engine.broadphase = engine.broadphase.controller.create(engine.broadphase);
engine.metrics = engine.metrics || {
extended: false
};
return engine;
};
/**
* Moves the simulation forward in time by `delta` ms.
* The `correction` argument is an optional `Number` that specifies the time correction factor to apply to the update.
* This can help improve the accuracy of the simulation in cases where `delta` is changing between updates.
* The value of `correction` is defined as `delta / lastDelta`, i.e. the percentage change of `delta` over the last step.
* Therefore the value is always `1` (no correction) when `delta` constant (or when no correction is desired, which is the default).
* See the paper on <a href="http://lonesock.net/article/verlet.html">Time Corrected Verlet</a> for more information.
*
* Triggers `beforeUpdate` and `afterUpdate` events.
* Triggers `collisionStart`, `collisionActive` and `collisionEnd` events.
* @method update
* @param {engine} engine
* @param {number} [delta=16.666]
* @param {number} [correction=1]
*/
Engine.update = function (engine, delta, correction) {
delta = delta || 1000 / 60;
correction = correction || 1;
var world = engine.world,
timing = engine.timing,
broadphase = engine.broadphase,
broadphasePairs = [],
i;
// increment timestamp
timing.timestamp += delta * timing.timeScale;
// create an event object
var event = {
timestamp: timing.timestamp
};
Events.trigger(engine, 'beforeUpdate', event);
// get lists of all bodies and constraints, no matter what composites they are in
var allBodies = Composite.allBodies(world),
allConstraints = Composite.allConstraints(world);
// if sleeping enabled, call the sleeping controller
if (engine.enableSleeping)
Sleeping.update(allBodies, timing.timeScale);
// applies gravity to all bodies
Engine._bodiesApplyGravity(allBodies, world.gravity);
// update all body position and rotation by integration
Engine._bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds);
// update all constraints (first pass)
Constraint.preSolveAll(allBodies);
for (i = 0; i < engine.constraintIterations; i++) {
Constraint.solveAll(allConstraints, timing.timeScale);
}
Constraint.postSolveAll(allBodies);
// broadphase pass: find potential collision pairs
if (broadphase.controller) {
// if world is dirty, we must flush the whole grid
if (world.isModified)
broadphase.controller.clear(broadphase);
// update the grid buckets based on current bodies
broadphase.controller.update(broadphase, allBodies, engine, world.isModified);
broadphasePairs = broadphase.pairsList;
} else {
// if no broadphase set, we just pass all bodies
broadphasePairs = allBodies;
}
// clear all composite modified flags
if (world.isModified) {
Composite.setModified(world, false, false, true);
}
// narrowphase pass: find actual collisions, then create or update collision pairs
var collisions = broadphase.detector(broadphasePairs, engine);
// update collision pairs
var pairs = engine.pairs,
timestamp = timing.timestamp;
Pairs.update(pairs, collisions, timestamp);
Pairs.removeOld(pairs, timestamp);
// wake up bodies involved in collisions
if (engine.enableSleeping)
Sleeping.afterCollisions(pairs.list, timing.timeScale);
// trigger collision events
if (pairs.collisionStart.length > 0)
Events.trigger(engine, 'collisionStart', {
pairs: pairs.collisionStart
});
// iteratively resolve position between collisions
Resolver.preSolvePosition(pairs.list);
for (i = 0; i < engine.positionIterations; i++) {
Resolver.solvePosition(pairs.list, timing.timeScale);
}
Resolver.postSolvePosition(allBodies);
// update all constraints (second pass)
Constraint.preSolveAll(allBodies);
for (i = 0; i < engine.constraintIterations; i++) {
Constraint.solveAll(allConstraints, timing.timeScale);
}
Constraint.postSolveAll(allBodies);
// iteratively resolve velocity between collisions
Resolver.preSolveVelocity(pairs.list);
for (i = 0; i < engine.velocityIterations; i++) {
Resolver.solveVelocity(pairs.list, timing.timeScale);
}
// trigger collision events
if (pairs.collisionActive.length > 0)
Events.trigger(engine, 'collisionActive', {
pairs: pairs.collisionActive
});
if (pairs.collisionEnd.length > 0)
Events.trigger(engine, 'collisionEnd', {
pairs: pairs.collisionEnd
});
// clear force buffers
Engine._bodiesClearForces(allBodies);
Events.trigger(engine, 'afterUpdate', event);
return engine;
};
/**
* Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`.
* @method merge
* @param {engine} engineA
* @param {engine} engineB
*/
Engine.merge = function (engineA, engineB) {
Common.extend(engineA, engineB);
if (engineB.world) {
engineA.world = engineB.world;
Engine.clear(engineA);
var bodies = Composite.allBodies(engineA.world);
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
Sleeping.set(body, false);
body.id = Common.nextId();
}
}
};
/**
* Clears the engine including the world, pairs and broadphase.
* @method clear
* @param {engine} engine
*/
Engine.clear = function (engine) {
var world = engine.world;
Pairs.clear(engine.pairs);
var broadphase = engine.broadphase;
if (broadphase.controller) {
var bodies = Composite.allBodies(world);
broadphase.controller.clear(broadphase);
broadphase.controller.update(broadphase, bodies, engine, true);
}
};
/**
* Zeroes the `body.force` and `body.torque` force buffers.
* @method _bodiesClearForces
* @private
* @param {body[]} bodies
*/
Engine._bodiesClearForces = function (bodies) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
// reset force buffers
body.force.x = 0;
body.force.y = 0;
body.torque = 0;
}
};
/**
* Applys a mass dependant force to all given bodies.
* @method _bodiesApplyGravity
* @private
* @param {body[]} bodies
* @param {vector} gravity
*/
Engine._bodiesApplyGravity = function (bodies, gravity) {
var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001;
if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) {
return;
}
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (body.isStatic || body.isSleeping)
continue;
// apply gravity
body.force.y += body.mass * gravity.y * gravityScale;
body.force.x += body.mass * gravity.x * gravityScale;
}
};
/**
* Applys `Body.update` to all given `bodies`.
* @method _bodiesUpdate
* @private
* @param {body[]} bodies
* @param {number} deltaTime
* The amount of time elapsed between updates
* @param {number} timeScale
* @param {number} correction
* The Verlet correction factor (deltaTime / lastDeltaTime)
* @param {bounds} worldBounds
*/
Engine._bodiesUpdate = function (bodies, deltaTime, timeScale, correction, worldBounds) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (body.isStatic || body.isSleeping)
continue;
Body.update(body, deltaTime, timeScale, correction);
}
};
/**
* An alias for `Runner.run`, see `Matter.Runner` for more information.
* @method run
* @param {engine} engine
*/
/**
* Fired just before an update
*
* @event beforeUpdate
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after engine update and all collision events
*
* @event afterUpdate
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any)
*
* @event collisionStart
* @param {} event An event object
* @param {} event.pairs List of affected pairs
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any)
*
* @event collisionActive
* @param {} event An event object
* @param {} event.pairs List of affected pairs
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any)
*
* @event collisionEnd
* @param {} event An event object
* @param {} event.pairs List of affected pairs
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/*
*
* Properties Documentation
*
*/
/**
* An integer `Number` that specifies the number of position iterations to perform each update.
* The higher the value, the higher quality the simulation will be at the expense of performance.
*
* @property positionIterations
* @type number
* @default 6
*/
/**
* An integer `Number` that specifies the number of velocity iterations to perform each update.
* The higher the value, the higher quality the simulation will be at the expense of performance.
*
* @property velocityIterations
* @type number
* @default 4
*/
/**
* An integer `Number` that specifies the number of constraint iterations to perform each update.
* The higher the value, the higher quality the simulation will be at the expense of performance.
* The default value of `2` is usually very adequate.
*
* @property constraintIterations
* @type number
* @default 2
*/
/**
* A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module.
* Sleeping can improve stability and performance, but often at the expense of accuracy.
*
* @property enableSleeping
* @type boolean
* @default false
*/
/**
* An `Object` containing properties regarding the timing systems of the engine.
*
* @property timing
* @type object
*/
/**
* A `Number` that specifies the global scaling factor of time for all bodies.
* A value of `0` freezes the simulation.
* A value of `0.1` gives a slow-motion effect.
* A value of `1.2` gives a speed-up effect.
*
* @property timing.timeScale
* @type number
* @default 1
*/
/**
* A `Number` that specifies the current simulation-time in milliseconds starting from `0`.
* It is incremented on every `Engine.update` by the given `delta` argument.
*
* @property timing.timestamp
* @type number
* @default 0
*/
/**
* An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`.
* One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`.
*
* A minimal custom renderer object must define at least three functions: `create`, `clear` and `world` (see `Matter.Render`).
* It is also possible to instead pass the _module_ reference via `options.render.controller` and `Engine.create` will instantiate one for you.
*
* @property render
* @type render
* @deprecated see Demo.js for an example of creating a renderer
* @default a Matter.Render instance
*/
/**
* An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`.
*
* @property broadphase
* @type grid
* @default a Matter.Grid instance
*/
/**
* A `World` composite object that will contain all simulated bodies and constraints.
*
* @property world
* @type world
* @default a Matter.World instance
*/
/**
* An object reserved for storing plugin-specific properties.
*
* @property plugin
* @type {}
*/
})();
}, {
"../body/Body": 1,
"../body/Composite": 2,
"../body/World": 3,
"../collision/Grid": 6,
"../collision/Pairs": 8,
"../collision/Resolver": 10,
"../constraint/Constraint": 12,
"../render/Render": 31,
"./Common": 14,
"./Events": 16,
"./Metrics": 18,
"./Sleeping": 22
}],
16: [function (_dereq_, module, exports) {
/**
* The `Matter.Events` module contains methods to fire and listen to events on other objects.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Events
*/
var Events = {};
module.exports = Events;
var Common = _dereq_('./Common');
(function () {
/**
* Subscribes a callback function to the given object's `eventName`.
* @method on
* @param {} object
* @param {string} eventNames
* @param {function} callback
*/
Events.on = function (object, eventNames, callback) {
var names = eventNames.split(' '),
name;
for (var i = 0; i < names.length; i++) {
name = names[i];
object.events = object.events || {};
object.events[name] = object.events[name] || [];
object.events[name].push(callback);
}
return callback;
};
/**
* Removes the given event callback. If no callback, clears all callbacks in `eventNames`. If no `eventNames`, clears all events.
* @method off
* @param {} object
* @param {string} eventNames
* @param {function} callback
*/
Events.off = function (object, eventNames, callback) {
if (!eventNames) {
object.events = {};
return;
}
// handle Events.off(object, callback)
if (typeof eventNames === 'function') {
callback = eventNames;
eventNames = Common.keys(object.events).join(' ');
}
var names = eventNames.split(' ');
for (var i = 0; i < names.length; i++) {
var callbacks = object.events[names[i]],
newCallbacks = [];
if (callback && callbacks) {
for (var j = 0; j < callbacks.length; j++) {
if (callbacks[j] !== callback)
newCallbacks.push(callbacks[j]);
}
}
object.events[names[i]] = newCallbacks;
}
};
/**
* Fires all the callbacks subscribed to the given object's `eventName`, in the order they subscribed, if any.
* @method trigger
* @param {} object
* @param {string} eventNames
* @param {} event
*/
Events.trigger = function (object, eventNames, event) {
var names,
name,
callbacks,
eventClone;
if (object.events) {
if (!event)
event = {};
names = eventNames.split(' ');
for (var i = 0; i < names.length; i++) {
name = names[i];
callbacks = object.events[name];
if (callbacks) {
eventClone = Common.clone(event, false);
eventClone.name = name;
eventClone.source = object;
for (var j = 0; j < callbacks.length; j++) {
callbacks[j].apply(object, [eventClone]);
}
}
}
}
};
})();
}, {
"./Common": 14
}],
17: [function (_dereq_, module, exports) {
/**
* The `Matter` module is the top level namespace. It also includes a function for installing plugins on top of the library.
*
* @class Matter
*/
var Matter = {};
module.exports = Matter;
var Plugin = _dereq_('./Plugin');
var Common = _dereq_('./Common');
(function () {
/**
* The library name.
* @property name
* @readOnly
* @type {String}
*/
Matter.name = 'matter-js';
/**
* The library version.
* @property version
* @readOnly
* @type {String}
*/
Matter.version = '0.14.2';
/**
* A list of plugin dependencies to be installed. These are normally set and installed through `Matter.use`.
* Alternatively you may set `Matter.uses` manually and install them by calling `Plugin.use(Matter)`.
* @property uses
* @type {Array}
*/
Matter.uses = [];
/**
* The plugins that have been installed through `Matter.Plugin.install`. Read only.
* @property used
* @readOnly
* @type {Array}
*/
Matter.used = [];
/**
* Installs the given plugins on the `Matter` namespace.
* This is a short-hand for `Plugin.use`, see it for more information.
* Call this function once at the start of your code, with all of the plugins you wish to install as arguments.
* Avoid calling this function multiple times unless you intend to manually control installation order.
* @method use
* @param ...plugin {Function} The plugin(s) to install on `base` (multi-argument).
*/
Matter.use = function () {
Plugin.use(Matter, Array.prototype.slice.call(arguments));
};
/**
* Chains a function to excute before the original function on the given `path` relative to `Matter`.
* See also docs for `Common.chain`.
* @method before
* @param {string} path The path relative to `Matter`
* @param {function} func The function to chain before the original
* @return {function} The chained function that replaced the original
*/
Matter.before = function (path, func) {
path = path.replace(/^Matter./, '');
return Common.chainPathBefore(Matter, path, func);
};
/**
* Chains a function to excute after the original function on the given `path` relative to `Matter`.
* See also docs for `Common.chain`.
* @method after
* @param {string} path The path relative to `Matter`
* @param {function} func The function to chain after the original
* @return {function} The chained function that replaced the original
*/
Matter.after = function (path, func) {
path = path.replace(/^Matter./, '');
return Common.chainPathAfter(Matter, path, func);
};
})();
}, {
"./Common": 14,
"./Plugin": 20
}],
18: [function (_dereq_, module, exports) {
}, {
"../body/Composite": 2,
"./Common": 14
}],
19: [function (_dereq_, module, exports) {
/**
* The `Matter.Mouse` module contains methods for creating and manipulating mouse inputs.
*
* @class Mouse
*/
var Mouse = {};
module.exports = Mouse;
var Common = _dereq_('../core/Common');
(function () {
/**
* Creates a mouse input.
* @method create
* @param {HTMLElement} element
* @return {mouse} A new mouse
*/
Mouse.create = function (element) {
var mouse = {};
if (!element) {
Common.log('Mouse.create: element was undefined, defaulting to document.body', 'warn');
}
mouse.element = element || document.body;
mouse.absolute = {
x: 0,
y: 0
};
mouse.position = {
x: 0,
y: 0
};
mouse.mousedownPosition = {
x: 0,
y: 0
};
mouse.mouseupPosition = {
x: 0,
y: 0
};
mouse.offset = {
x: 0,
y: 0
};
mouse.scale = {
x: 1,
y: 1
};
mouse.wheelDelta = 0;
mouse.button = -1;
mouse.pixelRatio = mouse.element.getAttribute('data-pixel-ratio') || 1;
mouse.sourceEvents = {
mousemove: null,
mousedown: null,
mouseup: null,
mousewheel: null
};
mouse.mousemove = function (event) {
var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),
touches = event.changedTouches;
if (touches) {
mouse.button = 0;
event.preventDefault();
}
mouse.absolute.x = position.x;
mouse.absolute.y = position.y;
mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;
mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;
mouse.sourceEvents.mousemove = event;
};
mouse.mousedown = function (event) {
var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),
touches = event.changedTouches;
if (touches) {
mouse.button = 0;
event.preventDefault();
} else {
mouse.button = event.button;
}
mouse.absolute.x = position.x;
mouse.absolute.y = position.y;
mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;
mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;
mouse.mousedownPosition.x = mouse.position.x;
mouse.mousedownPosition.y = mouse.position.y;
mouse.sourceEvents.mousedown = event;
};
mouse.mouseup = function (event) {
var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),
touches = event.changedTouches;
if (touches) {
event.preventDefault();
}
mouse.button = -1;
mouse.absolute.x = position.x;
mouse.absolute.y = position.y;
mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;
mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;
mouse.mouseupPosition.x = mouse.position.x;
mouse.mouseupPosition.y = mouse.position.y;
mouse.sourceEvents.mouseup = event;
};
mouse.mousewheel = function (event) {
mouse.wheelDelta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail));
event.preventDefault();
};
Mouse.setElement(mouse, mouse.element);
return mouse;
};
/**
* Sets the element the mouse is bound to (and relative to).
* @method setElement
* @param {mouse} mouse
* @param {HTMLElement} element
*/
Mouse.setElement = function (mouse, element) {
mouse.element = element;
element.addEventListener('mousemove', mouse.mousemove);
element.addEventListener('mousedown', mouse.mousedown);
element.addEventListener('mouseup', mouse.mouseup);
element.addEventListener('mousewheel', mouse.mousewheel);
element.addEventListener('DOMMouseScroll', mouse.mousewheel);
element.addEventListener('touchmove', mouse.mousemove);
element.addEventListener('touchstart', mouse.mousedown);
element.addEventListener('touchend', mouse.mouseup);
};
/**
* Clears all captured source events.
* @method clearSourceEvents
* @param {mouse} mouse
*/
Mouse.clearSourceEvents = function (mouse) {
mouse.sourceEvents.mousemove = null;
mouse.sourceEvents.mousedown = null;
mouse.sourceEvents.mouseup = null;
mouse.sourceEvents.mousewheel = null;
mouse.wheelDelta = 0;
};
/**
* Sets the mouse position offset.
* @method setOffset
* @param {mouse} mouse
* @param {vector} offset
*/
Mouse.setOffset = function (mouse, offset) {
mouse.offset.x = offset.x;
mouse.offset.y = offset.y;
mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;
mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;
};
/**
* Sets the mouse position scale.
* @method setScale
* @param {mouse} mouse
* @param {vector} scale
*/
Mouse.setScale = function (mouse, scale) {
mouse.scale.x = scale.x;
mouse.scale.y = scale.y;
mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;
mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;
};
/**
* Gets the mouse position relative to an element given a screen pixel ratio.
* @method _getRelativeMousePosition
* @private
* @param {} event
* @param {} element
* @param {number} pixelRatio
* @return {}
*/
Mouse._getRelativeMousePosition = function (event, element, pixelRatio) {
var elementBounds = element.getBoundingClientRect(),
rootNode = (document.documentElement || document.body.parentNode || document.body),
scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset : rootNode.scrollLeft,
scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : rootNode.scrollTop,
touches = event.changedTouches,
x, y;
if (touches) {
x = touches[0].pageX - elementBounds.left - scrollX;
y = touches[0].pageY - elementBounds.top - scrollY;
} else {
x = event.pageX - elementBounds.left - scrollX;
y = event.pageY - elementBounds.top - scrollY;
}
return {
x: x / (element.clientWidth / (element.width || element.clientWidth) * pixelRatio),
y: y / (element.clientHeight / (element.height || element.clientHeight) * pixelRatio)
};
};
})();
}, {
"../core/Common": 14
}],
20: [function (_dereq_, module, exports) {
/**
* The `Matter.Plugin` module contains functions for registering and installing plugins on modules.
*
* @class Plugin
*/
var Plugin = {};
module.exports = Plugin;
var Common = _dereq_('./Common');
(function () {
Plugin._registry = {};
/**
* Registers a plugin object so it can be resolved later by name.
* @method register
* @param plugin {} The plugin to register.
* @return {object} The plugin.
*/
Plugin.register = function (plugin) {
if (!Plugin.isPlugin(plugin)) {
Common.warn('Plugin.register:', Plugin.toString(plugin), 'does not implement all required fields.');
}
if (plugin.name in Plugin._registry) {
var registered = Plugin._registry[plugin.name],
pluginVersion = Plugin.versionParse(plugin.version).number,
registeredVersion = Plugin.versionParse(registered.version).number;
if (pluginVersion > registeredVersion) {
Common.warn('Plugin.register:', Plugin.toString(registered), 'was upgraded to', Plugin.toString(plugin));
Plugin._registry[plugin.name] = plugin;
} else if (pluginVersion < registeredVersion) {
Common.warn('Plugin.register:', Plugin.toString(registered), 'can not be downgraded to', Plugin.toString(plugin));
} else if (plugin !== registered) {
Common.warn('Plugin.register:', Plugin.toString(plugin), 'is already registered to different plugin object');
}
} else {
Plugin._registry[plugin.name] = plugin;
}
return plugin;
};
/**
* Resolves a dependency to a plugin object from the registry if it exists.
* The `dependency` may contain a version, but only the name matters when resolving.
* @method resolve
* @param dependency {string} The dependency.
* @return {object} The plugin if resolved, otherwise `undefined`.
*/
Plugin.resolve = function (dependency) {
return Plugin._registry[Plugin.dependencyParse(dependency).name];
};
/**
* Returns a pretty printed plugin name and version.
* @method toString
* @param plugin {} The plugin.
* @return {string} Pretty printed plugin name and version.
*/
Plugin.toString = function (plugin) {
return typeof plugin === 'string' ? plugin : (plugin.name || 'anonymous') + '@' + (plugin.version || plugin.range || '0.0.0');
};
/**
* Returns `true` if the object meets the minimum standard to be considered a plugin.
* This means it must define the following properties:
* - `name`
* - `version`
* - `install`
* @method isPlugin
* @param obj {} The obj to test.
* @return {boolean} `true` if the object can be considered a plugin otherwise `false`.
*/
Plugin.isPlugin = function (obj) {
return obj && obj.name && obj.version && obj.install;
};
/**
* Returns `true` if a plugin with the given `name` been installed on `module`.
* @method isUsed
* @param module {} The module.
* @param name {string} The plugin name.
* @return {boolean} `true` if a plugin with the given `name` been installed on `module`, otherwise `false`.
*/
Plugin.isUsed = function (module, name) {
return module.used.indexOf(name) > -1;
};
/**
* Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`.
* If `plugin.for` is not specified then it is assumed to be applicable.
* The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`.
* @method isFor
* @param plugin {} The plugin.
* @param module {} The module.
* @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`.
*/
Plugin.isFor = function (plugin, module) {
var parsed = plugin.for && Plugin.dependencyParse(plugin.for);
return !plugin.for || (module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range));
};
/**
* Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`.
* For installing plugins on `Matter` see the convenience function `Matter.use`.
* Plugins may be specified either by their name or a reference to the plugin object.
* Plugins themselves may specify further dependencies, but each plugin is installed only once.
* Order is important, a topological sort is performed to find the best resulting order of installation.
* This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases.
* This function logs the resulting status of each dependency in the console, along with any warnings.
* - A green tick ✅ indicates a dependency was resolved and installed.
* - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies.
* - A red cross ❌ indicates a dependency could not be resolved.
* Avoid calling this function multiple times on the same module unless you intend to manually control installation order.
* @method use
* @param module {} The module install plugins on.
* @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`).
*/
Plugin.use = function (module, plugins) {
module.uses = (module.uses || []).concat(plugins || []);
if (module.uses.length === 0) {
Common.warn('Plugin.use:', Plugin.toString(module), 'does not specify any dependencies to install.');
return;
}
var dependencies = Plugin.dependencies(module),
sortedDependencies = Common.topologicalSort(dependencies),
status = [];
for (var i = 0; i < sortedDependencies.length; i += 1) {
if (sortedDependencies[i] === module.name) {
continue;
}
var plugin = Plugin.resolve(sortedDependencies[i]);
if (!plugin) {
status.push('❌ ' + sortedDependencies[i]);
continue;
}
if (Plugin.isUsed(module, plugin.name)) {
continue;
}
if (!Plugin.isFor(plugin, module)) {
Common.warn('Plugin.use:', Plugin.toString(plugin), 'is for', plugin.for, 'but installed on', Plugin.toString(module) + '.');
plugin._warned = true;
}
if (plugin.install) {
plugin.install(module);
} else {
Common.warn('Plugin.use:', Plugin.toString(plugin), 'does not specify an install function.');
plugin._warned = true;
}
if (plugin._warned) {
status.push('🔶 ' + Plugin.toString(plugin));
delete plugin._warned;
} else {
status.push('✅ ' + Plugin.toString(plugin));
}
module.used.push(plugin.name);
}
if (status.length > 0) {
Common.info(status.join(' '));
}
};
/**
* Recursively finds all of a module's dependencies and returns a flat dependency graph.
* @method dependencies
* @param module {} The module.
* @return {object} A dependency graph.
*/
Plugin.dependencies = function (module, tracked) {
var parsedBase = Plugin.dependencyParse(module),
name = parsedBase.name;
tracked = tracked || {};
if (name in tracked) {
return;
}
module = Plugin.resolve(module) || module;
tracked[name] = Common.map(module.uses || [], function (dependency) {
if (Plugin.isPlugin(dependency)) {
Plugin.register(dependency);
}
var parsed = Plugin.dependencyParse(dependency),
resolved = Plugin.resolve(dependency);
if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) {
Common.warn(
'Plugin.dependencies:', Plugin.toString(resolved), 'does not satisfy',
Plugin.toString(parsed), 'used by', Plugin.toString(parsedBase) + '.'
);
resolved._warned = true;
module._warned = true;
} else if (!resolved) {
Common.warn(
'Plugin.dependencies:', Plugin.toString(dependency), 'used by',
Plugin.toString(parsedBase), 'could not be resolved.'
);
module._warned = true;
}
return parsed.name;
});
for (var i = 0; i < tracked[name].length; i += 1) {
Plugin.dependencies(tracked[name][i], tracked);
}
return tracked;
};
/**
* Parses a dependency string into its components.
* The `dependency` is a string of the format `'module-name'` or `'module-name@version'`.
* See documentation for `Plugin.versionParse` for a description of the format.
* This function can also handle dependencies that are already resolved (e.g. a module object).
* @method dependencyParse
* @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`.
* @return {object} The dependency parsed into its components.
*/
Plugin.dependencyParse = function (dependency) {
if (Common.isString(dependency)) {
var pattern = /^[\w-]+(@(\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?))?$/;
if (!pattern.test(dependency)) {
Common.warn('Plugin.dependencyParse:', dependency, 'is not a valid dependency string.');
}
return {
name: dependency.split('@')[0],
range: dependency.split('@')[1] || '*'
};
}
return {
name: dependency.name,
range: dependency.range || dependency.version
};
};
/**
* Parses a version string into its components.
* Versions are strictly of the format `x.y.z` (as in [semver](http://semver.org/)).
* Versions may optionally have a prerelease tag in the format `x.y.z-alpha`.
* Ranges are a strict subset of [npm ranges](https://docs.npmjs.com/misc/semver#advanced-range-syntax).
* Only the following range types are supported:
* - Tilde ranges e.g. `~1.2.3`
* - Caret ranges e.g. `^1.2.3`
* - Exact version e.g. `1.2.3`
* - Any version `*`
* @method versionParse
* @param range {string} The version string.
* @return {object} The version range parsed into its components.
*/
Plugin.versionParse = function (range) {
var pattern = /^\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?$/;
if (!pattern.test(range)) {
Common.warn('Plugin.versionParse:', range, 'is not a valid version or range.');
}
var identifiers = range.split('-');
range = identifiers[0];
var isRange = isNaN(Number(range[0])),
version = isRange ? range.substr(1) : range,
parts = Common.map(version.split('.'), function (part) {
return Number(part);
});
return {
isRange: isRange,
version: version,
range: range,
operator: isRange ? range[0] : '',
parts: parts,
prerelease: identifiers[1],
number: parts[0] * 1e8 + parts[1] * 1e4 + parts[2]
};
};
/**
* Returns `true` if `version` satisfies the given `range`.
* See documentation for `Plugin.versionParse` for a description of the format.
* If a version or range is not specified, then any version (`*`) is assumed to satisfy.
* @method versionSatisfies
* @param version {string} The version string.
* @param range {string} The range string.
* @return {boolean} `true` if `version` satisfies `range`, otherwise `false`.
*/
Plugin.versionSatisfies = function (version, range) {
range = range || '*';
var rangeParsed = Plugin.versionParse(range),
rangeParts = rangeParsed.parts,
versionParsed = Plugin.versionParse(version),
versionParts = versionParsed.parts;
if (rangeParsed.isRange) {
if (rangeParsed.operator === '*' || version === '*') {
return true;
}
if (rangeParsed.operator === '~') {
return versionParts[0] === rangeParts[0] && versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2];
}
if (rangeParsed.operator === '^') {
if (rangeParts[0] > 0) {
return versionParts[0] === rangeParts[0] && versionParsed.number >= rangeParsed.number;
}
if (rangeParts[1] > 0) {
return versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2];
}
return versionParts[2] === rangeParts[2];
}
}
return version === range || version === '*';
};
})();
}, {
"./Common": 14
}],
21: [function (_dereq_, module, exports) {
/**
* The `Matter.Runner` module is an optional utility which provides a game loop,
* that handles continuously updating a `Matter.Engine` for you within a browser.
* It is intended for development and debugging purposes, but may also be suitable for simple games.
* If you are using your own game loop instead, then you do not need the `Matter.Runner` module.
* Instead just call `Engine.update(engine, delta)` in your own loop.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Runner
*/
var Runner = {};
module.exports = Runner;
var Events = _dereq_('./Events');
var Engine = _dereq_('./Engine');
var Common = _dereq_('./Common');
(function () {
var _requestAnimationFrame,
_cancelAnimationFrame;
if (typeof window !== 'undefined') {
_requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
_cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame || window.msCancelAnimationFrame;
}
if (!_requestAnimationFrame) {
var _frameTimeout;
_requestAnimationFrame = function (callback) {
_frameTimeout = setTimeout(function () {
callback(Common.now());
}, 1000 / 60);
};
_cancelAnimationFrame = function () {
clearTimeout(_frameTimeout);
};
}
/**
* Creates a new Runner. The options parameter is an object that specifies any properties you wish to override the defaults.
* @method create
* @param {} options
*/
Runner.create = function (options) {
var defaults = {
fps: 60,
correction: 1,
deltaSampleSize: 60,
counterTimestamp: 0,
frameCounter: 0,
deltaHistory: [],
timePrev: null,
timeScalePrev: 1,
frameRequestId: null,
isFixed: false,
enabled: true
};
var runner = Common.extend(defaults, options);
runner.delta = runner.delta || 1000 / runner.fps;
runner.deltaMin = runner.deltaMin || 1000 / runner.fps;
runner.deltaMax = runner.deltaMax || 1000 / (runner.fps * 0.5);
runner.fps = 1000 / runner.delta;
return runner;
};
/**
* Continuously ticks a `Matter.Engine` by calling `Runner.tick` on the `requestAnimationFrame` event.
* @method run
* @param {engine} engine
*/
Runner.run = function (runner, engine) {
// create runner if engine is first argument
if (typeof runner.positionIterations !== 'undefined') {
engine = runner;
runner = Runner.create();
}
(function render(time) {
runner.frameRequestId = _requestAnimationFrame(render);
if (time && runner.enabled) {
Runner.tick(runner, engine, time);
}
})();
return runner;
};
/**
* A game loop utility that updates the engine and renderer by one step (a 'tick').
* Features delta smoothing, time correction and fixed or dynamic timing.
* Triggers `beforeTick`, `tick` and `afterTick` events on the engine.
* Consider just `Engine.update(engine, delta)` if you're using your own loop.
* @method tick
* @param {runner} runner
* @param {engine} engine
* @param {number} time
*/
Runner.tick = function (runner, engine, time) {
var timing = engine.timing,
correction = 1,
delta;
// create an event object
var event = {
timestamp: timing.timestamp
};
Events.trigger(runner, 'beforeTick', event);
Events.trigger(engine, 'beforeTick', event); // @deprecated
if (runner.isFixed) {
// fixed timestep
delta = runner.delta;
} else {
// dynamic timestep based on wall clock between calls
delta = (time - runner.timePrev) || runner.delta;
runner.timePrev = time;
// optimistically filter delta over a few frames, to improve stability
runner.deltaHistory.push(delta);
runner.deltaHistory = runner.deltaHistory.slice(-runner.deltaSampleSize);
delta = Math.min.apply(null, runner.deltaHistory);
// limit delta
delta = delta < runner.deltaMin ? runner.deltaMin : delta;
delta = delta > runner.deltaMax ? runner.deltaMax : delta;
// correction for delta
correction = delta / runner.delta;
// update engine timing object
runner.delta = delta;
}
// time correction for time scaling
if (runner.timeScalePrev !== 0)
correction *= timing.timeScale / runner.timeScalePrev;
if (timing.timeScale === 0)
correction = 0;
runner.timeScalePrev = timing.timeScale;
runner.correction = correction;
// fps counter
runner.frameCounter += 1;
if (time - runner.counterTimestamp >= 1000) {
runner.fps = runner.frameCounter * ((time - runner.counterTimestamp) / 1000);
runner.counterTimestamp = time;
runner.frameCounter = 0;
}
Events.trigger(runner, 'tick', event);
Events.trigger(engine, 'tick', event); // @deprecated
// if world has been modified, clear the render scene graph
if (engine.world.isModified &&
engine.render &&
engine.render.controller &&
engine.render.controller.clear) {
engine.render.controller.clear(engine.render); // @deprecated
}
// update
Events.trigger(runner, 'beforeUpdate', event);
Engine.update(engine, delta, correction);
Events.trigger(runner, 'afterUpdate', event);
// render
// @deprecated
if (engine.render && engine.render.controller) {
Events.trigger(runner, 'beforeRender', event);
Events.trigger(engine, 'beforeRender', event); // @deprecated
engine.render.controller.world(engine.render);
Events.trigger(runner, 'afterRender', event);
Events.trigger(engine, 'afterRender', event); // @deprecated
}
Events.trigger(runner, 'afterTick', event);
Events.trigger(engine, 'afterTick', event); // @deprecated
};
/**
* Ends execution of `Runner.run` on the given `runner`, by canceling the animation frame request event loop.
* If you wish to only temporarily pause the engine, see `engine.enabled` instead.
* @method stop
* @param {runner} runner
*/
Runner.stop = function (runner) {
_cancelAnimationFrame(runner.frameRequestId);
};
/**
* Alias for `Runner.run`.
* @method start
* @param {runner} runner
* @param {engine} engine
*/
Runner.start = function (runner, engine) {
Runner.run(runner, engine);
};
/*
*
* Events Documentation
*
*/
/**
* Fired at the start of a tick, before any updates to the engine or timing
*
* @event beforeTick
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after engine timing updated, but just before update
*
* @event tick
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired at the end of a tick, after engine update and after rendering
*
* @event afterTick
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired before update
*
* @event beforeUpdate
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after update
*
* @event afterUpdate
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired before rendering
*
* @event beforeRender
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
* @deprecated
*/
/**
* Fired after rendering
*
* @event afterRender
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
* @deprecated
*/
/*
*
* Properties Documentation
*
*/
/**
* A flag that specifies whether the runner is running or not.
*
* @property enabled
* @type boolean
* @default true
*/
/**
* A `Boolean` that specifies if the runner should use a fixed timestep (otherwise it is variable).
* If timing is fixed, then the apparent simulation speed will change depending on the frame rate (but behaviour will be deterministic).
* If the timing is variable, then the apparent simulation speed will be constant (approximately, but at the cost of determininism).
*
* @property isFixed
* @type boolean
* @default false
*/
/**
* A `Number` that specifies the time step between updates in milliseconds.
* If `engine.timing.isFixed` is set to `true`, then `delta` is fixed.
* If it is `false`, then `delta` can dynamically change to maintain the correct apparent simulation speed.
*
* @property delta
* @type number
* @default 1000 / 60
*/
})();
}, {
"./Common": 14,
"./Engine": 15,
"./Events": 16
}],
22: [function (_dereq_, module, exports) {
/**
* The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies.
*
* @class Sleeping
*/
var Sleeping = {};
module.exports = Sleeping;
var Events = _dereq_('./Events');
(function () {
Sleeping._motionWakeThreshold = 0.18;
Sleeping._motionSleepThreshold = 0.08;
Sleeping._minBias = 0.9;
/**
* Puts bodies to sleep or wakes them up depending on their motion.
* @method update
* @param {body[]} bodies
* @param {number} timeScale
*/
Sleeping.update = function (bodies, timeScale) {
var timeFactor = timeScale * timeScale * timeScale;
// update bodies sleeping status
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i],
motion = body.speed * body.speed + body.angularSpeed * body.angularSpeed;
// wake up bodies if they have a force applied
if (body.force.x !== 0 || body.force.y !== 0) {
Sleeping.set(body, false);
continue;
}
var minMotion = Math.min(body.motion, motion),
maxMotion = Math.max(body.motion, motion);
// biased average motion estimation between frames
body.motion = Sleeping._minBias * minMotion + (1 - Sleeping._minBias) * maxMotion;
if (body.sleepThreshold > 0 && body.motion < Sleeping._motionSleepThreshold * timeFactor) {
body.sleepCounter += 1;
if (body.sleepCounter >= body.sleepThreshold)
Sleeping.set(body, true);
} else if (body.sleepCounter > 0) {
body.sleepCounter -= 1;
}
}
};
/**
* Given a set of colliding pairs, wakes the sleeping bodies involved.
* @method afterCollisions
* @param {pair[]} pairs
* @param {number} timeScale
*/
Sleeping.afterCollisions = function (pairs, timeScale) {
var timeFactor = timeScale * timeScale * timeScale;
// wake up bodies involved in collisions
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
// don't wake inactive pairs
if (!pair.isActive)
continue;
var collision = pair.collision,
bodyA = collision.bodyA.parent,
bodyB = collision.bodyB.parent;
// don't wake if at least one body is static
if ((bodyA.isSleeping && bodyB.isSleeping) || bodyA.isStatic || bodyB.isStatic)
continue;
if (bodyA.isSleeping || bodyB.isSleeping) {
var sleepingBody = (bodyA.isSleeping && !bodyA.isStatic) ? bodyA : bodyB,
movingBody = sleepingBody === bodyA ? bodyB : bodyA;
if (!sleepingBody.isStatic && movingBody.motion > Sleeping._motionWakeThreshold * timeFactor) {
Sleeping.set(sleepingBody, false);
}
}
}
};
/**
* Set a body as sleeping or awake.
* @method set
* @param {body} body
* @param {boolean} isSleeping
*/
Sleeping.set = function (body, isSleeping) {
var wasSleeping = body.isSleeping;
if (isSleeping) {
body.isSleeping = true;
body.sleepCounter = body.sleepThreshold;
body.positionImpulse.x = 0;
body.positionImpulse.y = 0;
body.positionPrev.x = body.position.x;
body.positionPrev.y = body.position.y;
body.anglePrev = body.angle;
body.speed = 0;
body.angularSpeed = 0;
body.motion = 0;
if (!wasSleeping) {
Events.trigger(body, 'sleepStart');
}
} else {
body.isSleeping = false;
body.sleepCounter = 0;
if (wasSleeping) {
Events.trigger(body, 'sleepEnd');
}
}
};
})();
}, {
"./Events": 16
}],
23: [function (_dereq_, module, exports) {
/**
* The `Matter.Bodies` module contains factory methods for creating rigid body models
* with commonly used body configurations (such as rectangles, circles and other polygons).
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Bodies
*/
// TODO: true circle bodies
var Bodies = {};
module.exports = Bodies;
var Vertices = _dereq_('../geometry/Vertices');
var Common = _dereq_('../core/Common');
var Body = _dereq_('../body/Body');
var Bounds = _dereq_('../geometry/Bounds');
var Vector = _dereq_('../geometry/Vector');
var decomp;
(function () {
/**
* Creates a new rigid body model with a rectangle hull.
* The options parameter is an object that specifies any properties you wish to override the defaults.
* See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.
* @method rectangle
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {object} [options]
* @return {body} A new rectangle body
*/
Bodies.rectangle = function (x, y, width, height, options) {
options = options || {};
var rectangle = {
label: 'Rectangle Body',
position: {
x: x,
y: y
},
vertices: Vertices.fromPath('L 0 0 L ' + width + ' 0 L ' + width + ' ' + height + ' L 0 ' + height)
};
if (options.chamfer) {
var chamfer = options.chamfer;
rectangle.vertices = Vertices.chamfer(rectangle.vertices, chamfer.radius,
chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);
delete options.chamfer;
}
return Body.create(Common.extend({}, rectangle, options));
};
/**
* Creates a new rigid body model with a trapezoid hull.
* The options parameter is an object that specifies any properties you wish to override the defaults.
* See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.
* @method trapezoid
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {number} slope
* @param {object} [options]
* @return {body} A new trapezoid body
*/
Bodies.trapezoid = function (x, y, width, height, slope, options) {
options = options || {};
slope *= 0.5;
var roof = (1 - (slope * 2)) * width;
var x1 = width * slope,
x2 = x1 + roof,
x3 = x2 + x1,
verticesPath;
if (slope < 0.5) {
verticesPath = 'L 0 0 L ' + x1 + ' ' + (-height) + ' L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0';
} else {
verticesPath = 'L 0 0 L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0';
}
var trapezoid = {
label: 'Trapezoid Body',
position: {
x: x,
y: y
},
vertices: Vertices.fromPath(verticesPath)
};
if (options.chamfer) {
var chamfer = options.chamfer;
trapezoid.vertices = Vertices.chamfer(trapezoid.vertices, chamfer.radius,
chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);
delete options.chamfer;
}
return Body.create(Common.extend({}, trapezoid, options));
};
/**
* Creates a new rigid body model with a circle hull.
* The options parameter is an object that specifies any properties you wish to override the defaults.
* See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.
* @method circle
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {object} [options]
* @param {number} [maxSides]
* @return {body} A new circle body
*/
Bodies.circle = function (x, y, radius, options, maxSides) {
options = options || {};
var circle = {
label: 'Circle Body',
circleRadius: radius
};
// approximate circles with polygons until true circles implemented in SAT
maxSides = maxSides || 25;
var sides = Math.ceil(Math.max(10, Math.min(maxSides, radius)));
// optimisation: always use even number of sides (half the number of unique axes)
if (sides % 2 === 1)
sides += 1;
return Bodies.polygon(x, y, sides, radius, Common.extend({}, circle, options));
};
/**
* Creates a new rigid body model with a regular polygon hull with the given number of sides.
* The options parameter is an object that specifies any properties you wish to override the defaults.
* See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.
* @method polygon
* @param {number} x
* @param {number} y
* @param {number} sides
* @param {number} radius
* @param {object} [options]
* @return {body} A new regular polygon body
*/
Bodies.polygon = function (x, y, sides, radius, options) {
options = options || {};
if (sides < 3)
return Bodies.circle(x, y, radius, options);
var theta = 2 * Math.PI / sides,
path = '',
offset = theta * 0.5;
for (var i = 0; i < sides; i += 1) {
var angle = offset + (i * theta),
xx = Math.cos(angle) * radius,
yy = Math.sin(angle) * radius;
path += 'L ' + xx.toFixed(3) + ' ' + yy.toFixed(3) + ' ';
}
var polygon = {
label: 'Polygon Body',
position: {
x: x,
y: y
},
vertices: Vertices.fromPath(path)
};
if (options.chamfer) {
var chamfer = options.chamfer;
polygon.vertices = Vertices.chamfer(polygon.vertices, chamfer.radius,
chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);
delete options.chamfer;
}
return Body.create(Common.extend({}, polygon, options));
};
/**
* Creates a body using the supplied vertices (or an array containing multiple sets of vertices).
* If the vertices are convex, they will pass through as supplied.
* Otherwise if the vertices are concave, they will be decomposed if [poly-decomp.js](https://github.com/schteppe/poly-decomp.js) is available.
* Note that this process is not guaranteed to support complex sets of vertices (e.g. those with holes may fail).
* By default the decomposition will discard collinear edges (to improve performance).
* It can also optionally discard any parts that have an area less than `minimumArea`.
* If the vertices can not be decomposed, the result will fall back to using the convex hull.
* The options parameter is an object that specifies any `Matter.Body` properties you wish to override the defaults.
* See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.
* @method fromVertices
* @param {number} x
* @param {number} y
* @param [[vector]] vertexSets
* @param {object} [options]
* @param {bool} [flagInternal=false]
* @param {number} [removeCollinear=0.01]
* @param {number} [minimumArea=10]
* @return {body}
*/
Bodies.fromVertices = function (x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) {
if (!decomp) {
decomp = Common._requireGlobal('decomp', 'poly-decomp');
}
var body,
parts,
isConvex,
vertices,
i,
j,
k,
v,
z;
options = options || {};
parts = [];
flagInternal = typeof flagInternal !== 'undefined' ? flagInternal : false;
removeCollinear = typeof removeCollinear !== 'undefined' ? removeCollinear : 0.01;
minimumArea = typeof minimumArea !== 'undefined' ? minimumArea : 10;
if (!decomp) {
Common.warn('Bodies.fromVertices: poly-decomp.js required. Could not decompose vertices. Fallback to convex hull.');
}
// ensure vertexSets is an array of arrays
if (!Common.isArray(vertexSets[0])) {
vertexSets = [vertexSets];
}
for (v = 0; v < vertexSets.length; v += 1) {
vertices = vertexSets[v];
isConvex = Vertices.isConvex(vertices);
if (isConvex || !decomp) {
if (isConvex) {
vertices = Vertices.clockwiseSort(vertices);
} else {
// fallback to convex hull when decomposition is not possible
vertices = Vertices.hull(vertices);
}
parts.push({
position: {
x: x,
y: y
},
vertices: vertices
});
} else {
// initialise a decomposition
var concave = vertices.map(function (vertex) {
return [vertex.x, vertex.y];
});
// vertices are concave and simple, we can decompose into parts
decomp.makeCCW(concave);
if (removeCollinear !== false)
decomp.removeCollinearPoints(concave, removeCollinear);
// use the quick decomposition algorithm (Bayazit)
var decomposed = decomp.quickDecomp(concave);
// for each decomposed chunk
for (i = 0; i < decomposed.length; i++) {
var chunk = decomposed[i];
// convert vertices into the correct structure
var chunkVertices = chunk.map(function (vertices) {
return {
x: vertices[0],
y: vertices[1]
};
});
// skip small chunks
if (minimumArea > 0 && Vertices.area(chunkVertices) < minimumArea)
continue;
// create a compound part
parts.push({
position: Vertices.centre(chunkVertices),
vertices: chunkVertices
});
}
}
}
// create body parts
for (i = 0; i < parts.length; i++) {
parts[i] = Body.create(Common.extend(parts[i], options));
}
// flag internal edges (coincident part edges)
if (flagInternal) {
var coincident_max_dist = 5;
for (i = 0; i < parts.length; i++) {
var partA = parts[i];
for (j = i + 1; j < parts.length; j++) {
var partB = parts[j];
if (Bounds.overlaps(partA.bounds, partB.bounds)) {
var pav = partA.vertices,
pbv = partB.vertices;
// iterate vertices of both parts
for (k = 0; k < partA.vertices.length; k++) {
for (z = 0; z < partB.vertices.length; z++) {
// find distances between the vertices
var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])),
db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length]));
// if both vertices are very close, consider the edge concident (internal)
if (da < coincident_max_dist && db < coincident_max_dist) {
pav[k].isInternal = true;
pbv[z].isInternal = true;
}
}
}
}
}
}
}
if (parts.length > 1) {
// create the parent body to be returned, that contains generated compound parts
body = Body.create(Common.extend({
parts: parts.slice(0)
}, options));
Body.setPosition(body, {
x: x,
y: y
});
return body;
} else {
return parts[0];
}
};
})();
}, {
"../body/Body": 1,
"../core/Common": 14,
"../geometry/Bounds": 26,
"../geometry/Vector": 28,
"../geometry/Vertices": 29
}],
24: [function (_dereq_, module, exports) {
/**
* The `Matter.Composites` module contains factory methods for creating composite bodies
* with commonly used configurations (such as stacks and chains).
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Composites
*/
var Composites = {};
module.exports = Composites;
var Composite = _dereq_('../body/Composite');
var Constraint = _dereq_('../constraint/Constraint');
var Common = _dereq_('../core/Common');
var Body = _dereq_('../body/Body');
var Bodies = _dereq_('./Bodies');
(function () {
/**
* Create a new composite containing bodies created in the callback in a grid arrangement.
* This function uses the body's bounds to prevent overlaps.
* @method stack
* @param {number} xx
* @param {number} yy
* @param {number} columns
* @param {number} rows
* @param {number} columnGap
* @param {number} rowGap
* @param {function} callback
* @return {composite} A new composite containing objects created in the callback
*/
Composites.stack = function (xx, yy, columns, rows, columnGap, rowGap, callback) {
var stack = Composite.create({
label: 'Stack'
}),
x = xx,
y = yy,
lastBody,
i = 0;
for (var row = 0; row < rows; row++) {
var maxHeight = 0;
for (var column = 0; column < columns; column++) {
var body = callback(x, y, column, row, lastBody, i);
if (body) {
var bodyHeight = body.bounds.max.y - body.bounds.min.y,
bodyWidth = body.bounds.max.x - body.bounds.min.x;
if (bodyHeight > maxHeight)
maxHeight = bodyHeight;
Body.translate(body, {
x: bodyWidth * 0.5,
y: bodyHeight * 0.5
});
x = body.bounds.max.x + columnGap;
Composite.addBody(stack, body);
lastBody = body;
i += 1;
} else {
x += columnGap;
}
}
y += maxHeight + rowGap;
x = xx;
}
return stack;
};
/**
* Chains all bodies in the given composite together using constraints.
* @method chain
* @param {composite} composite
* @param {number} xOffsetA
* @param {number} yOffsetA
* @param {number} xOffsetB
* @param {number} yOffsetB
* @param {object} options
* @return {composite} A new composite containing objects chained together with constraints
*/
Composites.chain = function (composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) {
var bodies = composite.bodies;
for (var i = 1; i < bodies.length; i++) {
var bodyA = bodies[i - 1],
bodyB = bodies[i],
bodyAHeight = bodyA.bounds.max.y - bodyA.bounds.min.y,
bodyAWidth = bodyA.bounds.max.x - bodyA.bounds.min.x,
bodyBHeight = bodyB.bounds.max.y - bodyB.bounds.min.y,
bodyBWidth = bodyB.bounds.max.x - bodyB.bounds.min.x;
var defaults = {
bodyA: bodyA,
pointA: {
x: bodyAWidth * xOffsetA,
y: bodyAHeight * yOffsetA
},
bodyB: bodyB,
pointB: {
x: bodyBWidth * xOffsetB,
y: bodyBHeight * yOffsetB
}
};
var constraint = Common.extend(defaults, options);
Composite.addConstraint(composite, Constraint.create(constraint));
}
composite.label += ' Chain';
return composite;
};
/**
* Connects bodies in the composite with constraints in a grid pattern, with optional cross braces.
* @method mesh
* @param {composite} composite
* @param {number} columns
* @param {number} rows
* @param {boolean} crossBrace
* @param {object} options
* @return {composite} The composite containing objects meshed together with constraints
*/
Composites.mesh = function (composite, columns, rows, crossBrace, options) {
var bodies = composite.bodies,
row,
col,
bodyA,
bodyB,
bodyC;
for (row = 0; row < rows; row++) {
for (col = 1; col < columns; col++) {
bodyA = bodies[(col - 1) + (row * columns)];
bodyB = bodies[col + (row * columns)];
Composite.addConstraint(composite, Constraint.create(Common.extend({
bodyA: bodyA,
bodyB: bodyB
}, options)));
}
if (row > 0) {
for (col = 0; col < columns; col++) {
bodyA = bodies[col + ((row - 1) * columns)];
bodyB = bodies[col + (row * columns)];
Composite.addConstraint(composite, Constraint.create(Common.extend({
bodyA: bodyA,
bodyB: bodyB
}, options)));
if (crossBrace && col > 0) {
bodyC = bodies[(col - 1) + ((row - 1) * columns)];
Composite.addConstraint(composite, Constraint.create(Common.extend({
bodyA: bodyC,
bodyB: bodyB
}, options)));
}
if (crossBrace && col < columns - 1) {
bodyC = bodies[(col + 1) + ((row - 1) * columns)];
Composite.addConstraint(composite, Constraint.create(Common.extend({
bodyA: bodyC,
bodyB: bodyB
}, options)));
}
}
}
}
composite.label += ' Mesh';
return composite;
};
/**
* Create a new composite containing bodies created in the callback in a pyramid arrangement.
* This function uses the body's bounds to prevent overlaps.
* @method pyramid
* @param {number} xx
* @param {number} yy
* @param {number} columns
* @param {number} rows
* @param {number} columnGap
* @param {number} rowGap
* @param {function} callback
* @return {composite} A new composite containing objects created in the callback
*/
Composites.pyramid = function (xx, yy, columns, rows, columnGap, rowGap, callback) {
return Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function (x, y, column, row, lastBody, i) {
var actualRows = Math.min(rows, Math.ceil(columns / 2)),
lastBodyWidth = lastBody ? lastBody.bounds.max.x - lastBody.bounds.min.x : 0;
if (row > actualRows)
return;
// reverse row order
row = actualRows - row;
var start = row,
end = columns - 1 - row;
if (column < start || column > end)
return;
// retroactively fix the first body's position, since width was unknown
if (i === 1) {
Body.translate(lastBody, {
x: (column + (columns % 2 === 1 ? 1 : -1)) * lastBodyWidth,
y: 0
});
}
var xOffset = lastBody ? column * lastBodyWidth : 0;
return callback(xx + xOffset + column * columnGap, y, column, row, lastBody, i);
});
};
/**
* Creates a composite with a Newton's Cradle setup of bodies and constraints.
* @method newtonsCradle
* @param {number} xx
* @param {number} yy
* @param {number} number
* @param {number} size
* @param {number} length
* @return {composite} A new composite newtonsCradle body
*/
Composites.newtonsCradle = function (xx, yy, number, size, length) {
var newtonsCradle = Composite.create({
label: 'Newtons Cradle'
});
for (var i = 0; i < number; i++) {
var separation = 1.9,
circle = Bodies.circle(xx + i * (size * separation), yy + length, size, {
inertia: Infinity,
restitution: 1,
friction: 0,
frictionAir: 0.0001,
slop: 1
}),
constraint = Constraint.create({
pointA: {
x: xx + i * (size * separation),
y: yy
},
bodyB: circle
});
Composite.addBody(newtonsCradle, circle);
Composite.addConstraint(newtonsCradle, constraint);
}
return newtonsCradle;
};
/**
* Creates a composite with simple car setup of bodies and constraints.
* @method car
* @param {number} xx
* @param {number} yy
* @param {number} width
* @param {number} height
* @param {number} wheelSize
* @return {composite} A new composite car body
*/
Composites.car = function (xx, yy, width, height, wheelSize) {
var group = Body.nextGroup(true),
wheelBase = 20,
wheelAOffset = -width * 0.5 + wheelBase,
wheelBOffset = width * 0.5 - wheelBase,
wheelYOffset = 0;
var car = Composite.create({
label: 'Car'
}),
body = Bodies.rectangle(xx, yy, width, height, {
collisionFilter: {
group: group
},
chamfer: {
radius: height * 0.5
},
density: 0.0002
});
var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, {
collisionFilter: {
group: group
},
friction: 0.8
});
var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, {
collisionFilter: {
group: group
},
friction: 0.8
});
var axelA = Constraint.create({
bodyB: body,
pointB: {
x: wheelAOffset,
y: wheelYOffset
},
bodyA: wheelA,
stiffness: 1,
length: 0
});
var axelB = Constraint.create({
bodyB: body,
pointB: {
x: wheelBOffset,
y: wheelYOffset
},
bodyA: wheelB,
stiffness: 1,
length: 0
});
Composite.addBody(car, body);
Composite.addBody(car, wheelA);
Composite.addBody(car, wheelB);
Composite.addConstraint(car, axelA);
Composite.addConstraint(car, axelB);
return car;
};
/**
* Creates a simple soft body like object.
* @method softBody
* @param {number} xx
* @param {number} yy
* @param {number} columns
* @param {number} rows
* @param {number} columnGap
* @param {number} rowGap
* @param {boolean} crossBrace
* @param {number} particleRadius
* @param {} particleOptions
* @param {} constraintOptions
* @return {composite} A new composite softBody
*/
Composites.softBody = function (xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) {
particleOptions = Common.extend({
inertia: Infinity
}, particleOptions);
constraintOptions = Common.extend({
stiffness: 0.2,
render: {
type: 'line',
anchors: false
}
}, constraintOptions);
var softBody = Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function (x, y) {
return Bodies.circle(x, y, particleRadius, particleOptions);
});
Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions);
softBody.label = 'Soft Body';
return softBody;
};
})();
}, {
"../body/Body": 1,
"../body/Composite": 2,
"../constraint/Constraint": 12,
"../core/Common": 14,
"./Bodies": 23
}],
25: [function (_dereq_, module, exports) {
/**
* The `Matter.Axes` module contains methods for creating and manipulating sets of axes.
*
* @class Axes
*/
var Axes = {};
module.exports = Axes;
var Vector = _dereq_('../geometry/Vector');
var Common = _dereq_('../core/Common');
(function () {
/**
* Creates a new set of axes from the given vertices.
* @method fromVertices
* @param {vertices} vertices
* @return {axes} A new axes from the given vertices
*/
Axes.fromVertices = function (vertices) {
var axes = {};
// find the unique axes, using edge normal gradients
for (var i = 0; i < vertices.length; i++) {
var j = (i + 1) % vertices.length,
normal = Vector.normalise({
x: vertices[j].y - vertices[i].y,
y: vertices[i].x - vertices[j].x
}),
gradient = (normal.y === 0) ? Infinity : (normal.x / normal.y);
// limit precision
gradient = gradient.toFixed(3).toString();
axes[gradient] = normal;
}
return Common.values(axes);
};
/**
* Rotates a set of axes by the given angle.
* @method rotate
* @param {axes} axes
* @param {number} angle
*/
Axes.rotate = function (axes, angle) {
if (angle === 0)
return;
var cos = Math.cos(angle),
sin = Math.sin(angle);
for (var i = 0; i < axes.length; i++) {
var axis = axes[i],
xx;
xx = axis.x * cos - axis.y * sin;
axis.y = axis.x * sin + axis.y * cos;
axis.x = xx;
}
};
})();
}, {
"../core/Common": 14,
"../geometry/Vector": 28
}],
26: [function (_dereq_, module, exports) {
/**
* The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB).
*
* @class Bounds
*/
var Bounds = {};
module.exports = Bounds;
(function () {
/**
* Creates a new axis-aligned bounding box (AABB) for the given vertices.
* @method create
* @param {vertices} vertices
* @return {bounds} A new bounds object
*/
Bounds.create = function (vertices) {
var bounds = {
min: {
x: 0,
y: 0
},
max: {
x: 0,
y: 0
}
};
if (vertices)
Bounds.update(bounds, vertices);
return bounds;
};
/**
* Updates bounds using the given vertices and extends the bounds given a velocity.
* @method update
* @param {bounds} bounds
* @param {vertices} vertices
* @param {vector} velocity
*/
Bounds.update = function (bounds, vertices, velocity) {
bounds.min.x = Infinity;
bounds.max.x = -Infinity;
bounds.min.y = Infinity;
bounds.max.y = -Infinity;
for (var i = 0; i < vertices.length; i++) {
var vertex = vertices[i];
if (vertex.x > bounds.max.x) bounds.max.x = vertex.x;
if (vertex.x < bounds.min.x) bounds.min.x = vertex.x;
if (vertex.y > bounds.max.y) bounds.max.y = vertex.y;
if (vertex.y < bounds.min.y) bounds.min.y = vertex.y;
}
if (velocity) {
if (velocity.x > 0) {
bounds.max.x += velocity.x;
} else {
bounds.min.x += velocity.x;
}
if (velocity.y > 0) {
bounds.max.y += velocity.y;
} else {
bounds.min.y += velocity.y;
}
}
};
/**
* Returns true if the bounds contains the given point.
* @method contains
* @param {bounds} bounds
* @param {vector} point
* @return {boolean} True if the bounds contain the point, otherwise false
*/
Bounds.contains = function (bounds, point) {
return point.x >= bounds.min.x && point.x <= bounds.max.x &&
point.y >= bounds.min.y && point.y <= bounds.max.y;
};
/**
* Returns true if the two bounds intersect.
* @method overlaps
* @param {bounds} boundsA
* @param {bounds} boundsB
* @return {boolean} True if the bounds overlap, otherwise false
*/
Bounds.overlaps = function (boundsA, boundsB) {
return (boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x &&
boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y);
};
/**
* Translates the bounds by the given vector.
* @method translate
* @param {bounds} bounds
* @param {vector} vector
*/
Bounds.translate = function (bounds, vector) {
bounds.min.x += vector.x;
bounds.max.x += vector.x;
bounds.min.y += vector.y;
bounds.max.y += vector.y;
};
/**
* Shifts the bounds to the given position.
* @method shift
* @param {bounds} bounds
* @param {vector} position
*/
Bounds.shift = function (bounds, position) {
var deltaX = bounds.max.x - bounds.min.x,
deltaY = bounds.max.y - bounds.min.y;
bounds.min.x = position.x;
bounds.max.x = position.x + deltaX;
bounds.min.y = position.y;
bounds.max.y = position.y + deltaY;
};
})();
}, {}],
27: [function (_dereq_, module, exports) {
/**
* The `Matter.Svg` module contains methods for converting SVG images into an array of vector points.
*
* To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Svg
*/
var Svg = {};
module.exports = Svg;
var Bounds = _dereq_('../geometry/Bounds');
var Common = _dereq_('../core/Common');
(function () {
/**
* Converts an SVG path into an array of vector points.
* If the input path forms a concave shape, you must decompose the result into convex parts before use.
* See `Bodies.fromVertices` which provides support for this.
* Note that this function is not guaranteed to support complex paths (such as those with holes).
* You must load the `pathseg.js` polyfill on newer browsers.
* @method pathToVertices
* @param {SVGPathElement} path
* @param {Number} [sampleLength=15]
* @return {Vector[]} points
*/
Svg.pathToVertices = function (path, sampleLength) {
if (typeof window !== 'undefined' && !('SVGPathSeg' in window)) {
Common.warn('Svg.pathToVertices: SVGPathSeg not defined, a polyfill is required.');
}
// https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js
var i, il, total, point, segment, segments,
segmentsQueue, lastSegment,
lastPoint, segmentIndex, points = [],
lx, ly, length = 0,
x = 0,
y = 0;
sampleLength = sampleLength || 15;
var addPoint = function (px, py, pathSegType) {
// all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1)
var isRelative = pathSegType % 2 === 1 && pathSegType > 1;
// when the last point doesn't equal the current point add the current point
if (!lastPoint || px != lastPoint.x || py != lastPoint.y) {
if (lastPoint && isRelative) {
lx = lastPoint.x;
ly = lastPoint.y;
} else {
lx = 0;
ly = 0;
}
var point = {
x: lx + px,
y: ly + py
};
// set last point
if (isRelative || !lastPoint) {
lastPoint = point;
}
points.push(point);
x = lx + px;
y = ly + py;
}
};
var addSegmentPoint = function (segment) {
var segType = segment.pathSegTypeAsLetter.toUpperCase();
// skip path ends
if (segType === 'Z')
return;
// map segment to x and y
switch (segType) {
case 'M':
case 'L':
case 'T':
case 'C':
case 'S':
case 'Q':
x = segment.x;
y = segment.y;
break;
case 'H':
x = segment.x;
break;
case 'V':
y = segment.y;
break;
}
addPoint(x, y, segment.pathSegType);
};
// ensure path is absolute
Svg._svgPathToAbsolute(path);
// get total length
total = path.getTotalLength();
// queue segments
segments = [];
for (i = 0; i < path.pathSegList.numberOfItems; i += 1)
segments.push(path.pathSegList.getItem(i));
segmentsQueue = segments.concat();
// sample through path
while (length < total) {
// get segment at position
segmentIndex = path.getPathSegAtLength(length);
segment = segments[segmentIndex];
// new segment
if (segment != lastSegment) {
while (segmentsQueue.length && segmentsQueue[0] != segment)
addSegmentPoint(segmentsQueue.shift());
lastSegment = segment;
}
// add points in between when curving
// TODO: adaptive sampling
switch (segment.pathSegTypeAsLetter.toUpperCase()) {
case 'C':
case 'T':
case 'S':
case 'Q':
case 'A':
point = path.getPointAtLength(length);
addPoint(point.x, point.y, 0);
break;
}
// increment by sample value
length += sampleLength;
}
// add remaining segments not passed by sampling
for (i = 0, il = segmentsQueue.length; i < il; ++i)
addSegmentPoint(segmentsQueue[i]);
return points;
};
Svg._svgPathToAbsolute = function (path) {
// http://phrogz.net/convert-svg-path-to-all-absolute-commands
// Copyright (c) Gavin Kistner
// http://phrogz.net/js/_ReuseLicense.txt
// Modifications: tidy formatting and naming
var x0, y0, x1, y1, x2, y2, segs = path.pathSegList,
x = 0,
y = 0,
len = segs.numberOfItems;
for (var i = 0; i < len; ++i) {
var seg = segs.getItem(i),
segType = seg.pathSegTypeAsLetter;
if (/[MLHVCSQTA]/.test(segType)) {
if ('x' in seg) x = seg.x;
if ('y' in seg) y = seg.y;
} else {
if ('x1' in seg) x1 = x + seg.x1;
if ('x2' in seg) x2 = x + seg.x2;
if ('y1' in seg) y1 = y + seg.y1;
if ('y2' in seg) y2 = y + seg.y2;
if ('x' in seg) x += seg.x;
if ('y' in seg) y += seg.y;
switch (segType) {
case 'm':
segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i);
break;
case 'l':
segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i);
break;
case 'h':
segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i);
break;
case 'v':
segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i);
break;
case 'c':
segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i);
break;
case 's':
segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i);
break;
case 'q':
segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i);
break;
case 't':
segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i);
break;
case 'a':
segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i);
break;
case 'z':
case 'Z':
x = x0;
y = y0;
break;
}
}
if (segType == 'M' || segType == 'm') {
x0 = x;
y0 = y;
}
}
};
})();
}, {
"../core/Common": 14,
"../geometry/Bounds": 26
}],
28: [function (_dereq_, module, exports) {
/**
* The `Matter.Vector` module contains methods for creating and manipulating vectors.
* Vectors are the basis of all the geometry related operations in the engine.
* A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Vector
*/
// TODO: consider params for reusing vector objects
var Vector = {};
module.exports = Vector;
(function () {
/**
* Creates a new vector.
* @method create
* @param {number} x
* @param {number} y
* @return {vector} A new vector
*/
Vector.create = function (x, y) {
return {
x: x || 0,
y: y || 0
};
};
/**
* Returns a new vector with `x` and `y` copied from the given `vector`.
* @method clone
* @param {vector} vector
* @return {vector} A new cloned vector
*/
Vector.clone = function (vector) {
return {
x: vector.x,
y: vector.y
};
};
/**
* Returns the magnitude (length) of a vector.
* @method magnitude
* @param {vector} vector
* @return {number} The magnitude of the vector
*/
Vector.magnitude = function (vector) {
return Math.sqrt((vector.x * vector.x) + (vector.y * vector.y));
};
/**
* Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation).
* @method magnitudeSquared
* @param {vector} vector
* @return {number} The squared magnitude of the vector
*/
Vector.magnitudeSquared = function (vector) {
return (vector.x * vector.x) + (vector.y * vector.y);
};
/**
* Rotates the vector about (0, 0) by specified angle.
* @method rotate
* @param {vector} vector
* @param {number} angle
* @param {vector} [output]
* @return {vector} The vector rotated about (0, 0)
*/
Vector.rotate = function (vector, angle, output) {
var cos = Math.cos(angle),
sin = Math.sin(angle);
if (!output) output = {};
var x = vector.x * cos - vector.y * sin;
output.y = vector.x * sin + vector.y * cos;
output.x = x;
return output;
};
/**
* Rotates the vector about a specified point by specified angle.
* @method rotateAbout
* @param {vector} vector
* @param {number} angle
* @param {vector} point
* @param {vector} [output]
* @return {vector} A new vector rotated about the point
*/
Vector.rotateAbout = function (vector, angle, point, output) {
var cos = Math.cos(angle),
sin = Math.sin(angle);
if (!output) output = {};
var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin);
output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos);
output.x = x;
return output;
};
/**
* Normalises a vector (such that its magnitude is `1`).
* @method normalise
* @param {vector} vector
* @return {vector} A new vector normalised
*/
Vector.normalise = function (vector) {
var magnitude = Vector.magnitude(vector);
if (magnitude === 0)
return {
x: 0,
y: 0
};
return {
x: vector.x / magnitude,
y: vector.y / magnitude
};
};
/**
* Returns the dot-product of two vectors.
* @method dot
* @param {vector} vectorA
* @param {vector} vectorB
* @return {number} The dot product of the two vectors
*/
Vector.dot = function (vectorA, vectorB) {
return (vectorA.x * vectorB.x) + (vectorA.y * vectorB.y);
};
/**
* Returns the cross-product of two vectors.
* @method cross
* @param {vector} vectorA
* @param {vector} vectorB
* @return {number} The cross product of the two vectors
*/
Vector.cross = function (vectorA, vectorB) {
return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x);
};
/**
* Returns the cross-product of three vectors.
* @method cross3
* @param {vector} vectorA
* @param {vector} vectorB
* @param {vector} vectorC
* @return {number} The cross product of the three vectors
*/
Vector.cross3 = function (vectorA, vectorB, vectorC) {
return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x);
};
/**
* Adds the two vectors.
* @method add
* @param {vector} vectorA
* @param {vector} vectorB
* @param {vector} [output]
* @return {vector} A new vector of vectorA and vectorB added
*/
Vector.add = function (vectorA, vectorB, output) {
if (!output) output = {};
output.x = vectorA.x + vectorB.x;
output.y = vectorA.y + vectorB.y;
return output;
};
/**
* Subtracts the two vectors.
* @method sub
* @param {vector} vectorA
* @param {vector} vectorB
* @param {vector} [output]
* @return {vector} A new vector of vectorA and vectorB subtracted
*/
Vector.sub = function (vectorA, vectorB, output) {
if (!output) output = {};
output.x = vectorA.x - vectorB.x;
output.y = vectorA.y - vectorB.y;
return output;
};
/**
* Multiplies a vector and a scalar.
* @method mult
* @param {vector} vector
* @param {number} scalar
* @return {vector} A new vector multiplied by scalar
*/
Vector.mult = function (vector, scalar) {
return {
x: vector.x * scalar,
y: vector.y * scalar
};
};
/**
* Divides a vector and a scalar.
* @method div
* @param {vector} vector
* @param {number} scalar
* @return {vector} A new vector divided by scalar
*/
Vector.div = function (vector, scalar) {
return {
x: vector.x / scalar,
y: vector.y / scalar
};
};
/**
* Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction.
* @method perp
* @param {vector} vector
* @param {bool} [negate=false]
* @return {vector} The perpendicular vector
*/
Vector.perp = function (vector, negate) {
negate = negate === true ? -1 : 1;
return {
x: negate * -vector.y,
y: negate * vector.x
};
};
/**
* Negates both components of a vector such that it points in the opposite direction.
* @method neg
* @param {vector} vector
* @return {vector} The negated vector
*/
Vector.neg = function (vector) {
return {
x: -vector.x,
y: -vector.y
};
};
/**
* Returns the angle between the vector `vectorB - vectorA` and the x-axis in radians.
* @method angle
* @param {vector} vectorA
* @param {vector} vectorB
* @return {number} The angle in radians
*/
Vector.angle = function (vectorA, vectorB) {
return Math.atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x);
};
/**
* Temporary vector pool (not thread-safe).
* @property _temp
* @type {vector[]}
* @private
*/
Vector._temp = [
Vector.create(), Vector.create(),
Vector.create(), Vector.create(),
Vector.create(), Vector.create()
];
})();
}, {}],
29: [function (_dereq_, module, exports) {
/**
* The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices.
* A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`.
* A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull).
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Vertices
*/
var Vertices = {};
module.exports = Vertices;
var Vector = _dereq_('../geometry/Vector');
var Common = _dereq_('../core/Common');
(function () {
/**
* Creates a new set of `Matter.Body` compatible vertices.
* The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example:
*
* [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]
*
* The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects,
* but with some additional references required for efficient collision detection routines.
*
* Vertices must be specified in clockwise order.
*
* Note that the `body` argument is not optional, a `Matter.Body` reference must be provided.
*
* @method create
* @param {vector[]} points
* @param {body} body
*/
Vertices.create = function (points, body) {
var vertices = [];
for (var i = 0; i < points.length; i++) {
var point = points[i],
vertex = {
x: point.x,
y: point.y,
index: i,
body: body,
isInternal: false
};
vertices.push(vertex);
}
return vertices;
};
/**
* Parses a string containing ordered x y pairs separated by spaces (and optionally commas),
* into a `Matter.Vertices` object for the given `Matter.Body`.
* For parsing SVG paths, see `Svg.pathToVertices`.
* @method fromPath
* @param {string} path
* @param {body} body
* @return {vertices} vertices
*/
Vertices.fromPath = function (path, body) {
var pathPattern = /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/ig,
points = [];
path.replace(pathPattern, function (match, x, y) {
points.push({
x: parseFloat(x),
y: parseFloat(y)
});
});
return Vertices.create(points, body);
};
/**
* Returns the centre (centroid) of the set of vertices.
* @method centre
* @param {vertices} vertices
* @return {vector} The centre point
*/
Vertices.centre = function (vertices) {
var area = Vertices.area(vertices, true),
centre = {
x: 0,
y: 0
},
cross,
temp,
j;
for (var i = 0; i < vertices.length; i++) {
j = (i + 1) % vertices.length;
cross = Vector.cross(vertices[i], vertices[j]);
temp = Vector.mult(Vector.add(vertices[i], vertices[j]), cross);
centre = Vector.add(centre, temp);
}
return Vector.div(centre, 6 * area);
};
/**
* Returns the average (mean) of the set of vertices.
* @method mean
* @param {vertices} vertices
* @return {vector} The average point
*/
Vertices.mean = function (vertices) {
var average = {
x: 0,
y: 0
};
for (var i = 0; i < vertices.length; i++) {
average.x += vertices[i].x;
average.y += vertices[i].y;
}
return Vector.div(average, vertices.length);
};
/**
* Returns the area of the set of vertices.
* @method area
* @param {vertices} vertices
* @param {bool} signed
* @return {number} The area
*/
Vertices.area = function (vertices, signed) {
var area = 0,
j = vertices.length - 1;
for (var i = 0; i < vertices.length; i++) {
area += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y);
j = i;
}
if (signed)
return area / 2;
return Math.abs(area) / 2;
};
/**
* Returns the moment of inertia (second moment of area) of the set of vertices given the total mass.
* @method inertia
* @param {vertices} vertices
* @param {number} mass
* @return {number} The polygon's moment of inertia
*/
Vertices.inertia = function (vertices, mass) {
var numerator = 0,
denominator = 0,
v = vertices,
cross,
j;
// find the polygon's moment of inertia, using second moment of area
// from equations at http://www.physicsforums.com/showthread.php?t=25293
for (var n = 0; n < v.length; n++) {
j = (n + 1) % v.length;
cross = Math.abs(Vector.cross(v[j], v[n]));
numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n]));
denominator += cross;
}
return (mass / 6) * (numerator / denominator);
};
/**
* Translates the set of vertices in-place.
* @method translate
* @param {vertices} vertices
* @param {vector} vector
* @param {number} scalar
*/
Vertices.translate = function (vertices, vector, scalar) {
var i;
if (scalar) {
for (i = 0; i < vertices.length; i++) {
vertices[i].x += vector.x * scalar;
vertices[i].y += vector.y * scalar;
}
} else {
for (i = 0; i < vertices.length; i++) {
vertices[i].x += vector.x;
vertices[i].y += vector.y;
}
}
return vertices;
};
/**
* Rotates the set of vertices in-place.
* @method rotate
* @param {vertices} vertices
* @param {number} angle
* @param {vector} point
*/
Vertices.rotate = function (vertices, angle, point) {
if (angle === 0)
return;
var cos = Math.cos(angle),
sin = Math.sin(angle);
for (var i = 0; i < vertices.length; i++) {
var vertice = vertices[i],
dx = vertice.x - point.x,
dy = vertice.y - point.y;
vertice.x = point.x + (dx * cos - dy * sin);
vertice.y = point.y + (dx * sin + dy * cos);
}
return vertices;
};
/**
* Returns `true` if the `point` is inside the set of `vertices`.
* @method contains
* @param {vertices} vertices
* @param {vector} point
* @return {boolean} True if the vertices contains point, otherwise false
*/
Vertices.contains = function (vertices, point) {
for (var i = 0; i < vertices.length; i++) {
var vertice = vertices[i],
nextVertice = vertices[(i + 1) % vertices.length];
if ((point.x - vertice.x) * (nextVertice.y - vertice.y) + (point.y - vertice.y) * (vertice.x - nextVertice.x) > 0) {
return false;
}
}
return true;
};
/**
* Scales the vertices from a point (default is centre) in-place.
* @method scale
* @param {vertices} vertices
* @param {number} scaleX
* @param {number} scaleY
* @param {vector} point
*/
Vertices.scale = function (vertices, scaleX, scaleY, point) {
if (scaleX === 1 && scaleY === 1)
return vertices;
point = point || Vertices.centre(vertices);
var vertex,
delta;
for (var i = 0; i < vertices.length; i++) {
vertex = vertices[i];
delta = Vector.sub(vertex, point);
vertices[i].x = point.x + delta.x * scaleX;
vertices[i].y = point.y + delta.y * scaleY;
}
return vertices;
};
/**
* Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices.
* The radius parameter is a single number or an array to specify the radius for each vertex.
* @method chamfer
* @param {vertices} vertices
* @param {number[]} radius
* @param {number} quality
* @param {number} qualityMin
* @param {number} qualityMax
*/
Vertices.chamfer = function (vertices, radius, quality, qualityMin, qualityMax) {
if (typeof radius === 'number') {
radius = [radius];
} else {
radius = radius || [8];
}
// quality defaults to -1, which is auto
quality = (typeof quality !== 'undefined') ? quality : -1;
qualityMin = qualityMin || 2;
qualityMax = qualityMax || 14;
var newVertices = [];
for (var i = 0; i < vertices.length; i++) {
var prevVertex = vertices[i - 1 >= 0 ? i - 1 : vertices.length - 1],
vertex = vertices[i],
nextVertex = vertices[(i + 1) % vertices.length],
currentRadius = radius[i < radius.length ? i : radius.length - 1];
if (currentRadius === 0) {
newVertices.push(vertex);
continue;
}
var prevNormal = Vector.normalise({
x: vertex.y - prevVertex.y,
y: prevVertex.x - vertex.x
});
var nextNormal = Vector.normalise({
x: nextVertex.y - vertex.y,
y: vertex.x - nextVertex.x
});
var diagonalRadius = Math.sqrt(2 * Math.pow(currentRadius, 2)),
radiusVector = Vector.mult(Common.clone(prevNormal), currentRadius),
midNormal = Vector.normalise(Vector.mult(Vector.add(prevNormal, nextNormal), 0.5)),
scaledVertex = Vector.sub(vertex, Vector.mult(midNormal, diagonalRadius));
var precision = quality;
if (quality === -1) {
// automatically decide precision
precision = Math.pow(currentRadius, 0.32) * 1.75;
}
precision = Common.clamp(precision, qualityMin, qualityMax);
// use an even value for precision, more likely to reduce axes by using symmetry
if (precision % 2 === 1)
precision += 1;
var alpha = Math.acos(Vector.dot(prevNormal, nextNormal)),
theta = alpha / precision;
for (var j = 0; j < precision; j++) {
newVertices.push(Vector.add(Vector.rotate(radiusVector, theta * j), scaledVertex));
}
}
return newVertices;
};
/**
* Sorts the input vertices into clockwise order in place.
* @method clockwiseSort
* @param {vertices} vertices
* @return {vertices} vertices
*/
Vertices.clockwiseSort = function (vertices) {
var centre = Vertices.mean(vertices);
vertices.sort(function (vertexA, vertexB) {
return Vector.angle(centre, vertexA) - Vector.angle(centre, vertexB);
});
return vertices;
};
/**
* Returns true if the vertices form a convex shape (vertices must be in clockwise order).
* @method isConvex
* @param {vertices} vertices
* @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable).
*/
Vertices.isConvex = function (vertices) {
// http://paulbourke.net/geometry/polygonmesh/
// Copyright (c) Paul Bourke (use permitted)
var flag = 0,
n = vertices.length,
i,
j,
k,
z;
if (n < 3)
return null;
for (i = 0; i < n; i++) {
j = (i + 1) % n;
k = (i + 2) % n;
z = (vertices[j].x - vertices[i].x) * (vertices[k].y - vertices[j].y);
z -= (vertices[j].y - vertices[i].y) * (vertices[k].x - vertices[j].x);
if (z < 0) {
flag |= 1;
} else if (z > 0) {
flag |= 2;
}
if (flag === 3) {
return false;
}
}
if (flag !== 0) {
return true;
} else {
return null;
}
};
/**
* Returns the convex hull of the input vertices as a new array of points.
* @method hull
* @param {vertices} vertices
* @return [vertex] vertices
*/
Vertices.hull = function (vertices) {
// http://geomalgorithms.com/a10-_hull-1.html
var upper = [],
lower = [],
vertex,
i;
// sort vertices on x-axis (y-axis for ties)
vertices = vertices.slice(0);
vertices.sort(function (vertexA, vertexB) {
var dx = vertexA.x - vertexB.x;
return dx !== 0 ? dx : vertexA.y - vertexB.y;
});
// build lower hull
for (i = 0; i < vertices.length; i += 1) {
vertex = vertices[i];
while (lower.length >= 2 &&
Vector.cross3(lower[lower.length - 2], lower[lower.length - 1], vertex) <= 0) {
lower.pop();
}
lower.push(vertex);
}
// build upper hull
for (i = vertices.length - 1; i >= 0; i -= 1) {
vertex = vertices[i];
while (upper.length >= 2 &&
Vector.cross3(upper[upper.length - 2], upper[upper.length - 1], vertex) <= 0) {
upper.pop();
}
upper.push(vertex);
}
// concatenation of the lower and upper hulls gives the convex hull
// omit last points because they are repeated at the beginning of the other list
upper.pop();
lower.pop();
return upper.concat(lower);
};
})();
}, {
"../core/Common": 14,
"../geometry/Vector": 28
}],
30: [function (_dereq_, module, exports) {
var Matter = module.exports = _dereq_('../core/Matter');
Matter.Body = _dereq_('../body/Body');
Matter.Composite = _dereq_('../body/Composite');
Matter.World = _dereq_('../body/World');
Matter.Contact = _dereq_('../collision/Contact');
Matter.Detector = _dereq_('../collision/Detector');
Matter.Grid = _dereq_('../collision/Grid');
Matter.Pairs = _dereq_('../collision/Pairs');
Matter.Pair = _dereq_('../collision/Pair');
Matter.Query = _dereq_('../collision/Query');
Matter.Resolver = _dereq_('../collision/Resolver');
Matter.SAT = _dereq_('../collision/SAT');
Matter.Constraint = _dereq_('../constraint/Constraint');
Matter.MouseConstraint = _dereq_('../constraint/MouseConstraint');
Matter.Common = _dereq_('../core/Common');
Matter.Engine = _dereq_('../core/Engine');
Matter.Events = _dereq_('../core/Events');
Matter.Mouse = _dereq_('../core/Mouse');
Matter.Runner = _dereq_('../core/Runner');
Matter.Sleeping = _dereq_('../core/Sleeping');
Matter.Plugin = _dereq_('../core/Plugin');
Matter.Bodies = _dereq_('../factory/Bodies');
Matter.Composites = _dereq_('../factory/Composites');
Matter.Axes = _dereq_('../geometry/Axes');
Matter.Bounds = _dereq_('../geometry/Bounds');
Matter.Svg = _dereq_('../geometry/Svg');
Matter.Vector = _dereq_('../geometry/Vector');
Matter.Vertices = _dereq_('../geometry/Vertices');
Matter.Render = _dereq_('../render/Render');
Matter.RenderPixi = _dereq_('../render/RenderPixi');
// aliases
Matter.World.add = Matter.Composite.add;
Matter.World.remove = Matter.Composite.remove;
Matter.World.addComposite = Matter.Composite.addComposite;
Matter.World.addBody = Matter.Composite.addBody;
Matter.World.addConstraint = Matter.Composite.addConstraint;
Matter.World.clear = Matter.Composite.clear;
Matter.Engine.run = Matter.Runner.run;
}, {
"../body/Body": 1,
"../body/Composite": 2,
"../body/World": 3,
"../collision/Contact": 4,
"../collision/Detector": 5,
"../collision/Grid": 6,
"../collision/Pair": 7,
"../collision/Pairs": 8,
"../collision/Query": 9,
"../collision/Resolver": 10,
"../collision/SAT": 11,
"../constraint/Constraint": 12,
"../constraint/MouseConstraint": 13,
"../core/Common": 14,
"../core/Engine": 15,
"../core/Events": 16,
"../core/Matter": 17,
"../core/Metrics": 18,
"../core/Mouse": 19,
"../core/Plugin": 20,
"../core/Runner": 21,
"../core/Sleeping": 22,
"../factory/Bodies": 23,
"../factory/Composites": 24,
"../geometry/Axes": 25,
"../geometry/Bounds": 26,
"../geometry/Svg": 27,
"../geometry/Vector": 28,
"../geometry/Vertices": 29,
"../render/Render": 31,
"../render/RenderPixi": 32
}],
31: [function (_dereq_, module, exports) {
/**
* The `Matter.Render` module is a simple HTML5 canvas based renderer for visualising instances of `Matter.Engine`.
* It is intended for development and debugging purposes, but may also be suitable for simple games.
* It includes a number of drawing options including wireframe, vector with support for sprites and viewports.
*
* @class Render
*/
var Render = {};
module.exports = Render;
var Common = _dereq_('../core/Common');
var Composite = _dereq_('../body/Composite');
var Bounds = _dereq_('../geometry/Bounds');
var Events = _dereq_('../core/Events');
var Grid = _dereq_('../collision/Grid');
var Vector = _dereq_('../geometry/Vector');
var Mouse = _dereq_('../core/Mouse');
(function () {
var _requestAnimationFrame,
_cancelAnimationFrame;
if (typeof window !== 'undefined') {
_requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(function () {
callback(Common.now());
}, 1000 / 60);
};
_cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame || window.msCancelAnimationFrame;
}
/**
* Creates a new renderer. The options parameter is an object that specifies any properties you wish to override the defaults.
* All properties have default values, and many are pre-calculated automatically based on other properties.
* See the properties section below for detailed information on what you can pass via the `options` object.
* @method create
* @param {object} [options]
* @return {render} A new renderer
*/
Render.create = function (options) {
var defaults = {
controller: Render,
engine: null,
element: null,
canvas: null,
mouse: null,
frameRequestId: null,
options: {
width: 800,
height: 600,
pixelRatio: 1,
background: '#18181d',
wireframeBackground: '#0f0f13',
hasBounds: !!options.bounds,
enabled: true,
wireframes: true,
showSleeping: true,
showDebug: false,
showBroadphase: false,
showBounds: false,
showVelocity: false,
showCollisions: false,
showSeparations: false,
showAxes: false,
showPositions: false,
showAngleIndicator: false,
showIds: false,
showShadows: false,
showVertexNumbers: false,
showConvexHulls: false,
showInternalEdges: false,
showMousePosition: false
}
};
var render = Common.extend(defaults, options);
if (render.canvas) {
render.canvas.width = render.options.width || render.canvas.width;
render.canvas.height = render.options.height || render.canvas.height;
}
render.mouse = options.mouse;
render.engine = options.engine;
render.canvas = render.canvas || _createCanvas(render.options.width, render.options.height);
render.context = render.canvas.getContext('2d');
render.textures = {};
render.bounds = render.bounds || {
min: {
x: 0,
y: 0
},
max: {
x: render.canvas.width,
y: render.canvas.height
}
};
if (render.options.pixelRatio !== 1) {
Render.setPixelRatio(render, render.options.pixelRatio);
}
if (Common.isElement(render.element)) {
render.element.appendChild(render.canvas);
} else if (!render.canvas.parentNode) {
Common.log('Render.create: options.element was undefined, render.canvas was created but not appended', 'warn');
}
return render;
};
/**
* Continuously updates the render canvas on the `requestAnimationFrame` event.
* @method run
* @param {render} render
*/
Render.run = function (render) {
(function loop(time) {
render.frameRequestId = _requestAnimationFrame(loop);
Render.world(render);
})();
};
/**
* Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop.
* @method stop
* @param {render} render
*/
Render.stop = function (render) {
_cancelAnimationFrame(render.frameRequestId);
};
/**
* Sets the pixel ratio of the renderer and updates the canvas.
* To automatically detect the correct ratio, pass the string `'auto'` for `pixelRatio`.
* @method setPixelRatio
* @param {render} render
* @param {number} pixelRatio
*/
Render.setPixelRatio = function (render, pixelRatio) {
var options = render.options,
canvas = render.canvas;
if (pixelRatio === 'auto') {
pixelRatio = _getPixelRatio(canvas);
}
options.pixelRatio = pixelRatio;
canvas.setAttribute('data-pixel-ratio', pixelRatio);
canvas.width = options.width * pixelRatio;
canvas.height = options.height * pixelRatio;
canvas.style.width = options.width + 'px';
canvas.style.height = options.height + 'px';
render.context.scale(pixelRatio, pixelRatio);
};
/**
* Positions and sizes the viewport around the given object bounds.
* Objects must have at least one of the following properties:
* - `object.bounds`
* - `object.position`
* - `object.min` and `object.max`
* - `object.x` and `object.y`
* @method lookAt
* @param {render} render
* @param {object[]} objects
* @param {vector} [padding]
* @param {bool} [center=true]
*/
Render.lookAt = function (render, objects, padding, center) {
center = typeof center !== 'undefined' ? center : true;
objects = Common.isArray(objects) ? objects : [objects];
padding = padding || {
x: 0,
y: 0
};
// find bounds of all objects
var bounds = {
min: {
x: Infinity,
y: Infinity
},
max: {
x: -Infinity,
y: -Infinity
}
};
for (var i = 0; i < objects.length; i += 1) {
var object = objects[i],
min = object.bounds ? object.bounds.min : (object.min || object.position || object),
max = object.bounds ? object.bounds.max : (object.max || object.position || object);
if (min && max) {
if (min.x < bounds.min.x)
bounds.min.x = min.x;
if (max.x > bounds.max.x)
bounds.max.x = max.x;
if (min.y < bounds.min.y)
bounds.min.y = min.y;
if (max.y > bounds.max.y)
bounds.max.y = max.y;
}
}
// find ratios
var width = (bounds.max.x - bounds.min.x) + 2 * padding.x,
height = (bounds.max.y - bounds.min.y) + 2 * padding.y,
viewHeight = render.canvas.height,
viewWidth = render.canvas.width,
outerRatio = viewWidth / viewHeight,
innerRatio = width / height,
scaleX = 1,
scaleY = 1;
// find scale factor
if (innerRatio > outerRatio) {
scaleY = innerRatio / outerRatio;
} else {
scaleX = outerRatio / innerRatio;
}
// enable bounds
render.options.hasBounds = true;
// position and size
render.bounds.min.x = bounds.min.x;
render.bounds.max.x = bounds.min.x + width * scaleX;
render.bounds.min.y = bounds.min.y;
render.bounds.max.y = bounds.min.y + height * scaleY;
// center
if (center) {
render.bounds.min.x += width * 0.5 - (width * scaleX) * 0.5;
render.bounds.max.x += width * 0.5 - (width * scaleX) * 0.5;
render.bounds.min.y += height * 0.5 - (height * scaleY) * 0.5;
render.bounds.max.y += height * 0.5 - (height * scaleY) * 0.5;
}
// padding
render.bounds.min.x -= padding.x;
render.bounds.max.x -= padding.x;
render.bounds.min.y -= padding.y;
render.bounds.max.y -= padding.y;
// update mouse
if (render.mouse) {
Mouse.setScale(render.mouse, {
x: (render.bounds.max.x - render.bounds.min.x) / render.canvas.width,
y: (render.bounds.max.y - render.bounds.min.y) / render.canvas.height
});
Mouse.setOffset(render.mouse, render.bounds.min);
}
};
/**
* Applies viewport transforms based on `render.bounds` to a render context.
* @method startViewTransform
* @param {render} render
*/
Render.startViewTransform = function (render) {
var boundsWidth = render.bounds.max.x - render.bounds.min.x,
boundsHeight = render.bounds.max.y - render.bounds.min.y,
boundsScaleX = boundsWidth / render.options.width,
boundsScaleY = boundsHeight / render.options.height;
render.context.scale(1 / boundsScaleX, 1 / boundsScaleY);
render.context.translate(-render.bounds.min.x, -render.bounds.min.y);
};
/**
* Resets all transforms on the render context.
* @method endViewTransform
* @param {render} render
*/
Render.endViewTransform = function (render) {
render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);
};
/**
* Renders the given `engine`'s `Matter.World` object.
* This is the entry point for all rendering and should be called every time the scene changes.
* @method world
* @param {render} render
*/
Render.world = function (render) {
var engine = render.engine,
world = engine.world,
canvas = render.canvas,
context = render.context,
options = render.options,
allBodies = Composite.allBodies(world),
allConstraints = Composite.allConstraints(world),
background = options.wireframes ? options.wireframeBackground : options.background,
bodies = [],
constraints = [],
i;
var event = {
timestamp: engine.timing.timestamp
};
Events.trigger(render, 'beforeRender', event);
// apply background if it has changed
if (render.currentBackground !== background)
_applyBackground(render, background);
// clear the canvas with a transparent fill, to allow the canvas background to show
context.globalCompositeOperation = 'source-in';
context.fillStyle = "transparent";
context.fillRect(0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = 'source-over';
// handle bounds
if (options.hasBounds) {
// filter out bodies that are not in view
for (i = 0; i < allBodies.length; i++) {
var body = allBodies[i];
if (Bounds.overlaps(body.bounds, render.bounds))
bodies.push(body);
}
// filter out constraints that are not in view
for (i = 0; i < allConstraints.length; i++) {
var constraint = allConstraints[i],
bodyA = constraint.bodyA,
bodyB = constraint.bodyB,
pointAWorld = constraint.pointA,
pointBWorld = constraint.pointB;
if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA);
if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB);
if (!pointAWorld || !pointBWorld)
continue;
if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld))
constraints.push(constraint);
}
// transform the view
Render.startViewTransform(render);
// update mouse
if (render.mouse) {
Mouse.setScale(render.mouse, {
x: (render.bounds.max.x - render.bounds.min.x) / render.canvas.width,
y: (render.bounds.max.y - render.bounds.min.y) / render.canvas.height
});
Mouse.setOffset(render.mouse, render.bounds.min);
}
} else {
constraints = allConstraints;
bodies = allBodies;
}
if (!options.wireframes || (engine.enableSleeping && options.showSleeping)) {
// fully featured rendering of bodies
Render.bodies(render, bodies, context);
} else {
if (options.showConvexHulls)
Render.bodyConvexHulls(render, bodies, context);
// optimised method for wireframes only
Render.bodyWireframes(render, bodies, context);
}
if (options.showBounds)
Render.bodyBounds(render, bodies, context);
if (options.showAxes || options.showAngleIndicator)
Render.bodyAxes(render, bodies, context);
if (options.showPositions)
Render.bodyPositions(render, bodies, context);
if (options.showVelocity)
Render.bodyVelocity(render, bodies, context);
if (options.showIds)
Render.bodyIds(render, bodies, context);
if (options.showSeparations)
Render.separations(render, engine.pairs.list, context);
if (options.showCollisions)
Render.collisions(render, engine.pairs.list, context);
if (options.showVertexNumbers)
Render.vertexNumbers(render, bodies, context);
if (options.showMousePosition)
Render.mousePosition(render, render.mouse, context);
Render.constraints(constraints, context);
if (options.showBroadphase && engine.broadphase.controller === Grid)
Render.grid(render, engine.broadphase, context);
if (options.showDebug)
Render.debug(render, context);
if (options.hasBounds) {
// revert view transforms
Render.endViewTransform(render);
}
Events.trigger(render, 'afterRender', event);
};
/**
* Description
* @private
* @method debug
* @param {render} render
* @param {RenderingContext} context
*/
Render.debug = function (render, context) {
var c = context,
engine = render.engine,
world = engine.world,
metrics = engine.metrics,
options = render.options,
bodies = Composite.allBodies(world),
space = " ";
if (engine.timing.timestamp - (render.debugTimestamp || 0) >= 500) {
var text = "";
if (metrics.timing) {
text += "fps: " + Math.round(metrics.timing.fps) + space;
}
render.debugString = text;
render.debugTimestamp = engine.timing.timestamp;
}
if (render.debugString) {
c.font = "12px Arial";
if (options.wireframes) {
c.fillStyle = 'rgba(255,255,255,0.5)';
} else {
c.fillStyle = 'rgba(0,0,0,0.5)';
}
var split = render.debugString.split('\n');
for (var i = 0; i < split.length; i++) {
c.fillText(split[i], 50, 50 + i * 18);
}
}
};
/**
* Description
* @private
* @method constraints
* @param {constraint[]} constraints
* @param {RenderingContext} context
*/
Render.constraints = function (constraints, context) {
var c = context;
for (var i = 0; i < constraints.length; i++) {
var constraint = constraints[i];
if (!constraint.render.visible || !constraint.pointA || !constraint.pointB)
continue;
var bodyA = constraint.bodyA,
bodyB = constraint.bodyB,
start,
end;
if (bodyA) {
start = Vector.add(bodyA.position, constraint.pointA);
} else {
start = constraint.pointA;
}
if (constraint.render.type === 'pin') {
c.beginPath();
c.arc(start.x, start.y, 3, 0, 2 * Math.PI);
c.closePath();
} else {
if (bodyB) {
end = Vector.add(bodyB.position, constraint.pointB);
} else {
end = constraint.pointB;
}
c.beginPath();
c.moveTo(start.x, start.y);
if (constraint.render.type === 'spring') {
var delta = Vector.sub(end, start),
normal = Vector.perp(Vector.normalise(delta)),
coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)),
offset;
for (var j = 1; j < coils; j += 1) {
offset = j % 2 === 0 ? 1 : -1;
c.lineTo(
start.x + delta.x * (j / coils) + normal.x * offset * 4,
start.y + delta.y * (j / coils) + normal.y * offset * 4
);
}
}
c.lineTo(end.x, end.y);
}
if (constraint.render.lineWidth) {
c.lineWidth = constraint.render.lineWidth;
c.strokeStyle = constraint.render.strokeStyle;
c.stroke();
}
if (constraint.render.anchors) {
c.fillStyle = constraint.render.strokeStyle;
c.beginPath();
c.arc(start.x, start.y, 3, 0, 2 * Math.PI);
c.arc(end.x, end.y, 3, 0, 2 * Math.PI);
c.closePath();
c.fill();
}
}
};
/**
* Description
* @private
* @method bodyShadows
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyShadows = function (render, bodies, context) {
var c = context,
engine = render.engine;
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (!body.render.visible)
continue;
if (body.circleRadius) {
c.beginPath();
c.arc(body.position.x, body.position.y, body.circleRadius, 0, 2 * Math.PI);
c.closePath();
} else {
c.beginPath();
c.moveTo(body.vertices[0].x, body.vertices[0].y);
for (var j = 1; j < body.vertices.length; j++) {
c.lineTo(body.vertices[j].x, body.vertices[j].y);
}
c.closePath();
}
var distanceX = body.position.x - render.options.width * 0.5,
distanceY = body.position.y - render.options.height * 0.2,
distance = Math.abs(distanceX) + Math.abs(distanceY);
c.shadowColor = 'rgba(0,0,0,0.15)';
c.shadowOffsetX = 0.05 * distanceX;
c.shadowOffsetY = 0.05 * distanceY;
c.shadowBlur = 1 + 12 * Math.min(1, distance / 1000);
c.fill();
c.shadowColor = null;
c.shadowOffsetX = null;
c.shadowOffsetY = null;
c.shadowBlur = null;
}
};
/**
* Description
* @private
* @method bodies
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodies = function (render, bodies, context) {
var c = context,
engine = render.engine,
options = render.options,
showInternalEdges = options.showInternalEdges || !options.wireframes,
body,
part,
i,
k;
for (i = 0; i < bodies.length; i++) {
body = bodies[i];
if (!body.render.visible)
continue;
// handle compound parts
for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {
part = body.parts[k];
if (!part.render.visible)
continue;
if (options.showSleeping && body.isSleeping) {
c.globalAlpha = 0.5 * part.render.opacity;
} else if (part.render.opacity !== 1) {
c.globalAlpha = part.render.opacity;
}
if (part.render.sprite && part.render.sprite.texture && !options.wireframes) {
// part sprite
var sprite = part.render.sprite,
texture = _getTexture(render, sprite.texture);
c.translate(part.position.x, part.position.y);
c.rotate(part.angle);
c.drawImage(
texture,
texture.width * -sprite.xOffset * sprite.xScale,
texture.height * -sprite.yOffset * sprite.yScale,
texture.width * sprite.xScale,
texture.height * sprite.yScale
);
// revert translation, hopefully faster than save / restore
c.rotate(-part.angle);
c.translate(-part.position.x, -part.position.y);
} else {
// part polygon
if (part.circleRadius) {
c.beginPath();
c.arc(part.position.x, part.position.y, part.circleRadius, 0, 2 * Math.PI);
} else {
c.beginPath();
c.moveTo(part.vertices[0].x, part.vertices[0].y);
for (var j = 1; j < part.vertices.length; j++) {
if (!part.vertices[j - 1].isInternal || showInternalEdges) {
c.lineTo(part.vertices[j].x, part.vertices[j].y);
} else {
c.moveTo(part.vertices[j].x, part.vertices[j].y);
}
if (part.vertices[j].isInternal && !showInternalEdges) {
c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y);
}
}
c.lineTo(part.vertices[0].x, part.vertices[0].y);
c.closePath();
}
if (!options.wireframes) {
c.fillStyle = part.render.fillStyle;
if (part.render.lineWidth) {
c.lineWidth = part.render.lineWidth;
c.strokeStyle = part.render.strokeStyle;
c.stroke();
}
c.fill();
} else {
c.lineWidth = 1;
c.strokeStyle = '#bbb';
c.stroke();
}
}
c.globalAlpha = 1;
}
}
};
/**
* Optimised method for drawing body wireframes in one pass
* @private
* @method bodyWireframes
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyWireframes = function (render, bodies, context) {
var c = context,
showInternalEdges = render.options.showInternalEdges,
body,
part,
i,
j,
k;
c.beginPath();
// render all bodies
for (i = 0; i < bodies.length; i++) {
body = bodies[i];
if (!body.render.visible)
continue;
// handle compound parts
for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {
part = body.parts[k];
c.moveTo(part.vertices[0].x, part.vertices[0].y);
for (j = 1; j < part.vertices.length; j++) {
if (!part.vertices[j - 1].isInternal || showInternalEdges) {
c.lineTo(part.vertices[j].x, part.vertices[j].y);
} else {
c.moveTo(part.vertices[j].x, part.vertices[j].y);
}
if (part.vertices[j].isInternal && !showInternalEdges) {
c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y);
}
}
c.lineTo(part.vertices[0].x, part.vertices[0].y);
}
}
c.lineWidth = 1;
c.strokeStyle = '#bbb';
c.stroke();
};
/**
* Optimised method for drawing body convex hull wireframes in one pass
* @private
* @method bodyConvexHulls
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyConvexHulls = function (render, bodies, context) {
var c = context,
body,
part,
i,
j,
k;
c.beginPath();
// render convex hulls
for (i = 0; i < bodies.length; i++) {
body = bodies[i];
if (!body.render.visible || body.parts.length === 1)
continue;
c.moveTo(body.vertices[0].x, body.vertices[0].y);
for (j = 1; j < body.vertices.length; j++) {
c.lineTo(body.vertices[j].x, body.vertices[j].y);
}
c.lineTo(body.vertices[0].x, body.vertices[0].y);
}
c.lineWidth = 1;
c.strokeStyle = 'rgba(255,255,255,0.2)';
c.stroke();
};
/**
* Renders body vertex numbers.
* @private
* @method vertexNumbers
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.vertexNumbers = function (render, bodies, context) {
var c = context,
i,
j,
k;
for (i = 0; i < bodies.length; i++) {
var parts = bodies[i].parts;
for (k = parts.length > 1 ? 1 : 0; k < parts.length; k++) {
var part = parts[k];
for (j = 0; j < part.vertices.length; j++) {
c.fillStyle = 'rgba(255,255,255,0.2)';
c.fillText(i + '_' + j, part.position.x + (part.vertices[j].x - part.position.x) * 0.8, part.position.y + (part.vertices[j].y - part.position.y) * 0.8);
}
}
}
};
/**
* Renders mouse position.
* @private
* @method mousePosition
* @param {render} render
* @param {mouse} mouse
* @param {RenderingContext} context
*/
Render.mousePosition = function (render, mouse, context) {
var c = context;
c.fillStyle = 'rgba(255,255,255,0.8)';
c.fillText(mouse.position.x + ' ' + mouse.position.y, mouse.position.x + 5, mouse.position.y - 5);
};
/**
* Draws body bounds
* @private
* @method bodyBounds
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyBounds = function (render, bodies, context) {
var c = context,
engine = render.engine,
options = render.options;
c.beginPath();
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (body.render.visible) {
var parts = bodies[i].parts;
for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {
var part = parts[j];
c.rect(part.bounds.min.x, part.bounds.min.y, part.bounds.max.x - part.bounds.min.x, part.bounds.max.y - part.bounds.min.y);
}
}
}
if (options.wireframes) {
c.strokeStyle = 'rgba(255,255,255,0.08)';
} else {
c.strokeStyle = 'rgba(0,0,0,0.1)';
}
c.lineWidth = 1;
c.stroke();
};
/**
* Draws body angle indicators and axes
* @private
* @method bodyAxes
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyAxes = function (render, bodies, context) {
var c = context,
engine = render.engine,
options = render.options,
part,
i,
j,
k;
c.beginPath();
for (i = 0; i < bodies.length; i++) {
var body = bodies[i],
parts = body.parts;
if (!body.render.visible)
continue;
if (options.showAxes) {
// render all axes
for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {
part = parts[j];
for (k = 0; k < part.axes.length; k++) {
var axis = part.axes[k];
c.moveTo(part.position.x, part.position.y);
c.lineTo(part.position.x + axis.x * 20, part.position.y + axis.y * 20);
}
}
} else {
for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {
part = parts[j];
for (k = 0; k < part.axes.length; k++) {
// render a single axis indicator
c.moveTo(part.position.x, part.position.y);
c.lineTo((part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2,
(part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2);
}
}
}
}
if (options.wireframes) {
c.strokeStyle = 'indianred';
c.lineWidth = 1;
} else {
c.strokeStyle = 'rgba(255, 255, 255, 0.4)';
c.globalCompositeOperation = 'overlay';
c.lineWidth = 2;
}
c.stroke();
c.globalCompositeOperation = 'source-over';
};
/**
* Draws body positions
* @private
* @method bodyPositions
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyPositions = function (render, bodies, context) {
var c = context,
engine = render.engine,
options = render.options,
body,
part,
i,
k;
c.beginPath();
// render current positions
for (i = 0; i < bodies.length; i++) {
body = bodies[i];
if (!body.render.visible)
continue;
// handle compound parts
for (k = 0; k < body.parts.length; k++) {
part = body.parts[k];
c.arc(part.position.x, part.position.y, 3, 0, 2 * Math.PI, false);
c.closePath();
}
}
if (options.wireframes) {
c.fillStyle = 'indianred';
} else {
c.fillStyle = 'rgba(0,0,0,0.5)';
}
c.fill();
c.beginPath();
// render previous positions
for (i = 0; i < bodies.length; i++) {
body = bodies[i];
if (body.render.visible) {
c.arc(body.positionPrev.x, body.positionPrev.y, 2, 0, 2 * Math.PI, false);
c.closePath();
}
}
c.fillStyle = 'rgba(255,165,0,0.8)';
c.fill();
};
/**
* Draws body velocity
* @private
* @method bodyVelocity
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyVelocity = function (render, bodies, context) {
var c = context;
c.beginPath();
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (!body.render.visible)
continue;
c.moveTo(body.position.x, body.position.y);
c.lineTo(body.position.x + (body.position.x - body.positionPrev.x) * 2, body.position.y + (body.position.y - body.positionPrev.y) * 2);
}
c.lineWidth = 3;
c.strokeStyle = 'cornflowerblue';
c.stroke();
};
/**
* Draws body ids
* @private
* @method bodyIds
* @param {render} render
* @param {body[]} bodies
* @param {RenderingContext} context
*/
Render.bodyIds = function (render, bodies, context) {
var c = context,
i,
j;
for (i = 0; i < bodies.length; i++) {
if (!bodies[i].render.visible)
continue;
var parts = bodies[i].parts;
for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {
var part = parts[j];
c.font = "12px Arial";
c.fillStyle = 'rgba(255,255,255,0.5)';
c.fillText(part.id, part.position.x + 10, part.position.y - 10);
}
}
};
/**
* Description
* @private
* @method collisions
* @param {render} render
* @param {pair[]} pairs
* @param {RenderingContext} context
*/
Render.collisions = function (render, pairs, context) {
var c = context,
options = render.options,
pair,
collision,
corrected,
bodyA,
bodyB,
i,
j;
c.beginPath();
// render collision positions
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive)
continue;
collision = pair.collision;
for (j = 0; j < pair.activeContacts.length; j++) {
var contact = pair.activeContacts[j],
vertex = contact.vertex;
c.rect(vertex.x - 1.5, vertex.y - 1.5, 3.5, 3.5);
}
}
if (options.wireframes) {
c.fillStyle = 'rgba(255,255,255,0.7)';
} else {
c.fillStyle = 'orange';
}
c.fill();
c.beginPath();
// render collision normals
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive)
continue;
collision = pair.collision;
if (pair.activeContacts.length > 0) {
var normalPosX = pair.activeContacts[0].vertex.x,
normalPosY = pair.activeContacts[0].vertex.y;
if (pair.activeContacts.length === 2) {
normalPosX = (pair.activeContacts[0].vertex.x + pair.activeContacts[1].vertex.x) / 2;
normalPosY = (pair.activeContacts[0].vertex.y + pair.activeContacts[1].vertex.y) / 2;
}
if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic === true) {
c.moveTo(normalPosX - collision.normal.x * 8, normalPosY - collision.normal.y * 8);
} else {
c.moveTo(normalPosX + collision.normal.x * 8, normalPosY + collision.normal.y * 8);
}
c.lineTo(normalPosX, normalPosY);
}
}
if (options.wireframes) {
c.strokeStyle = 'rgba(255,165,0,0.7)';
} else {
c.strokeStyle = 'orange';
}
c.lineWidth = 1;
c.stroke();
};
/**
* Description
* @private
* @method separations
* @param {render} render
* @param {pair[]} pairs
* @param {RenderingContext} context
*/
Render.separations = function (render, pairs, context) {
var c = context,
options = render.options,
pair,
collision,
corrected,
bodyA,
bodyB,
i,
j;
c.beginPath();
// render separations
for (i = 0; i < pairs.length; i++) {
pair = pairs[i];
if (!pair.isActive)
continue;
collision = pair.collision;
bodyA = collision.bodyA;
bodyB = collision.bodyB;
var k = 1;
if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5;
if (bodyB.isStatic) k = 0;
c.moveTo(bodyB.position.x, bodyB.position.y);
c.lineTo(bodyB.position.x - collision.penetration.x * k, bodyB.position.y - collision.penetration.y * k);
k = 1;
if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5;
if (bodyA.isStatic) k = 0;
c.moveTo(bodyA.position.x, bodyA.position.y);
c.lineTo(bodyA.position.x + collision.penetration.x * k, bodyA.position.y + collision.penetration.y * k);
}
if (options.wireframes) {
c.strokeStyle = 'rgba(255,165,0,0.5)';
} else {
c.strokeStyle = 'orange';
}
c.stroke();
};
/**
* Description
* @private
* @method grid
* @param {render} render
* @param {grid} grid
* @param {RenderingContext} context
*/
Render.grid = function (render, grid, context) {
var c = context,
options = render.options;
if (options.wireframes) {
c.strokeStyle = 'rgba(255,180,0,0.1)';
} else {
c.strokeStyle = 'rgba(255,180,0,0.5)';
}
c.beginPath();
var bucketKeys = Common.keys(grid.buckets);
for (var i = 0; i < bucketKeys.length; i++) {
var bucketId = bucketKeys[i];
if (grid.buckets[bucketId].length < 2)
continue;
var region = bucketId.split(/C|R/);
c.rect(0.5 + parseInt(region[1], 10) * grid.bucketWidth,
0.5 + parseInt(region[2], 10) * grid.bucketHeight,
grid.bucketWidth,
grid.bucketHeight);
}
c.lineWidth = 1;
c.stroke();
};
/**
* Description
* @private
* @method inspector
* @param {inspector} inspector
* @param {RenderingContext} context
*/
Render.inspector = function (inspector, context) {
var engine = inspector.engine,
selected = inspector.selected,
render = inspector.render,
options = render.options,
bounds;
if (options.hasBounds) {
var boundsWidth = render.bounds.max.x - render.bounds.min.x,
boundsHeight = render.bounds.max.y - render.bounds.min.y,
boundsScaleX = boundsWidth / render.options.width,
boundsScaleY = boundsHeight / render.options.height;
context.scale(1 / boundsScaleX, 1 / boundsScaleY);
context.translate(-render.bounds.min.x, -render.bounds.min.y);
}
for (var i = 0; i < selected.length; i++) {
var item = selected[i].data;
context.translate(0.5, 0.5);
context.lineWidth = 1;
context.strokeStyle = 'rgba(255,165,0,0.9)';
context.setLineDash([1, 2]);
switch (item.type) {
case 'body':
// render body selections
bounds = item.bounds;
context.beginPath();
context.rect(Math.floor(bounds.min.x - 3), Math.floor(bounds.min.y - 3),
Math.floor(bounds.max.x - bounds.min.x + 6), Math.floor(bounds.max.y - bounds.min.y + 6));
context.closePath();
context.stroke();
break;
case 'constraint':
// render constraint selections
var point = item.pointA;
if (item.bodyA)
point = item.pointB;
context.beginPath();
context.arc(point.x, point.y, 10, 0, 2 * Math.PI);
context.closePath();
context.stroke();
break;
}
context.setLineDash([]);
context.translate(-0.5, -0.5);
}
// render selection region
if (inspector.selectStart !== null) {
context.translate(0.5, 0.5);
context.lineWidth = 1;
context.strokeStyle = 'rgba(255,165,0,0.6)';
context.fillStyle = 'rgba(255,165,0,0.1)';
bounds = inspector.selectBounds;
context.beginPath();
context.rect(Math.floor(bounds.min.x), Math.floor(bounds.min.y),
Math.floor(bounds.max.x - bounds.min.x), Math.floor(bounds.max.y - bounds.min.y));
context.closePath();
context.stroke();
context.fill();
context.translate(-0.5, -0.5);
}
if (options.hasBounds)
context.setTransform(1, 0, 0, 1, 0, 0);
};
/**
* Description
* @method _createCanvas
* @private
* @param {} width
* @param {} height
* @return canvas
*/
var _createCanvas = function (width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.oncontextmenu = function () {
return false;
};
canvas.onselectstart = function () {
return false;
};
return canvas;
};
/**
* Gets the pixel ratio of the canvas.
* @method _getPixelRatio
* @private
* @param {HTMLElement} canvas
* @return {Number} pixel ratio
*/
var _getPixelRatio = function (canvas) {
var context = canvas.getContext('2d'),
devicePixelRatio = window.devicePixelRatio || 1,
backingStorePixelRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio || context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return devicePixelRatio / backingStorePixelRatio;
};
/**
* Gets the requested texture (an Image) via its path
* @method _getTexture
* @private
* @param {render} render
* @param {string} imagePath
* @return {Image} texture
*/
var _getTexture = function (render, imagePath) {
var image = render.textures[imagePath];
if (image)
return image;
image = render.textures[imagePath] = new Image();
image.src = imagePath;
return image;
};
/**
* Applies the background to the canvas using CSS.
* @method applyBackground
* @private
* @param {render} render
* @param {string} background
*/
var _applyBackground = function (render, background) {
var cssBackground = background;
if (/(jpg|gif|png)$/.test(background))
cssBackground = 'url(' + background + ')';
render.canvas.style.background = cssBackground;
render.canvas.style.backgroundSize = "contain";
render.currentBackground = background;
};
/*
*
* Events Documentation
*
*/
/**
* Fired before rendering
*
* @event beforeRender
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/**
* Fired after rendering
*
* @event afterRender
* @param {} event An event object
* @param {number} event.timestamp The engine.timing.timestamp of the event
* @param {} event.source The source object of the event
* @param {} event.name The name of the event
*/
/*
*
* Properties Documentation
*
*/
/**
* A back-reference to the `Matter.Render` module.
*
* @property controller
* @type render
*/
/**
* A reference to the `Matter.Engine` instance to be used.
*
* @property engine
* @type engine
*/
/**
* A reference to the element where the canvas is to be inserted (if `render.canvas` has not been specified)
*
* @property element
* @type HTMLElement
* @default null
*/
/**
* The canvas element to render to. If not specified, one will be created if `render.element` has been specified.
*
* @property canvas
* @type HTMLCanvasElement
* @default null
*/
/**
* The configuration options of the renderer.
*
* @property options
* @type {}
*/
/**
* The target width in pixels of the `render.canvas` to be created.
*
* @property options.width
* @type number
* @default 800
*/
/**
* The target height in pixels of the `render.canvas` to be created.
*
* @property options.height
* @type number
* @default 600
*/
/**
* A flag that specifies if `render.bounds` should be used when rendering.
*
* @property options.hasBounds
* @type boolean
* @default false
*/
/**
* A `Bounds` object that specifies the drawing view region.
* Rendering will be automatically transformed and scaled to fit within the canvas size (`render.options.width` and `render.options.height`).
* This allows for creating views that can pan or zoom around the scene.
* You must also set `render.options.hasBounds` to `true` to enable bounded rendering.
*
* @property bounds
* @type bounds
*/
/**
* The 2d rendering context from the `render.canvas` element.
*
* @property context
* @type CanvasRenderingContext2D
*/
/**
* The sprite texture cache.
*
* @property textures
* @type {}
*/
})();
}, {
"../body/Composite": 2,
"../collision/Grid": 6,
"../core/Common": 14,
"../core/Events": 16,
"../core/Mouse": 19,
"../geometry/Bounds": 26,
"../geometry/Vector": 28
}],
32: [function (_dereq_, module, exports) {
/**
* The `Matter.RenderPixi` module is an example renderer using pixi.js.
* See also `Matter.Render` for a canvas based renderer.
*
* @class RenderPixi
* @deprecated the Matter.RenderPixi module will soon be removed from the Matter.js core.
* It will likely be moved to its own repository (but maintenance will be limited).
*/
var RenderPixi = {};
module.exports = RenderPixi;
var Bounds = _dereq_('../geometry/Bounds');
var Composite = _dereq_('../body/Composite');
var Common = _dereq_('../core/Common');
var Events = _dereq_('../core/Events');
var Vector = _dereq_('../geometry/Vector');
(function () {
var _requestAnimationFrame,
_cancelAnimationFrame;
if (typeof window !== 'undefined') {
_requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(function () {
callback(Common.now());
}, 1000 / 60);
};
_cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame || window.msCancelAnimationFrame;
}
/**
* Creates a new Pixi.js WebGL renderer
* @method create
* @param {object} options
* @return {RenderPixi} A new renderer
* @deprecated
*/
RenderPixi.create = function (options) {
Common.warn('RenderPixi.create: Matter.RenderPixi is deprecated (see docs)');
var defaults = {
controller: RenderPixi,
engine: null,
element: null,
frameRequestId: null,
canvas: null,
renderer: null,
container: null,
spriteContainer: null,
pixiOptions: null,
options: {
width: 800,
height: 600,
background: '#fafafa',
wireframeBackground: '#222',
hasBounds: false,
enabled: true,
wireframes: true,
showSleeping: true,
showDebug: false,
showBroadphase: false,
showBounds: false,
showVelocity: false,
showCollisions: false,
showAxes: false,
showPositions: false,
showAngleIndicator: false,
showIds: false,
showShadows: false
}
};
var render = Common.extend(defaults, options),
transparent = !render.options.wireframes && render.options.background === 'transparent';
// init pixi
render.pixiOptions = render.pixiOptions || {
view: render.canvas,
transparent: transparent,
antialias: true,
backgroundColor: options.background
};
render.mouse = options.mouse;
render.engine = options.engine;
render.renderer = render.renderer || new PIXI.WebGLRenderer(render.options.width, render.options.height, render.pixiOptions);
render.container = render.container || new PIXI.Container();
render.spriteContainer = render.spriteContainer || new PIXI.Container();
render.canvas = render.canvas || render.renderer.view;
render.bounds = render.bounds || {
min: {
x: 0,
y: 0
},
max: {
x: render.options.width,
y: render.options.height
}
};
// event listeners
Events.on(render.engine, 'beforeUpdate', function () {
RenderPixi.clear(render);
});
// caches
render.textures = {};
render.sprites = {};
render.primitives = {};
// use a sprite batch for performance
render.container.addChild(render.spriteContainer);
// insert canvas
if (Common.isElement(render.element)) {
render.element.appendChild(render.canvas);
} else {
Common.warn('No "render.element" passed, "render.canvas" was not inserted into document.');
}
// prevent menus on canvas
render.canvas.oncontextmenu = function () {
return false;
};
render.canvas.onselectstart = function () {
return false;
};
return render;
};
/**
* Continuously updates the render canvas on the `requestAnimationFrame` event.
* @method run
* @param {render} render
* @deprecated
*/
RenderPixi.run = function (render) {
(function loop(time) {
render.frameRequestId = _requestAnimationFrame(loop);
RenderPixi.world(render);
})();
};
/**
* Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop.
* @method stop
* @param {render} render
* @deprecated
*/
RenderPixi.stop = function (render) {
_cancelAnimationFrame(render.frameRequestId);
};
/**
* Clears the scene graph
* @method clear
* @param {RenderPixi} render
* @deprecated
*/
RenderPixi.clear = function (render) {
var container = render.container,
spriteContainer = render.spriteContainer;
// clear stage container
while (container.children[0]) {
container.removeChild(container.children[0]);
}
// clear sprite batch
while (spriteContainer.children[0]) {
spriteContainer.removeChild(spriteContainer.children[0]);
}
var bgSprite = render.sprites['bg-0'];
// clear caches
render.textures = {};
render.sprites = {};
render.primitives = {};
// set background sprite
render.sprites['bg-0'] = bgSprite;
if (bgSprite)
container.addChildAt(bgSprite, 0);
// add sprite batch back into container
render.container.addChild(render.spriteContainer);
// reset background state
render.currentBackground = null;
// reset bounds transforms
container.scale.set(1, 1);
container.position.set(0, 0);
};
/**
* Sets the background of the canvas
* @method setBackground
* @param {RenderPixi} render
* @param {string} background
* @deprecated
*/
RenderPixi.setBackground = function (render, background) {
if (render.currentBackground !== background) {
var isColor = background.indexOf && background.indexOf('#') !== -1,
bgSprite = render.sprites['bg-0'];
if (isColor) {
// if solid background color
var color = Common.colorToNumber(background);
render.renderer.backgroundColor = color;
// remove background sprite if existing
if (bgSprite)
render.container.removeChild(bgSprite);
} else {
// initialise background sprite if needed
if (!bgSprite) {
var texture = _getTexture(render, background);
bgSprite = render.sprites['bg-0'] = new PIXI.Sprite(texture);
bgSprite.position.x = 0;
bgSprite.position.y = 0;
render.container.addChildAt(bgSprite, 0);
}
}
render.currentBackground = background;
}
};
/**
* Description
* @method world
* @param {engine} engine
* @deprecated
*/
RenderPixi.world = function (render) {
var engine = render.engine,
world = engine.world,
renderer = render.renderer,
container = render.container,
options = render.options,
bodies = Composite.allBodies(world),
allConstraints = Composite.allConstraints(world),
constraints = [],
i;
if (options.wireframes) {
RenderPixi.setBackground(render, options.wireframeBackground);
} else {
RenderPixi.setBackground(render, options.background);
}
// handle bounds
var boundsWidth = render.bounds.max.x - render.bounds.min.x,
boundsHeight = render.bounds.max.y - render.bounds.min.y,
boundsScaleX = boundsWidth / render.options.width,
boundsScaleY = boundsHeight / render.options.height;
if (options.hasBounds) {
// Hide bodies that are not in view
for (i = 0; i < bodies.length; i++) {
var body = bodies[i];
body.render.sprite.visible = Bounds.overlaps(body.bounds, render.bounds);
}
// filter out constraints that are not in view
for (i = 0; i < allConstraints.length; i++) {
var constraint = allConstraints[i],
bodyA = constraint.bodyA,
bodyB = constraint.bodyB,
pointAWorld = constraint.pointA,
pointBWorld = constraint.pointB;
if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA);
if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB);
if (!pointAWorld || !pointBWorld)
continue;
if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld))
constraints.push(constraint);
}
// transform the view
container.scale.set(1 / boundsScaleX, 1 / boundsScaleY);
container.position.set(-render.bounds.min.x * (1 / boundsScaleX), -render.bounds.min.y * (1 / boundsScaleY));
} else {
constraints = allConstraints;
}
for (i = 0; i < bodies.length; i++)
RenderPixi.body(render, bodies[i]);
for (i = 0; i < constraints.length; i++)
RenderPixi.constraint(render, constraints[i]);
renderer.render(container);
};
/**
* Description
* @method constraint
* @param {engine} engine
* @param {constraint} constraint
* @deprecated
*/
RenderPixi.constraint = function (render, constraint) {
var engine = render.engine,
bodyA = constraint.bodyA,
bodyB = constraint.bodyB,
pointA = constraint.pointA,
pointB = constraint.pointB,
container = render.container,
constraintRender = constraint.render,
primitiveId = 'c-' + constraint.id,
primitive = render.primitives[primitiveId];
// initialise constraint primitive if not existing
if (!primitive)
primitive = render.primitives[primitiveId] = new PIXI.Graphics();
// don't render if constraint does not have two end points
if (!constraintRender.visible || !constraint.pointA || !constraint.pointB) {
primitive.clear();
return;
}
// add to scene graph if not already there
if (Common.indexOf(container.children, primitive) === -1)
container.addChild(primitive);
// render the constraint on every update, since they can change dynamically
primitive.clear();
primitive.beginFill(0, 0);
primitive.lineStyle(constraintRender.lineWidth, Common.colorToNumber(constraintRender.strokeStyle), 1);
if (bodyA) {
primitive.moveTo(bodyA.position.x + pointA.x, bodyA.position.y + pointA.y);
} else {
primitive.moveTo(pointA.x, pointA.y);
}
if (bodyB) {
primitive.lineTo(bodyB.position.x + pointB.x, bodyB.position.y + pointB.y);
} else {
primitive.lineTo(pointB.x, pointB.y);
}
primitive.endFill();
};
/**
* Description
* @method body
* @param {engine} engine
* @param {body} body
* @deprecated
*/
RenderPixi.body = function (render, body) {
var engine = render.engine,
bodyRender = body.render;
if (!bodyRender.visible)
return;
if (bodyRender.sprite && bodyRender.sprite.texture) {
var spriteId = 'b-' + body.id,
sprite = render.sprites[spriteId],
spriteContainer = render.spriteContainer;
// initialise body sprite if not existing
if (!sprite)
sprite = render.sprites[spriteId] = _createBodySprite(render, body);
// add to scene graph if not already there
if (Common.indexOf(spriteContainer.children, sprite) === -1)
spriteContainer.addChild(sprite);
// update body sprite
sprite.position.x = body.position.x;
sprite.position.y = body.position.y;
sprite.rotation = body.angle;
sprite.scale.x = bodyRender.sprite.xScale || 1;
sprite.scale.y = bodyRender.sprite.yScale || 1;
} else {
var primitiveId = 'b-' + body.id,
primitive = render.primitives[primitiveId],
container = render.container;
// initialise body primitive if not existing
if (!primitive) {
primitive = render.primitives[primitiveId] = _createBodyPrimitive(render, body);
primitive.initialAngle = body.angle;
}
// add to scene graph if not already there
if (Common.indexOf(container.children, primitive) === -1)
container.addChild(primitive);
// update body primitive
primitive.position.x = body.position.x;
primitive.position.y = body.position.y;
primitive.rotation = body.angle - primitive.initialAngle;
}
};
/**
* Creates a body sprite
* @method _createBodySprite
* @private
* @param {RenderPixi} render
* @param {body} body
* @return {PIXI.Sprite} sprite
* @deprecated
*/
var _createBodySprite = function (render, body) {
var bodyRender = body.render,
texturePath = bodyRender.sprite.texture,
texture = _getTexture(render, texturePath),
sprite = new PIXI.Sprite(texture);
sprite.anchor.x = body.render.sprite.xOffset;
sprite.anchor.y = body.render.sprite.yOffset;
return sprite;
};
/**
* Creates a body primitive
* @method _createBodyPrimitive
* @private
* @param {RenderPixi} render
* @param {body} body
* @return {PIXI.Graphics} graphics
* @deprecated
*/
var _createBodyPrimitive = function (render, body) {
var bodyRender = body.render,
options = render.options,
primitive = new PIXI.Graphics(),
fillStyle = Common.colorToNumber(bodyRender.fillStyle),
strokeStyle = Common.colorToNumber(bodyRender.strokeStyle),
strokeStyleIndicator = Common.colorToNumber(bodyRender.strokeStyle),
strokeStyleWireframe = Common.colorToNumber('#bbb'),
strokeStyleWireframeIndicator = Common.colorToNumber('#CD5C5C'),
part;
primitive.clear();
// handle compound parts
for (var k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {
part = body.parts[k];
if (!options.wireframes) {
primitive.beginFill(fillStyle, 1);
primitive.lineStyle(bodyRender.lineWidth, strokeStyle, 1);
} else {
primitive.beginFill(0, 0);
primitive.lineStyle(1, strokeStyleWireframe, 1);
}
primitive.moveTo(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y);
for (var j = 1; j < part.vertices.length; j++) {
primitive.lineTo(part.vertices[j].x - body.position.x, part.vertices[j].y - body.position.y);
}
primitive.lineTo(part.vertices[0].x - body.position.x, part.vertices[0].y - body.position.y);
primitive.endFill();
// angle indicator
if (options.showAngleIndicator || options.showAxes) {
primitive.beginFill(0, 0);
if (options.wireframes) {
primitive.lineStyle(1, strokeStyleWireframeIndicator, 1);
} else {
primitive.lineStyle(1, strokeStyleIndicator);
}
primitive.moveTo(part.position.x - body.position.x, part.position.y - body.position.y);
primitive.lineTo(((part.vertices[0].x + part.vertices[part.vertices.length - 1].x) / 2 - body.position.x),
((part.vertices[0].y + part.vertices[part.vertices.length - 1].y) / 2 - body.position.y));
primitive.endFill();
}
}
return primitive;
};
/**
* Gets the requested texture (a PIXI.Texture) via its path
* @method _getTexture
* @private
* @param {RenderPixi} render
* @param {string} imagePath
* @return {PIXI.Texture} texture
* @deprecated
*/
var _getTexture = function (render, imagePath) {
var texture = render.textures[imagePath];
if (!texture)
texture = render.textures[imagePath] = PIXI.Texture.fromImage(imagePath);
return texture;
};
})();
}, {
"../body/Composite": 2,
"../core/Common": 14,
"../core/Events": 16,
"../geometry/Bounds": 26,
"../geometry/Vector": 28
}]
}, {}, [30])(30)
}); |
"use strict";
var mockito4js = getMockito4jsBuilder().build(getMockito4jsBuilder()); |
(function(g) {
"use strict";
g.load('gdata', '1');
var
body = document.body,
cal = document.getElementById('calendar'),
feed = 'https://www.google.com/calendar/feeds/4qc3thgj9ocunpfist563utr6g@group.calendar.google.com/public/full',
service,
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
currentStart,
tmpl = document.getElementById('template').innerHTML;
function autolink(text) {
// http://jsfiddle.net/kachibito/hEgvc/1/light/
return text.replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g,"<a href='$1'>$1</a>");
}
function formatTime(date) {
var
output = [];
output.push((date.getHours() % 12) || 12);
output.push(':');
output.push(('0' + date.getMinutes()).slice(-2));
output.push(date.getHours() > 11 ? ' p.m.' : ' a.m.');
return output.join('');
}
function sortEvents(a, b) {
if(a.start < b.start) {
return -1;
} else if(a.start > b.start) {
return 1;
} else {
return 0;
}
}
function displayEvents(data) {
var
events = [],
feed = data.feed.getEntries(),
i = feed.length;
while(i--) {
var
evnt = feed[i],
j = evnt.gd$when.length;
while(j--) {
var
obj = {};
obj.title = evnt.getTitle().getText();
obj.content = autolink(evnt.getContent().getText());
obj.start = new Date(evnt.gd$when[j].startTime);
obj.day = obj.start.getDate();
obj.time = formatTime(obj.start);
try {
obj.address = evnt.gd$where[0].valueString.replace(', United States', '');
} catch(e) {}
events.unshift(obj);
}
}
events.sort(sortEvents);
cal.innerHTML = window.Mustache.render(tmpl, {
'month': [months[currentStart.getMonth()], currentStart.getFullYear()].join(' '),
'events': events
});
body.classList.remove('loading');
}
function errorHandler(error) {
window.console.error(error);
}
function getFirstOfMonth(month, year) {
var
start = new Date();
if(month) {
start.setMonth(month);
}
if(year) {
start.setYear(year);
}
start.setDate(1);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
start.setMilliseconds(0);
return start;
}
function getEndOfMonth(start) {
var
end = new Date(start.getTime());
end.setMonth(start.getMonth() + 1);
end = new Date(end - (24 * 60 * 60 * 1000));
end.setHours(23);
end.setMinutes(59);
end.setSeconds(59);
end.setMilliseconds(999);
return end;
}
function hashHandler() {
var
hash = window.location.hash.replace(/^#/, '');
if(/^[\d]{4}-[\d]{2}$/.exec(hash)) {
hash = hash.split('-');
var
year = parseInt(hash[0], 10),
month = parseInt(hash[1], 10) - 1,
start = new Date();
start.setYear(year);
start.setMonth(month);
start.setDate(1);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
start.setMilliseconds(0);
displayEventsFor(start);
}
}
window.addEventListener('hashchange', hashHandler);
function setHash(start) {
if(!start) { return; }
window.location.hash = [start.getFullYear(), ('0' + (start.getMonth() + 1)).slice(-2)].join('-');
}
function init() {
service = new g.gdata.calendar.CalendarService('chadev-events-1');
if(/^#?[\d]{4}-[\d]{2}$/.exec(window.location.hash)) {
hashHandler();
return;
}
setHash(getFirstOfMonth());
}
function displayEventsFor(start, end) {
if(!service || !start) { return; }
if(!end) {
end = getEndOfMonth(start);
}
var
query = new g.gdata.calendar.CalendarEventQuery(feed);
query.setMinimumStartTime(start.toISOString());
query.setMaximumStartTime(end.toISOString());
cal.innerHTML = '';
body.classList.add('loading');
currentStart = start;
service.getEventsFeed(query, displayEvents, errorHandler);
}
function clickHandler(e) {
var
start = new Date(currentStart.getTime());
if(e.srcElement && e.srcElement.id === 'previous') {
e.preventDefault();
start.setMonth(start.getMonth() - 1);
setHash(start);
} else if(e.srcElement && e.srcElement.id === 'next') {
e.preventDefault();
start.setMonth(start.getMonth() + 1);
setHash(start);
}
}
cal.addEventListener('click', clickHandler);
g.setOnLoadCallback(init);
})(window.google);
|
angular.module('UserModule').controller('AdministrationController', ['$scope', '$state','$http', 'toastr', function($scope,$state, $http, toastr){
$scope.me = window.SAILS_LOCALS.me;
if (!$scope.me.admin) $state.go('home');
$scope.recordSave = 'Запись успешно сохранена!';
// set-up loading state
$scope.userList = {
loading: false
};
$http.get('/user/adminUsers')
.then(function onSuccess(sailsResponse){
console.log('sailsResponse.data: ', sailsResponse.data);
$scope.userList.contents = sailsResponse.data;
})
.catch(function onError(sailsResponse){
//console.log(sailsResponse);
})
.finally(function eitherWay(){
$scope.userList.loading = false;
});
$scope.saveAdmin = function(id, change){
//console.log('id: ', id);
//console.log('change: ', change);
var theRoute = '/user/update-admin/' + id;
// Submit PUT request to Sails.
$http.put(theRoute, {
id: id,
admin: change
})
.then(function onSuccess(sailsResponse) {
// Notice that the sailsResponse is an array and not a single object
// The .update() model method returns an array and not a single record.
// window.location = '#/profile/' + sailsResponse.data[0].id;
// $scope.editProfile.loading = false;
toastr.success($scope.recordSave,'', { timeOut: 1000 });
//console.log('sailsResponse: ', sailsResponse);
})
.catch(function onError(sailsResponse) {
// console.log(sailsResponse);
// Otherwise, display generic error if the error is unrecognized.
$scope.editProfile.errorMsg = 'Произошла непредвиденная ошибка: ' + (sailsResponse.data || sailsResponse.status);
})
.finally(function eitherWay() {
$scope.editProfile.loading = false;
});
};
$scope.saveKadr = function(id, change){
var theRoute = '/user/update-kadr/' + id;
$http.put(theRoute, {
id: id,
kadr: change
})
.then(function onSuccess(sailsResponse) {
toastr.success($scope.recordSave,'', { timeOut: 1000 });
//console.log('sailsResponse: ', sailsResponse);
})
.catch(function onError(sailsResponse) {
$scope.editProfile.errorMsg = 'Произошла непредвиденная ошибка: ' + (sailsResponse.data || sailsResponse.status);
})
.finally(function eitherWay() {
$scope.editProfile.loading = false;
});
};
$scope.saveLeader = function(id, change){
var theRoute = '/user/update-leader/' + id;
$http.put(theRoute, {
id: id,
leader: change
})
.then(function onSuccess(sailsResponse) {
toastr.success($scope.recordSave,'', { timeOut: 1000 });
//console.log('sailsResponse: ', sailsResponse);
})
.catch(function onError(sailsResponse) {
$scope.editProfile.errorMsg = 'Произошла непредвиденная ошибка: ' + (sailsResponse.data || sailsResponse.status);
})
.finally(function eitherWay() {
$scope.editProfile.loading = false;
});
};
$scope.saveAction = function(id, change){
//console.log('id: ', id);
//console.log('change: ', change);
var theRoute = '/user/update-action/' + id;
// Submit PUT request to Sails.
$http.put(theRoute, {
id: id,
action: change
})
.then(function onSuccess(sailsResponse) {
// Notice that the sailsResponse is an array and not a single object
// The .update() model method returns an array and not a single record.
// window.location = '#/profile/' + sailsResponse.data[0].id;
// $scope.editProfile.loading = false;
// toastr.options.fadeOut = 1000;
// toastr.success('Successfully Saved!');
toastr.success($scope.recordSave,'', { timeOut: 1000 });
//console.log('sailsResponse: ', sailsResponse);
})
.catch(function onError(sailsResponse) {
// console.log(sailsResponse);
// Otherwise, display generic error if the error is unrecognized.
$scope.editProfile.errorMsg = 'Произошла непредвиденная ошибка: ' + (sailsResponse.data || sailsResponse.status);
})
.finally(function eitherWay() {
$scope.editProfile.loading = false;
});
};
$scope.saveDeleted = function(id, change){
var theRoute = '/user/update-deleted/' + id;
$http.put(theRoute, {
id: id,
deleted: change
})
.then(function onSuccess(sailsResponse) {
toastr.success($scope.recordSave,'', { timeOut: 1000 });
//console.log('sailsResponse: ', sailsResponse);
})
.catch(function onError(sailsResponse) {
$scope.editProfile.errorMsg = 'Произошла непредвиденная ошибка: ' + (sailsResponse.data || sailsResponse.status);
})
.finally(function eitherWay() {
$scope.editProfile.loading = false;
});
};
}]); |
var link=message.content(owner);
bot.setAvatar(link);
|
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import Subheader from './Subheader';
import { cardSubheaderDriverFactory } from './Subheader.uni.driver';
describe('Subheader', () => {
const render = createRendererWithUniDriver(cardSubheaderDriverFactory);
afterEach(() => {
cleanup();
});
it('should render', async () => {
const { driver } = render(<Subheader title="title" />);
expect(await driver.exists()).toBe(true);
});
describe('`title` prop', () => {
it('should render as string', async () => {
const { driver } = render(<Subheader title="title" />);
expect(await driver.title()).toBe('title');
});
it('should render as component', async () => {
const { driver } = render(
<Subheader title={<span data-hook="custom-node">hello world</span>} />,
);
expect(await (await driver.titleNode()).text()).toBe('hello world');
});
});
describe('`suffix` prop', () => {
it('should render as component', async () => {
const { driver } = render(
<Subheader
title="hi there"
suffix={<span data-hook="custom-node">hello world</span>}
/>,
);
expect(await (await driver.suffixNode()).text()).toBe('hello world');
});
});
});
|
'use strict';
const fs = require('fs');
const path = require('path');
const utils = require('./scripts/utils.js');
const parsers = require('./scripts/parse-blocks-scripts-properties.js');
parsers.parseBidiBrackets = require('./scripts/parse-bidi-brackets.js');
parsers.parseCaseFolding = require('./scripts/parse-case-folding.js');
parsers.parseCategories = require('./scripts/parse-categories.js');
parsers.parseCompositionExclusions = require('./scripts/parse-composition-exclusions.js');
parsers.parseLineBreak = require('./scripts/parse-line-break.js');
parsers.parseScriptExtensions = require('./scripts/parse-script-extensions.js');
parsers.parseWordBreak = require('./scripts/parse-word-break.js');
parsers.parseEmoji = require('./scripts/parse-emoji.js');
parsers.parseEmojiSequences = require('./scripts/parse-emoji-sequences.js');
parsers.parseNames = require('./scripts/parse-names.js');
const extend = utils.extend;
const cp = require('cp');
const jsesc = require('jsesc');
const template = require('lodash.template');
const templatePath = path.resolve(__dirname, 'templates');
const staticPath = path.resolve(__dirname, 'static');
const compileReadMe = template(fs.readFileSync(
path.resolve(templatePath, 'README.md'),
'utf-8')
);
const compilePackage = template(fs.readFileSync(
path.resolve(templatePath, 'package.json'),
'utf-8')
);
const compileIndex = template('module.exports=<%= data %>');
const generateData = function(version) {
const dirMap = {};
console.log('Generating data for Unicode v%s…', version);
console.log('Parsing Unicode v%s categories…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseCategories(version),
'type': function(category) {
if (/^(?:Any|ASCII|Assigned|Bidi_Mirrored)$/.test(category)) {
return 'Binary_Property';
}
if (/^Bidi_/.test(category)) {
return 'Bidi_Class';
}
return 'General_Category';
}
}));
console.log('Parsing Unicode v%s `Script`…', version);
const scriptsMap = parsers.parseScripts(version)
extend(dirMap, utils.writeFiles({
'version': version,
'map': scriptsMap,
'type': 'Script'
}));
console.log('Parsing Unicode v%s `Script_Extensions`…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseScriptExtensions(version, scriptsMap),
'type': 'Script_Extensions'
}));
console.log('Parsing Unicode v%s properties…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseProperties(version),
'type': 'Binary_Property'
}));
console.log('Parsing Unicode v%s derived core properties…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseDerivedCoreProperties(version),
'type': 'Binary_Property'
}));
console.log('Parsing Unicode v%s derived normalization properties…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseDerivedNormalizationProperties(version),
'type': 'Binary_Property'
}));
console.log('Parsing Unicode v%s composition exclusions…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseCompositionExclusions(version),
'type': 'Binary_Property'
}));
console.log('Parsing Unicode v%s `Case_Folding`…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseCaseFolding(version),
'type': 'Case_Folding'
}));
console.log('Parsing Unicode v%s `Block`…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseBlocks(version),
'type': 'Block'
}));
console.log('Parsing Unicode v%s `Bidi_Mirroring_Glyph`', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseMirroring(version),
'type': 'Bidi_Mirroring_Glyph'
}));
console.log('Parsing Unicode v%s bidi brackets…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseBidiBrackets(version),
'type': 'Bidi_Paired_Bracket_Type'
}));
console.log('Parsing Unicode v%s `Line_Break`…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseLineBreak(version),
'type': 'Line_Break'
}));
console.log('Parsing Unicode v%s `Word_Break`…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseWordBreak(version),
'type': 'Word_Break'
}));
console.log('Parsing Unicode v%s binary emoji properties…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseEmoji(version),
'type': 'Binary_Property'
}));
console.log('Parsing Unicode v%s emoji sequence properties…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseEmojiSequences(version),
'type': 'Sequence_Property'
}));
console.log('Parsing Unicode v%s `Names`…', version);
extend(dirMap, utils.writeFiles({
'version': version,
'map': parsers.parseNames(version),
'type': 'Names'
}));
// Sort array values.
for (const property of Object.keys(dirMap)) {
if (Array.isArray(dirMap[property])) {
dirMap[property] = dirMap[property].sort();
}
}
fs.writeFileSync(
path.resolve(__dirname, `output/unicode-${version}/README.md`),
compileReadMe({
'version': version,
'dirs': dirMap,
'regenerateExample': '<%= set.toString() %>'
})
);
fs.writeFileSync(
path.resolve(__dirname, `output/unicode-${version}/index.js`),
compileIndex({ 'version': version, 'data': jsesc(dirMap) })
);
fs.writeFileSync(
path.resolve(__dirname, `output/unicode-${version}/package.json`),
compilePackage({ 'version': version })
);
fs.mkdirSync(
path.resolve(__dirname, `output/unicode-${version}/.github/workflows`),
{
recursive: true,
}
);
[
'.github/workflows/publish-on-tag.yml',
'.gitattributes',
'.gitignore',
'.npmignore',
'decode-property-map.js',
'decode-ranges.js',
].forEach(function(file) {
cp.sync(
path.resolve(staticPath, file),
path.resolve(__dirname, `output/unicode-${version}/${file}`)
);
});
return dirMap;
};
module.exports = generateData;
|
'use strict';
var BaseRequest = require('./BaseRequest'),
util = require('util'),
iyzicoUtils = require('../utils'),
SubscriptionCustomer = require('./model/SubscriptionCustomer');
function CreateSubscriptionCustomerRequest(request) {
BaseRequest.call(this, iyzicoUtils.mergeObjects({
locale: request['locale'],
conversationId: request['conversationId']
}, SubscriptionCustomer.body(request)));
}
util.inherits(CreateSubscriptionCustomerRequest, BaseRequest);
module.exports = CreateSubscriptionCustomerRequest;
|
/**
* Created by Papa on 5/28/2016.
*/
"use strict";
const LocalStoreConfig_1 = require("./LocalStoreConfig");
const DeltaStoreConfig_1 = require("./DeltaStoreConfig");
const index_1 = require("delta-store/lib/index");
const LocalStoreApi_1 = require("../localStore/LocalStoreApi");
const IdGenerator_1 = require("../localStore/IdGenerator");
class PersistenceConfig {
constructor(config) {
this.config = config;
if (config.deltaStore) {
let phDeltaStoreConfig = config.deltaStore;
this.deltaStoreConfig = DeltaStoreConfig_1.createDeltaStoreConfig(phDeltaStoreConfig);
}
if (config.localStore) {
this.localStoreConfig = LocalStoreConfig_1.createLocalStoreConfig(config.appName, config.localStore);
}
}
static getDefaultPHConfig(appName = 'DefaultApp', distributionStrategy = index_1.DistributionStrategy.S3_SECURE_POLL, deltaStorePlatform = index_1.PlatformType.GOOGLE, localStoreType = LocalStoreApi_1.LocalStoreType.SQLITE_CORDOVA, offlineDeltaStoreType = LocalStoreApi_1.LocalStoreType.SQLITE_CORDOVA, idGeneration = IdGenerator_1.IdGeneration.ENTITY_CHANGE_ID) {
return {
appName: appName,
deltaStore: {
changeList: {
distributionStrategy: distributionStrategy
},
offlineDeltaStore: {
type: offlineDeltaStoreType
},
recordIdField: "id",
platform: deltaStorePlatform
},
localStore: {
type: localStoreType,
idGeneration: idGeneration
}
};
}
}
exports.PersistenceConfig = PersistenceConfig;
//# sourceMappingURL=PersistenceConfig.js.map |
/*!
* js-file-browser
* Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file.
*
* With components from: Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/**
* @class Ext.data.JsonStore
* @extends Ext.data.Store
* <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
* A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
* <p>A store configuration would be something like:<pre><code>
var store = new Ext.data.JsonStore({
// store configs
autoDestroy: true,
url: 'get-images.php',
storeId: 'myStore',
// reader configs
root: 'images',
idProperty: 'name',
fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
});
* </code></pre></p>
* <p>This store is configured to consume a returned object of the form:<pre><code>
{
images: [
{name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
{name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
]
}
* </code></pre>
* An object literal of this form could also be used as the {@link #data} config option.</p>
* <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
* <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
* @constructor
* @param {Object} config
* @xtype jsonstore
*/
Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
/**
* @cfg {Ext.data.DataReader} reader @hide
*/
constructor: function(config){
Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new Ext.data.JsonReader(config)
}));
}
});
Ext.reg('jsonstore', Ext.data.JsonStore); |
/**
* Popup script
*/
'use strict';
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app-component';
/**
* Temporary solution.
* At least required for autocomplete component
* @see https://github.com/callemall/material-ui#react-tap-event-plugin
*/
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
ReactDOM.render(<App/>, document.getElementById('styleme-app'));
|
//定义界面数据,主要用于设置语言,固定的id名叫iData
define({
header: [{
id: "inputData",
text: "输入数据"
}, {
id: "viewData",
text: "查看数据"
}],
card: {
inputData: {
top: {
title: "输入数据",
content: "将数据字符串粘贴到文本域内"
},
main: {
textarea: {
placeholder: "在此粘贴数据"
}
},
bottom: {
content: '<div style="line-height:50px;text-align:center;">可打开调试工具,运行 require.br.viewMap.expore 方法,可以得到测试用的 数据字符串 </div>'
}
},
viewData: {
top: {
title: "加载数据",
content: '<div class="tip_content"><div class="color_tip" title="没有下载过的模块或文件,第一次加载"><div class="color_example" style="background:#77b3de;"></div>初次加载</div><div class="color_tip" title="还未完成第一次加载的模块,重复调用该模块"><div class="color_example" style="background:#eba446;"></div>插队加载</div><div class="color_tip" title="已经下载完成的模块,从缓存获取模块数据"><div class="color_example" style="background:#72c380;"></div>缓存加载</div><div class="color_tip" title="加载失败的模块或文件"><div class="color_example" style="background:#df6164;"></div>加载错误</div></div>'
},
main: {
infoTab: {
title: "加载信息",
tips: "点击模块可查看模块加载信息",
moduleName: "模块名",
registName: "注册资源",
start: "开始加载",
end: "结束加载",
userTime: "使用时间",
group: "同组模块",
prevGroup: "前组模块",
parent: "父节点"
}
},
bottom: {
content: ""
}
}
}
}, 'iData'); |
'use strict';
angular.module('shufabeitie.show', ['ngRoute', 'ksSwiper'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/shufa/:author/:fatie', {
templateUrl: 'show/show.html',
controller: 'ShowCtrl'
});
}
])
.directive('ksFatieImage', function() {
function link(scope, element, attrs) {
element.on('slideChangeEnd', function(e) {
// 也可以在这个事件监控里完成img对象的src属性操作。
console.log(e, e.target);
});
// 操作显示的slide的image大图
scope.$on('slideChangeEnd' + attrs.index, function() {
var $img = $(element).find('img.beitie-img');
var src = $img.attr('src');
if (!/w1000/.test(src)) {
var preload = new Image();
preload.src = src.replace(/w100/, 'w1000');
preload.onload = function() {
$img.attr('src', preload.src);
};
}
});
}
return {
restrict: 'E',
link: link,
scope: {
image: '=image',
fatie: '=fatie'
},
template: '<img ng-src="/{{fatie.path100}}/{{image}}" class="img-responsive beitie-img">'
};
})
.controller('ShowCtrl', ['$scope', '$http', '$routeParams', '$sce',
function($scope, $http, $routeParams, $sce) {
var url = ['/shufa/', $routeParams.author, '/', $routeParams.fatie, '/'].join('');
var callback = function(swiper) {
swiper.wrapper.find('.swiper-slide-active img.beitie-img').trigger('slideChangeEnd');
$scope.$broadcast('slideChangeEnd' + swiper.activeIndex);
};
$scope.fatie = {
author: $routeParams.author,
paper: $routeParams.fatie,
images: []
};
$http.get(url, {
cache: true
}).success(function(data) {
$scope.fatie = data;
$scope.published = 'hide';
$scope.cover = '/' + data.path1000 + '/' + data.images[0];
if (data.info) {
if (data.info.published) {
$scope.published = 'show';
}
if (data.info.text) {
data.info.html = $sce.trustAsHtml('<p>' + data.info.text.trim().replace(/\n/g, '<p>'));
}
}
$scope.swiper = {};
$scope.onReadySwiper = function(swiper) {
callback(swiper);
swiper.on('slideChangeEnd', callback);
};
});
}
]);
|
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
// Portions ©2008-2010 Apple Inc. All rights reserved.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
sc_require('views/list') ;
sc_require('views/source_list_group');
SC.BENCHMARK_SOURCE_LIST_VIEW = YES ;
/** @class
Displays a source list like the source list in iTunes. SourceList views
are very similar to ListView's but come preconfigured with the correct
appearance and default behaviors of a source list.
@extends SC.ListView
@since SproutCore 1.0
*/
SC.SourceListView = SC.ListView.extend(
/** @scope SC.SourceListView.prototype */ {
/**
Add class name to HTML for styling.
*/
classNames: ['sc-source-list'],
/**
Default row height for source list items is larger.
*/
rowHeight: 32,
/**
By default source lists should not select on mouse down since you will
often want to drag an item instead of selecting it.
*/
selectOnMouseDown: NO,
/**
By default, SourceListView's trigger any action you set whenever the user
clicks on an item. This gives the SourceList a "menu" like behavior.
*/
actOnSelect: YES
});
|
'use strict';
const ghGot = require('gh-got');
function searchCommits(email, token) {
return ghGot('search/commits', {
token,
query: {
q: `author-email:${email}`,
sort: 'author-date',
// eslint-disable-next-line camelcase
per_page: 1
},
headers: {
accept: 'application/vnd.github.cloak-preview',
'user-agent': 'https://github.com/sindresorhus/github-username'
}
}).then(result => {
const data = result.body;
if (data.total_count === 0) {
throw new Error(`Couldn't find username for \`${email}\``);
}
return data.items[0].author.login;
});
}
module.exports = (email, token) => {
if (!(typeof email === 'string' && email.includes('@'))) {
return Promise.reject(new Error('Email required'));
}
return ghGot('search/users', {
token,
query: {
q: `${email} in:email`
},
headers: {
'user-agent': 'https://github.com/sindresorhus/github-username'
}
}).then(result => {
const data = result.body;
if (data.total_count === 0) {
return searchCommits(email, token);
}
return data.items[0].login;
});
};
|
"use strict";
var myobj = {
myprop: 1,
'my-prop': 2,
"my'-prop": 3
};
|
// Imports.
var fs = require('fs');
var helpers = require('helpers');
var inherits = require('inherits');
/**
* Test Suite
* PLEASE, DO NOT TOUCH IT
*
* @package gina
* @author Rhinostone
*/
var TestSuite = function() {
var self = this;
this.root = __dirname;
var d = _(__dirname).split(/\//);
d.splice(d.length-1, 1);
var gina = d.join('/');
this.config = {
root : this.root,
gina : gina,
target : this.root +'/workspace',
nodeModules : this.root +'/node_modules'
};
var ignored = [
/^\./ ,
/node_modules/,
/workspace/
];
/**
* Init
* @constructor
* */
var init = function() {
// load on startup
loadScripts(self.root);
}
var loadScripts = function(path) {
var files = fs.readdirSync(path);
var file = '', filename = '';
for (var f=0; f<files.length; ++f) {
file = files[f].replace(/.js/, '');
filename = path + '/' +files[f];
var passed = true;
for (var i in ignored) {
if ( ignored[i].test(files[f]) ) {
passed = false
}
}
if ( isDir(filename) &&
!/node_modules/.test(filename.replace(self.root, '')) &&
!/workspace/.test(filename.replace(self.root, '')) &&
passed
) {
//console.log('loading [ ' + filename +' ]\n');
loadScripts(filename)
} else if ( passed ) {
//console.log('suite is : ', files[f]);
// if (files[f] == '02-add_new_bundle.js') {
if ( filename.substr(filename.length-3) == '.js') {
var Suite = require(filename);
if ( typeof(Suite) == 'function') {
Suite = inherits(Suite, self.Suite);
new Suite(self.config, exports)
}
}
}
}
}
this.Suite = function(config, exports) {
var self = this;
this.hasFramework = function() {
return self.hasWorkspace
}
}
var isDir = function(path) {
return fs.statSync(path).isDirectory()
}
init()
}()
|
/*!
* Material Design for Bootstrap 4
* Version: MDB FREE 4.16.0
*
*
* Copyright: Material Design for Bootstrap
* https://mdbootstrap.com/
*
* Read the license: https://mdbootstrap.com/general/license/
*
*
* Documentation: https://mdbootstrap.com/
*
* Getting started: https://mdbootstrap.com/docs/jquery/getting-started/download/
*
* Tutorials: https://mdbootstrap.com/education/bootstrap/
*
* Templates: https://mdbootstrap.com/templates/
*
* Support: https://mdbootstrap.com/support/
*
* Contact: office@mdbootstrap.com
*
* Attribution: Animate CSS, Twitter Bootstrap, Materialize CSS, Normalize CSS, Waves JS, WOW JS, Toastr, Chart.js, jquery.easing.js, velocity.min.js, chart.js, wow.js, scrolling-navbar.js, waves.js, forms-free.js, enhanced-modals.js, treeview.js
*/
! function(t) {
var e = {};
function n(r) {
if (e[r]) return e[r].exports;
var i = e[r] = {
i: r,
l: !1,
exports: {}
};
return t[r].call(i.exports, i, i.exports, n), i.l = !0, i.exports
}
n.m = t, n.c = e, n.d = function(t, e, r) {
n.o(t, e) || Object.defineProperty(t, e, {
enumerable: !0,
get: r
})
}, n.r = function(t) {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, {
value: "Module"
}), Object.defineProperty(t, "__esModule", {
value: !0
})
}, n.t = function(t, e) {
if (1 & e && (t = n(t)), 8 & e) return t;
if (4 & e && "object" == typeof t && t && t.__esModule) return t;
var r = Object.create(null);
if (n.r(r), Object.defineProperty(r, "default", {
enumerable: !0,
value: t
}), 2 & e && "string" != typeof t)
for (var i in t) n.d(r, i, function(e) {
return t[e]
}.bind(null, i));
return r
}, n.n = function(t) {
var e = t && t.__esModule ? function() {
return t.default
} : function() {
return t
};
return n.d(e, "a", e), e
}, n.o = function(t, e) {
return Object.prototype.hasOwnProperty.call(t, e)
}, n.p = "", n(n.s = 152)
}([function(t, e, n) {
(function(e) {
var n = function(t) {
return t && t.Math == Math && t
};
t.exports = n("object" == typeof globalThis && globalThis) || n("object" == typeof window && window) || n("object" == typeof self && self) || n("object" == typeof e && e) || Function("return this")()
}).call(this, n(59))
}, function(t, e) {
t.exports = function(t) {
try {
return !!t()
} catch (t) {
return !0
}
}
}, function(t, e, n) {
var r = n(0),
i = n(15),
o = n(28),
a = n(50),
s = r.Symbol,
l = i("wks");
t.exports = function(t) {
return l[t] || (l[t] = a && s[t] || (a ? s : o)("Symbol." + t))
}
}, function(t, e, n) {
var r = n(0),
i = n(26).f,
o = n(6),
a = n(14),
s = n(25),
l = n(47),
u = n(51);
t.exports = function(t, e) {
var n, c, d, f, h, p = t.target,
g = t.global,
v = t.stat;
if (n = g ? r : v ? r[p] || s(p, {}) : (r[p] || {}).prototype)
for (c in e) {
if (f = e[c], d = t.noTargetGet ? (h = i(n, c)) && h.value : n[c], !u(g ? c : p + (v ? "." : "#") + c, t.forced) && void 0 !== d) {
if (typeof f == typeof d) continue;
l(f, d)
}(t.sham || d && d.sham) && o(f, "sham", !0), a(n, c, f, t)
}
}
}, function(t, e) {
var n = {}.hasOwnProperty;
t.exports = function(t, e) {
return n.call(t, e)
}
}, function(t, e) {
t.exports = function(t) {
return "object" == typeof t ? null !== t : "function" == typeof t
}
}, function(t, e, n) {
var r = n(9),
i = n(8),
o = n(17);
t.exports = r ? function(t, e, n) {
return i.f(t, e, o(1, n))
} : function(t, e, n) {
return t[e] = n, t
}
}, function(t, e, n) {
var r = n(5);
t.exports = function(t) {
if (!r(t)) throw TypeError(String(t) + " is not an object");
return t
}
}, function(t, e, n) {
var r = n(9),
i = n(36),
o = n(7),
a = n(19),
s = Object.defineProperty;
e.f = r ? s : function(t, e, n) {
if (o(t), e = a(e, !0), o(n), i) try {
return s(t, e, n)
} catch (t) {}
if ("get" in n || "set" in n) throw TypeError("Accessors not supported");
return "value" in n && (t[e] = n.value), t
}
}, function(t, e, n) {
var r = n(1);
t.exports = !r((function() {
return 7 != Object.defineProperty({}, "a", {
get: function() {
return 7
}
}).a
}))
}, function(t, e, n) {
var r = n(31),
i = n(13);
t.exports = function(t) {
return r(i(t))
}
}, function(t, e, n) {
var r = n(12),
i = Math.min;
t.exports = function(t) {
return t > 0 ? i(r(t), 9007199254740991) : 0
}
}, function(t, e) {
var n = Math.ceil,
r = Math.floor;
t.exports = function(t) {
return isNaN(t = +t) ? 0 : (t > 0 ? r : n)(t)
}
}, function(t, e) {
t.exports = function(t) {
if (null == t) throw TypeError("Can't call method on " + t);
return t
}
}, function(t, e, n) {
var r = n(0),
i = n(15),
o = n(6),
a = n(4),
s = n(25),
l = n(37),
u = n(21),
c = u.get,
d = u.enforce,
f = String(l).split("toString");
i("inspectSource", (function(t) {
return l.call(t)
})), (t.exports = function(t, e, n, i) {
var l = !!i && !!i.unsafe,
u = !!i && !!i.enumerable,
c = !!i && !!i.noTargetGet;
"function" == typeof n && ("string" != typeof e || a(n, "name") || o(n, "name", e), d(n).source = f.join("string" == typeof e ? e : "")), t !== r ? (l ? !c && t[e] && (u = !0) : delete t[e], u ? t[e] = n : o(t, e, n)) : u ? t[e] = n : s(e, n)
})(Function.prototype, "toString", (function() {
return "function" == typeof this && c(this).source || l.call(this)
}))
}, function(t, e, n) {
var r = n(24),
i = n(61);
(t.exports = function(t, e) {
return i[t] || (i[t] = void 0 !== e ? e : {})
})("versions", []).push({
version: "3.3.2",
mode: r ? "pure" : "global",
copyright: "© 2019 Denis Pushkarev (zloirock.ru)"
})
}, function(t, e, n) {
var r = n(13);
t.exports = function(t) {
return Object(r(t))
}
}, function(t, e) {
t.exports = function(t, e) {
return {
enumerable: !(1 & t),
configurable: !(2 & t),
writable: !(4 & t),
value: e
}
}
}, function(t, e) {
var n = {}.toString;
t.exports = function(t) {
return n.call(t).slice(8, -1)
}
}, function(t, e, n) {
var r = n(5);
t.exports = function(t, e) {
if (!r(t)) return t;
var n, i;
if (e && "function" == typeof(n = t.toString) && !r(i = n.call(t))) return i;
if ("function" == typeof(n = t.valueOf) && !r(i = n.call(t))) return i;
if (!e && "function" == typeof(n = t.toString) && !r(i = n.call(t))) return i;
throw TypeError("Can't convert object to primitive value")
}
}, function(t, e) {
t.exports = {}
}, function(t, e, n) {
var r, i, o, a = n(62),
s = n(0),
l = n(5),
u = n(6),
c = n(4),
d = n(22),
f = n(20),
h = s.WeakMap;
if (a) {
var p = new h,
g = p.get,
v = p.has,
m = p.set;
r = function(t, e) {
return m.call(p, t, e), e
}, i = function(t) {
return g.call(p, t) || {}
}, o = function(t) {
return v.call(p, t)
}
} else {
var y = d("state");
f[y] = !0, r = function(t, e) {
return u(t, y, e), e
}, i = function(t) {
return c(t, y) ? t[y] : {}
}, o = function(t) {
return c(t, y)
}
}
t.exports = {
set: r,
get: i,
has: o,
enforce: function(t) {
return o(t) ? i(t) : r(t, {})
},
getterFor: function(t) {
return function(e) {
var n;
if (!l(e) || (n = i(e)).type !== t) throw TypeError("Incompatible receiver, " + t + " required");
return n
}
}
}
}, function(t, e, n) {
var r = n(15),
i = n(28),
o = r("keys");
t.exports = function(t) {
return o[t] || (o[t] = i(t))
}
}, function(t, e, n) {
var r = n(75),
i = n(31),
o = n(16),
a = n(11),
s = n(43),
l = [].push,
u = function(t) {
var e = 1 == t,
n = 2 == t,
u = 3 == t,
c = 4 == t,
d = 6 == t,
f = 5 == t || d;
return function(h, p, g, v) {
for (var m, y, b = o(h), x = i(b), w = r(p, g, 3), S = a(x.length), k = 0, C = v || s, M = e ? C(h, S) : n ? C(h, 0) : void 0; S > k; k++)
if ((f || k in x) && (y = w(m = x[k], k, b), t))
if (e) M[k] = y;
else if (y) switch (t) {
case 3:
return !0;
case 5:
return m;
case 6:
return k;
case 2:
l.call(M, m)
} else if (c) return !1;
return d ? -1 : u || c ? c : M
}
};
t.exports = {
forEach: u(0),
map: u(1),
filter: u(2),
some: u(3),
every: u(4),
find: u(5),
findIndex: u(6)
}
}, function(t, e) {
t.exports = !1
}, function(t, e, n) {
var r = n(0),
i = n(6);
t.exports = function(t, e) {
try {
i(r, t, e)
} catch (n) {
r[t] = e
}
return e
}
}, function(t, e, n) {
var r = n(9),
i = n(46),
o = n(17),
a = n(10),
s = n(19),
l = n(4),
u = n(36),
c = Object.getOwnPropertyDescriptor;
e.f = r ? c : function(t, e) {
if (t = a(t), e = s(e, !0), u) try {
return c(t, e)
} catch (t) {}
if (l(t, e)) return o(!i.f.call(t, e), t[e])
}
}, function(t, e, n) {
var r = n(39),
i = n(30).concat("length", "prototype");
e.f = Object.getOwnPropertyNames || function(t) {
return r(t, i)
}
}, function(t, e) {
var n = 0,
r = Math.random();
t.exports = function(t) {
return "Symbol(" + String(void 0 === t ? "" : t) + ")_" + (++n + r).toString(36)
}
}, function(t, e, n) {
var r = n(18);
t.exports = Array.isArray || function(t) {
return "Array" == r(t)
}
}, function(t, e) {
t.exports = ["constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "toString", "valueOf"]
}, function(t, e, n) {
var r = n(1),
i = n(18),
o = "".split;
t.exports = r((function() {
return !Object("z").propertyIsEnumerable(0)
})) ? function(t) {
return "String" == i(t) ? o.call(t, "") : Object(t)
} : Object
}, function(t, e, n) {
var r = n(12),
i = Math.max,
o = Math.min;
t.exports = function(t, e) {
var n = r(t);
return n < 0 ? i(n + e, 0) : o(n, e)
}
}, function(t, e, n) {
var r = n(1),
i = n(2)("species");
t.exports = function(t) {
return !r((function() {
var e = [];
return (e.constructor = {})[i] = function() {
return {
foo: 1
}
}, 1 !== e[t](Boolean).foo
}))
}
}, function(t, e, n) {
var r = n(7),
i = n(79),
o = n(30),
a = n(20),
s = n(80),
l = n(38),
u = n(22)("IE_PROTO"),
c = function() {},
d = function() {
var t, e = l("iframe"),
n = o.length;
for (e.style.display = "none", s.appendChild(e), e.src = String("javascript:"), (t = e.contentWindow.document).open(), t.write("<script>document.F=Object<\/script>"), t.close(), d = t.F; n--;) delete d.prototype[o[n]];
return d()
};
t.exports = Object.create || function(t, e) {
var n;
return null !== t ? (c.prototype = r(t), n = new c, c.prototype = null, n[u] = t) : n = d(), void 0 === e ? n : i(n, e)
}, a[u] = !0
}, function(t, e, n) {
var r = n(48),
i = n(0),
o = function(t) {
return "function" == typeof t ? t : void 0
};
t.exports = function(t, e) {
return arguments.length < 2 ? o(r[t]) || o(i[t]) : r[t] && r[t][e] || i[t] && i[t][e]
}
}, function(t, e, n) {
var r = n(9),
i = n(1),
o = n(38);
t.exports = !r && !i((function() {
return 7 != Object.defineProperty(o("div"), "a", {
get: function() {
return 7
}
}).a
}))
}, function(t, e, n) {
var r = n(15);
t.exports = r("native-function-to-string", Function.toString)
}, function(t, e, n) {
var r = n(0),
i = n(5),
o = r.document,
a = i(o) && i(o.createElement);
t.exports = function(t) {
return a ? o.createElement(t) : {}
}
}, function(t, e, n) {
var r = n(4),
i = n(10),
o = n(41).indexOf,
a = n(20);
t.exports = function(t, e) {
var n, s = i(t),
l = 0,
u = [];
for (n in s) !r(a, n) && r(s, n) && u.push(n);
for (; e.length > l;) r(s, n = e[l++]) && (~o(u, n) || u.push(n));
return u
}
}, function(t, e) {
t.exports = {}
}, function(t, e, n) {
var r = n(10),
i = n(11),
o = n(32),
a = function(t) {
return function(e, n, a) {
var s, l = r(e),
u = i(l.length),
c = o(a, u);
if (t && n != n) {
for (; u > c;)
if ((s = l[c++]) != s) return !0
} else
for (; u > c; c++)
if ((t || c in l) && l[c] === n) return t || c || 0;
return !t && -1
}
};
t.exports = {
includes: a(!0),
indexOf: a(!1)
}
}, function(t, e, n) {
var r = n(8).f,
i = n(4),
o = n(2)("toStringTag");
t.exports = function(t, e, n) {
t && !i(t = n ? t : t.prototype, o) && r(t, o, {
configurable: !0,
value: e
})
}
}, function(t, e, n) {
var r = n(5),
i = n(29),
o = n(2)("species");
t.exports = function(t, e) {
var n;
return i(t) && ("function" != typeof(n = t.constructor) || n !== Array && !i(n.prototype) ? r(n) && null === (n = n[o]) && (n = void 0) : n = void 0), new(void 0 === n ? Array : n)(0 === e ? 0 : e)
}
}, function(t, e, n) {
"use strict";
var r = n(1);
t.exports = function(t, e) {
var n = [][t];
return !n || !r((function() {
n.call(null, e || function() {
throw 1
}, 1)
}))
}
}, function(t, e, n) {
"use strict";
var r, i, o = n(68),
a = RegExp.prototype.exec,
s = String.prototype.replace,
l = a,
u = (r = /a/, i = /b*/g, a.call(r, "a"), a.call(i, "a"), 0 !== r.lastIndex || 0 !== i.lastIndex),
c = void 0 !== /()??/.exec("")[1];
(u || c) && (l = function(t) {
var e, n, r, i, l = this;
return c && (n = new RegExp("^" + l.source + "$(?!\\s)", o.call(l))), u && (e = l.lastIndex), r = a.call(l, t), u && r && (l.lastIndex = l.global ? r.index + r[0].length : e), c && r && r.length > 1 && s.call(r[0], n, (function() {
for (i = 1; i < arguments.length - 2; i++) void 0 === arguments[i] && (r[i] = void 0)
})), r
}), t.exports = l
}, function(t, e, n) {
"use strict";
var r = {}.propertyIsEnumerable,
i = Object.getOwnPropertyDescriptor,
o = i && !r.call({
1: 2
}, 1);
e.f = o ? function(t) {
var e = i(this, t);
return !!e && e.enumerable
} : r
}, function(t, e, n) {
var r = n(4),
i = n(63),
o = n(26),
a = n(8);
t.exports = function(t, e) {
for (var n = i(e), s = a.f, l = o.f, u = 0; u < n.length; u++) {
var c = n[u];
r(t, c) || s(t, c, l(e, c))
}
}
}, function(t, e, n) {
t.exports = n(0)
}, function(t, e) {
e.f = Object.getOwnPropertySymbols
}, function(t, e, n) {
var r = n(1);
t.exports = !!Object.getOwnPropertySymbols && !r((function() {
return !String(Symbol())
}))
}, function(t, e, n) {
var r = n(1),
i = /#|\.prototype\./,
o = function(t, e) {
var n = s[a(t)];
return n == u || n != l && ("function" == typeof e ? r(e) : !!e)
},
a = o.normalize = function(t) {
return String(t).replace(i, ".").toLowerCase()
},
s = o.data = {},
l = o.NATIVE = "N",
u = o.POLYFILL = "P";
t.exports = o
}, function(t, e, n) {
var r = n(39),
i = n(30);
t.exports = Object.keys || function(t) {
return r(t, i)
}
}, function(t, e) {
t.exports = function(t) {
if ("function" != typeof t) throw TypeError(String(t) + " is not a function");
return t
}
}, function(t, e, n) {
"use strict";
var r = n(10),
i = n(58),
o = n(40),
a = n(21),
s = n(66),
l = a.set,
u = a.getterFor("Array Iterator");
t.exports = s(Array, "Array", (function(t, e) {
l(this, {
type: "Array Iterator",
target: r(t),
index: 0,
kind: e
})
}), (function() {
var t = u(this),
e = t.target,
n = t.kind,
r = t.index++;
return !e || r >= e.length ? (t.target = void 0, {
value: void 0,
done: !0
}) : "keys" == n ? {
value: r,
done: !1
} : "values" == n ? {
value: e[r],
done: !1
} : {
value: [r, e[r]],
done: !1
}
}), "values"), o.Arguments = o.Array, i("keys"), i("values"), i("entries")
}, function(t, e) {
(function(e) {
t.exports = e
}).call(this, {})
}, function(t, e, n) {
"use strict";
var r, i = n(9),
o = n(0),
a = n(5),
s = n(4),
l = n(76),
u = n(6),
c = n(14),
d = n(8).f,
f = n(60),
h = n(70),
p = n(2),
g = n(28),
v = o.DataView,
m = v && v.prototype,
y = o.Int8Array,
b = y && y.prototype,
x = o.Uint8ClampedArray,
w = x && x.prototype,
S = y && f(y),
k = b && f(b),
C = Object.prototype,
M = C.isPrototypeOf,
A = p("toStringTag"),
P = g("TYPED_ARRAY_TAG"),
_ = !(!o.ArrayBuffer || !v),
T = _ && !!h && "Opera" !== l(o.opera),
I = !1,
O = {
Int8Array: 1,
Uint8Array: 1,
Uint8ClampedArray: 1,
Int16Array: 2,
Uint16Array: 2,
Int32Array: 4,
Uint32Array: 4,
Float32Array: 4,
Float64Array: 8
},
F = function(t) {
return a(t) && s(O, l(t))
};
for (r in O) o[r] || (T = !1);
if ((!T || "function" != typeof S || S === Function.prototype) && (S = function() {
throw TypeError("Incorrect invocation")
}, T))
for (r in O) o[r] && h(o[r], S);
if ((!T || !k || k === C) && (k = S.prototype, T))
for (r in O) o[r] && h(o[r].prototype, k);
if (T && f(w) !== k && h(w, k), i && !s(k, A))
for (r in I = !0, d(k, A, {
get: function() {
return a(this) ? this[P] : void 0
}
}), O) o[r] && u(o[r], P, r);
_ && h && f(m) !== C && h(m, C), t.exports = {
NATIVE_ARRAY_BUFFER: _,
NATIVE_ARRAY_BUFFER_VIEWS: T,
TYPED_ARRAY_TAG: I && P,
aTypedArray: function(t) {
if (F(t)) return t;
throw TypeError("Target is not a typed array")
},
aTypedArrayConstructor: function(t) {
if (h) {
if (M.call(S, t)) return t
} else
for (var e in O)
if (s(O, r)) {
var n = o[e];
if (n && (t === n || M.call(n, t))) return t
} throw TypeError("Target is not a typed array constructor")
},
exportProto: function(t, e, n) {
if (i) {
if (n)
for (var r in O) {
var a = o[r];
a && s(a.prototype, t) && delete a.prototype[t]
}
k[t] && !n || c(k, t, n ? e : T && b[t] || e)
}
},
exportStatic: function(t, e, n) {
var r, a;
if (i) {
if (h) {
if (n)
for (r in O)(a = o[r]) && s(a, t) && delete a[t];
if (S[t] && !n) return;
try {
return c(S, t, n ? e : T && y[t] || e)
} catch (t) {}
}
for (r in O) !(a = o[r]) || a[t] && !n || c(a, t, e)
}
},
isView: function(t) {
var e = l(t);
return "DataView" === e || s(O, e)
},
isTypedArray: F,
TypedArray: S,
TypedArrayPrototype: k
}
}, function(t, e, n) {
"use strict";
var r = n(19),
i = n(8),
o = n(17);
t.exports = function(t, e, n) {
var a = r(e);
a in t ? i.f(t, a, o(0, n)) : t[a] = n
}
}, function(t, e, n) {
var r = n(2),
i = n(34),
o = n(6),
a = r("unscopables"),
s = Array.prototype;
null == s[a] && o(s, a, i(null)), t.exports = function(t) {
s[a][t] = !0
}
}, function(t, e) {
var n;
n = function() {
return this
}();
try {
n = n || new Function("return this")()
} catch (t) {
"object" == typeof window && (n = window)
}
t.exports = n
}, function(t, e, n) {
var r = n(4),
i = n(16),
o = n(22),
a = n(94),
s = o("IE_PROTO"),
l = Object.prototype;
t.exports = a ? Object.getPrototypeOf : function(t) {
return t = i(t), r(t, s) ? t[s] : "function" == typeof t.constructor && t instanceof t.constructor ? t.constructor.prototype : t instanceof Object ? l : null
}
}, function(t, e, n) {
var r = n(0),
i = n(25),
o = r["__core-js_shared__"] || i("__core-js_shared__", {});
t.exports = o
}, function(t, e, n) {
var r = n(0),
i = n(37),
o = r.WeakMap;
t.exports = "function" == typeof o && /native code/.test(i.call(o))
}, function(t, e, n) {
var r = n(35),
i = n(27),
o = n(49),
a = n(7);
t.exports = r("Reflect", "ownKeys") || function(t) {
var e = i.f(a(t)),
n = o.f;
return n ? e.concat(n(t)) : e
}
}, function(t, e, n) {
e.f = n(2)
}, function(t, e, n) {
var r = n(48),
i = n(4),
o = n(64),
a = n(8).f;
t.exports = function(t) {
var e = r.Symbol || (r.Symbol = {});
i(e, t) || a(e, t, {
value: o.f(t)
})
}
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(93),
o = n(60),
a = n(70),
s = n(42),
l = n(6),
u = n(14),
c = n(2),
d = n(24),
f = n(40),
h = n(67),
p = h.IteratorPrototype,
g = h.BUGGY_SAFARI_ITERATORS,
v = c("iterator"),
m = function() {
return this
};
t.exports = function(t, e, n, c, h, y, b) {
i(n, e, c);
var x, w, S, k = function(t) {
if (t === h && _) return _;
if (!g && t in A) return A[t];
switch (t) {
case "keys":
case "values":
case "entries":
return function() {
return new n(this, t)
}
}
return function() {
return new n(this)
}
},
C = e + " Iterator",
M = !1,
A = t.prototype,
P = A[v] || A["@@iterator"] || h && A[h],
_ = !g && P || k(h),
T = "Array" == e && A.entries || P;
if (T && (x = o(T.call(new t)), p !== Object.prototype && x.next && (d || o(x) === p || (a ? a(x, p) : "function" != typeof x[v] && l(x, v, m)), s(x, C, !0, !0), d && (f[C] = m))), "values" == h && P && "values" !== P.name && (M = !0, _ = function() {
return P.call(this)
}), d && !b || A[v] === _ || l(A, v, _), f[e] = _, h)
if (w = {
values: k("values"),
keys: y ? _ : k("keys"),
entries: k("entries")
}, b)
for (S in w) !g && !M && S in A || u(A, S, w[S]);
else r({
target: e,
proto: !0,
forced: g || M
}, w);
return w
}
}, function(t, e, n) {
"use strict";
var r, i, o, a = n(60),
s = n(6),
l = n(4),
u = n(2),
c = n(24),
d = u("iterator"),
f = !1;
[].keys && ("next" in (o = [].keys()) ? (i = a(a(o))) !== Object.prototype && (r = i) : f = !0), null == r && (r = {}), c || l(r, d) || s(r, d, (function() {
return this
})), t.exports = {
IteratorPrototype: r,
BUGGY_SAFARI_ITERATORS: f
}
}, function(t, e, n) {
"use strict";
var r = n(7);
t.exports = function() {
var t = r(this),
e = "";
return t.global && (e += "g"), t.ignoreCase && (e += "i"), t.multiline && (e += "m"), t.dotAll && (e += "s"), t.unicode && (e += "u"), t.sticky && (e += "y"), e
}
}, function(t, e, n) {
var r = n(12),
i = n(13),
o = function(t) {
return function(e, n) {
var o, a, s = String(i(e)),
l = r(n),
u = s.length;
return l < 0 || l >= u ? t ? "" : void 0 : (o = s.charCodeAt(l)) < 55296 || o > 56319 || l + 1 === u || (a = s.charCodeAt(l + 1)) < 56320 || a > 57343 ? t ? s.charAt(l) : o : t ? s.slice(l, l + 2) : a - 56320 + (o - 55296 << 10) + 65536
}
};
t.exports = {
codeAt: o(!1),
charAt: o(!0)
}
}, function(t, e, n) {
var r = n(7),
i = n(88);
t.exports = Object.setPrototypeOf || ("__proto__" in {} ? function() {
var t, e = !1,
n = {};
try {
(t = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__").set).call(n, []), e = n instanceof Array
} catch (t) {}
return function(n, o) {
return r(n), i(o), e ? t.call(n, o) : n.__proto__ = o, n
}
}() : void 0)
}, function(t, e, n) {
var r = n(14),
i = n(89),
o = Object.prototype;
i !== o.toString && r(o, "toString", i, {
unsafe: !0
})
}, function(t, e, n) {
"use strict";
var r = n(6),
i = n(14),
o = n(1),
a = n(2),
s = n(45),
l = a("species"),
u = !o((function() {
var t = /./;
return t.exec = function() {
var t = [];
return t.groups = {
a: "7"
}, t
}, "7" !== "".replace(t, "$<a>")
})),
c = !o((function() {
var t = /(?:)/,
e = t.exec;
t.exec = function() {
return e.apply(this, arguments)
};
var n = "ab".split(t);
return 2 !== n.length || "a" !== n[0] || "b" !== n[1]
}));
t.exports = function(t, e, n, d) {
var f = a(t),
h = !o((function() {
var e = {};
return e[f] = function() {
return 7
}, 7 != "" [t](e)
})),
p = h && !o((function() {
var e = !1,
n = /a/;
return n.exec = function() {
return e = !0, null
}, "split" === t && (n.constructor = {}, n.constructor[l] = function() {
return n
}), n[f](""), !e
}));
if (!h || !p || "replace" === t && !u || "split" === t && !c) {
var g = /./ [f],
v = n(f, "" [t], (function(t, e, n, r, i) {
return e.exec === s ? h && !i ? {
done: !0,
value: g.call(e, n, r)
} : {
done: !0,
value: t.call(n, e, r)
} : {
done: !1
}
})),
m = v[0],
y = v[1];
i(String.prototype, t, m), i(RegExp.prototype, f, 2 == e ? function(t, e) {
return y.call(t, this, e)
} : function(t) {
return y.call(t, this)
}), d && r(RegExp.prototype[f], "sham", !0)
}
}
}, function(t, e, n) {
var r = n(18),
i = n(45);
t.exports = function(t, e) {
var n = t.exec;
if ("function" == typeof n) {
var o = n.call(t, e);
if ("object" != typeof o) throw TypeError("RegExp exec method returned something other than an Object or null");
return o
}
if ("RegExp" !== r(t)) throw TypeError("RegExp#exec called on incompatible receiver");
return i.call(t, e)
}
}, function(t, e) {
t.exports = "\t\n\v\f\r \u2028\u2029\ufeff"
}, function(t, e, n) {
var r = n(53);
t.exports = function(t, e, n) {
if (r(t), void 0 === e) return t;
switch (n) {
case 0:
return function() {
return t.call(e)
};
case 1:
return function(n) {
return t.call(e, n)
};
case 2:
return function(n, r) {
return t.call(e, n, r)
};
case 3:
return function(n, r, i) {
return t.call(e, n, r, i)
}
}
return function() {
return t.apply(e, arguments)
}
}
}, function(t, e, n) {
var r = n(18),
i = n(2)("toStringTag"),
o = "Arguments" == r(function() {
return arguments
}());
t.exports = function(t) {
var e, n, a;
return void 0 === t ? "Undefined" : null === t ? "Null" : "string" == typeof(n = function(t, e) {
try {
return t[e]
} catch (t) {}
}(e = Object(t), i)) ? n : o ? r(e) : "Object" == (a = r(e)) && "function" == typeof e.callee ? "Arguments" : a
}
}, function(t, e, n) {
"use strict";
var r = n(69).charAt;
t.exports = function(t, e, n) {
return e + (n ? r(t, e).length : 1)
}
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(0),
o = n(24),
a = n(9),
s = n(50),
l = n(1),
u = n(4),
c = n(29),
d = n(5),
f = n(7),
h = n(16),
p = n(10),
g = n(19),
v = n(17),
m = n(34),
y = n(52),
b = n(27),
x = n(92),
w = n(49),
S = n(26),
k = n(8),
C = n(46),
M = n(6),
A = n(14),
P = n(15),
_ = n(22),
T = n(20),
I = n(28),
O = n(2),
F = n(64),
D = n(65),
E = n(42),
L = n(21),
R = n(23).forEach,
N = _("hidden"),
V = O("toPrimitive"),
z = L.set,
B = L.getterFor("Symbol"),
W = Object.prototype,
j = i.Symbol,
H = i.JSON,
q = H && H.stringify,
U = S.f,
$ = k.f,
Y = x.f,
G = C.f,
Q = P("symbols"),
X = P("op-symbols"),
Z = P("string-to-symbol-registry"),
J = P("symbol-to-string-registry"),
K = P("wks"),
tt = i.QObject,
et = !tt || !tt.prototype || !tt.prototype.findChild,
nt = a && l((function() {
return 7 != m($({}, "a", {
get: function() {
return $(this, "a", {
value: 7
}).a
}
})).a
})) ? function(t, e, n) {
var r = U(W, e);
r && delete W[e], $(t, e, n), r && t !== W && $(W, e, r)
} : $,
rt = function(t, e) {
var n = Q[t] = m(j.prototype);
return z(n, {
type: "Symbol",
tag: t,
description: e
}), a || (n.description = e), n
},
it = s && "symbol" == typeof j.iterator ? function(t) {
return "symbol" == typeof t
} : function(t) {
return Object(t) instanceof j
},
ot = function(t, e, n) {
t === W && ot(X, e, n), f(t);
var r = g(e, !0);
return f(n), u(Q, r) ? (n.enumerable ? (u(t, N) && t[N][r] && (t[N][r] = !1), n = m(n, {
enumerable: v(0, !1)
})) : (u(t, N) || $(t, N, v(1, {})), t[N][r] = !0), nt(t, r, n)) : $(t, r, n)
},
at = function(t, e) {
f(t);
var n = p(e),
r = y(n).concat(ct(n));
return R(r, (function(e) {
a && !st.call(n, e) || ot(t, e, n[e])
})), t
},
st = function(t) {
var e = g(t, !0),
n = G.call(this, e);
return !(this === W && u(Q, e) && !u(X, e)) && (!(n || !u(this, e) || !u(Q, e) || u(this, N) && this[N][e]) || n)
},
lt = function(t, e) {
var n = p(t),
r = g(e, !0);
if (n !== W || !u(Q, r) || u(X, r)) {
var i = U(n, r);
return !i || !u(Q, r) || u(n, N) && n[N][r] || (i.enumerable = !0), i
}
},
ut = function(t) {
var e = Y(p(t)),
n = [];
return R(e, (function(t) {
u(Q, t) || u(T, t) || n.push(t)
})), n
},
ct = function(t) {
var e = t === W,
n = Y(e ? X : p(t)),
r = [];
return R(n, (function(t) {
!u(Q, t) || e && !u(W, t) || r.push(Q[t])
})), r
};
s || (A((j = function() {
if (this instanceof j) throw TypeError("Symbol is not a constructor");
var t = arguments.length && void 0 !== arguments[0] ? String(arguments[0]) : void 0,
e = I(t),
n = function(t) {
this === W && n.call(X, t), u(this, N) && u(this[N], e) && (this[N][e] = !1), nt(this, e, v(1, t))
};
return a && et && nt(W, e, {
configurable: !0,
set: n
}), rt(e, t)
}).prototype, "toString", (function() {
return B(this).tag
})), C.f = st, k.f = ot, S.f = lt, b.f = x.f = ut, w.f = ct, a && ($(j.prototype, "description", {
configurable: !0,
get: function() {
return B(this).description
}
}), o || A(W, "propertyIsEnumerable", st, {
unsafe: !0
})), F.f = function(t) {
return rt(O(t), t)
}), r({
global: !0,
wrap: !0,
forced: !s,
sham: !s
}, {
Symbol: j
}), R(y(K), (function(t) {
D(t)
})), r({
target: "Symbol",
stat: !0,
forced: !s
}, {
for: function(t) {
var e = String(t);
if (u(Z, e)) return Z[e];
var n = j(e);
return Z[e] = n, J[n] = e, n
},
keyFor: function(t) {
if (!it(t)) throw TypeError(t + " is not a symbol");
if (u(J, t)) return J[t]
},
useSetter: function() {
et = !0
},
useSimple: function() {
et = !1
}
}), r({
target: "Object",
stat: !0,
forced: !s,
sham: !a
}, {
create: function(t, e) {
return void 0 === e ? m(t) : at(m(t), e)
},
defineProperty: ot,
defineProperties: at,
getOwnPropertyDescriptor: lt
}), r({
target: "Object",
stat: !0,
forced: !s
}, {
getOwnPropertyNames: ut,
getOwnPropertySymbols: ct
}), r({
target: "Object",
stat: !0,
forced: l((function() {
w.f(1)
}))
}, {
getOwnPropertySymbols: function(t) {
return w.f(h(t))
}
}), H && r({
target: "JSON",
stat: !0,
forced: !s || l((function() {
var t = j();
return "[null]" != q([t]) || "{}" != q({
a: t
}) || "{}" != q(Object(t))
}))
}, {
stringify: function(t) {
for (var e, n, r = [t], i = 1; arguments.length > i;) r.push(arguments[i++]);
if (n = e = r[1], (d(e) || void 0 !== t) && !it(t)) return c(e) || (e = function(t, e) {
if ("function" == typeof n && (e = n.call(this, t, e)), !it(e)) return e
}), r[1] = e, q.apply(H, r)
}
}), j.prototype[V] || M(j.prototype, V, j.prototype.valueOf), E(j, "Symbol"), T[N] = !0
}, function(t, e, n) {
var r = n(9),
i = n(8),
o = n(7),
a = n(52);
t.exports = r ? Object.defineProperties : function(t, e) {
o(t);
for (var n, r = a(e), s = r.length, l = 0; s > l;) i.f(t, n = r[l++], e[n]);
return t
}
}, function(t, e, n) {
var r = n(35);
t.exports = r("document", "documentElement")
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(9),
o = n(0),
a = n(4),
s = n(5),
l = n(8).f,
u = n(47),
c = o.Symbol;
if (i && "function" == typeof c && (!("description" in c.prototype) || void 0 !== c().description)) {
var d = {},
f = function() {
var t = arguments.length < 1 || void 0 === arguments[0] ? void 0 : String(arguments[0]),
e = this instanceof f ? new c(t) : void 0 === t ? c() : c(t);
return "" === t && (d[e] = !0), e
};
u(f, c);
var h = f.prototype = c.prototype;
h.constructor = f;
var p = h.toString,
g = "Symbol(test)" == String(c("test")),
v = /^Symbol\((.*)\)[^)]+$/;
l(h, "description", {
configurable: !0,
get: function() {
var t = s(this) ? this.valueOf() : this,
e = p.call(t);
if (a(d, t)) return "";
var n = g ? e.slice(7, -1) : e.replace(v, "$1");
return "" === n ? void 0 : n
}
}), r({
global: !0,
forced: !0
}, {
Symbol: f
})
}
}, function(t, e, n) {
n(65)("iterator")
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(45);
r({
target: "RegExp",
proto: !0,
forced: /./.exec !== i
}, {
exec: i
})
}, function(t, e, n) {
"use strict";
var r = n(69).charAt,
i = n(21),
o = n(66),
a = i.set,
s = i.getterFor("String Iterator");
o(String, "String", (function(t) {
a(this, {
type: "String Iterator",
string: String(t),
index: 0
})
}), (function() {
var t, e = s(this),
n = e.string,
i = e.index;
return i >= n.length ? {
value: void 0,
done: !0
} : (t = r(n, i), e.index += t.length, {
value: t,
done: !1
})
}))
}, function(t, e, n) {
var r = n(0),
i = n(86),
o = n(54),
a = n(6),
s = n(2),
l = s("iterator"),
u = s("toStringTag"),
c = o.values;
for (var d in i) {
var f = r[d],
h = f && f.prototype;
if (h) {
if (h[l] !== c) try {
a(h, l, c)
} catch (t) {
h[l] = c
}
if (h[u] || a(h, u, d), i[d])
for (var p in o)
if (h[p] !== o[p]) try {
a(h, p, o[p])
} catch (t) {
h[p] = o[p]
}
}
}
}, function(t, e) {
t.exports = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
}
}, function(t, e) {
t.exports = function(t) {
if (!t.webpackPolyfill) {
var e = Object.create(t);
e.children || (e.children = []), Object.defineProperty(e, "loaded", {
enumerable: !0,
get: function() {
return e.l
}
}), Object.defineProperty(e, "id", {
enumerable: !0,
get: function() {
return e.i
}
}), Object.defineProperty(e, "exports", {
enumerable: !0
}), e.webpackPolyfill = 1
}
return e
}
}, function(t, e, n) {
var r = n(5);
t.exports = function(t) {
if (!r(t) && null !== t) throw TypeError("Can't set " + String(t) + " as a prototype");
return t
}
}, function(t, e, n) {
"use strict";
var r = n(76),
i = {};
i[n(2)("toStringTag")] = "z", t.exports = "[object z]" !== String(i) ? function() {
return "[object " + r(this) + "]"
} : i.toString
}, function(t, e, n) {
var r = n(13),
i = "[" + n(74) + "]",
o = RegExp("^" + i + i + "*"),
a = RegExp(i + i + "*$"),
s = function(t) {
return function(e) {
var n = String(r(e));
return 1 & t && (n = n.replace(o, "")), 2 & t && (n = n.replace(a, "")), n
}
};
t.exports = {
start: s(1),
end: s(2),
trim: s(3)
}
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(41).indexOf,
o = n(44),
a = [].indexOf,
s = !!a && 1 / [1].indexOf(1, -0) < 0,
l = o("indexOf");
r({
target: "Array",
proto: !0,
forced: s || l
}, {
indexOf: function(t) {
return s ? a.apply(this, arguments) || 0 : i(this, t, arguments.length > 1 ? arguments[1] : void 0)
}
})
}, function(t, e, n) {
var r = n(10),
i = n(27).f,
o = {}.toString,
a = "object" == typeof window && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [];
t.exports.f = function(t) {
return a && "[object Window]" == o.call(t) ? function(t) {
try {
return i(t)
} catch (t) {
return a.slice()
}
}(t) : i(r(t))
}
}, function(t, e, n) {
"use strict";
var r = n(67).IteratorPrototype,
i = n(34),
o = n(17),
a = n(42),
s = n(40),
l = function() {
return this
};
t.exports = function(t, e, n) {
var u = e + " Iterator";
return t.prototype = i(r, {
next: o(1, n)
}), a(t, u, !1, !0), s[u] = l, t
}
}, function(t, e, n) {
var r = n(1);
t.exports = !r((function() {
function t() {}
return t.prototype.constructor = null, Object.getPrototypeOf(new t) !== t.prototype
}))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(23).map;
r({
target: "Array",
proto: !0,
forced: !n(33)("map")
}, {
map: function(t) {
return i(this, t, arguments.length > 1 ? arguments[1] : void 0)
}
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(5),
o = n(29),
a = n(32),
s = n(11),
l = n(10),
u = n(57),
c = n(33),
d = n(2)("species"),
f = [].slice,
h = Math.max;
r({
target: "Array",
proto: !0,
forced: !c("slice")
}, {
slice: function(t, e) {
var n, r, c, p = l(this),
g = s(p.length),
v = a(t, g),
m = a(void 0 === e ? g : e, g);
if (o(p) && ("function" != typeof(n = p.constructor) || n !== Array && !o(n.prototype) ? i(n) && null === (n = n[d]) && (n = void 0) : n = void 0, n === Array || void 0 === n)) return f.call(p, v, m);
for (r = new(void 0 === n ? Array : n)(h(m - v, 0)), c = 0; v < m; v++, c++) v in p && u(r, c, p[v]);
return r.length = c, r
}
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(32),
o = n(12),
a = n(11),
s = n(16),
l = n(43),
u = n(57),
c = n(33),
d = Math.max,
f = Math.min;
r({
target: "Array",
proto: !0,
forced: !c("splice")
}, {
splice: function(t, e) {
var n, r, c, h, p, g, v = s(this),
m = a(v.length),
y = i(t, m),
b = arguments.length;
if (0 === b ? n = r = 0 : 1 === b ? (n = 0, r = m - y) : (n = b - 2, r = f(d(o(e), 0), m - y)), m + n - r > 9007199254740991) throw TypeError("Maximum allowed length exceeded");
for (c = l(v, r), h = 0; h < r; h++)(p = y + h) in v && u(c, h, v[p]);
if (c.length = r, n < r) {
for (h = y; h < m - r; h++) g = h + n, (p = h + r) in v ? v[g] = v[p] : delete v[g];
for (h = m; h > m - r + n; h--) delete v[h - 1]
} else if (n > r)
for (h = m - r; h > y; h--) g = h + n - 1, (p = h + r - 1) in v ? v[g] = v[p] : delete v[g];
for (h = 0; h < n; h++) v[h + y] = arguments[h + 2];
return v.length = m - r + n, c
}
})
}, function(t, e, n) {
"use strict";
var r = n(72),
i = n(7),
o = n(16),
a = n(11),
s = n(12),
l = n(13),
u = n(77),
c = n(73),
d = Math.max,
f = Math.min,
h = Math.floor,
p = /\$([$&'`]|\d\d?|<[^>]*>)/g,
g = /\$([$&'`]|\d\d?)/g;
r("replace", 2, (function(t, e, n) {
return [function(n, r) {
var i = l(this),
o = null == n ? void 0 : n[t];
return void 0 !== o ? o.call(n, i, r) : e.call(String(i), n, r)
}, function(t, o) {
var l = n(e, t, this, o);
if (l.done) return l.value;
var h = i(t),
p = String(this),
g = "function" == typeof o;
g || (o = String(o));
var v = h.global;
if (v) {
var m = h.unicode;
h.lastIndex = 0
}
for (var y = [];;) {
var b = c(h, p);
if (null === b) break;
if (y.push(b), !v) break;
"" === String(b[0]) && (h.lastIndex = u(p, a(h.lastIndex), m))
}
for (var x, w = "", S = 0, k = 0; k < y.length; k++) {
b = y[k];
for (var C = String(b[0]), M = d(f(s(b.index), p.length), 0), A = [], P = 1; P < b.length; P++) A.push(void 0 === (x = b[P]) ? x : String(x));
var _ = b.groups;
if (g) {
var T = [C].concat(A, M, p);
void 0 !== _ && T.push(_);
var I = String(o.apply(void 0, T))
} else I = r(C, p, M, A, _, o);
M >= S && (w += p.slice(S, M) + I, S = M + C.length)
}
return w + p.slice(S)
}];
function r(t, n, r, i, a, s) {
var l = r + t.length,
u = i.length,
c = g;
return void 0 !== a && (a = o(a), c = p), e.call(s, c, (function(e, o) {
var s;
switch (o.charAt(0)) {
case "$":
return "$";
case "&":
return t;
case "`":
return n.slice(0, r);
case "'":
return n.slice(l);
case "<":
s = a[o.slice(1, -1)];
break;
default:
var c = +o;
if (0 === c) return e;
if (c > u) {
var d = h(c / 10);
return 0 === d ? e : d <= u ? void 0 === i[d - 1] ? o.charAt(1) : i[d - 1] + o.charAt(1) : e
}
s = i[c - 1]
}
return void 0 === s ? "" : s
}))
}
}))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(23).filter;
r({
target: "Array",
proto: !0,
forced: !n(33)("filter")
}, {
filter: function(t) {
return i(this, t, arguments.length > 1 ? arguments[1] : void 0)
}
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(23).find,
o = n(58),
a = !0;
"find" in [] && Array(1).find((function() {
a = !1
})), r({
target: "Array",
proto: !0,
forced: a
}, {
find: function(t) {
return i(this, t, arguments.length > 1 ? arguments[1] : void 0)
}
}), o("find")
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(31),
o = n(10),
a = n(44),
s = [].join,
l = i != Object,
u = a("join", ",");
r({
target: "Array",
proto: !0,
forced: l || u
}, {
join: function(t) {
return s.call(o(this), void 0 === t ? "," : t)
}
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(1),
o = n(29),
a = n(5),
s = n(16),
l = n(11),
u = n(57),
c = n(43),
d = n(33),
f = n(2)("isConcatSpreadable"),
h = !i((function() {
var t = [];
return t[f] = !1, t.concat()[0] !== t
})),
p = d("concat"),
g = function(t) {
if (!a(t)) return !1;
var e = t[f];
return void 0 !== e ? !!e : o(t)
};
r({
target: "Array",
proto: !0,
forced: !h || !p
}, {
concat: function(t) {
var e, n, r, i, o, a = s(this),
d = c(a, 0),
f = 0;
for (e = -1, r = arguments.length; e < r; e++)
if (o = -1 === e ? a : arguments[e], g(o)) {
if (f + (i = l(o.length)) > 9007199254740991) throw TypeError("Maximum allowed index exceeded");
for (n = 0; n < i; n++, f++) n in o && u(d, f, o[n])
} else {
if (f >= 9007199254740991) throw TypeError("Maximum allowed index exceeded");
u(d, f++, o)
} return d.length = f, d
}
})
}, function(t, e, n) {
var r = n(7),
i = n(53),
o = n(2)("species");
t.exports = function(t, e) {
var n, a = r(t).constructor;
return void 0 === a || null == (n = r(a)[o]) ? e : i(n)
}
}, function(t, e, n) {
var r = n(14),
i = Date.prototype,
o = i.toString,
a = i.getTime;
new Date(NaN) + "" != "Invalid Date" && r(i, "toString", (function() {
var t = a.call(this);
return t == t ? o.call(this) : "Invalid Date"
}))
}, function(t, e, n) {
var r = n(3),
i = n(108);
r({
global: !0,
forced: parseFloat != i
}, {
parseFloat: i
})
}, function(t, e, n) {
"use strict";
var r = n(14),
i = n(7),
o = n(1),
a = n(68),
s = RegExp.prototype,
l = s.toString,
u = o((function() {
return "/a/b" != l.call({
source: "a",
flags: "b"
})
})),
c = "toString" != l.name;
(u || c) && r(RegExp.prototype, "toString", (function() {
var t = i(this),
e = String(t.source),
n = t.flags;
return "/" + e + "/" + String(void 0 === n && t instanceof RegExp && !("flags" in s) ? a.call(t) : n)
}), {
unsafe: !0
})
}, function(t, e, n) {
var r = n(53),
i = n(16),
o = n(31),
a = n(11),
s = function(t) {
return function(e, n, s, l) {
r(n);
var u = i(e),
c = o(u),
d = a(u.length),
f = t ? d - 1 : 0,
h = t ? -1 : 1;
if (s < 2)
for (;;) {
if (f in c) {
l = c[f], f += h;
break
}
if (f += h, t ? f < 0 : d <= f) throw TypeError("Reduce of empty array with no initial value")
}
for (; t ? f >= 0 : d > f; f += h) f in c && (l = n(l, c[f], f, u));
return l
}
};
t.exports = {
left: s(!1),
right: s(!0)
}
}, function(t, e, n) {
var r = n(0),
i = n(90).trim,
o = n(74),
a = r.parseFloat,
s = 1 / a(o + "-0") != -1 / 0;
t.exports = s ? function(t) {
var e = i(String(t)),
n = a(e);
return 0 === n && "-" == e.charAt(0) ? -0 : n
} : a
}, function(t, e, n) {
"use strict";
var r = n(72),
i = n(110),
o = n(7),
a = n(13),
s = n(103),
l = n(77),
u = n(11),
c = n(73),
d = n(45),
f = n(1),
h = [].push,
p = Math.min,
g = !f((function() {
return !RegExp(4294967295, "y")
}));
r("split", 2, (function(t, e, n) {
var r;
return r = "c" == "abbc".split(/(b)*/)[1] || 4 != "test".split(/(?:)/, -1).length || 2 != "ab".split(/(?:ab)*/).length || 4 != ".".split(/(.?)(.?)/).length || ".".split(/()()/).length > 1 || "".split(/.?/).length ? function(t, n) {
var r = String(a(this)),
o = void 0 === n ? 4294967295 : n >>> 0;
if (0 === o) return [];
if (void 0 === t) return [r];
if (!i(t)) return e.call(r, t, o);
for (var s, l, u, c = [], f = (t.ignoreCase ? "i" : "") + (t.multiline ? "m" : "") + (t.unicode ? "u" : "") + (t.sticky ? "y" : ""), p = 0, g = new RegExp(t.source, f + "g");
(s = d.call(g, r)) && !((l = g.lastIndex) > p && (c.push(r.slice(p, s.index)), s.length > 1 && s.index < r.length && h.apply(c, s.slice(1)), u = s[0].length, p = l, c.length >= o));) g.lastIndex === s.index && g.lastIndex++;
return p === r.length ? !u && g.test("") || c.push("") : c.push(r.slice(p)), c.length > o ? c.slice(0, o) : c
} : "0".split(void 0, 0).length ? function(t, n) {
return void 0 === t && 0 === n ? [] : e.call(this, t, n)
} : e, [function(e, n) {
var i = a(this),
o = null == e ? void 0 : e[t];
return void 0 !== o ? o.call(e, i, n) : r.call(String(i), e, n)
}, function(t, i) {
var a = n(r, t, this, i, r !== e);
if (a.done) return a.value;
var d = o(t),
f = String(this),
h = s(d, RegExp),
v = d.unicode,
m = (d.ignoreCase ? "i" : "") + (d.multiline ? "m" : "") + (d.unicode ? "u" : "") + (g ? "y" : "g"),
y = new h(g ? d : "^(?:" + d.source + ")", m),
b = void 0 === i ? 4294967295 : i >>> 0;
if (0 === b) return [];
if (0 === f.length) return null === c(y, f) ? [f] : [];
for (var x = 0, w = 0, S = []; w < f.length;) {
y.lastIndex = g ? w : 0;
var k, C = c(y, g ? f : f.slice(w));
if (null === C || (k = p(u(y.lastIndex + (g ? 0 : w)), f.length)) === x) w = l(f, w, v);
else {
if (S.push(f.slice(x, w)), S.length === b) return S;
for (var M = 1; M <= C.length - 1; M++)
if (S.push(C[M]), S.length === b) return S;
w = x = k
}
}
return S.push(f.slice(x)), S
}]
}), !g)
}, function(t, e, n) {
var r = n(5),
i = n(18),
o = n(2)("match");
t.exports = function(t) {
var e;
return r(t) && (void 0 !== (e = t[o]) ? !!e : "RegExp" == i(t))
}
}, function(t, e, n) {
"use strict";
var r = n(23).forEach,
i = n(44);
t.exports = i("forEach") ? function(t) {
return r(this, t, arguments.length > 1 ? arguments[1] : void 0)
} : [].forEach
}, function(t, e, n) {
var r = n(5),
i = n(70);
t.exports = function(t, e, n) {
var o, a;
return i && "function" == typeof(o = e.constructor) && o !== n && r(a = o.prototype) && a !== n.prototype && i(t, a), t
}
}, function(t, e, n) {
"use strict";
var r = n(72),
i = n(7),
o = n(11),
a = n(13),
s = n(77),
l = n(73);
r("match", 1, (function(t, e, n) {
return [function(e) {
var n = a(this),
r = null == e ? void 0 : e[t];
return void 0 !== r ? r.call(e, n) : new RegExp(e)[t](String(n))
}, function(t) {
var r = n(e, t, this);
if (r.done) return r.value;
var a = i(t),
u = String(this);
if (!a.global) return l(a, u);
var c = a.unicode;
a.lastIndex = 0;
for (var d, f = [], h = 0; null !== (d = l(a, u));) {
var p = String(d[0]);
f[h] = p, "" === p && (a.lastIndex = s(u, o(a.lastIndex), c)), h++
}
return 0 === h ? null : f
}]
}))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(12),
o = n(115),
a = n(116),
s = n(1),
l = 1..toFixed,
u = Math.floor,
c = function(t, e, n) {
return 0 === e ? n : e % 2 == 1 ? c(t, e - 1, n * t) : c(t * t, e / 2, n)
};
r({
target: "Number",
proto: !0,
forced: l && ("0.000" !== 8e-5.toFixed(3) || "1" !== .9.toFixed(0) || "1.25" !== 1.255.toFixed(2) || "1000000000000000128" !== (0xde0b6b3a7640080).toFixed(0)) || !s((function() {
l.call({})
}))
}, {
toFixed: function(t) {
var e, n, r, s, l = o(this),
d = i(t),
f = [0, 0, 0, 0, 0, 0],
h = "",
p = "0",
g = function(t, e) {
for (var n = -1, r = e; ++n < 6;) r += t * f[n], f[n] = r % 1e7, r = u(r / 1e7)
},
v = function(t) {
for (var e = 6, n = 0; --e >= 0;) n += f[e], f[e] = u(n / t), n = n % t * 1e7
},
m = function() {
for (var t = 6, e = ""; --t >= 0;)
if ("" !== e || 0 === t || 0 !== f[t]) {
var n = String(f[t]);
e = "" === e ? n : e + a.call("0", 7 - n.length) + n
} return e
};
if (d < 0 || d > 20) throw RangeError("Incorrect fraction digits");
if (l != l) return "NaN";
if (l <= -1e21 || l >= 1e21) return String(l);
if (l < 0 && (h = "-", l = -l), l > 1e-21)
if (n = (e = function(t) {
for (var e = 0, n = t; n >= 4096;) e += 12, n /= 4096;
for (; n >= 2;) e += 1, n /= 2;
return e
}(l * c(2, 69, 1)) - 69) < 0 ? l * c(2, -e, 1) : l / c(2, e, 1), n *= 4503599627370496, (e = 52 - e) > 0) {
for (g(0, n), r = d; r >= 7;) g(1e7, 0), r -= 7;
for (g(c(10, r, 1), 0), r = e - 1; r >= 23;) v(1 << 23), r -= 23;
v(1 << r), g(1, 1), v(2), p = m()
} else g(0, n), g(1 << -e, 0), p = m() + a.call("0", d);
return p = d > 0 ? h + ((s = p.length) <= d ? "0." + a.call("0", d - s) + p : p.slice(0, s - d) + "." + p.slice(s - d)) : h + p
}
})
}, function(t, e, n) {
var r = n(18);
t.exports = function(t) {
if ("number" != typeof t && "Number" != r(t)) throw TypeError("Incorrect invocation");
return +t
}
}, function(t, e, n) {
"use strict";
var r = n(12),
i = n(13);
t.exports = "".repeat || function(t) {
var e = String(i(this)),
n = "",
o = r(t);
if (o < 0 || o == 1 / 0) throw RangeError("Wrong number of repetitions");
for (; o > 0;
(o >>>= 1) && (e += e)) 1 & o && (n += e);
return n
}
}, , , function(t, e, n) {
"use strict";
var r = n(3),
i = n(111);
r({
target: "Array",
proto: !0,
forced: [].forEach != i
}, {
forEach: i
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(107).left;
r({
target: "Array",
proto: !0,
forced: n(44)("reduce")
}, {
reduce: function(t) {
return i(this, t, arguments.length, arguments.length > 1 ? arguments[1] : void 0)
}
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(29),
o = [].reverse,
a = [1, 2];
r({
target: "Array",
proto: !0,
forced: String(a) === String(a.reverse())
}, {
reverse: function() {
return i(this) && (this.length = this.length), o.call(this)
}
})
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(53),
o = n(16),
a = n(1),
s = n(44),
l = [].sort,
u = [1, 2, 3],
c = a((function() {
u.sort(void 0)
})),
d = a((function() {
u.sort(null)
})),
f = s("sort");
r({
target: "Array",
proto: !0,
forced: c || !d || f
}, {
sort: function(t) {
return void 0 === t ? l.call(o(this)) : l.call(o(this), i(t))
}
})
}, function(t, e, n) {
"use strict";
var r = n(9),
i = n(0),
o = n(51),
a = n(14),
s = n(4),
l = n(18),
u = n(112),
c = n(19),
d = n(1),
f = n(34),
h = n(27).f,
p = n(26).f,
g = n(8).f,
v = n(90).trim,
m = i.Number,
y = m.prototype,
b = "Number" == l(f(y)),
x = function(t) {
var e, n, r, i, o, a, s, l, u = c(t, !1);
if ("string" == typeof u && u.length > 2)
if (43 === (e = (u = v(u)).charCodeAt(0)) || 45 === e) {
if (88 === (n = u.charCodeAt(2)) || 120 === n) return NaN
} else if (48 === e) {
switch (u.charCodeAt(1)) {
case 66:
case 98:
r = 2, i = 49;
break;
case 79:
case 111:
r = 8, i = 55;
break;
default:
return +u
}
for (a = (o = u.slice(2)).length, s = 0; s < a; s++)
if ((l = o.charCodeAt(s)) < 48 || l > i) return NaN;
return parseInt(o, r)
}
return +u
};
if (o("Number", !m(" 0o1") || !m("0b1") || m("+0x1"))) {
for (var w, S = function(t) {
var e = arguments.length < 1 ? 0 : t,
n = this;
return n instanceof S && (b ? d((function() {
y.valueOf.call(n)
})) : "Number" != l(n)) ? u(new m(x(e)), n, S) : x(e)
}, k = r ? h(m) : "MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","), C = 0; k.length > C; C++) s(m, w = k[C]) && !s(S, w) && g(S, w, p(m, w));
S.prototype = y, y.constructor = S, a(i, "Number", S)
}
}, function(t, e, n) {
var r = n(3),
i = n(128);
r({
global: !0,
forced: parseInt != i
}, {
parseInt: i
})
}, function(t, e, n) {
var r = n(0),
i = n(86),
o = n(111),
a = n(6);
for (var s in i) {
var l = r[s],
u = l && l.prototype;
if (u && u.forEach !== o) try {
a(u, "forEach", o)
} catch (t) {
u.forEach = o
}
}
}, function(t, e, n) {
"use strict";
var r = n(35),
i = n(8),
o = n(2),
a = n(9),
s = o("species");
t.exports = function(t) {
var e = r(t),
n = i.f;
a && e && !e[s] && n(e, s, {
configurable: !0,
get: function() {
return this
}
})
}
}, function(t, e, n) {
var r = n(9),
i = n(8).f,
o = Function.prototype,
a = o.toString,
s = /^\s*function ([^ (]*)/;
!r || "name" in o || i(o, "name", {
configurable: !0,
get: function() {
try {
return a.call(this).match(s)[1]
} catch (t) {
return ""
}
}
})
}, function(t, e, n) {
var r = n(0),
i = n(90).trim,
o = n(74),
a = r.parseInt,
s = /^[+-]?0[Xx]/,
l = 8 !== a(o + "08") || 22 !== a(o + "0x16");
t.exports = l ? function(t, e) {
var n = i(String(t));
return a(n, e >>> 0 || (s.test(n) ? 16 : 10))
} : a
}, function(t, e, n) {
var r = n(9),
i = n(0),
o = n(51),
a = n(112),
s = n(8).f,
l = n(27).f,
u = n(110),
c = n(68),
d = n(14),
f = n(1),
h = n(126),
p = n(2)("match"),
g = i.RegExp,
v = g.prototype,
m = /a/g,
y = /a/g,
b = new g(m) !== m;
if (r && o("RegExp", !b || f((function() {
return y[p] = !1, g(m) != m || g(y) == y || "/a/i" != g(m, "i")
})))) {
for (var x = function(t, e) {
var n = this instanceof x,
r = u(t),
i = void 0 === e;
return !n && r && t.constructor === x && i ? t : a(b ? new g(r && !i ? t.source : t, e) : g((r = t instanceof x) ? t.source : t, r && i ? c.call(t) : e), n ? this : v, x)
}, w = function(t) {
t in x || s(x, t, {
configurable: !0,
get: function() {
return g[t]
},
set: function(e) {
g[t] = e
}
})
}, S = l(g), k = 0; S.length > k;) w(S[k++]);
v.constructor = x, x.prototype = v, d(i, "RegExp", x)
}
h("RegExp")
}, function(t, e, n) {
"use strict";
var r = n(10),
i = n(12),
o = n(11),
a = n(44),
s = Math.min,
l = [].lastIndexOf,
u = !!l && 1 / [1].lastIndexOf(1, -0) < 0,
c = a("lastIndexOf");
t.exports = u || c ? function(t) {
if (u) return l.apply(this, arguments) || 0;
var e = r(this),
n = o(e.length),
a = n - 1;
for (arguments.length > 1 && (a = s(a, i(arguments[1]))), a < 0 && (a = n + a); a >= 0; a--)
if (a in e && e[a] === t) return a || 0;
return -1
} : l
}, , function(t, e, n) {
"use strict";
var r = n(16),
i = n(32),
o = n(11);
t.exports = function(t) {
for (var e = r(this), n = o(e.length), a = arguments.length, s = i(a > 1 ? arguments[1] : void 0, n), l = a > 2 ? arguments[2] : void 0, u = void 0 === l ? n : i(l, n); u > s;) e[s++] = t;
return e
}
}, function(t, e, n) {
"use strict";
n.r(e);
n(100), n(101), n(95), n(123), n(83), n(98);
function r(t, e) {
for (var n = 0; n < e.length; n++) {
var r = e[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(t, r.key, r)
}
}
jQuery((function(t) {
(new(function() {
function e() {
! function(t, e) {
if (!(t instanceof e)) throw new TypeError("Cannot call a class as a function")
}(this, e), this.inputSelector = "".concat(["text", "password", "email", "url", "tel", "number", "search", "search-md"].map((function(t) {
return "input[type=".concat(t, "]")
})).join(", "), ", textarea"), this.textAreaSelector = ".materialize-textarea", this.$text = t(".md-textarea-auto"), this.$body = t("body"), this.$document = t(document)
}
var n, i, o;
return n = e, (i = [{
key: "init",
value: function() {
var e, n = this;
this.$text.length && (e = window.attachEvent ? function(t, e, n) {
t.attachEvent("on".concat(e), n)
} : function(t, e, n) {
t.addEventListener(e, n, !1)
}, this.$text.each((function() {
var t = this;
function n() {
t.style.height = "auto", t.style.height = "".concat(t.scrollHeight, "px")
}
function r() {
window.setTimeout(n, 0)
}
e(t, "change", n), e(t, "cut", r), e(t, "paste", r), e(t, "drop", r), e(t, "keydown", r), n()
}))), t(this.inputSelector).each((function(e, r) {
var i = t(r),
o = r.validity.badInput;
n.updateTextFields(i), o && n.toggleActiveClass(i, "add")
})), this.addOnFocusEvent(), this.addOnBlurEvent(), this.addOnChangeEvent(), this.addOnResetEvent(), this.appendHiddenDiv(), this.ChangeDateInputType(), this.makeActiveAutofocus(), t(this.textAreaSelector).each(this.textAreaAutoResize), this.$body.on("keyup keydown", this.textAreaSelector, this.textAreaAutoResize)
}
}, {
key: "makeActiveAutofocus",
value: function() {
this.toggleActiveClass(t("input[autofocus]"), "add")
}
}, {
key: "toggleActiveClass",
value: function(t, e) {
var n;
e = "".concat(e, "Class"), n = t.parent().hasClass("timepicker") ? "label" : "label, i, .input-prefix", t.siblings(n)[e]("active")
}
}, {
key: "addOnFocusEvent",
value: function() {
var e = this;
this.$document.on("focus", this.inputSelector, (function(n) {
e.toggleActiveClass(t(n.target), "add")
}))
}
}, {
key: "addOnBlurEvent",
value: function() {
var e = this;
this.$document.on("blur", this.inputSelector, (function(n) {
var r = t(n.target),
i = !r.val(),
o = !n.target.validity.badInput,
a = void 0 === r.attr("placeholder");
i && o && a && e.toggleActiveClass(r, "remove"), !i && o && a && r.siblings("i, .input-prefix").removeClass("active"), e.validateField(r)
}))
}
}, {
key: "addOnChangeEvent",
value: function() {
var e = this;
this.$document.on("change", this.inputSelector, (function(n) {
var r = t(n.target);
e.updateTextFields(r), e.validateField(r)
}))
}
}, {
key: "addOnResetEvent",
value: function() {
var e = this;
this.$document.on("reset", (function(n) {
var r = t(n.target);
r.is("form") && (r.find(e.inputSelector).removeClass("valid invalid").each((function(n, r) {
var i = t(r),
o = !i.val(),
a = !i.attr("placeholder");
o && a && e.toggleActiveClass(i, "remove")
})), r.find("select.initialized").each((function(e, n) {
var r = t(n),
i = r.siblings("input.select-dropdown"),
o = r.children("[selected]").val();
r.val(o), i.val(o)
})))
}))
}
}, {
key: "appendHiddenDiv",
value: function() {
if (!t(".hiddendiv").first().length) {
var e = t('<div class="hiddendiv common"></div>');
this.$body.append(e)
}
}
}, {
key: "updateTextFields",
value: function(t) {
var e = Boolean(t.val().length),
n = Boolean(t.attr("placeholder")),
r = e || n ? "add" : "remove";
this.toggleActiveClass(t, r)
}
}, {
key: "validateField",
value: function(t) {
if (t.hasClass("validate")) {
var e = t.val(),
n = !e.length,
r = !t[0].validity.badInput;
if (n && r) t.removeClass("valid").removeClass("invalid");
else {
var i = t[0].validity.valid,
o = Number(t.attr("length")) || 0;
i && (!o || o > e.length) ? t.removeClass("invalid").addClass("valid") : t.removeClass("valid").addClass("invalid")
}
}
}
}, {
key: "ChangeDateInputType",
value: function() {
var e = t('input[type="date"]');
e.each((function(t, e) {
e.type = "text"
})), e.on("focus", (function(t) {
t.target.type = "date"
})), e.on("blur", (function(e) {
e.target.type = "text", 0 === e.target.value.length && t("label[for=".concat(e.target.id, "]")).removeClass("active")
}))
}
}, {
key: "textAreaAutoResize",
value: function() {
var e = t(this);
if (e.val().length) {
var n = t(".hiddendiv"),
r = e.css("font-family"),
i = e.css("font-size");
i && n.css("font-size", i), r && n.css("font-family", r), "off" === e.attr("wrap") && n.css("overflow-wrap", "normal").css("white-space", "pre"), n.text("".concat(e.val(), "\n"));
var o = n.html().replace(/\n/g, "<br>");
n.html(o), n.css("width", e.is(":visible") ? e.width() : t(window).width() / 2), e.css("height", n.height())
}
}
}]) && r(n.prototype, i), o && r(n, o), e
}())).init()
}))
}, function(t, e) {
jQuery((function(t) {
t(window).on("scroll", (function() {
var e = t(".navbar");
e.length && t(".scrolling-navbar")[e.offset().top > 50 ? "addClass" : "removeClass"]("top-nav-collapse")
}))
}))
}, function(t, e, n) {
"use strict";
n.r(e);
n(100);
jQuery((function(t) {
t.fn.mdbTreeview = function() {
var e = t(this);
e.hasClass("treeview") && function(e) {
e.find(".rotate").each((function() {
var e = t(this);
e.off("click"), e.on("click", (function() {
var e = t(this);
e.siblings(".nested").toggleClass("active"), e.toggleClass("down")
}))
}))
}(e), e.hasClass("treeview-animated") && function(e) {
var n = e.find(".treeview-animated-element"),
r = e.find(".closed");
e.find(".nested").hide(), r.off("click"), r.on("click", (function() {
var e = t(this),
n = e.siblings(".nested"),
r = e.children(".fa-angle-right");
e.toggleClass("open"), r.toggleClass("down"), n.hasClass("active") ? n.removeClass("active").slideUp() : n.addClass("active").slideDown()
})), n.off("click"), n.on("click", (function() {
var e = t(this);
e.hasClass("opened") ? e.removeClass("opened") : (n.removeClass("opened"), e.addClass("opened"))
}))
}(e), e.hasClass("treeview-colorful") && function(e) {
var n = e.find(".treeview-colorful-element"),
r = e.find(".treeview-colorful-items-header");
e.find(".nested").hide(), r.off("click"), r.on("click", (function() {
var e = t(this),
n = e.siblings(".nested"),
r = e.children(".fa-plus-circle"),
i = e.children(".fa-minus-circle");
e.toggleClass("open"), r.removeClass("fa-plus-circle"), r.addClass("fa-minus-circle"), i.removeClass("fa-minus-circle"), i.addClass("fa-plus-circle"), n.hasClass("active") ? n.removeClass("active").slideUp() : n.addClass("active").slideDown()
})), n.off("click"), n.on("click", (function() {
var e = t(this);
e.hasClass("opened") ? n.removeClass("opened") : (n.removeClass("opened"), e.addClass("opened"))
}))
}(e)
}
}))
}, function(t, e, n) {
"use strict";
n.r(e);
n(96), n(104), n(71), n(106);
function r(t, e) {
if (!(t instanceof e)) throw new TypeError("Cannot call a class as a function")
}
function i(t, e) {
for (var n = 0; n < e.length; n++) {
var r = e[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(t, r.key, r)
}
}
function o(t, e, n) {
return e && i(t.prototype, e), n && i(t, n), t
}
jQuery((function(t) {
var e = function() {
function e() {
r(this, e)
}
return o(e, [{
key: "init",
value: function() {
t(".wow").wow()
}
}]), e
}(),
n = function() {
function e(t, n) {
r(this, e), this.$wowElement = t, this.customization = n, this.animated = !0, this.options = this.assignElementCustomization()
}
return o(e, [{
key: "init",
value: function() {
var e = this;
t(window).scroll((function() {
e.animated ? e.hide() : e.mdbWow()
})), this.appear()
}
}, {
key: "assignElementCustomization",
value: function() {
return {
animationName: this.$wowElement.css("animation-name"),
offset: 100,
iteration: this.fallback().or(this.$wowElement.data("wow-iteration")).or(1).value(),
duration: this.fallback().or(this.$wowElement.data("wow-duration")).or(1e3).value(),
delay: this.fallback().or(this.$wowElement.data("wow-delay")).or(0).value()
}
}
}, {
key: "mdbWow",
value: function() {
var t = this;
"visible" !== this.$wowElement.css("visibility") && this.shouldElementBeVisible(!0) && (setTimeout((function() {
return t.$wowElement.removeClass("animated")
}), this.countRemoveTime()), this.appear())
}
}, {
key: "appear",
value: function() {
this.$wowElement.addClass("animated"), this.$wowElement.css({
visibility: "visible",
"animation-name": this.options.animationName,
"animation-iteration-count": this.options.iteration,
"animation-duration": this.options.duration,
"animation-delay": this.options.delay
})
}
}, {
key: "hide",
value: function() {
var t = this;
this.shouldElementBeVisible(!1) ? (this.$wowElement.removeClass("animated"), this.$wowElement.css({
"animation-name": "none",
visibility: "hidden"
})) : setTimeout((function() {
t.$wowElement.removeClass("animated")
}), this.countRemoveTime()), this.mdbWow(), this.animated = !this.animated
}
}, {
key: "shouldElementBeVisible",
value: function(e) {
var n = this.getOffset(this.$wowElement[0]),
r = this.$wowElement.height(),
i = t(document).height(),
o = window.innerHeight,
a = window.scrollY,
s = o + a - this.options.offset > n,
l = o + a - this.options.offset > n + r,
u = a < n,
c = a < n + r,
d = o + a === i,
f = n + this.options.offset > i,
h = o + a - this.options.offset < n,
p = a > n + this.options.offset,
g = a < n + this.options.offset,
v = n + r > i - this.options.offset;
return e ? s && u || l && c || d && f : s && p || h && g || v
}
}, {
key: "countRemoveTime",
value: function() {
var t = 1e3 * this.$wowElement.css("animation-duration").slice(0, -1),
e = 0;
return this.options.duration && (e = t + this.checkOptionsStringFormat(this.options.duration)), this.options.delay && (e += this.checkOptionsStringFormat(this.options.delay)), e
}
}, {
key: "checkOptionsStringFormat",
value: function(t) {
var e;
if ("s" === t.toString().slice(-1)) e = t.toString().slice(0, -1);
else {
if (isNaN(t.toString().slice(-1))) return console.log("Not supported animation customization format.");
e = t
}
return e
}
}, {
key: "getOffset",
value: function(t) {
var e = t.getBoundingClientRect(),
n = document.body,
r = document.documentElement,
i = window.pageYOffset || r.scrollTop || n.scrollTop,
o = r.clientTop || n.clientTop || 0,
a = e.top + i - o;
return Math.round(a)
}
}, {
key: "fallback",
value: function() {
return {
_value: void 0,
or: function(t) {
return void 0 !== t && void 0 === this._value && (this._value = t), this
},
value: function() {
return this._value
}
}
}
}]), e
}();
t.fn.wow = function(e) {
this.each((function() {
new n(t(this), e).init()
}))
}, window.WOW = e
}))
}, , , , , , , , function(t, e, n) {
var r = n(3),
i = n(132),
o = n(58);
r({
target: "Array",
proto: !0
}, {
fill: i
}), o("fill")
}, function(t, e, n) {
n(3)({
target: "Number",
stat: !0
}, {
MAX_SAFE_INTEGER: 9007199254740991
})
}, function(t, e, n) {
n(3)({
target: "Number",
stat: !0
}, {
MIN_SAFE_INTEGER: -9007199254740991
})
}, function(t, e, n) {
var r = n(3),
i = n(16),
o = n(52);
r({
target: "Object",
stat: !0,
forced: n(1)((function() {
o(1)
}))
}, {
keys: function(t) {
return o(i(t))
}
})
}, function(t, e, n) {
"use strict";
var r = n(0),
i = n(9),
o = n(56).NATIVE_ARRAY_BUFFER,
a = n(6),
s = n(171),
l = n(1),
u = n(149),
c = n(12),
d = n(11),
f = n(150),
h = n(27).f,
p = n(8).f,
g = n(132),
v = n(42),
m = n(21),
y = m.get,
b = m.set,
x = r.ArrayBuffer,
w = x,
S = r.DataView,
k = r.Math,
C = r.RangeError,
M = k.abs,
A = k.pow,
P = k.floor,
_ = k.log,
T = k.LN2,
I = function(t, e, n) {
var r, i, o, a = new Array(n),
s = 8 * n - e - 1,
l = (1 << s) - 1,
u = l >> 1,
c = 23 === e ? A(2, -24) - A(2, -77) : 0,
d = t < 0 || 0 === t && 1 / t < 0 ? 1 : 0,
f = 0;
for ((t = M(t)) != t || t === 1 / 0 ? (i = t != t ? 1 : 0, r = l) : (r = P(_(t) / T), t * (o = A(2, -r)) < 1 && (r--, o *= 2), (t += r + u >= 1 ? c / o : c * A(2, 1 - u)) * o >= 2 && (r++, o /= 2), r + u >= l ? (i = 0, r = l) : r + u >= 1 ? (i = (t * o - 1) * A(2, e), r += u) : (i = t * A(2, u - 1) * A(2, e), r = 0)); e >= 8; a[f++] = 255 & i, i /= 256, e -= 8);
for (r = r << e | i, s += e; s > 0; a[f++] = 255 & r, r /= 256, s -= 8);
return a[--f] |= 128 * d, a
},
O = function(t, e) {
var n, r = t.length,
i = 8 * r - e - 1,
o = (1 << i) - 1,
a = o >> 1,
s = i - 7,
l = r - 1,
u = t[l--],
c = 127 & u;
for (u >>= 7; s > 0; c = 256 * c + t[l], l--, s -= 8);
for (n = c & (1 << -s) - 1, c >>= -s, s += e; s > 0; n = 256 * n + t[l], l--, s -= 8);
if (0 === c) c = 1 - a;
else {
if (c === o) return n ? NaN : u ? -1 / 0 : 1 / 0;
n += A(2, e), c -= a
}
return (u ? -1 : 1) * n * A(2, c - e)
},
F = function(t) {
return t[3] << 24 | t[2] << 16 | t[1] << 8 | t[0]
},
D = function(t) {
return [255 & t]
},
E = function(t) {
return [255 & t, t >> 8 & 255]
},
L = function(t) {
return [255 & t, t >> 8 & 255, t >> 16 & 255, t >> 24 & 255]
},
R = function(t) {
return I(t, 23, 4)
},
N = function(t) {
return I(t, 52, 8)
},
V = function(t, e) {
p(t.prototype, e, {
get: function() {
return y(this)[e]
}
})
},
z = function(t, e, n, r) {
var i = f(+n),
o = y(t);
if (i + e > o.byteLength) throw C("Wrong index");
var a = y(o.buffer).bytes,
s = i + o.byteOffset,
l = a.slice(s, s + e);
return r ? l : l.reverse()
},
B = function(t, e, n, r, i, o) {
var a = f(+n),
s = y(t);
if (a + e > s.byteLength) throw C("Wrong index");
for (var l = y(s.buffer).bytes, u = a + s.byteOffset, c = r(+i), d = 0; d < e; d++) l[u + d] = c[o ? d : e - d - 1]
};
if (o) {
if (!l((function() {
x(1)
})) || !l((function() {
new x(-1)
})) || l((function() {
return new x, new x(1.5), new x(NaN), "ArrayBuffer" != x.name
}))) {
for (var W, j = (w = function(t) {
return u(this, w), new x(f(t))
}).prototype = x.prototype, H = h(x), q = 0; H.length > q;)(W = H[q++]) in w || a(w, W, x[W]);
j.constructor = w
}
var U = new S(new w(2)),
$ = S.prototype.setInt8;
U.setInt8(0, 2147483648), U.setInt8(1, 2147483649), !U.getInt8(0) && U.getInt8(1) || s(S.prototype, {
setInt8: function(t, e) {
$.call(this, t, e << 24 >> 24)
},
setUint8: function(t, e) {
$.call(this, t, e << 24 >> 24)
}
}, {
unsafe: !0
})
} else w = function(t) {
u(this, w, "ArrayBuffer");
var e = f(t);
b(this, {
bytes: g.call(new Array(e), 0),
byteLength: e
}), i || (this.byteLength = e)
}, S = function(t, e, n) {
u(this, S, "DataView"), u(t, w, "DataView");
var r = y(t).byteLength,
o = c(e);
if (o < 0 || o > r) throw C("Wrong offset");
if (o + (n = void 0 === n ? r - o : d(n)) > r) throw C("Wrong length");
b(this, {
buffer: t,
byteLength: n,
byteOffset: o
}), i || (this.buffer = t, this.byteLength = n, this.byteOffset = o)
}, i && (V(w, "byteLength"), V(S, "buffer"), V(S, "byteLength"), V(S, "byteOffset")), s(S.prototype, {
getInt8: function(t) {
return z(this, 1, t)[0] << 24 >> 24
},
getUint8: function(t) {
return z(this, 1, t)[0]
},
getInt16: function(t) {
var e = z(this, 2, t, arguments.length > 1 ? arguments[1] : void 0);
return (e[1] << 8 | e[0]) << 16 >> 16
},
getUint16: function(t) {
var e = z(this, 2, t, arguments.length > 1 ? arguments[1] : void 0);
return e[1] << 8 | e[0]
},
getInt32: function(t) {
return F(z(this, 4, t, arguments.length > 1 ? arguments[1] : void 0))
},
getUint32: function(t) {
return F(z(this, 4, t, arguments.length > 1 ? arguments[1] : void 0)) >>> 0
},
getFloat32: function(t) {
return O(z(this, 4, t, arguments.length > 1 ? arguments[1] : void 0), 23)
},
getFloat64: function(t) {
return O(z(this, 8, t, arguments.length > 1 ? arguments[1] : void 0), 52)
},
setInt8: function(t, e) {
B(this, 1, t, D, e)
},
setUint8: function(t, e) {
B(this, 1, t, D, e)
},
setInt16: function(t, e) {
B(this, 2, t, E, e, arguments.length > 2 ? arguments[2] : void 0)
},
setUint16: function(t, e) {
B(this, 2, t, E, e, arguments.length > 2 ? arguments[2] : void 0)
},
setInt32: function(t, e) {
B(this, 4, t, L, e, arguments.length > 2 ? arguments[2] : void 0)
},
setUint32: function(t, e) {
B(this, 4, t, L, e, arguments.length > 2 ? arguments[2] : void 0)
},
setFloat32: function(t, e) {
B(this, 4, t, R, e, arguments.length > 2 ? arguments[2] : void 0)
},
setFloat64: function(t, e) {
B(this, 8, t, N, e, arguments.length > 2 ? arguments[2] : void 0)
}
});
v(w, "ArrayBuffer"), v(S, "DataView"), t.exports = {
ArrayBuffer: w,
DataView: S
}
}, function(t, e) {
t.exports = function(t, e, n) {
if (!(t instanceof e)) throw TypeError("Incorrect " + (n ? n + " " : "") + "invocation");
return t
}
}, function(t, e, n) {
var r = n(12),
i = n(11);
t.exports = function(t) {
if (void 0 === t) return 0;
var e = r(t),
n = i(e);
if (e !== n) throw RangeError("Wrong length or index");
return n
}
}, function(t, e, n) {
var r = n(176);
t.exports = function(t, e) {
var n = r(t);
if (n % e) throw RangeError("Wrong offset");
return n
}
}, function(t, e, n) {
n(153), t.exports = n(154)
}, function(t, e, n) {}, function(t, e, n) {
"use strict";
n.r(e);
n(155), n(156), n(162), n(167), n(168), n(169), n(204), n(133), n(134), n(135), n(136)
}, function(t, e, n) {
"use strict";
(function(t) {
var e, r;
n(78), n(81), n(82), n(99), n(91), n(54), n(101), n(95), n(96), n(127), n(71), n(83), n(84), n(109), n(85);
function i(t) {
return (i = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
return typeof t
} : function(t) {
return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
})(t)
}
/*!
* bsCustomFileInput v1.3.2 (https://github.com/Johann-S/bs-custom-file-input)
* Copyright 2018 - 2019 Johann-S <johann.servoire@gmail.com>
* Licensed under MIT (https://github.com/Johann-S/bs-custom-file-input/blob/master/LICENSE)
*/
e = void 0, r = function() {
var t = {
CUSTOMFILE: '.custom-file input[type="file"]',
CUSTOMFILELABEL: ".custom-file-label",
FORM: "form",
INPUT: "input"
},
e = function(e) {
var n = "",
r = e.parentNode.querySelector(t.CUSTOMFILELABEL);
return r && (n = r.innerHTML), n
},
n = function(t) {
if (t.childNodes.length > 0)
for (var e = [].slice.call(t.childNodes), n = 0; n < e.length; n++) {
var r = e[n];
if (3 !== r.nodeType) return r
}
return t
},
r = function(e) {
var r = e.bsCustomFileInput.defaultText,
i = e.parentNode.querySelector(t.CUSTOMFILELABEL);
i && (n(i).innerHTML = r)
},
i = !!window.File,
o = function(t) {
if (t.hasAttribute("multiple") && i) return [].slice.call(t.files).map((function(t) {
return t.name
})).join(", ");
if (-1 !== t.value.indexOf("fakepath")) {
var e = t.value.split("\\");
return e[e.length - 1]
}
return t.value
};
function a() {
var e = this.parentNode.querySelector(t.CUSTOMFILELABEL);
if (e) {
var i = n(e),
a = o(this);
a.length ? i.innerHTML = a : r(this)
}
}
function s() {
for (var e = [].slice.call(this.querySelectorAll(t.INPUT)).filter((function(t) {
return !!t.bsCustomFileInput
})), n = 0, i = e.length; n < i; n++) r(e[n])
}
var l = "reset",
u = "change";
return {
init: function(n, r) {
void 0 === n && (n = t.CUSTOMFILE), void 0 === r && (r = t.FORM);
for (var i = [].slice.call(document.querySelectorAll(n)), o = [].slice.call(document.querySelectorAll(r)), c = 0, d = i.length; c < d; c++) {
var f = i[c];
Object.defineProperty(f, "bsCustomFileInput", {
value: {
defaultText: e(f)
},
writable: !0
}), a.call(f), f.addEventListener(u, a)
}
for (var h = 0, p = o.length; h < p; h++) o[h].addEventListener(l, s), Object.defineProperty(o[h], "bsCustomFileInput", {
value: !0,
writable: !0
})
},
destroy: function() {
for (var e = [].slice.call(document.querySelectorAll(t.FORM)).filter((function(t) {
return !!t.bsCustomFileInput
})), n = [].slice.call(document.querySelectorAll(t.INPUT)).filter((function(t) {
return !!t.bsCustomFileInput
})), i = 0, o = n.length; i < o; i++) {
var c = n[i];
r(c), c.bsCustomFileInput = void 0, c.removeEventListener(u, a)
}
for (var d = 0, f = e.length; d < f; d++) e[d].removeEventListener(l, s), e[d].bsCustomFileInput = void 0
}
}
}, "object" === ("undefined" == typeof exports ? "undefined" : i(exports)) && void 0 !== t ? t.exports = r() : "function" == typeof define && n(55) ? define(r) : (e = e || self).bsCustomFileInput = r(), document.addEventListener("DOMContentLoaded", (function() {
bsCustomFileInput.init()
}))
}).call(this, n(87)(t))
}, function(t, e, n) {
"use strict";
(function(t, e) {
var i;
n(78), n(81), n(82), n(102), n(144), n(99), n(157), n(119), n(91), n(54), n(101), n(95), n(120), n(121), n(96), n(122), n(97), n(104), n(158), n(159), n(123), n(161), n(145), n(146), n(114), n(147), n(71), n(105), n(124), n(83), n(106), n(84), n(113), n(109), n(125), n(85);
function o(t) {
return (o = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
return typeof t
} : function(t) {
return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
})(t)
}
/*!
* Chart.js
* http://chartjs.org/
* Version: 2.7.3
*
* Copyright 2018 Chart.js Contributors
* Released under the MIT license
* https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
*/
! function(r) {
if ("object" === ("undefined" == typeof exports ? "undefined" : o(exports)) && void 0 !== t) t.exports = r();
else if ("function" == typeof define && n(55)) define([], r);
else {
("undefined" != typeof window ? window : void 0 !== e ? e : "undefined" != typeof self ? self : this).Chart = r()
}
}((function() {
return function t(e, n, r) {
function o(s, l) {
if (!n[s]) {
if (!e[s]) {
if (!l && "function" == typeof i && i) return i(s, !0);
if (a) return a(s, !0);
var u = new Error("Cannot find module '" + s + "'");
throw u.code = "MODULE_NOT_FOUND", u
}
var c = n[s] = {
exports: {}
};
e[s][0].call(c.exports, (function(t) {
return o(e[s][1][t] || t)
}), c, c.exports, t, e, n, r)
}
return n[s].exports
}
for (var a = "function" == typeof i && i, s = 0; s < r.length; s++) o(r[s]);
return o
}({
1: [function(t, e, n) {}, {}],
2: [function(t, e, n) {
var r = t(6);
function i(t) {
if (t) {
var e = [0, 0, 0],
n = 1,
i = t.match(/^#([a-fA-F0-9]{3})$/i);
if (i) {
i = i[1];
for (var o = 0; o < e.length; o++) e[o] = parseInt(i[o] + i[o], 16)
} else if (i = t.match(/^#([a-fA-F0-9]{6})$/i)) {
i = i[1];
for (o = 0; o < e.length; o++) e[o] = parseInt(i.slice(2 * o, 2 * o + 2), 16)
} else if (i = t.match(/^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i)) {
for (o = 0; o < e.length; o++) e[o] = parseInt(i[o + 1]);
n = parseFloat(i[4])
} else if (i = t.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i)) {
for (o = 0; o < e.length; o++) e[o] = Math.round(2.55 * parseFloat(i[o + 1]));
n = parseFloat(i[4])
} else if (i = t.match(/(\w+)/)) {
if ("transparent" == i[1]) return [0, 0, 0, 0];
if (!(e = r[i[1]])) return
}
for (o = 0; o < e.length; o++) e[o] = c(e[o], 0, 255);
return n = n || 0 == n ? c(n, 0, 1) : 1, e[3] = n, e
}
}
function o(t) {
if (t) {
var e = t.match(/^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/);
if (e) {
var n = parseFloat(e[4]);
return [c(parseInt(e[1]), 0, 360), c(parseFloat(e[2]), 0, 100), c(parseFloat(e[3]), 0, 100), c(isNaN(n) ? 1 : n, 0, 1)]
}
}
}
function a(t) {
if (t) {
var e = t.match(/^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/);
if (e) {
var n = parseFloat(e[4]);
return [c(parseInt(e[1]), 0, 360), c(parseFloat(e[2]), 0, 100), c(parseFloat(e[3]), 0, 100), c(isNaN(n) ? 1 : n, 0, 1)]
}
}
}
function s(t, e) {
return void 0 === e && (e = void 0 !== t[3] ? t[3] : 1), "rgba(" + t[0] + ", " + t[1] + ", " + t[2] + ", " + e + ")"
}
function l(t, e) {
return "rgba(" + Math.round(t[0] / 255 * 100) + "%, " + Math.round(t[1] / 255 * 100) + "%, " + Math.round(t[2] / 255 * 100) + "%, " + (e || t[3] || 1) + ")"
}
function u(t, e) {
return void 0 === e && (e = void 0 !== t[3] ? t[3] : 1), "hsla(" + t[0] + ", " + t[1] + "%, " + t[2] + "%, " + e + ")"
}
function c(t, e, n) {
return Math.min(Math.max(e, t), n)
}
function d(t) {
var e = t.toString(16).toUpperCase();
return e.length < 2 ? "0" + e : e
}
e.exports = {
getRgba: i,
getHsla: o,
getRgb: function(t) {
var e = i(t);
return e && e.slice(0, 3)
},
getHsl: function(t) {
var e = o(t);
return e && e.slice(0, 3)
},
getHwb: a,
getAlpha: function(t) {
var e = i(t);
if (e) return e[3];
if (e = o(t)) return e[3];
if (e = a(t)) return e[3]
},
hexString: function(t) {
return "#" + d(t[0]) + d(t[1]) + d(t[2])
},
rgbString: function(t, e) {
if (e < 1 || t[3] && t[3] < 1) return s(t, e);
return "rgb(" + t[0] + ", " + t[1] + ", " + t[2] + ")"
},
rgbaString: s,
percentString: function(t, e) {
if (e < 1 || t[3] && t[3] < 1) return l(t, e);
var n = Math.round(t[0] / 255 * 100),
r = Math.round(t[1] / 255 * 100),
i = Math.round(t[2] / 255 * 100);
return "rgb(" + n + "%, " + r + "%, " + i + "%)"
},
percentaString: l,
hslString: function(t, e) {
if (e < 1 || t[3] && t[3] < 1) return u(t, e);
return "hsl(" + t[0] + ", " + t[1] + "%, " + t[2] + "%)"
},
hslaString: u,
hwbString: function(t, e) {
void 0 === e && (e = void 0 !== t[3] ? t[3] : 1);
return "hwb(" + t[0] + ", " + t[1] + "%, " + t[2] + "%" + (void 0 !== e && 1 !== e ? ", " + e : "") + ")"
},
keyword: function(t) {
return f[t.slice(0, 3)]
}
};
var f = {};
for (var h in r) f[r[h]] = h
}, {
6: 6
}],
3: [function(t, e, n) {
var r = t(5),
i = t(2),
a = function t(e) {
return e instanceof t ? e : this instanceof t ? (this.valid = !1, this.values = {
rgb: [0, 0, 0],
hsl: [0, 0, 0],
hsv: [0, 0, 0],
hwb: [0, 0, 0],
cmyk: [0, 0, 0, 0],
alpha: 1
}, void("string" == typeof e ? (n = i.getRgba(e)) ? this.setValues("rgb", n) : (n = i.getHsla(e)) ? this.setValues("hsl", n) : (n = i.getHwb(e)) && this.setValues("hwb", n) : "object" === o(e) && (void 0 !== (n = e).r || void 0 !== n.red ? this.setValues("rgb", n) : void 0 !== n.l || void 0 !== n.lightness ? this.setValues("hsl", n) : void 0 !== n.v || void 0 !== n.value ? this.setValues("hsv", n) : void 0 !== n.w || void 0 !== n.whiteness ? this.setValues("hwb", n) : void 0 === n.c && void 0 === n.cyan || this.setValues("cmyk", n)))) : new t(e);
var n
};
(a.prototype = {
isValid: function() {
return this.valid
},
rgb: function() {
return this.setSpace("rgb", arguments)
},
hsl: function() {
return this.setSpace("hsl", arguments)
},
hsv: function() {
return this.setSpace("hsv", arguments)
},
hwb: function() {
return this.setSpace("hwb", arguments)
},
cmyk: function() {
return this.setSpace("cmyk", arguments)
},
rgbArray: function() {
return this.values.rgb
},
hslArray: function() {
return this.values.hsl
},
hsvArray: function() {
return this.values.hsv
},
hwbArray: function() {
var t = this.values;
return 1 !== t.alpha ? t.hwb.concat([t.alpha]) : t.hwb
},
cmykArray: function() {
return this.values.cmyk
},
rgbaArray: function() {
var t = this.values;
return t.rgb.concat([t.alpha])
},
hslaArray: function() {
var t = this.values;
return t.hsl.concat([t.alpha])
},
alpha: function(t) {
return void 0 === t ? this.values.alpha : (this.setValues("alpha", t), this)
},
red: function(t) {
return this.setChannel("rgb", 0, t)
},
green: function(t) {
return this.setChannel("rgb", 1, t)
},
blue: function(t) {
return this.setChannel("rgb", 2, t)
},
hue: function(t) {
return t && (t = (t %= 360) < 0 ? 360 + t : t), this.setChannel("hsl", 0, t)
},
saturation: function(t) {
return this.setChannel("hsl", 1, t)
},
lightness: function(t) {
return this.setChannel("hsl", 2, t)
},
saturationv: function(t) {
return this.setChannel("hsv", 1, t)
},
whiteness: function(t) {
return this.setChannel("hwb", 1, t)
},
blackness: function(t) {
return this.setChannel("hwb", 2, t)
},
value: function(t) {
return this.setChannel("hsv", 2, t)
},
cyan: function(t) {
return this.setChannel("cmyk", 0, t)
},
magenta: function(t) {
return this.setChannel("cmyk", 1, t)
},
yellow: function(t) {
return this.setChannel("cmyk", 2, t)
},
black: function(t) {
return this.setChannel("cmyk", 3, t)
},
hexString: function() {
return i.hexString(this.values.rgb)
},
rgbString: function() {
return i.rgbString(this.values.rgb, this.values.alpha)
},
rgbaString: function() {
return i.rgbaString(this.values.rgb, this.values.alpha)
},
percentString: function() {
return i.percentString(this.values.rgb, this.values.alpha)
},
hslString: function() {
return i.hslString(this.values.hsl, this.values.alpha)
},
hslaString: function() {
return i.hslaString(this.values.hsl, this.values.alpha)
},
hwbString: function() {
return i.hwbString(this.values.hwb, this.values.alpha)
},
keyword: function() {
return i.keyword(this.values.rgb, this.values.alpha)
},
rgbNumber: function() {
var t = this.values.rgb;
return t[0] << 16 | t[1] << 8 | t[2]
},
luminosity: function() {
for (var t = this.values.rgb, e = [], n = 0; n < t.length; n++) {
var r = t[n] / 255;
e[n] = r <= .03928 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4)
}
return .2126 * e[0] + .7152 * e[1] + .0722 * e[2]
},
contrast: function(t) {
var e = this.luminosity(),
n = t.luminosity();
return e > n ? (e + .05) / (n + .05) : (n + .05) / (e + .05)
},
level: function(t) {
var e = this.contrast(t);
return e >= 7.1 ? "AAA" : e >= 4.5 ? "AA" : ""
},
dark: function() {
var t = this.values.rgb;
return (299 * t[0] + 587 * t[1] + 114 * t[2]) / 1e3 < 128
},
light: function() {
return !this.dark()
},
negate: function() {
for (var t = [], e = 0; e < 3; e++) t[e] = 255 - this.values.rgb[e];
return this.setValues("rgb", t), this
},
lighten: function(t) {
var e = this.values.hsl;
return e[2] += e[2] * t, this.setValues("hsl", e), this
},
darken: function(t) {
var e = this.values.hsl;
return e[2] -= e[2] * t, this.setValues("hsl", e), this
},
saturate: function(t) {
var e = this.values.hsl;
return e[1] += e[1] * t, this.setValues("hsl", e), this
},
desaturate: function(t) {
var e = this.values.hsl;
return e[1] -= e[1] * t, this.setValues("hsl", e), this
},
whiten: function(t) {
var e = this.values.hwb;
return e[1] += e[1] * t, this.setValues("hwb", e), this
},
blacken: function(t) {
var e = this.values.hwb;
return e[2] += e[2] * t, this.setValues("hwb", e), this
},
greyscale: function() {
var t = this.values.rgb,
e = .3 * t[0] + .59 * t[1] + .11 * t[2];
return this.setValues("rgb", [e, e, e]), this
},
clearer: function(t) {
var e = this.values.alpha;
return this.setValues("alpha", e - e * t), this
},
opaquer: function(t) {
var e = this.values.alpha;
return this.setValues("alpha", e + e * t), this
},
rotate: function(t) {
var e = this.values.hsl,
n = (e[0] + t) % 360;
return e[0] = n < 0 ? 360 + n : n, this.setValues("hsl", e), this
},
mix: function(t, e) {
var n = t,
r = void 0 === e ? .5 : e,
i = 2 * r - 1,
o = this.alpha() - n.alpha(),
a = ((i * o == -1 ? i : (i + o) / (1 + i * o)) + 1) / 2,
s = 1 - a;
return this.rgb(a * this.red() + s * n.red(), a * this.green() + s * n.green(), a * this.blue() + s * n.blue()).alpha(this.alpha() * r + n.alpha() * (1 - r))
},
toJSON: function() {
return this.rgb()
},
clone: function() {
var t, e, n = new a,
r = this.values,
i = n.values;
for (var o in r) r.hasOwnProperty(o) && (t = r[o], "[object Array]" === (e = {}.toString.call(t)) ? i[o] = t.slice(0) : "[object Number]" === e ? i[o] = t : console.error("unexpected color value:", t));
return n
}
}).spaces = {
rgb: ["red", "green", "blue"],
hsl: ["hue", "saturation", "lightness"],
hsv: ["hue", "saturation", "value"],
hwb: ["hue", "whiteness", "blackness"],
cmyk: ["cyan", "magenta", "yellow", "black"]
}, a.prototype.maxes = {
rgb: [255, 255, 255],
hsl: [360, 100, 100],
hsv: [360, 100, 100],
hwb: [360, 100, 100],
cmyk: [100, 100, 100, 100]
}, a.prototype.getValues = function(t) {
for (var e = this.values, n = {}, r = 0; r < t.length; r++) n[t.charAt(r)] = e[t][r];
return 1 !== e.alpha && (n.a = e.alpha), n
}, a.prototype.setValues = function(t, e) {
var n, i, o = this.values,
a = this.spaces,
s = this.maxes,
l = 1;
if (this.valid = !0, "alpha" === t) l = e;
else if (e.length) o[t] = e.slice(0, t.length), l = e[t.length];
else if (void 0 !== e[t.charAt(0)]) {
for (n = 0; n < t.length; n++) o[t][n] = e[t.charAt(n)];
l = e.a
} else if (void 0 !== e[a[t][0]]) {
var u = a[t];
for (n = 0; n < t.length; n++) o[t][n] = e[u[n]];
l = e.alpha
}
if (o.alpha = Math.max(0, Math.min(1, void 0 === l ? o.alpha : l)), "alpha" === t) return !1;
for (n = 0; n < t.length; n++) i = Math.max(0, Math.min(s[t][n], o[t][n])), o[t][n] = Math.round(i);
for (var c in a) c !== t && (o[c] = r[t][c](o[t]));
return !0
}, a.prototype.setSpace = function(t, e) {
var n = e[0];
return void 0 === n ? this.getValues(t) : ("number" == typeof n && (n = Array.prototype.slice.call(e)), this.setValues(t, n), this)
}, a.prototype.setChannel = function(t, e, n) {
var r = this.values[t];
return void 0 === n ? r[e] : n === r[e] ? this : (r[e] = n, this.setValues(t, r), this)
}, "undefined" != typeof window && (window.Color = a), e.exports = a
}, {
2: 2,
5: 5
}],
4: [function(t, e, n) {
function i(t) {
var e, n, r = t[0] / 255,
i = t[1] / 255,
o = t[2] / 255,
a = Math.min(r, i, o),
s = Math.max(r, i, o),
l = s - a;
return s == a ? e = 0 : r == s ? e = (i - o) / l : i == s ? e = 2 + (o - r) / l : o == s && (e = 4 + (r - i) / l), (e = Math.min(60 * e, 360)) < 0 && (e += 360), n = (a + s) / 2, [e, 100 * (s == a ? 0 : n <= .5 ? l / (s + a) : l / (2 - s - a)), 100 * n]
}
function o(t) {
var e, n, r = t[0],
i = t[1],
o = t[2],
a = Math.min(r, i, o),
s = Math.max(r, i, o),
l = s - a;
return n = 0 == s ? 0 : l / s * 1e3 / 10, s == a ? e = 0 : r == s ? e = (i - o) / l : i == s ? e = 2 + (o - r) / l : o == s && (e = 4 + (r - i) / l), (e = Math.min(60 * e, 360)) < 0 && (e += 360), [e, n, s / 255 * 1e3 / 10]
}
function a(t) {
var e = t[0],
n = t[1],
r = t[2];
return [i(t)[0], 100 * (1 / 255 * Math.min(e, Math.min(n, r))), 100 * (r = 1 - 1 / 255 * Math.max(e, Math.max(n, r)))]
}
function s(t) {
var e, n = t[0] / 255,
r = t[1] / 255,
i = t[2] / 255;
return [100 * ((1 - n - (e = Math.min(1 - n, 1 - r, 1 - i))) / (1 - e) || 0), 100 * ((1 - r - e) / (1 - e) || 0), 100 * ((1 - i - e) / (1 - e) || 0), 100 * e]
}
function l(t) {
return M[JSON.stringify(t)]
}
function u(t) {
var e = t[0] / 255,
n = t[1] / 255,
r = t[2] / 255;
return [100 * (.4124 * (e = e > .04045 ? Math.pow((e + .055) / 1.055, 2.4) : e / 12.92) + .3576 * (n = n > .04045 ? Math.pow((n + .055) / 1.055, 2.4) : n / 12.92) + .1805 * (r = r > .04045 ? Math.pow((r + .055) / 1.055, 2.4) : r / 12.92)), 100 * (.2126 * e + .7152 * n + .0722 * r), 100 * (.0193 * e + .1192 * n + .9505 * r)]
}
function c(t) {
var e = u(t),
n = e[0],
r = e[1],
i = e[2];
return r /= 100, i /= 108.883, n = (n /= 95.047) > .008856 ? Math.pow(n, 1 / 3) : 7.787 * n + 16 / 116, [116 * (r = r > .008856 ? Math.pow(r, 1 / 3) : 7.787 * r + 16 / 116) - 16, 500 * (n - r), 200 * (r - (i = i > .008856 ? Math.pow(i, 1 / 3) : 7.787 * i + 16 / 116))]
}
function d(t) {
var e, n, r, i, o, a = t[0] / 360,
s = t[1] / 100,
l = t[2] / 100;
if (0 == s) return [o = 255 * l, o, o];
e = 2 * l - (n = l < .5 ? l * (1 + s) : l + s - l * s), i = [0, 0, 0];
for (var u = 0; u < 3; u++)(r = a + 1 / 3 * -(u - 1)) < 0 && r++, r > 1 && r--, o = 6 * r < 1 ? e + 6 * (n - e) * r : 2 * r < 1 ? n : 3 * r < 2 ? e + (n - e) * (2 / 3 - r) * 6 : e, i[u] = 255 * o;
return i
}
function f(t) {
var e = t[0] / 60,
n = t[1] / 100,
r = t[2] / 100,
i = Math.floor(e) % 6,
o = e - Math.floor(e),
a = 255 * r * (1 - n),
s = 255 * r * (1 - n * o),
l = 255 * r * (1 - n * (1 - o));
r *= 255;
switch (i) {
case 0:
return [r, l, a];
case 1:
return [s, r, a];
case 2:
return [a, r, l];
case 3:
return [a, s, r];
case 4:
return [l, a, r];
case 5:
return [r, a, s]
}
}
function h(t) {
var e, n, i, o, a = t[0] / 360,
s = t[1] / 100,
l = t[2] / 100,
u = s + l;
switch (u > 1 && (s /= u, l /= u), i = 6 * a - (e = Math.floor(6 * a)), 0 != (1 & e) && (i = 1 - i), o = s + i * ((n = 1 - l) - s), e) {
default:
case 6:
case 0:
r = n, g = o, b = s;
break;
case 1:
r = o, g = n, b = s;
break;
case 2:
r = s, g = n, b = o;
break;
case 3:
r = s, g = o, b = n;
break;
case 4:
r = o, g = s, b = n;
break;
case 5:
r = n, g = s, b = o
}
return [255 * r, 255 * g, 255 * b]
}
function p(t) {
var e = t[0] / 100,
n = t[1] / 100,
r = t[2] / 100,
i = t[3] / 100;
return [255 * (1 - Math.min(1, e * (1 - i) + i)), 255 * (1 - Math.min(1, n * (1 - i) + i)), 255 * (1 - Math.min(1, r * (1 - i) + i))]
}
function v(t) {
var e, n, r, i = t[0] / 100,
o = t[1] / 100,
a = t[2] / 100;
return n = -.9689 * i + 1.8758 * o + .0415 * a, r = .0557 * i + -.204 * o + 1.057 * a, e = (e = 3.2406 * i + -1.5372 * o + -.4986 * a) > .0031308 ? 1.055 * Math.pow(e, 1 / 2.4) - .055 : e *= 12.92, n = n > .0031308 ? 1.055 * Math.pow(n, 1 / 2.4) - .055 : n *= 12.92, r = r > .0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - .055 : r *= 12.92, [255 * (e = Math.min(Math.max(0, e), 1)), 255 * (n = Math.min(Math.max(0, n), 1)), 255 * (r = Math.min(Math.max(0, r), 1))]
}
function m(t) {
var e = t[0],
n = t[1],
r = t[2];
return n /= 100, r /= 108.883, e = (e /= 95.047) > .008856 ? Math.pow(e, 1 / 3) : 7.787 * e + 16 / 116, [116 * (n = n > .008856 ? Math.pow(n, 1 / 3) : 7.787 * n + 16 / 116) - 16, 500 * (e - n), 200 * (n - (r = r > .008856 ? Math.pow(r, 1 / 3) : 7.787 * r + 16 / 116))]
}
function y(t) {
var e, n, r, i, o = t[0],
a = t[1],
s = t[2];
return o <= 8 ? i = (n = 100 * o / 903.3) / 100 * 7.787 + 16 / 116 : (n = 100 * Math.pow((o + 16) / 116, 3), i = Math.pow(n / 100, 1 / 3)), [e = e / 95.047 <= .008856 ? e = 95.047 * (a / 500 + i - 16 / 116) / 7.787 : 95.047 * Math.pow(a / 500 + i, 3), n, r = r / 108.883 <= .008859 ? r = 108.883 * (i - s / 200 - 16 / 116) / 7.787 : 108.883 * Math.pow(i - s / 200, 3)]
}
function x(t) {
var e, n = t[0],
r = t[1],
i = t[2];
return (e = 360 * Math.atan2(i, r) / 2 / Math.PI) < 0 && (e += 360), [n, Math.sqrt(r * r + i * i), e]
}
function w(t) {
return v(y(t))
}
function S(t) {
var e, n = t[0],
r = t[1];
return e = t[2] / 360 * 2 * Math.PI, [n, r * Math.cos(e), r * Math.sin(e)]
}
function k(t) {
return C[t]
}
e.exports = {
rgb2hsl: i,
rgb2hsv: o,
rgb2hwb: a,
rgb2cmyk: s,
rgb2keyword: l,
rgb2xyz: u,
rgb2lab: c,
rgb2lch: function(t) {
return x(c(t))
},
hsl2rgb: d,
hsl2hsv: function(t) {
var e = t[0],
n = t[1] / 100,
r = t[2] / 100;
if (0 === r) return [0, 0, 0];
return [e, 100 * (2 * (n *= (r *= 2) <= 1 ? r : 2 - r) / (r + n)), 100 * ((r + n) / 2)]
},
hsl2hwb: function(t) {
return a(d(t))
},
hsl2cmyk: function(t) {
return s(d(t))
},
hsl2keyword: function(t) {
return l(d(t))
},
hsv2rgb: f,
hsv2hsl: function(t) {
var e, n, r = t[0],
i = t[1] / 100,
o = t[2] / 100;
return e = i * o, [r, 100 * (e = (e /= (n = (2 - i) * o) <= 1 ? n : 2 - n) || 0), 100 * (n /= 2)]
},
hsv2hwb: function(t) {
return a(f(t))
},
hsv2cmyk: function(t) {
return s(f(t))
},
hsv2keyword: function(t) {
return l(f(t))
},
hwb2rgb: h,
hwb2hsl: function(t) {
return i(h(t))
},
hwb2hsv: function(t) {
return o(h(t))
},
hwb2cmyk: function(t) {
return s(h(t))
},
hwb2keyword: function(t) {
return l(h(t))
},
cmyk2rgb: p,
cmyk2hsl: function(t) {
return i(p(t))
},
cmyk2hsv: function(t) {
return o(p(t))
},
cmyk2hwb: function(t) {
return a(p(t))
},
cmyk2keyword: function(t) {
return l(p(t))
},
keyword2rgb: k,
keyword2hsl: function(t) {
return i(k(t))
},
keyword2hsv: function(t) {
return o(k(t))
},
keyword2hwb: function(t) {
return a(k(t))
},
keyword2cmyk: function(t) {
return s(k(t))
},
keyword2lab: function(t) {
return c(k(t))
},
keyword2xyz: function(t) {
return u(k(t))
},
xyz2rgb: v,
xyz2lab: m,
xyz2lch: function(t) {
return x(m(t))
},
lab2xyz: y,
lab2rgb: w,
lab2lch: x,
lch2lab: S,
lch2xyz: function(t) {
return y(S(t))
},
lch2rgb: function(t) {
return w(S(t))
}
};
var C = {
aliceblue: [240, 248, 255],
antiquewhite: [250, 235, 215],
aqua: [0, 255, 255],
aquamarine: [127, 255, 212],
azure: [240, 255, 255],
beige: [245, 245, 220],
bisque: [255, 228, 196],
black: [0, 0, 0],
blanchedalmond: [255, 235, 205],
blue: [0, 0, 255],
blueviolet: [138, 43, 226],
brown: [165, 42, 42],
burlywood: [222, 184, 135],
cadetblue: [95, 158, 160],
chartreuse: [127, 255, 0],
chocolate: [210, 105, 30],
coral: [255, 127, 80],
cornflowerblue: [100, 149, 237],
cornsilk: [255, 248, 220],
crimson: [220, 20, 60],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgoldenrod: [184, 134, 11],
darkgray: [169, 169, 169],
darkgreen: [0, 100, 0],
darkgrey: [169, 169, 169],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkseagreen: [143, 188, 143],
darkslateblue: [72, 61, 139],
darkslategray: [47, 79, 79],
darkslategrey: [47, 79, 79],
darkturquoise: [0, 206, 209],
darkviolet: [148, 0, 211],
deeppink: [255, 20, 147],
deepskyblue: [0, 191, 255],
dimgray: [105, 105, 105],
dimgrey: [105, 105, 105],
dodgerblue: [30, 144, 255],
firebrick: [178, 34, 34],
floralwhite: [255, 250, 240],
forestgreen: [34, 139, 34],
fuchsia: [255, 0, 255],
gainsboro: [220, 220, 220],
ghostwhite: [248, 248, 255],
gold: [255, 215, 0],
goldenrod: [218, 165, 32],
gray: [128, 128, 128],
green: [0, 128, 0],
greenyellow: [173, 255, 47],
grey: [128, 128, 128],
honeydew: [240, 255, 240],
hotpink: [255, 105, 180],
indianred: [205, 92, 92],
indigo: [75, 0, 130],
ivory: [255, 255, 240],
khaki: [240, 230, 140],
lavender: [230, 230, 250],
lavenderblush: [255, 240, 245],
lawngreen: [124, 252, 0],
lemonchiffon: [255, 250, 205],
lightblue: [173, 216, 230],
lightcoral: [240, 128, 128],
lightcyan: [224, 255, 255],
lightgoldenrodyellow: [250, 250, 210],
lightgray: [211, 211, 211],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightsalmon: [255, 160, 122],
lightseagreen: [32, 178, 170],
lightskyblue: [135, 206, 250],
lightslategray: [119, 136, 153],
lightslategrey: [119, 136, 153],
lightsteelblue: [176, 196, 222],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
limegreen: [50, 205, 50],
linen: [250, 240, 230],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
mediumaquamarine: [102, 205, 170],
mediumblue: [0, 0, 205],
mediumorchid: [186, 85, 211],
mediumpurple: [147, 112, 219],
mediumseagreen: [60, 179, 113],
mediumslateblue: [123, 104, 238],
mediumspringgreen: [0, 250, 154],
mediumturquoise: [72, 209, 204],
mediumvioletred: [199, 21, 133],
midnightblue: [25, 25, 112],
mintcream: [245, 255, 250],
mistyrose: [255, 228, 225],
moccasin: [255, 228, 181],
navajowhite: [255, 222, 173],
navy: [0, 0, 128],
oldlace: [253, 245, 230],
olive: [128, 128, 0],
olivedrab: [107, 142, 35],
orange: [255, 165, 0],
orangered: [255, 69, 0],
orchid: [218, 112, 214],
palegoldenrod: [238, 232, 170],
palegreen: [152, 251, 152],
paleturquoise: [175, 238, 238],
palevioletred: [219, 112, 147],
papayawhip: [255, 239, 213],
peachpuff: [255, 218, 185],
peru: [205, 133, 63],
pink: [255, 192, 203],
plum: [221, 160, 221],
powderblue: [176, 224, 230],
purple: [128, 0, 128],
rebeccapurple: [102, 51, 153],
red: [255, 0, 0],
rosybrown: [188, 143, 143],
royalblue: [65, 105, 225],
saddlebrown: [139, 69, 19],
salmon: [250, 128, 114],
sandybrown: [244, 164, 96],
seagreen: [46, 139, 87],
seashell: [255, 245, 238],
sienna: [160, 82, 45],
silver: [192, 192, 192],
skyblue: [135, 206, 235],
slateblue: [106, 90, 205],
slategray: [112, 128, 144],
slategrey: [112, 128, 144],
snow: [255, 250, 250],
springgreen: [0, 255, 127],
steelblue: [70, 130, 180],
tan: [210, 180, 140],
teal: [0, 128, 128],
thistle: [216, 191, 216],
tomato: [255, 99, 71],
turquoise: [64, 224, 208],
violet: [238, 130, 238],
wheat: [245, 222, 179],
white: [255, 255, 255],
whitesmoke: [245, 245, 245],
yellow: [255, 255, 0],
yellowgreen: [154, 205, 50]
},
M = {};
for (var A in C) M[JSON.stringify(C[A])] = A
}, {}],
5: [function(t, e, n) {
var r = t(4),
i = function() {
return new u
};
for (var o in r) {
i[o + "Raw"] = function(t) {
return function(e) {
return "number" == typeof e && (e = Array.prototype.slice.call(arguments)), r[t](e)
}
}(o);
var a = /(\w+)2(\w+)/.exec(o),
s = a[1],
l = a[2];
(i[s] = i[s] || {})[l] = i[o] = function(t) {
return function(e) {
"number" == typeof e && (e = Array.prototype.slice.call(arguments));
var n = r[t](e);
if ("string" == typeof n || void 0 === n) return n;
for (var i = 0; i < n.length; i++) n[i] = Math.round(n[i]);
return n
}
}(o)
}
var u = function() {
this.convs = {}
};
u.prototype.routeSpace = function(t, e) {
var n = e[0];
return void 0 === n ? this.getValues(t) : ("number" == typeof n && (n = Array.prototype.slice.call(e)), this.setValues(t, n))
}, u.prototype.setValues = function(t, e) {
return this.space = t, this.convs = {}, this.convs[t] = e, this
}, u.prototype.getValues = function(t) {
var e = this.convs[t];
if (!e) {
var n = this.space,
r = this.convs[n];
e = i[n][t](r), this.convs[t] = e
}
return e
}, ["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach((function(t) {
u.prototype[t] = function(e) {
return this.routeSpace(t, arguments)
}
})), e.exports = i
}, {
4: 4
}],
6: [function(t, e, n) {
e.exports = {
aliceblue: [240, 248, 255],
antiquewhite: [250, 235, 215],
aqua: [0, 255, 255],
aquamarine: [127, 255, 212],
azure: [240, 255, 255],
beige: [245, 245, 220],
bisque: [255, 228, 196],
black: [0, 0, 0],
blanchedalmond: [255, 235, 205],
blue: [0, 0, 255],
blueviolet: [138, 43, 226],
brown: [165, 42, 42],
burlywood: [222, 184, 135],
cadetblue: [95, 158, 160],
chartreuse: [127, 255, 0],
chocolate: [210, 105, 30],
coral: [255, 127, 80],
cornflowerblue: [100, 149, 237],
cornsilk: [255, 248, 220],
crimson: [220, 20, 60],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgoldenrod: [184, 134, 11],
darkgray: [169, 169, 169],
darkgreen: [0, 100, 0],
darkgrey: [169, 169, 169],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkseagreen: [143, 188, 143],
darkslateblue: [72, 61, 139],
darkslategray: [47, 79, 79],
darkslategrey: [47, 79, 79],
darkturquoise: [0, 206, 209],
darkviolet: [148, 0, 211],
deeppink: [255, 20, 147],
deepskyblue: [0, 191, 255],
dimgray: [105, 105, 105],
dimgrey: [105, 105, 105],
dodgerblue: [30, 144, 255],
firebrick: [178, 34, 34],
floralwhite: [255, 250, 240],
forestgreen: [34, 139, 34],
fuchsia: [255, 0, 255],
gainsboro: [220, 220, 220],
ghostwhite: [248, 248, 255],
gold: [255, 215, 0],
goldenrod: [218, 165, 32],
gray: [128, 128, 128],
green: [0, 128, 0],
greenyellow: [173, 255, 47],
grey: [128, 128, 128],
honeydew: [240, 255, 240],
hotpink: [255, 105, 180],
indianred: [205, 92, 92],
indigo: [75, 0, 130],
ivory: [255, 255, 240],
khaki: [240, 230, 140],
lavender: [230, 230, 250],
lavenderblush: [255, 240, 245],
lawngreen: [124, 252, 0],
lemonchiffon: [255, 250, 205],
lightblue: [173, 216, 230],
lightcoral: [240, 128, 128],
lightcyan: [224, 255, 255],
lightgoldenrodyellow: [250, 250, 210],
lightgray: [211, 211, 211],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightsalmon: [255, 160, 122],
lightseagreen: [32, 178, 170],
lightskyblue: [135, 206, 250],
lightslategray: [119, 136, 153],
lightslategrey: [119, 136, 153],
lightsteelblue: [176, 196, 222],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
limegreen: [50, 205, 50],
linen: [250, 240, 230],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
mediumaquamarine: [102, 205, 170],
mediumblue: [0, 0, 205],
mediumorchid: [186, 85, 211],
mediumpurple: [147, 112, 219],
mediumseagreen: [60, 179, 113],
mediumslateblue: [123, 104, 238],
mediumspringgreen: [0, 250, 154],
mediumturquoise: [72, 209, 204],
mediumvioletred: [199, 21, 133],
midnightblue: [25, 25, 112],
mintcream: [245, 255, 250],
mistyrose: [255, 228, 225],
moccasin: [255, 228, 181],
navajowhite: [255, 222, 173],
navy: [0, 0, 128],
oldlace: [253, 245, 230],
olive: [128, 128, 0],
olivedrab: [107, 142, 35],
orange: [255, 165, 0],
orangered: [255, 69, 0],
orchid: [218, 112, 214],
palegoldenrod: [238, 232, 170],
palegreen: [152, 251, 152],
paleturquoise: [175, 238, 238],
palevioletred: [219, 112, 147],
papayawhip: [255, 239, 213],
peachpuff: [255, 218, 185],
peru: [205, 133, 63],
pink: [255, 192, 203],
plum: [221, 160, 221],
powderblue: [176, 224, 230],
purple: [128, 0, 128],
rebeccapurple: [102, 51, 153],
red: [255, 0, 0],
rosybrown: [188, 143, 143],
royalblue: [65, 105, 225],
saddlebrown: [139, 69, 19],
salmon: [250, 128, 114],
sandybrown: [244, 164, 96],
seagreen: [46, 139, 87],
seashell: [255, 245, 238],
sienna: [160, 82, 45],
silver: [192, 192, 192],
skyblue: [135, 206, 235],
slateblue: [106, 90, 205],
slategray: [112, 128, 144],
slategrey: [112, 128, 144],
snow: [255, 250, 250],
springgreen: [0, 255, 127],
steelblue: [70, 130, 180],
tan: [210, 180, 140],
teal: [0, 128, 128],
thistle: [216, 191, 216],
tomato: [255, 99, 71],
turquoise: [64, 224, 208],
violet: [238, 130, 238],
wheat: [245, 222, 179],
white: [255, 255, 255],
whitesmoke: [245, 245, 245],
yellow: [255, 255, 0],
yellowgreen: [154, 205, 50]
}
}, {}],
7: [function(t, e, n) {
var r = t(30)();
r.helpers = t(46), t(28)(r), r.Animation = t(22), r.animationService = t(23), r.defaults = t(26), r.Element = t(27), r.elements = t(41), r.Interaction = t(29), r.layouts = t(31), r.platform = t(49), r.plugins = t(32), r.Scale = t(33), r.scaleService = t(34), r.Ticks = t(35), r.Tooltip = t(36), t(24)(r), t(25)(r), t(56)(r), t(54)(r), t(55)(r), t(57)(r), t(58)(r), t(59)(r), t(15)(r), t(16)(r), t(17)(r), t(18)(r), t(19)(r), t(20)(r), t(21)(r), t(8)(r), t(9)(r), t(10)(r), t(11)(r), t(12)(r), t(13)(r), t(14)(r);
var i = t(50);
for (var o in i) i.hasOwnProperty(o) && r.plugins.register(i[o]);
r.platform.initialize(), e.exports = r, "undefined" != typeof window && (window.Chart = r), r.Legend = i.legend._element, r.Title = i.title._element, r.pluginService = r.plugins, r.PluginBase = r.Element.extend({}), r.canvasHelpers = r.helpers.canvas, r.layoutService = r.layouts
}, {
10: 10,
11: 11,
12: 12,
13: 13,
14: 14,
15: 15,
16: 16,
17: 17,
18: 18,
19: 19,
20: 20,
21: 21,
22: 22,
23: 23,
24: 24,
25: 25,
26: 26,
27: 27,
28: 28,
29: 29,
30: 30,
31: 31,
32: 32,
33: 33,
34: 34,
35: 35,
36: 36,
41: 41,
46: 46,
49: 49,
50: 50,
54: 54,
55: 55,
56: 56,
57: 57,
58: 58,
59: 59,
8: 8,
9: 9
}],
8: [function(t, e, n) {
e.exports = function(t) {
t.Bar = function(e, n) {
return n.type = "bar", new t(e, n)
}
}
}, {}],
9: [function(t, e, n) {
e.exports = function(t) {
t.Bubble = function(e, n) {
return n.type = "bubble", new t(e, n)
}
}
}, {}],
10: [function(t, e, n) {
e.exports = function(t) {
t.Doughnut = function(e, n) {
return n.type = "doughnut", new t(e, n)
}
}
}, {}],
11: [function(t, e, n) {
e.exports = function(t) {
t.Line = function(e, n) {
return n.type = "line", new t(e, n)
}
}
}, {}],
12: [function(t, e, n) {
e.exports = function(t) {
t.PolarArea = function(e, n) {
return n.type = "polarArea", new t(e, n)
}
}
}, {}],
13: [function(t, e, n) {
e.exports = function(t) {
t.Radar = function(e, n) {
return n.type = "radar", new t(e, n)
}
}
}, {}],
14: [function(t, e, n) {
e.exports = function(t) {
t.Scatter = function(e, n) {
return n.type = "scatter", new t(e, n)
}
}
}, {}],
15: [function(t, e, n) {
var r = t(26),
i = t(41),
o = t(46);
r._set("bar", {
hover: {
mode: "label"
},
scales: {
xAxes: [{
type: "category",
categoryPercentage: .8,
barPercentage: .9,
offset: !0,
gridLines: {
offsetGridLines: !0
}
}],
yAxes: [{
type: "linear"
}]
}
}), r._set("horizontalBar", {
hover: {
mode: "index",
axis: "y"
},
scales: {
xAxes: [{
type: "linear",
position: "bottom"
}],
yAxes: [{
position: "left",
type: "category",
categoryPercentage: .8,
barPercentage: .9,
offset: !0,
gridLines: {
offsetGridLines: !0
}
}]
},
elements: {
rectangle: {
borderSkipped: "left"
}
},
tooltips: {
callbacks: {
title: function(t, e) {
var n = "";
return t.length > 0 && (t[0].yLabel ? n = t[0].yLabel : e.labels.length > 0 && t[0].index < e.labels.length && (n = e.labels[t[0].index])), n
},
label: function(t, e) {
return (e.datasets[t.datasetIndex].label || "") + ": " + t.xLabel
}
},
mode: "index",
axis: "y"
}
}), e.exports = function(t) {
t.controllers.bar = t.DatasetController.extend({
dataElementType: i.Rectangle,
initialize: function() {
var e, n = this;
t.DatasetController.prototype.initialize.apply(n, arguments), (e = n.getMeta()).stack = n.getDataset().stack, e.bar = !0
},
update: function(t) {
var e, n, r = this.getMeta().data;
for (this._ruler = this.getRuler(), e = 0, n = r.length; e < n; ++e) this.updateElement(r[e], e, t)
},
updateElement: function(t, e, n) {
var r = this,
i = r.chart,
a = r.getMeta(),
s = r.getDataset(),
l = t.custom || {},
u = i.options.elements.rectangle;
t._xScale = r.getScaleForId(a.xAxisID), t._yScale = r.getScaleForId(a.yAxisID), t._datasetIndex = r.index, t._index = e, t._model = {
datasetLabel: s.label,
label: i.data.labels[e],
borderSkipped: l.borderSkipped ? l.borderSkipped : u.borderSkipped,
backgroundColor: l.backgroundColor ? l.backgroundColor : o.valueAtIndexOrDefault(s.backgroundColor, e, u.backgroundColor),
borderColor: l.borderColor ? l.borderColor : o.valueAtIndexOrDefault(s.borderColor, e, u.borderColor),
borderWidth: l.borderWidth ? l.borderWidth : o.valueAtIndexOrDefault(s.borderWidth, e, u.borderWidth)
}, r.updateElementGeometry(t, e, n), t.pivot()
},
updateElementGeometry: function(t, e, n) {
var r = this,
i = t._model,
o = r.getValueScale(),
a = o.getBasePixel(),
s = o.isHorizontal(),
l = r._ruler || r.getRuler(),
u = r.calculateBarValuePixels(r.index, e),
c = r.calculateBarIndexPixels(r.index, e, l);
i.horizontal = s, i.base = n ? a : u.base, i.x = s ? n ? a : u.head : c.center, i.y = s ? c.center : n ? a : u.head, i.height = s ? c.size : void 0, i.width = s ? void 0 : c.size
},
getValueScaleId: function() {
return this.getMeta().yAxisID
},
getIndexScaleId: function() {
return this.getMeta().xAxisID
},
getValueScale: function() {
return this.getScaleForId(this.getValueScaleId())
},
getIndexScale: function() {
return this.getScaleForId(this.getIndexScaleId())
},
_getStacks: function(t) {
var e, n, r = this.chart,
i = this.getIndexScale().options.stacked,
o = void 0 === t ? r.data.datasets.length : t + 1,
a = [];
for (e = 0; e < o; ++e)(n = r.getDatasetMeta(e)).bar && r.isDatasetVisible(e) && (!1 === i || !0 === i && -1 === a.indexOf(n.stack) || void 0 === i && (void 0 === n.stack || -1 === a.indexOf(n.stack))) && a.push(n.stack);
return a
},
getStackCount: function() {
return this._getStacks().length
},
getStackIndex: function(t, e) {
var n = this._getStacks(t),
r = void 0 !== e ? n.indexOf(e) : -1;
return -1 === r ? n.length - 1 : r
},
getRuler: function() {
var t, e, n = this.getIndexScale(),
r = this.getStackCount(),
i = this.index,
a = n.isHorizontal(),
s = a ? n.left : n.top,
l = s + (a ? n.width : n.height),
u = [];
for (t = 0, e = this.getMeta().data.length; t < e; ++t) u.push(n.getPixelForValue(null, t, i));
return {
min: o.isNullOrUndef(n.options.barThickness) ? function(t, e) {
var n, r, i, o, a = t.isHorizontal() ? t.width : t.height,
s = t.getTicks();
for (i = 1, o = e.length; i < o; ++i) a = Math.min(a, e[i] - e[i - 1]);
for (i = 0, o = s.length; i < o; ++i) r = t.getPixelForTick(i), a = i > 0 ? Math.min(a, r - n) : a, n = r;
return a
}(n, u) : -1,
pixels: u,
start: s,
end: l,
stackCount: r,
scale: n
}
},
calculateBarValuePixels: function(t, e) {
var n, r, i, o, a, s, l = this.chart,
u = this.getMeta(),
c = this.getValueScale(),
d = l.data.datasets,
f = c.getRightValue(d[t].data[e]),
h = c.options.stacked,
p = u.stack,
g = 0;
if (h || void 0 === h && void 0 !== p)
for (n = 0; n < t; ++n)(r = l.getDatasetMeta(n)).bar && r.stack === p && r.controller.getValueScaleId() === c.id && l.isDatasetVisible(n) && (i = c.getRightValue(d[n].data[e]), (f < 0 && i < 0 || f >= 0 && i > 0) && (g += i));
return o = c.getPixelForValue(g), {
size: s = ((a = c.getPixelForValue(g + f)) - o) / 2,
base: o,
head: a,
center: a + s / 2
}
},
calculateBarIndexPixels: function(t, e, n) {
var r = n.scale.options,
i = "flex" === r.barThickness ? function(t, e, n) {
var r, i = e.pixels,
o = i[t],
a = t > 0 ? i[t - 1] : null,
s = t < i.length - 1 ? i[t + 1] : null,
l = n.categoryPercentage;
return null === a && (a = o - (null === s ? e.end - o : s - o)), null === s && (s = o + o - a), r = o - (o - a) / 2 * l, {
chunk: (s - a) / 2 * l / e.stackCount,
ratio: n.barPercentage,
start: r
}
}(e, n, r) : function(t, e, n) {
var r, i, a = n.barThickness,
s = e.stackCount,
l = e.pixels[t];
return o.isNullOrUndef(a) ? (r = e.min * n.categoryPercentage, i = n.barPercentage) : (r = a * s, i = 1), {
chunk: r / s,
ratio: i,
start: l - r / 2
}
}(e, n, r),
a = this.getStackIndex(t, this.getMeta().stack),
s = i.start + i.chunk * a + i.chunk / 2,
l = Math.min(o.valueOrDefault(r.maxBarThickness, 1 / 0), i.chunk * i.ratio);
return {
base: s - l / 2,
head: s + l / 2,
center: s,
size: l
}
},
draw: function() {
var t = this.chart,
e = this.getValueScale(),
n = this.getMeta().data,
r = this.getDataset(),
i = n.length,
a = 0;
for (o.canvas.clipArea(t.ctx, t.chartArea); a < i; ++a) isNaN(e.getRightValue(r.data[a])) || n[a].draw();
o.canvas.unclipArea(t.ctx)
}
}), t.controllers.horizontalBar = t.controllers.bar.extend({
getValueScaleId: function() {
return this.getMeta().xAxisID
},
getIndexScaleId: function() {
return this.getMeta().yAxisID
}
})
}
}, {
26: 26,
41: 41,
46: 46
}],
16: [function(t, e, n) {
var r = t(26),
i = t(41),
a = t(46);
r._set("bubble", {
hover: {
mode: "single"
},
scales: {
xAxes: [{
type: "linear",
position: "bottom",
id: "x-axis-0"
}],
yAxes: [{
type: "linear",
position: "left",
id: "y-axis-0"
}]
},
tooltips: {
callbacks: {
title: function() {
return ""
},
label: function(t, e) {
var n = e.datasets[t.datasetIndex].label || "",
r = e.datasets[t.datasetIndex].data[t.index];
return n + ": (" + t.xLabel + ", " + t.yLabel + ", " + r.r + ")"
}
}
}
}), e.exports = function(t) {
t.controllers.bubble = t.DatasetController.extend({
dataElementType: i.Point,
update: function(t) {
var e = this,
n = e.getMeta().data;
a.each(n, (function(n, r) {
e.updateElement(n, r, t)
}))
},
updateElement: function(t, e, n) {
var r = this,
i = r.getMeta(),
a = t.custom || {},
s = r.getScaleForId(i.xAxisID),
l = r.getScaleForId(i.yAxisID),
u = r._resolveElementOptions(t, e),
c = r.getDataset().data[e],
d = r.index,
f = n ? s.getPixelForDecimal(.5) : s.getPixelForValue("object" === o(c) ? c : NaN, e, d),
h = n ? l.getBasePixel() : l.getPixelForValue(c, e, d);
t._xScale = s, t._yScale = l, t._options = u, t._datasetIndex = d, t._index = e, t._model = {
backgroundColor: u.backgroundColor,
borderColor: u.borderColor,
borderWidth: u.borderWidth,
hitRadius: u.hitRadius,
pointStyle: u.pointStyle,
rotation: u.rotation,
radius: n ? 0 : u.radius,
skip: a.skip || isNaN(f) || isNaN(h),
x: f,
y: h
}, t.pivot()
},
setHoverStyle: function(t) {
var e = t._model,
n = t._options;
t.$previousStyle = {
backgroundColor: e.backgroundColor,
borderColor: e.borderColor,
borderWidth: e.borderWidth,
radius: e.radius
}, e.backgroundColor = a.valueOrDefault(n.hoverBackgroundColor, a.getHoverColor(n.backgroundColor)), e.borderColor = a.valueOrDefault(n.hoverBorderColor, a.getHoverColor(n.borderColor)), e.borderWidth = a.valueOrDefault(n.hoverBorderWidth, n.borderWidth), e.radius = n.radius + n.hoverRadius
},
_resolveElementOptions: function(t, e) {
var n, r, i, o = this.chart,
s = o.data.datasets[this.index],
l = t.custom || {},
u = o.options.elements.point,
c = a.options.resolve,
d = s.data[e],
f = {},
h = {
chart: o,
dataIndex: e,
dataset: s,
datasetIndex: this.index
},
p = ["backgroundColor", "borderColor", "borderWidth", "hoverBackgroundColor", "hoverBorderColor", "hoverBorderWidth", "hoverRadius", "hitRadius", "pointStyle", "rotation"];
for (n = 0, r = p.length; n < r; ++n) f[i = p[n]] = c([l[i], s[i], u[i]], h, e);
return f.radius = c([l.radius, d ? d.r : void 0, s.radius, u.radius], h, e), f
}
})
}
}, {
26: 26,
41: 41,
46: 46
}],
17: [function(t, e, n) {
var r = t(26),
i = t(41),
o = t(46);
r._set("doughnut", {
animation: {
animateRotate: !0,
animateScale: !1
},
hover: {
mode: "single"
},
legendCallback: function(t) {
var e = [];
e.push('<ul class="' + t.id + '-legend">');
var n = t.data,
r = n.datasets,
i = n.labels;
if (r.length)
for (var o = 0; o < r[0].data.length; ++o) e.push('<li><span style="background-color:' + r[0].backgroundColor[o] + '"></span>'), i[o] && e.push(i[o]), e.push("</li>");
return e.push("</ul>"), e.join("")
},
legend: {
labels: {
generateLabels: function(t) {
var e = t.data;
return e.labels.length && e.datasets.length ? e.labels.map((function(n, r) {
var i = t.getDatasetMeta(0),
a = e.datasets[0],
s = i.data[r],
l = s && s.custom || {},
u = o.valueAtIndexOrDefault,
c = t.options.elements.arc;
return {
text: n,
fillStyle: l.backgroundColor ? l.backgroundColor : u(a.backgroundColor, r, c.backgroundColor),
strokeStyle: l.borderColor ? l.borderColor : u(a.borderColor, r, c.borderColor),
lineWidth: l.borderWidth ? l.borderWidth : u(a.borderWidth, r, c.borderWidth),
hidden: isNaN(a.data[r]) || i.data[r].hidden,
index: r
}
})) : []
}
},
onClick: function(t, e) {
var n, r, i, o = e.index,
a = this.chart;
for (n = 0, r = (a.data.datasets || []).length; n < r; ++n)(i = a.getDatasetMeta(n)).data[o] && (i.data[o].hidden = !i.data[o].hidden);
a.update()
}
},
cutoutPercentage: 50,
rotation: -.5 * Math.PI,
circumference: 2 * Math.PI,
tooltips: {
callbacks: {
title: function() {
return ""
},
label: function(t, e) {
var n = e.labels[t.index],
r = ": " + e.datasets[t.datasetIndex].data[t.index];
return o.isArray(n) ? (n = n.slice())[0] += r : n += r, n
}
}
}
}), r._set("pie", o.clone(r.doughnut)), r._set("pie", {
cutoutPercentage: 0
}), e.exports = function(t) {
t.controllers.doughnut = t.controllers.pie = t.DatasetController.extend({
dataElementType: i.Arc,
linkScales: o.noop,
getRingIndex: function(t) {
for (var e = 0, n = 0; n < t; ++n) this.chart.isDatasetVisible(n) && ++e;
return e
},
update: function(t) {
var e = this,
n = e.chart,
r = n.chartArea,
i = n.options,
a = i.elements.arc,
s = r.right - r.left - a.borderWidth,
l = r.bottom - r.top - a.borderWidth,
u = Math.min(s, l),
c = {
x: 0,
y: 0
},
d = e.getMeta(),
f = i.cutoutPercentage,
h = i.circumference;
if (h < 2 * Math.PI) {
var p = i.rotation % (2 * Math.PI),
g = (p += 2 * Math.PI * (p >= Math.PI ? -1 : p < -Math.PI ? 1 : 0)) + h,
v = {
x: Math.cos(p),
y: Math.sin(p)
},
m = {
x: Math.cos(g),
y: Math.sin(g)
},
y = p <= 0 && g >= 0 || p <= 2 * Math.PI && 2 * Math.PI <= g,
b = p <= .5 * Math.PI && .5 * Math.PI <= g || p <= 2.5 * Math.PI && 2.5 * Math.PI <= g,
x = p <= -Math.PI && -Math.PI <= g || p <= Math.PI && Math.PI <= g,
w = p <= .5 * -Math.PI && .5 * -Math.PI <= g || p <= 1.5 * Math.PI && 1.5 * Math.PI <= g,
S = f / 100,
k = {
x: x ? -1 : Math.min(v.x * (v.x < 0 ? 1 : S), m.x * (m.x < 0 ? 1 : S)),
y: w ? -1 : Math.min(v.y * (v.y < 0 ? 1 : S), m.y * (m.y < 0 ? 1 : S))
},
C = {
x: y ? 1 : Math.max(v.x * (v.x > 0 ? 1 : S), m.x * (m.x > 0 ? 1 : S)),
y: b ? 1 : Math.max(v.y * (v.y > 0 ? 1 : S), m.y * (m.y > 0 ? 1 : S))
},
M = {
width: .5 * (C.x - k.x),
height: .5 * (C.y - k.y)
};
u = Math.min(s / M.width, l / M.height), c = {
x: -.5 * (C.x + k.x),
y: -.5 * (C.y + k.y)
}
}
n.borderWidth = e.getMaxBorderWidth(d.data), n.outerRadius = Math.max((u - n.borderWidth) / 2, 0), n.innerRadius = Math.max(f ? n.outerRadius / 100 * f : 0, 0), n.radiusLength = (n.outerRadius - n.innerRadius) / n.getVisibleDatasetCount(), n.offsetX = c.x * n.outerRadius, n.offsetY = c.y * n.outerRadius, d.total = e.calculateTotal(), e.outerRadius = n.outerRadius - n.radiusLength * e.getRingIndex(e.index), e.innerRadius = Math.max(e.outerRadius - n.radiusLength, 0), o.each(d.data, (function(n, r) {
e.updateElement(n, r, t)
}))
},
updateElement: function(t, e, n) {
var r = this,
i = r.chart,
a = i.chartArea,
s = i.options,
l = s.animation,
u = (a.left + a.right) / 2,
c = (a.top + a.bottom) / 2,
d = s.rotation,
f = s.rotation,
h = r.getDataset(),
p = n && l.animateRotate ? 0 : t.hidden ? 0 : r.calculateCircumference(h.data[e]) * (s.circumference / (2 * Math.PI)),
g = n && l.animateScale ? 0 : r.innerRadius,
v = n && l.animateScale ? 0 : r.outerRadius,
m = o.valueAtIndexOrDefault;
o.extend(t, {
_datasetIndex: r.index,
_index: e,
_model: {
x: u + i.offsetX,
y: c + i.offsetY,
startAngle: d,
endAngle: f,
circumference: p,
outerRadius: v,
innerRadius: g,
label: m(h.label, e, i.data.labels[e])
}
});
var y = t._model,
b = t.custom || {},
x = o.valueAtIndexOrDefault,
w = this.chart.options.elements.arc;
y.backgroundColor = b.backgroundColor ? b.backgroundColor : x(h.backgroundColor, e, w.backgroundColor), y.borderColor = b.borderColor ? b.borderColor : x(h.borderColor, e, w.borderColor), y.borderWidth = b.borderWidth ? b.borderWidth : x(h.borderWidth, e, w.borderWidth), n && l.animateRotate || (y.startAngle = 0 === e ? s.rotation : r.getMeta().data[e - 1]._model.endAngle, y.endAngle = y.startAngle + y.circumference), t.pivot()
},
calculateTotal: function() {
var t, e = this.getDataset(),
n = this.getMeta(),
r = 0;
return o.each(n.data, (function(n, i) {
t = e.data[i], isNaN(t) || n.hidden || (r += Math.abs(t))
})), r
},
calculateCircumference: function(t) {
var e = this.getMeta().total;
return e > 0 && !isNaN(t) ? 2 * Math.PI * (Math.abs(t) / e) : 0
},
getMaxBorderWidth: function(t) {
for (var e, n, r = 0, i = this.index, o = t.length, a = 0; a < o; a++) e = t[a]._model ? t[a]._model.borderWidth : 0, r = (n = t[a]._chart ? t[a]._chart.config.data.datasets[i].hoverBorderWidth : 0) > (r = e > r ? e : r) ? n : r;
return r
}
})
}
}, {
26: 26,
41: 41,
46: 46
}],
18: [function(t, e, n) {
var r = t(26),
i = t(41),
a = t(46);
r._set("line", {
showLines: !0,
spanGaps: !1,
hover: {
mode: "label"
},
scales: {
xAxes: [{
type: "category",
id: "x-axis-0"
}],
yAxes: [{
type: "linear",
id: "y-axis-0"
}]
}
}), e.exports = function(t) {
function e(t, e) {
return a.valueOrDefault(t.showLine, e.showLines)
}
t.controllers.line = t.DatasetController.extend({
datasetElementType: i.Line,
dataElementType: i.Point,
update: function(t) {
var n, r, i, o = this,
s = o.getMeta(),
l = s.dataset,
u = s.data || [],
c = o.chart.options,
d = c.elements.line,
f = o.getScaleForId(s.yAxisID),
h = o.getDataset(),
p = e(h, c);
for (p && (i = l.custom || {}, void 0 !== h.tension && void 0 === h.lineTension && (h.lineTension = h.tension), l._scale = f, l._datasetIndex = o.index, l._children = u, l._model = {
spanGaps: h.spanGaps ? h.spanGaps : c.spanGaps,
tension: i.tension ? i.tension : a.valueOrDefault(h.lineTension, d.tension),
backgroundColor: i.backgroundColor ? i.backgroundColor : h.backgroundColor || d.backgroundColor,
borderWidth: i.borderWidth ? i.borderWidth : h.borderWidth || d.borderWidth,
borderColor: i.borderColor ? i.borderColor : h.borderColor || d.borderColor,
borderCapStyle: i.borderCapStyle ? i.borderCapStyle : h.borderCapStyle || d.borderCapStyle,
borderDash: i.borderDash ? i.borderDash : h.borderDash || d.borderDash,
borderDashOffset: i.borderDashOffset ? i.borderDashOffset : h.borderDashOffset || d.borderDashOffset,
borderJoinStyle: i.borderJoinStyle ? i.borderJoinStyle : h.borderJoinStyle || d.borderJoinStyle,
fill: i.fill ? i.fill : void 0 !== h.fill ? h.fill : d.fill,
steppedLine: i.steppedLine ? i.steppedLine : a.valueOrDefault(h.steppedLine, d.stepped),
cubicInterpolationMode: i.cubicInterpolationMode ? i.cubicInterpolationMode : a.valueOrDefault(h.cubicInterpolationMode, d.cubicInterpolationMode)
}, l.pivot()), n = 0, r = u.length; n < r; ++n) o.updateElement(u[n], n, t);
for (p && 0 !== l._model.tension && o.updateBezierControlPoints(), n = 0, r = u.length; n < r; ++n) u[n].pivot()
},
getPointBackgroundColor: function(t, e) {
var n = this.chart.options.elements.point.backgroundColor,
r = this.getDataset(),
i = t.custom || {};
return i.backgroundColor ? n = i.backgroundColor : r.pointBackgroundColor ? n = a.valueAtIndexOrDefault(r.pointBackgroundColor, e, n) : r.backgroundColor && (n = r.backgroundColor), n
},
getPointBorderColor: function(t, e) {
var n = this.chart.options.elements.point.borderColor,
r = this.getDataset(),
i = t.custom || {};
return i.borderColor ? n = i.borderColor : r.pointBorderColor ? n = a.valueAtIndexOrDefault(r.pointBorderColor, e, n) : r.borderColor && (n = r.borderColor), n
},
getPointBorderWidth: function(t, e) {
var n = this.chart.options.elements.point.borderWidth,
r = this.getDataset(),
i = t.custom || {};
return isNaN(i.borderWidth) ? !isNaN(r.pointBorderWidth) || a.isArray(r.pointBorderWidth) ? n = a.valueAtIndexOrDefault(r.pointBorderWidth, e, n) : isNaN(r.borderWidth) || (n = r.borderWidth) : n = i.borderWidth, n
},
getPointRotation: function(t, e) {
var n = this.chart.options.elements.point.rotation,
r = this.getDataset(),
i = t.custom || {};
return isNaN(i.rotation) ? isNaN(r.pointRotation) && !a.isArray(r.pointRotation) || (n = a.valueAtIndexOrDefault(r.pointRotation, e, n)) : n = i.rotation, n
},
updateElement: function(t, e, n) {
var r, i, s = this,
l = s.getMeta(),
u = t.custom || {},
c = s.getDataset(),
d = s.index,
f = c.data[e],
h = s.getScaleForId(l.yAxisID),
p = s.getScaleForId(l.xAxisID),
g = s.chart.options.elements.point;
void 0 !== c.radius && void 0 === c.pointRadius && (c.pointRadius = c.radius), void 0 !== c.hitRadius && void 0 === c.pointHitRadius && (c.pointHitRadius = c.hitRadius), r = p.getPixelForValue("object" === o(f) ? f : NaN, e, d), i = n ? h.getBasePixel() : s.calculatePointY(f, e, d), t._xScale = p, t._yScale = h, t._datasetIndex = d, t._index = e, t._model = {
x: r,
y: i,
skip: u.skip || isNaN(r) || isNaN(i),
radius: u.radius || a.valueAtIndexOrDefault(c.pointRadius, e, g.radius),
pointStyle: u.pointStyle || a.valueAtIndexOrDefault(c.pointStyle, e, g.pointStyle),
rotation: s.getPointRotation(t, e),
backgroundColor: s.getPointBackgroundColor(t, e),
borderColor: s.getPointBorderColor(t, e),
borderWidth: s.getPointBorderWidth(t, e),
tension: l.dataset._model ? l.dataset._model.tension : 0,
steppedLine: !!l.dataset._model && l.dataset._model.steppedLine,
hitRadius: u.hitRadius || a.valueAtIndexOrDefault(c.pointHitRadius, e, g.hitRadius)
}
},
calculatePointY: function(t, e, n) {
var r, i, o, a = this.chart,
s = this.getMeta(),
l = this.getScaleForId(s.yAxisID),
u = 0,
c = 0;
if (l.options.stacked) {
for (r = 0; r < n; r++)
if (i = a.data.datasets[r], "line" === (o = a.getDatasetMeta(r)).type && o.yAxisID === l.id && a.isDatasetVisible(r)) {
var d = Number(l.getRightValue(i.data[e]));
d < 0 ? c += d || 0 : u += d || 0
} var f = Number(l.getRightValue(t));
return f < 0 ? l.getPixelForValue(c + f) : l.getPixelForValue(u + f)
}
return l.getPixelForValue(t)
},
updateBezierControlPoints: function() {
var t, e, n, r, i = this.getMeta(),
o = this.chart.chartArea,
s = i.data || [];
function l(t, e, n) {
return Math.max(Math.min(t, n), e)
}
if (i.dataset._model.spanGaps && (s = s.filter((function(t) {
return !t._model.skip
}))), "monotone" === i.dataset._model.cubicInterpolationMode) a.splineCurveMonotone(s);
else
for (t = 0, e = s.length; t < e; ++t) n = s[t]._model, r = a.splineCurve(a.previousItem(s, t)._model, n, a.nextItem(s, t)._model, i.dataset._model.tension), n.controlPointPreviousX = r.previous.x, n.controlPointPreviousY = r.previous.y, n.controlPointNextX = r.next.x, n.controlPointNextY = r.next.y;
if (this.chart.options.elements.line.capBezierPoints)
for (t = 0, e = s.length; t < e; ++t)(n = s[t]._model).controlPointPreviousX = l(n.controlPointPreviousX, o.left, o.right), n.controlPointPreviousY = l(n.controlPointPreviousY, o.top, o.bottom), n.controlPointNextX = l(n.controlPointNextX, o.left, o.right), n.controlPointNextY = l(n.controlPointNextY, o.top, o.bottom)
},
draw: function() {
var t, n = this.chart,
r = this.getMeta(),
i = r.data || [],
o = n.chartArea,
s = i.length,
l = 0;
for (e(this.getDataset(), n.options) && (t = (r.dataset._model.borderWidth || 0) / 2, a.canvas.clipArea(n.ctx, {
left: o.left,
right: o.right,
top: o.top - t,
bottom: o.bottom + t
}), r.dataset.draw(), a.canvas.unclipArea(n.ctx)); l < s; ++l) i[l].draw(o)
},
setHoverStyle: function(t) {
var e = this.chart.data.datasets[t._datasetIndex],
n = t._index,
r = t.custom || {},
i = t._model;
t.$previousStyle = {
backgroundColor: i.backgroundColor,
borderColor: i.borderColor,
borderWidth: i.borderWidth,
radius: i.radius
}, i.backgroundColor = r.hoverBackgroundColor || a.valueAtIndexOrDefault(e.pointHoverBackgroundColor, n, a.getHoverColor(i.backgroundColor)), i.borderColor = r.hoverBorderColor || a.valueAtIndexOrDefault(e.pointHoverBorderColor, n, a.getHoverColor(i.borderColor)), i.borderWidth = r.hoverBorderWidth || a.valueAtIndexOrDefault(e.pointHoverBorderWidth, n, i.borderWidth), i.radius = r.hoverRadius || a.valueAtIndexOrDefault(e.pointHoverRadius, n, this.chart.options.elements.point.hoverRadius)
}
})
}
}, {
26: 26,
41: 41,
46: 46
}],
19: [function(t, e, n) {
var r = t(26),
i = t(41),
o = t(46);
r._set("polarArea", {
scale: {
type: "radialLinear",
angleLines: {
display: !1
},
gridLines: {
circular: !0
},
pointLabels: {
display: !1
},
ticks: {
beginAtZero: !0
}
},
animation: {
animateRotate: !0,
animateScale: !0
},
startAngle: -.5 * Math.PI,
legendCallback: function(t) {
var e = [];
e.push('<ul class="' + t.id + '-legend">');
var n = t.data,
r = n.datasets,
i = n.labels;
if (r.length)
for (var o = 0; o < r[0].data.length; ++o) e.push('<li><span style="background-color:' + r[0].backgroundColor[o] + '"></span>'), i[o] && e.push(i[o]), e.push("</li>");
return e.push("</ul>"), e.join("")
},
legend: {
labels: {
generateLabels: function(t) {
var e = t.data;
return e.labels.length && e.datasets.length ? e.labels.map((function(n, r) {
var i = t.getDatasetMeta(0),
a = e.datasets[0],
s = i.data[r].custom || {},
l = o.valueAtIndexOrDefault,
u = t.options.elements.arc;
return {
text: n,
fillStyle: s.backgroundColor ? s.backgroundColor : l(a.backgroundColor, r, u.backgroundColor),
strokeStyle: s.borderColor ? s.borderColor : l(a.borderColor, r, u.borderColor),
lineWidth: s.borderWidth ? s.borderWidth : l(a.borderWidth, r, u.borderWidth),
hidden: isNaN(a.data[r]) || i.data[r].hidden,
index: r
}
})) : []
}
},
onClick: function(t, e) {
var n, r, i, o = e.index,
a = this.chart;
for (n = 0, r = (a.data.datasets || []).length; n < r; ++n)(i = a.getDatasetMeta(n)).data[o].hidden = !i.data[o].hidden;
a.update()
}
},
tooltips: {
callbacks: {
title: function() {
return ""
},
label: function(t, e) {
return e.labels[t.index] + ": " + t.yLabel
}
}
}
}), e.exports = function(t) {
t.controllers.polarArea = t.DatasetController.extend({
dataElementType: i.Arc,
linkScales: o.noop,
update: function(t) {
var e, n, r, i = this,
a = i.getDataset(),
s = i.getMeta(),
l = i.chart.options.startAngle || 0,
u = i._starts = [],
c = i._angles = [];
for (i._updateRadius(), s.count = i.countVisibleElements(), e = 0, n = a.data.length; e < n; e++) u[e] = l, r = i._computeAngle(e), c[e] = r, l += r;
o.each(s.data, (function(e, n) {
i.updateElement(e, n, t)
}))
},
_updateRadius: function() {
var t = this,
e = t.chart,
n = e.chartArea,
r = e.options,
i = r.elements.arc,
o = Math.min(n.right - n.left, n.bottom - n.top);
e.outerRadius = Math.max((o - i.borderWidth / 2) / 2, 0), e.innerRadius = Math.max(r.cutoutPercentage ? e.outerRadius / 100 * r.cutoutPercentage : 1, 0), e.radiusLength = (e.outerRadius - e.innerRadius) / e.getVisibleDatasetCount(), t.outerRadius = e.outerRadius - e.radiusLength * t.index, t.innerRadius = t.outerRadius - e.radiusLength
},
updateElement: function(t, e, n) {
var r = this,
i = r.chart,
a = r.getDataset(),
s = i.options,
l = s.animation,
u = i.scale,
c = i.data.labels,
d = u.xCenter,
f = u.yCenter,
h = s.startAngle,
p = t.hidden ? 0 : u.getDistanceFromCenterForValue(a.data[e]),
g = r._starts[e],
v = g + (t.hidden ? 0 : r._angles[e]),
m = l.animateScale ? 0 : u.getDistanceFromCenterForValue(a.data[e]);
o.extend(t, {
_datasetIndex: r.index,
_index: e,
_scale: u,
_model: {
x: d,
y: f,
innerRadius: 0,
outerRadius: n ? m : p,
startAngle: n && l.animateRotate ? h : g,
endAngle: n && l.animateRotate ? h : v,
label: o.valueAtIndexOrDefault(c, e, c[e])
}
});
var y = this.chart.options.elements.arc,
b = t.custom || {},
x = o.valueAtIndexOrDefault,
w = t._model;
w.backgroundColor = b.backgroundColor ? b.backgroundColor : x(a.backgroundColor, e, y.backgroundColor), w.borderColor = b.borderColor ? b.borderColor : x(a.borderColor, e, y.borderColor), w.borderWidth = b.borderWidth ? b.borderWidth : x(a.borderWidth, e, y.borderWidth), t.pivot()
},
countVisibleElements: function() {
var t = this.getDataset(),
e = this.getMeta(),
n = 0;
return o.each(e.data, (function(e, r) {
isNaN(t.data[r]) || e.hidden || n++
})), n
},
_computeAngle: function(t) {
var e = this,
n = this.getMeta().count,
r = e.getDataset(),
i = e.getMeta();
if (isNaN(r.data[t]) || i.data[t].hidden) return 0;
var a = {
chart: e.chart,
dataIndex: t,
dataset: r,
datasetIndex: e.index
};
return o.options.resolve([e.chart.options.elements.arc.angle, 2 * Math.PI / n], a, t)
}
})
}
}, {
26: 26,
41: 41,
46: 46
}],
20: [function(t, e, n) {
var r = t(26),
i = t(41),
o = t(46);
r._set("radar", {
scale: {
type: "radialLinear"
},
elements: {
line: {
tension: 0
}
}
}), e.exports = function(t) {
t.controllers.radar = t.DatasetController.extend({
datasetElementType: i.Line,
dataElementType: i.Point,
linkScales: o.noop,
update: function(t) {
var e = this,
n = e.getMeta(),
r = n.dataset,
i = n.data,
a = r.custom || {},
s = e.getDataset(),
l = e.chart.options.elements.line,
u = e.chart.scale;
void 0 !== s.tension && void 0 === s.lineTension && (s.lineTension = s.tension), o.extend(n.dataset, {
_datasetIndex: e.index,
_scale: u,
_children: i,
_loop: !0,
_model: {
tension: a.tension ? a.tension : o.valueOrDefault(s.lineTension, l.tension),
backgroundColor: a.backgroundColor ? a.backgroundColor : s.backgroundColor || l.backgroundColor,
borderWidth: a.borderWidth ? a.borderWidth : s.borderWidth || l.borderWidth,
borderColor: a.borderColor ? a.borderColor : s.borderColor || l.borderColor,
fill: a.fill ? a.fill : void 0 !== s.fill ? s.fill : l.fill,
borderCapStyle: a.borderCapStyle ? a.borderCapStyle : s.borderCapStyle || l.borderCapStyle,
borderDash: a.borderDash ? a.borderDash : s.borderDash || l.borderDash,
borderDashOffset: a.borderDashOffset ? a.borderDashOffset : s.borderDashOffset || l.borderDashOffset,
borderJoinStyle: a.borderJoinStyle ? a.borderJoinStyle : s.borderJoinStyle || l.borderJoinStyle
}
}), n.dataset.pivot(), o.each(i, (function(n, r) {
e.updateElement(n, r, t)
}), e), e.updateBezierControlPoints()
},
updateElement: function(t, e, n) {
var r = this,
i = t.custom || {},
a = r.getDataset(),
s = r.chart.scale,
l = r.chart.options.elements.point,
u = s.getPointPositionForValue(e, a.data[e]);
void 0 !== a.radius && void 0 === a.pointRadius && (a.pointRadius = a.radius), void 0 !== a.hitRadius && void 0 === a.pointHitRadius && (a.pointHitRadius = a.hitRadius), o.extend(t, {
_datasetIndex: r.index,
_index: e,
_scale: s,
_model: {
x: n ? s.xCenter : u.x,
y: n ? s.yCenter : u.y,
tension: i.tension ? i.tension : o.valueOrDefault(a.lineTension, r.chart.options.elements.line.tension),
radius: i.radius ? i.radius : o.valueAtIndexOrDefault(a.pointRadius, e, l.radius),
backgroundColor: i.backgroundColor ? i.backgroundColor : o.valueAtIndexOrDefault(a.pointBackgroundColor, e, l.backgroundColor),
borderColor: i.borderColor ? i.borderColor : o.valueAtIndexOrDefault(a.pointBorderColor, e, l.borderColor),
borderWidth: i.borderWidth ? i.borderWidth : o.valueAtIndexOrDefault(a.pointBorderWidth, e, l.borderWidth),
pointStyle: i.pointStyle ? i.pointStyle : o.valueAtIndexOrDefault(a.pointStyle, e, l.pointStyle),
rotation: i.rotation ? i.rotation : o.valueAtIndexOrDefault(a.pointRotation, e, l.rotation),
hitRadius: i.hitRadius ? i.hitRadius : o.valueAtIndexOrDefault(a.pointHitRadius, e, l.hitRadius)
}
}), t._model.skip = i.skip ? i.skip : isNaN(t._model.x) || isNaN(t._model.y)
},
updateBezierControlPoints: function() {
var t = this.chart.chartArea,
e = this.getMeta();
o.each(e.data, (function(n, r) {
var i = n._model,
a = o.splineCurve(o.previousItem(e.data, r, !0)._model, i, o.nextItem(e.data, r, !0)._model, i.tension);
i.controlPointPreviousX = Math.max(Math.min(a.previous.x, t.right), t.left), i.controlPointPreviousY = Math.max(Math.min(a.previous.y, t.bottom), t.top), i.controlPointNextX = Math.max(Math.min(a.next.x, t.right), t.left), i.controlPointNextY = Math.max(Math.min(a.next.y, t.bottom), t.top), n.pivot()
}))
},
setHoverStyle: function(t) {
var e = this.chart.data.datasets[t._datasetIndex],
n = t.custom || {},
r = t._index,
i = t._model;
t.$previousStyle = {
backgroundColor: i.backgroundColor,
borderColor: i.borderColor,
borderWidth: i.borderWidth,
radius: i.radius
}, i.radius = n.hoverRadius ? n.hoverRadius : o.valueAtIndexOrDefault(e.pointHoverRadius, r, this.chart.options.elements.point.hoverRadius), i.backgroundColor = n.hoverBackgroundColor ? n.hoverBackgroundColor : o.valueAtIndexOrDefault(e.pointHoverBackgroundColor, r, o.getHoverColor(i.backgroundColor)), i.borderColor = n.hoverBorderColor ? n.hoverBorderColor : o.valueAtIndexOrDefault(e.pointHoverBorderColor, r, o.getHoverColor(i.borderColor)), i.borderWidth = n.hoverBorderWidth ? n.hoverBorderWidth : o.valueAtIndexOrDefault(e.pointHoverBorderWidth, r, i.borderWidth)
}
})
}
}, {
26: 26,
41: 41,
46: 46
}],
21: [function(t, e, n) {
t(26)._set("scatter", {
hover: {
mode: "single"
},
scales: {
xAxes: [{
id: "x-axis-1",
type: "linear",
position: "bottom"
}],
yAxes: [{
id: "y-axis-1",
type: "linear",
position: "left"
}]
},
showLines: !1,
tooltips: {
callbacks: {
title: function() {
return ""
},
label: function(t) {
return "(" + t.xLabel + ", " + t.yLabel + ")"
}
}
}
}), e.exports = function(t) {
t.controllers.scatter = t.controllers.line
}
}, {
26: 26
}],
22: [function(t, e, n) {
var r = t(27);
n = e.exports = r.extend({
chart: null,
currentStep: 0,
numSteps: 60,
easing: "",
render: null,
onAnimationProgress: null,
onAnimationComplete: null
});
Object.defineProperty(n.prototype, "animationObject", {
get: function() {
return this
}
}), Object.defineProperty(n.prototype, "chartInstance", {
get: function() {
return this.chart
},
set: function(t) {
this.chart = t
}
})
}, {
27: 27
}],
23: [function(t, e, n) {
var r = t(26),
i = t(46);
r._set("global", {
animation: {
duration: 1e3,
easing: "easeOutQuart",
onProgress: i.noop,
onComplete: i.noop
}
}), e.exports = {
frameDuration: 17,
animations: [],
dropFrames: 0,
request: null,
addAnimation: function(t, e, n, r) {
var i, o, a = this.animations;
for (e.chart = t, r || (t.animating = !0), i = 0, o = a.length; i < o; ++i)
if (a[i].chart === t) return void(a[i] = e);
a.push(e), 1 === a.length && this.requestAnimationFrame()
},
cancelAnimation: function(t) {
var e = i.findIndex(this.animations, (function(e) {
return e.chart === t
})); - 1 !== e && (this.animations.splice(e, 1), t.animating = !1)
},
requestAnimationFrame: function() {
var t = this;
null === t.request && (t.request = i.requestAnimFrame.call(window, (function() {
t.request = null, t.startDigest()
})))
},
startDigest: function() {
var t = this,
e = Date.now(),
n = 0;
t.dropFrames > 1 && (n = Math.floor(t.dropFrames), t.dropFrames = t.dropFrames % 1), t.advance(1 + n);
var r = Date.now();
t.dropFrames += (r - e) / t.frameDuration, t.animations.length > 0 && t.requestAnimationFrame()
},
advance: function(t) {
for (var e, n, r = this.animations, o = 0; o < r.length;) n = (e = r[o]).chart, e.currentStep = (e.currentStep || 0) + t, e.currentStep = Math.min(e.currentStep, e.numSteps), i.callback(e.render, [n, e], n), i.callback(e.onAnimationProgress, [e], n), e.currentStep >= e.numSteps ? (i.callback(e.onAnimationComplete, [e], n), n.animating = !1, r.splice(o, 1)) : ++o
}
}
}, {
26: 26,
46: 46
}],
24: [function(t, e, n) {
var r = t(22),
i = t(23),
a = t(26),
s = t(46),
l = t(29),
u = t(31),
c = t(49),
d = t(32),
f = t(34),
h = t(36);
e.exports = function(t) {
function e(e) {
var n = e.options;
s.each(e.scales, (function(t) {
u.removeBox(e, t)
})), n = s.configMerge(t.defaults.global, t.defaults[e.config.type], n), e.options = e.config.options = n, e.ensureScalesHaveIDs(), e.buildOrUpdateScales(), e.tooltip._options = n.tooltips, e.tooltip.initialize()
}
function n(t) {
return "top" === t || "bottom" === t
}
t.types = {}, t.instances = {}, t.controllers = {}, s.extend(t.prototype, {
construct: function(e, n) {
var r = this;
n = function(t) {
var e = (t = t || {}).data = t.data || {};
return e.datasets = e.datasets || [], e.labels = e.labels || [], t.options = s.configMerge(a.global, a[t.type], t.options || {}), t
}(n);
var i = c.acquireContext(e, n),
o = i && i.canvas,
l = o && o.height,
u = o && o.width;
r.id = s.uid(), r.ctx = i, r.canvas = o, r.config = n, r.width = u, r.height = l, r.aspectRatio = l ? u / l : null, r.options = n.options, r._bufferedRender = !1, r.chart = r, r.controller = r, t.instances[r.id] = r, Object.defineProperty(r, "data", {
get: function() {
return r.config.data
},
set: function(t) {
r.config.data = t
}
}), i && o ? (r.initialize(), r.update()) : console.error("Failed to create chart: can't acquire context from the given item")
},
initialize: function() {
var t = this;
return d.notify(t, "beforeInit"), s.retinaScale(t, t.options.devicePixelRatio), t.bindEvents(), t.options.responsive && t.resize(!0), t.ensureScalesHaveIDs(), t.buildOrUpdateScales(), t.initToolTip(), d.notify(t, "afterInit"), t
},
clear: function() {
return s.canvas.clear(this), this
},
stop: function() {
return i.cancelAnimation(this), this
},
resize: function(t) {
var e = this,
n = e.options,
r = e.canvas,
i = n.maintainAspectRatio && e.aspectRatio || null,
o = Math.max(0, Math.floor(s.getMaximumWidth(r))),
a = Math.max(0, Math.floor(i ? o / i : s.getMaximumHeight(r)));
if ((e.width !== o || e.height !== a) && (r.width = e.width = o, r.height = e.height = a, r.style.width = o + "px", r.style.height = a + "px", s.retinaScale(e, n.devicePixelRatio), !t)) {
var l = {
width: o,
height: a
};
d.notify(e, "resize", [l]), e.options.onResize && e.options.onResize(e, l), e.stop(), e.update({
duration: e.options.responsiveAnimationDuration
})
}
},
ensureScalesHaveIDs: function() {
var t = this.options,
e = t.scales || {},
n = t.scale;
s.each(e.xAxes, (function(t, e) {
t.id = t.id || "x-axis-" + e
})), s.each(e.yAxes, (function(t, e) {
t.id = t.id || "y-axis-" + e
})), n && (n.id = n.id || "scale")
},
buildOrUpdateScales: function() {
var t = this,
e = t.options,
r = t.scales || {},
i = [],
o = Object.keys(r).reduce((function(t, e) {
return t[e] = !1, t
}), {});
e.scales && (i = i.concat((e.scales.xAxes || []).map((function(t) {
return {
options: t,
dtype: "category",
dposition: "bottom"
}
})), (e.scales.yAxes || []).map((function(t) {
return {
options: t,
dtype: "linear",
dposition: "left"
}
})))), e.scale && i.push({
options: e.scale,
dtype: "radialLinear",
isDefault: !0,
dposition: "chartArea"
}), s.each(i, (function(e) {
var i = e.options,
a = i.id,
l = s.valueOrDefault(i.type, e.dtype);
n(i.position) !== n(e.dposition) && (i.position = e.dposition), o[a] = !0;
var u = null;
if (a in r && r[a].type === l)(u = r[a]).options = i, u.ctx = t.ctx, u.chart = t;
else {
var c = f.getScaleConstructor(l);
if (!c) return;
u = new c({
id: a,
type: l,
options: i,
ctx: t.ctx,
chart: t
}), r[u.id] = u
}
u.mergeTicksOptions(), e.isDefault && (t.scale = u)
})), s.each(o, (function(t, e) {
t || delete r[e]
})), t.scales = r, f.addScalesToLayout(this)
},
buildOrUpdateControllers: function() {
var e = this,
n = [],
r = [];
return s.each(e.data.datasets, (function(i, o) {
var a = e.getDatasetMeta(o),
s = i.type || e.config.type;
if (a.type && a.type !== s && (e.destroyDatasetMeta(o), a = e.getDatasetMeta(o)), a.type = s, n.push(a.type), a.controller) a.controller.updateIndex(o), a.controller.linkScales();
else {
var l = t.controllers[a.type];
if (void 0 === l) throw new Error('"' + a.type + '" is not a chart type.');
a.controller = new l(e, o), r.push(a.controller)
}
}), e), r
},
resetElements: function() {
var t = this;
s.each(t.data.datasets, (function(e, n) {
t.getDatasetMeta(n).controller.reset()
}), t)
},
reset: function() {
this.resetElements(), this.tooltip.initialize()
},
update: function(t) {
var n = this;
if (t && "object" === o(t) || (t = {
duration: t,
lazy: arguments[1]
}), e(n), d._invalidate(n), !1 !== d.notify(n, "beforeUpdate")) {
n.tooltip._data = n.data;
var r = n.buildOrUpdateControllers();
s.each(n.data.datasets, (function(t, e) {
n.getDatasetMeta(e).controller.buildOrUpdateElements()
}), n), n.updateLayout(), n.options.animation && n.options.animation.duration && s.each(r, (function(t) {
t.reset()
})), n.updateDatasets(), n.tooltip.initialize(), n.lastActive = [], d.notify(n, "afterUpdate"), n._bufferedRender ? n._bufferedRequest = {
duration: t.duration,
easing: t.easing,
lazy: t.lazy
} : n.render(t)
}
},
updateLayout: function() {
!1 !== d.notify(this, "beforeLayout") && (u.update(this, this.width, this.height), d.notify(this, "afterScaleUpdate"), d.notify(this, "afterLayout"))
},
updateDatasets: function() {
if (!1 !== d.notify(this, "beforeDatasetsUpdate")) {
for (var t = 0, e = this.data.datasets.length; t < e; ++t) this.updateDataset(t);
d.notify(this, "afterDatasetsUpdate")
}
},
updateDataset: function(t) {
var e = this.getDatasetMeta(t),
n = {
meta: e,
index: t
};
!1 !== d.notify(this, "beforeDatasetUpdate", [n]) && (e.controller.update(), d.notify(this, "afterDatasetUpdate", [n]))
},
render: function(t) {
var e = this;
t && "object" === o(t) || (t = {
duration: t,
lazy: arguments[1]
});
var n = t.duration,
a = t.lazy;
if (!1 !== d.notify(e, "beforeRender")) {
var l = e.options.animation,
u = function(t) {
d.notify(e, "afterRender"), s.callback(l && l.onComplete, [t], e)
};
if (l && (void 0 !== n && 0 !== n || void 0 === n && 0 !== l.duration)) {
var c = new r({
numSteps: (n || l.duration) / 16.66,
easing: t.easing || l.easing,
render: function(t, e) {
var n = s.easing.effects[e.easing],
r = e.currentStep,
i = r / e.numSteps;
t.draw(n(i), i, r)
},
onAnimationProgress: l.onProgress,
onAnimationComplete: u
});
i.addAnimation(e, c, n, a)
} else e.draw(), u(new r({
numSteps: 0,
chart: e
}));
return e
}
},
draw: function(t) {
var e = this;
e.clear(), s.isNullOrUndef(t) && (t = 1), e.transition(t), e.width <= 0 || e.height <= 0 || !1 !== d.notify(e, "beforeDraw", [t]) && (s.each(e.boxes, (function(t) {
t.draw(e.chartArea)
}), e), e.scale && e.scale.draw(), e.drawDatasets(t), e._drawTooltip(t), d.notify(e, "afterDraw", [t]))
},
transition: function(t) {
for (var e = 0, n = (this.data.datasets || []).length; e < n; ++e) this.isDatasetVisible(e) && this.getDatasetMeta(e).controller.transition(t);
this.tooltip.transition(t)
},
drawDatasets: function(t) {
var e = this;
if (!1 !== d.notify(e, "beforeDatasetsDraw", [t])) {
for (var n = (e.data.datasets || []).length - 1; n >= 0; --n) e.isDatasetVisible(n) && e.drawDataset(n, t);
d.notify(e, "afterDatasetsDraw", [t])
}
},
drawDataset: function(t, e) {
var n = this.getDatasetMeta(t),
r = {
meta: n,
index: t,
easingValue: e
};
!1 !== d.notify(this, "beforeDatasetDraw", [r]) && (n.controller.draw(e), d.notify(this, "afterDatasetDraw", [r]))
},
_drawTooltip: function(t) {
var e = this.tooltip,
n = {
tooltip: e,
easingValue: t
};
!1 !== d.notify(this, "beforeTooltipDraw", [n]) && (e.draw(), d.notify(this, "afterTooltipDraw", [n]))
},
getElementAtEvent: function(t) {
return l.modes.single(this, t)
},
getElementsAtEvent: function(t) {
return l.modes.label(this, t, {
intersect: !0
})
},
getElementsAtXAxis: function(t) {
return l.modes["x-axis"](this, t, {
intersect: !0
})
},
getElementsAtEventForMode: function(t, e, n) {
var r = l.modes[e];
return "function" == typeof r ? r(this, t, n) : []
},
getDatasetAtEvent: function(t) {
return l.modes.dataset(this, t, {
intersect: !0
})
},
getDatasetMeta: function(t) {
var e = this.data.datasets[t];
e._meta || (e._meta = {});
var n = e._meta[this.id];
return n || (n = e._meta[this.id] = {
type: null,
data: [],
dataset: null,
controller: null,
hidden: null,
xAxisID: null,
yAxisID: null
}), n
},
getVisibleDatasetCount: function() {
for (var t = 0, e = 0, n = this.data.datasets.length; e < n; ++e) this.isDatasetVisible(e) && t++;
return t
},
isDatasetVisible: function(t) {
var e = this.getDatasetMeta(t);
return "boolean" == typeof e.hidden ? !e.hidden : !this.data.datasets[t].hidden
},
generateLegend: function() {
return this.options.legendCallback(this)
},
destroyDatasetMeta: function(t) {
var e = this.id,
n = this.data.datasets[t],
r = n._meta && n._meta[e];
r && (r.controller.destroy(), delete n._meta[e])
},
destroy: function() {
var e, n, r = this,
i = r.canvas;
for (r.stop(), e = 0, n = r.data.datasets.length; e < n; ++e) r.destroyDatasetMeta(e);
i && (r.unbindEvents(), s.canvas.clear(r), c.releaseContext(r.ctx), r.canvas = null, r.ctx = null), d.notify(r, "destroy"), delete t.instances[r.id]
},
toBase64Image: function() {
return this.canvas.toDataURL.apply(this.canvas, arguments)
},
initToolTip: function() {
var t = this;
t.tooltip = new h({
_chart: t,
_chartInstance: t,
_data: t.data,
_options: t.options.tooltips
}, t)
},
bindEvents: function() {
var t = this,
e = t._listeners = {},
n = function() {
t.eventHandler.apply(t, arguments)
};
s.each(t.options.events, (function(r) {
c.addEventListener(t, r, n), e[r] = n
})), t.options.responsive && (n = function() {
t.resize()
}, c.addEventListener(t, "resize", n), e.resize = n)
},
unbindEvents: function() {
var t = this,
e = t._listeners;
e && (delete t._listeners, s.each(e, (function(e, n) {
c.removeEventListener(t, n, e)
})))
},
updateHoverStyle: function(t, e, n) {
var r, i, o, a = n ? "setHoverStyle" : "removeHoverStyle";
for (i = 0, o = t.length; i < o; ++i)(r = t[i]) && this.getDatasetMeta(r._datasetIndex).controller[a](r)
},
eventHandler: function(t) {
var e = this,
n = e.tooltip;
if (!1 !== d.notify(e, "beforeEvent", [t])) {
e._bufferedRender = !0, e._bufferedRequest = null;
var r = e.handleEvent(t);
n && (r = n._start ? n.handleEvent(t) : r | n.handleEvent(t)), d.notify(e, "afterEvent", [t]);
var i = e._bufferedRequest;
return i ? e.render(i) : r && !e.animating && (e.stop(), e.render({
duration: e.options.hover.animationDuration,
lazy: !0
})), e._bufferedRender = !1, e._bufferedRequest = null, e
}
},
handleEvent: function(t) {
var e, n = this,
r = n.options || {},
i = r.hover;
return n.lastActive = n.lastActive || [], "mouseout" === t.type ? n.active = [] : n.active = n.getElementsAtEventForMode(t, i.mode, i), s.callback(r.onHover || r.hover.onHover, [t.native, n.active], n), "mouseup" !== t.type && "click" !== t.type || r.onClick && r.onClick.call(n, t.native, n.active), n.lastActive.length && n.updateHoverStyle(n.lastActive, i.mode, !1), n.active.length && i.mode && n.updateHoverStyle(n.active, i.mode, !0), e = !s.arrayEquals(n.active, n.lastActive), n.lastActive = n.active, e
}
}), t.Controller = t
}
}, {
22: 22,
23: 23,
26: 26,
29: 29,
31: 31,
32: 32,
34: 34,
36: 36,
46: 46,
49: 49
}],
25: [function(t, e, n) {
var r = t(46);
e.exports = function(t) {
var e = ["push", "pop", "shift", "splice", "unshift"];
function n(t, n) {
var r = t._chartjs;
if (r) {
var i = r.listeners,
o = i.indexOf(n); - 1 !== o && i.splice(o, 1), i.length > 0 || (e.forEach((function(e) {
delete t[e]
})), delete t._chartjs)
}
}
t.DatasetController = function(t, e) {
this.initialize(t, e)
}, r.extend(t.DatasetController.prototype, {
datasetElementType: null,
dataElementType: null,
initialize: function(t, e) {
this.chart = t, this.index = e, this.linkScales(), this.addElements()
},
updateIndex: function(t) {
this.index = t
},
linkScales: function() {
var t = this,
e = t.getMeta(),
n = t.getDataset();
null !== e.xAxisID && e.xAxisID in t.chart.scales || (e.xAxisID = n.xAxisID || t.chart.options.scales.xAxes[0].id), null !== e.yAxisID && e.yAxisID in t.chart.scales || (e.yAxisID = n.yAxisID || t.chart.options.scales.yAxes[0].id)
},
getDataset: function() {
return this.chart.data.datasets[this.index]
},
getMeta: function() {
return this.chart.getDatasetMeta(this.index)
},
getScaleForId: function(t) {
return this.chart.scales[t]
},
reset: function() {
this.update(!0)
},
destroy: function() {
this._data && n(this._data, this)
},
createMetaDataset: function() {
var t = this.datasetElementType;
return t && new t({
_chart: this.chart,
_datasetIndex: this.index
})
},
createMetaData: function(t) {
var e = this.dataElementType;
return e && new e({
_chart: this.chart,
_datasetIndex: this.index,
_index: t
})
},
addElements: function() {
var t, e, n = this.getMeta(),
r = this.getDataset().data || [],
i = n.data;
for (t = 0, e = r.length; t < e; ++t) i[t] = i[t] || this.createMetaData(t);
n.dataset = n.dataset || this.createMetaDataset()
},
addElementAndReset: function(t) {
var e = this.createMetaData(t);
this.getMeta().data.splice(t, 0, e), this.updateElement(e, t, !0)
},
buildOrUpdateElements: function() {
var t, i, o = this,
a = o.getDataset(),
s = a.data || (a.data = []);
o._data !== s && (o._data && n(o._data, o), i = o, (t = s)._chartjs ? t._chartjs.listeners.push(i) : (Object.defineProperty(t, "_chartjs", {
configurable: !0,
enumerable: !1,
value: {
listeners: [i]
}
}), e.forEach((function(e) {
var n = "onData" + e.charAt(0).toUpperCase() + e.slice(1),
i = t[e];
Object.defineProperty(t, e, {
configurable: !0,
enumerable: !1,
value: function() {
var e = Array.prototype.slice.call(arguments),
o = i.apply(this, e);
return r.each(t._chartjs.listeners, (function(t) {
"function" == typeof t[n] && t[n].apply(t, e)
})), o
}
})
}))), o._data = s), o.resyncElements()
},
update: r.noop,
transition: function(t) {
for (var e = this.getMeta(), n = e.data || [], r = n.length, i = 0; i < r; ++i) n[i].transition(t);
e.dataset && e.dataset.transition(t)
},
draw: function() {
var t = this.getMeta(),
e = t.data || [],
n = e.length,
r = 0;
for (t.dataset && t.dataset.draw(); r < n; ++r) e[r].draw()
},
removeHoverStyle: function(t) {
r.merge(t._model, t.$previousStyle || {}), delete t.$previousStyle
},
setHoverStyle: function(t) {
var e = this.chart.data.datasets[t._datasetIndex],
n = t._index,
i = t.custom || {},
o = r.valueAtIndexOrDefault,
a = r.getHoverColor,
s = t._model;
t.$previousStyle = {
backgroundColor: s.backgroundColor,
borderColor: s.borderColor,
borderWidth: s.borderWidth
}, s.backgroundColor = i.hoverBackgroundColor ? i.hoverBackgroundColor : o(e.hoverBackgroundColor, n, a(s.backgroundColor)), s.borderColor = i.hoverBorderColor ? i.hoverBorderColor : o(e.hoverBorderColor, n, a(s.borderColor)), s.borderWidth = i.hoverBorderWidth ? i.hoverBorderWidth : o(e.hoverBorderWidth, n, s.borderWidth)
},
resyncElements: function() {
var t = this.getMeta(),
e = this.getDataset().data,
n = t.data.length,
r = e.length;
r < n ? t.data.splice(r, n - r) : r > n && this.insertElements(n, r - n)
},
insertElements: function(t, e) {
for (var n = 0; n < e; ++n) this.addElementAndReset(t + n)
},
onDataPush: function() {
this.insertElements(this.getDataset().data.length - 1, arguments.length)
},
onDataPop: function() {
this.getMeta().data.pop()
},
onDataShift: function() {
this.getMeta().data.shift()
},
onDataSplice: function(t, e) {
this.getMeta().data.splice(t, e), this.insertElements(t, arguments.length - 2)
},
onDataUnshift: function() {
this.insertElements(0, arguments.length)
}
}), t.DatasetController.extend = r.inherits
}
}, {
46: 46
}],
26: [function(t, e, n) {
var r = t(46);
e.exports = {
_set: function(t, e) {
return r.merge(this[t] || (this[t] = {}), e)
}
}
}, {
46: 46
}],
27: [function(t, e, n) {
var r = t(3),
i = t(46);
var a = function(t) {
i.extend(this, t), this.initialize.apply(this, arguments)
};
i.extend(a.prototype, {
initialize: function() {
this.hidden = !1
},
pivot: function() {
var t = this;
return t._view || (t._view = i.clone(t._model)), t._start = {}, t
},
transition: function(t) {
var e = this,
n = e._model,
i = e._start,
a = e._view;
return n && 1 !== t ? (a || (a = e._view = {}), i || (i = e._start = {}), function(t, e, n, i) {
var a, s, l, u, c, d, f, h, p, g = Object.keys(n);
for (a = 0, s = g.length; a < s; ++a)
if (d = n[l = g[a]], e.hasOwnProperty(l) || (e[l] = d), (u = e[l]) !== d && "_" !== l[0]) {
if (t.hasOwnProperty(l) || (t[l] = u), c = t[l], (f = o(d)) === o(c))
if ("string" === f) {
if ((h = r(c)).valid && (p = r(d)).valid) {
e[l] = p.mix(h, i).rgbString();
continue
}
} else if ("number" === f && isFinite(c) && isFinite(d)) {
e[l] = c + (d - c) * i;
continue
}
e[l] = d
}
}(i, a, n, t), e) : (e._view = n, e._start = null, e)
},
tooltipPosition: function() {
return {
x: this._model.x,
y: this._model.y
}
},
hasValue: function() {
return i.isNumber(this._model.x) && i.isNumber(this._model.y)
}
}), a.extend = i.inherits, e.exports = a
}, {
3: 3,
46: 46
}],
28: [function(t, e, n) {
var r = t(3),
i = t(26),
o = t(46),
a = t(34);
e.exports = function() {
function t(t, e, n) {
var r;
return "string" == typeof t ? (r = parseInt(t, 10), -1 !== t.indexOf("%") && (r = r / 100 * e.parentNode[n])) : r = t, r
}
function e(t) {
return null != t && "none" !== t
}
function n(n, r, i) {
var a = document.defaultView,
s = o._getParentNode(n),
l = a.getComputedStyle(n)[r],
u = a.getComputedStyle(s)[r],
c = e(l),
d = e(u),
f = Number.POSITIVE_INFINITY;
return c || d ? Math.min(c ? t(l, n, i) : f, d ? t(u, s, i) : f) : "none"
}
o.configMerge = function() {
return o.merge(o.clone(arguments[0]), [].slice.call(arguments, 1), {
merger: function(t, e, n, r) {
var i = e[t] || {},
s = n[t];
"scales" === t ? e[t] = o.scaleMerge(i, s) : "scale" === t ? e[t] = o.merge(i, [a.getScaleDefaults(s.type), s]) : o._merger(t, e, n, r)
}
})
}, o.scaleMerge = function() {
return o.merge(o.clone(arguments[0]), [].slice.call(arguments, 1), {
merger: function(t, e, n, r) {
if ("xAxes" === t || "yAxes" === t) {
var i, s, l, u = n[t].length;
for (e[t] || (e[t] = []), i = 0; i < u; ++i) l = n[t][i], s = o.valueOrDefault(l.type, "xAxes" === t ? "category" : "linear"), i >= e[t].length && e[t].push({}), !e[t][i].type || l.type && l.type !== e[t][i].type ? o.merge(e[t][i], [a.getScaleDefaults(s), l]) : o.merge(e[t][i], l)
} else o._merger(t, e, n, r)
}
})
}, o.where = function(t, e) {
if (o.isArray(t) && Array.prototype.filter) return t.filter(e);
var n = [];
return o.each(t, (function(t) {
e(t) && n.push(t)
})), n
}, o.findIndex = Array.prototype.findIndex ? function(t, e, n) {
return t.findIndex(e, n)
} : function(t, e, n) {
n = void 0 === n ? t : n;
for (var r = 0, i = t.length; r < i; ++r)
if (e.call(n, t[r], r, t)) return r;
return -1
}, o.findNextWhere = function(t, e, n) {
o.isNullOrUndef(n) && (n = -1);
for (var r = n + 1; r < t.length; r++) {
var i = t[r];
if (e(i)) return i
}
}, o.findPreviousWhere = function(t, e, n) {
o.isNullOrUndef(n) && (n = t.length);
for (var r = n - 1; r >= 0; r--) {
var i = t[r];
if (e(i)) return i
}
}, o.isNumber = function(t) {
return !isNaN(parseFloat(t)) && isFinite(t)
}, o.almostEquals = function(t, e, n) {
return Math.abs(t - e) < n
}, o.almostWhole = function(t, e) {
var n = Math.round(t);
return n - e < t && n + e > t
}, o.max = function(t) {
return t.reduce((function(t, e) {
return isNaN(e) ? t : Math.max(t, e)
}), Number.NEGATIVE_INFINITY)
}, o.min = function(t) {
return t.reduce((function(t, e) {
return isNaN(e) ? t : Math.min(t, e)
}), Number.POSITIVE_INFINITY)
}, o.sign = Math.sign ? function(t) {
return Math.sign(t)
} : function(t) {
return 0 === (t = +t) || isNaN(t) ? t : t > 0 ? 1 : -1
}, o.log10 = Math.log10 ? function(t) {
return Math.log10(t)
} : function(t) {
var e = Math.log(t) * Math.LOG10E,
n = Math.round(e);
return t === Math.pow(10, n) ? n : e
}, o.toRadians = function(t) {
return t * (Math.PI / 180)
}, o.toDegrees = function(t) {
return t * (180 / Math.PI)
}, o.getAngleFromPoint = function(t, e) {
var n = e.x - t.x,
r = e.y - t.y,
i = Math.sqrt(n * n + r * r),
o = Math.atan2(r, n);
return o < -.5 * Math.PI && (o += 2 * Math.PI), {
angle: o,
distance: i
}
}, o.distanceBetweenPoints = function(t, e) {
return Math.sqrt(Math.pow(e.x - t.x, 2) + Math.pow(e.y - t.y, 2))
}, o.aliasPixel = function(t) {
return t % 2 == 0 ? 0 : .5
}, o.splineCurve = function(t, e, n, r) {
var i = t.skip ? e : t,
o = e,
a = n.skip ? e : n,
s = Math.sqrt(Math.pow(o.x - i.x, 2) + Math.pow(o.y - i.y, 2)),
l = Math.sqrt(Math.pow(a.x - o.x, 2) + Math.pow(a.y - o.y, 2)),
u = s / (s + l),
c = l / (s + l),
d = r * (u = isNaN(u) ? 0 : u),
f = r * (c = isNaN(c) ? 0 : c);
return {
previous: {
x: o.x - d * (a.x - i.x),
y: o.y - d * (a.y - i.y)
},
next: {
x: o.x + f * (a.x - i.x),
y: o.y + f * (a.y - i.y)
}
}
}, o.EPSILON = Number.EPSILON || 1e-14, o.splineCurveMonotone = function(t) {
var e, n, r, i, a, s, l, u, c, d = (t || []).map((function(t) {
return {
model: t._model,
deltaK: 0,
mK: 0
}
})),
f = d.length;
for (e = 0; e < f; ++e)
if (!(r = d[e]).model.skip) {
if (n = e > 0 ? d[e - 1] : null, (i = e < f - 1 ? d[e + 1] : null) && !i.model.skip) {
var h = i.model.x - r.model.x;
r.deltaK = 0 !== h ? (i.model.y - r.model.y) / h : 0
}!n || n.model.skip ? r.mK = r.deltaK : !i || i.model.skip ? r.mK = n.deltaK : this.sign(n.deltaK) !== this.sign(r.deltaK) ? r.mK = 0 : r.mK = (n.deltaK + r.deltaK) / 2
} for (e = 0; e < f - 1; ++e) r = d[e], i = d[e + 1], r.model.skip || i.model.skip || (o.almostEquals(r.deltaK, 0, this.EPSILON) ? r.mK = i.mK = 0 : (a = r.mK / r.deltaK, s = i.mK / r.deltaK, (u = Math.pow(a, 2) + Math.pow(s, 2)) <= 9 || (l = 3 / Math.sqrt(u), r.mK = a * l * r.deltaK, i.mK = s * l * r.deltaK)));
for (e = 0; e < f; ++e)(r = d[e]).model.skip || (n = e > 0 ? d[e - 1] : null, i = e < f - 1 ? d[e + 1] : null, n && !n.model.skip && (c = (r.model.x - n.model.x) / 3, r.model.controlPointPreviousX = r.model.x - c, r.model.controlPointPreviousY = r.model.y - c * r.mK), i && !i.model.skip && (c = (i.model.x - r.model.x) / 3, r.model.controlPointNextX = r.model.x + c, r.model.controlPointNextY = r.model.y + c * r.mK))
}, o.nextItem = function(t, e, n) {
return n ? e >= t.length - 1 ? t[0] : t[e + 1] : e >= t.length - 1 ? t[t.length - 1] : t[e + 1]
}, o.previousItem = function(t, e, n) {
return n ? e <= 0 ? t[t.length - 1] : t[e - 1] : e <= 0 ? t[0] : t[e - 1]
}, o.niceNum = function(t, e) {
var n = Math.floor(o.log10(t)),
r = t / Math.pow(10, n);
return (e ? r < 1.5 ? 1 : r < 3 ? 2 : r < 7 ? 5 : 10 : r <= 1 ? 1 : r <= 2 ? 2 : r <= 5 ? 5 : 10) * Math.pow(10, n)
}, o.requestAnimFrame = "undefined" == typeof window ? function(t) {
t()
} : window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(t) {
return window.setTimeout(t, 1e3 / 60)
}, o.getRelativePosition = function(t, e) {
var n, r, i = t.originalEvent || t,
a = t.target || t.srcElement,
s = a.getBoundingClientRect(),
l = i.touches;
l && l.length > 0 ? (n = l[0].clientX, r = l[0].clientY) : (n = i.clientX, r = i.clientY);
var u = parseFloat(o.getStyle(a, "padding-left")),
c = parseFloat(o.getStyle(a, "padding-top")),
d = parseFloat(o.getStyle(a, "padding-right")),
f = parseFloat(o.getStyle(a, "padding-bottom")),
h = s.right - s.left - u - d,
p = s.bottom - s.top - c - f;
return {
x: n = Math.round((n - s.left - u) / h * a.width / e.currentDevicePixelRatio),
y: r = Math.round((r - s.top - c) / p * a.height / e.currentDevicePixelRatio)
}
}, o.getConstraintWidth = function(t) {
return n(t, "max-width", "clientWidth")
}, o.getConstraintHeight = function(t) {
return n(t, "max-height", "clientHeight")
}, o._calculatePadding = function(t, e, n) {
return (e = o.getStyle(t, e)).indexOf("%") > -1 ? n / parseInt(e, 10) : parseInt(e, 10)
}, o._getParentNode = function(t) {
var e = t.parentNode;
return e && e.host && (e = e.host), e
}, o.getMaximumWidth = function(t) {
var e = o._getParentNode(t);
if (!e) return t.clientWidth;
var n = e.clientWidth,
r = n - o._calculatePadding(e, "padding-left", n) - o._calculatePadding(e, "padding-right", n),
i = o.getConstraintWidth(t);
return isNaN(i) ? r : Math.min(r, i)
}, o.getMaximumHeight = function(t) {
var e = o._getParentNode(t);
if (!e) return t.clientHeight;
var n = e.clientHeight,
r = n - o._calculatePadding(e, "padding-top", n) - o._calculatePadding(e, "padding-bottom", n),
i = o.getConstraintHeight(t);
return isNaN(i) ? r : Math.min(r, i)
}, o.getStyle = function(t, e) {
return t.currentStyle ? t.currentStyle[e] : document.defaultView.getComputedStyle(t, null).getPropertyValue(e)
}, o.retinaScale = function(t, e) {
var n = t.currentDevicePixelRatio = e || "undefined" != typeof window && window.devicePixelRatio || 1;
if (1 !== n) {
var r = t.canvas,
i = t.height,
o = t.width;
r.height = i * n, r.width = o * n, t.ctx.scale(n, n), r.style.height || r.style.width || (r.style.height = i + "px", r.style.width = o + "px")
}
}, o.fontString = function(t, e, n) {
return e + " " + t + "px " + n
}, o.longestText = function(t, e, n, r) {
var i = (r = r || {}).data = r.data || {},
a = r.garbageCollect = r.garbageCollect || [];
r.font !== e && (i = r.data = {}, a = r.garbageCollect = [], r.font = e), t.font = e;
var s = 0;
o.each(n, (function(e) {
null != e && !0 !== o.isArray(e) ? s = o.measureText(t, i, a, s, e) : o.isArray(e) && o.each(e, (function(e) {
null == e || o.isArray(e) || (s = o.measureText(t, i, a, s, e))
}))
}));
var l = a.length / 2;
if (l > n.length) {
for (var u = 0; u < l; u++) delete i[a[u]];
a.splice(0, l)
}
return s
}, o.measureText = function(t, e, n, r, i) {
var o = e[i];
return o || (o = e[i] = t.measureText(i).width, n.push(i)), o > r && (r = o), r
}, o.numberOfLabelLines = function(t) {
var e = 1;
return o.each(t, (function(t) {
o.isArray(t) && t.length > e && (e = t.length)
})), e
}, o.color = r ? function(t) {
return t instanceof CanvasGradient && (t = i.global.defaultColor), r(t)
} : function(t) {
return console.error("Color.js not found!"), t
}, o.getHoverColor = function(t) {
return t instanceof CanvasPattern ? t : o.color(t).saturate(.5).darken(.1).rgbString()
}
}
}, {
26: 26,
3: 3,
34: 34,
46: 46
}],
29: [function(t, e, n) {
var r = t(46);
function i(t, e) {
return t.native ? {
x: t.x,
y: t.y
} : r.getRelativePosition(t, e)
}
function o(t, e) {
var n, r, i, o, a;
for (r = 0, o = t.data.datasets.length; r < o; ++r)
if (t.isDatasetVisible(r))
for (i = 0, a = (n = t.getDatasetMeta(r)).data.length; i < a; ++i) {
var s = n.data[i];
s._view.skip || e(s)
}
}
function a(t, e) {
var n = [];
return o(t, (function(t) {
t.inRange(e.x, e.y) && n.push(t)
})), n
}
function s(t, e, n, r) {
var i = Number.POSITIVE_INFINITY,
a = [];
return o(t, (function(t) {
if (!n || t.inRange(e.x, e.y)) {
var o = t.getCenterPoint(),
s = r(e, o);
s < i ? (a = [t], i = s) : s === i && a.push(t)
}
})), a
}
function l(t) {
var e = -1 !== t.indexOf("x"),
n = -1 !== t.indexOf("y");
return function(t, r) {
var i = e ? Math.abs(t.x - r.x) : 0,
o = n ? Math.abs(t.y - r.y) : 0;
return Math.sqrt(Math.pow(i, 2) + Math.pow(o, 2))
}
}
function u(t, e, n) {
var r = i(e, t);
n.axis = n.axis || "x";
var o = l(n.axis),
u = n.intersect ? a(t, r) : s(t, r, !1, o),
c = [];
return u.length ? (t.data.datasets.forEach((function(e, n) {
if (t.isDatasetVisible(n)) {
var r = t.getDatasetMeta(n).data[u[0]._index];
r && !r._view.skip && c.push(r)
}
})), c) : []
}
e.exports = {
modes: {
single: function(t, e) {
var n = i(e, t),
r = [];
return o(t, (function(t) {
if (t.inRange(n.x, n.y)) return r.push(t), r
})), r.slice(0, 1)
},
label: u,
index: u,
dataset: function(t, e, n) {
var r = i(e, t);
n.axis = n.axis || "xy";
var o = l(n.axis),
u = n.intersect ? a(t, r) : s(t, r, !1, o);
return u.length > 0 && (u = t.getDatasetMeta(u[0]._datasetIndex).data), u
},
"x-axis": function(t, e) {
return u(t, e, {
intersect: !1
})
},
point: function(t, e) {
return a(t, i(e, t))
},
nearest: function(t, e, n) {
var r = i(e, t);
n.axis = n.axis || "xy";
var o = l(n.axis),
a = s(t, r, n.intersect, o);
return a.length > 1 && a.sort((function(t, e) {
var n = t.getArea() - e.getArea();
return 0 === n && (n = t._datasetIndex - e._datasetIndex), n
})), a.slice(0, 1)
},
x: function(t, e, n) {
var r = i(e, t),
a = [],
s = !1;
return o(t, (function(t) {
t.inXRange(r.x) && a.push(t), t.inRange(r.x, r.y) && (s = !0)
})), n.intersect && !s && (a = []), a
},
y: function(t, e, n) {
var r = i(e, t),
a = [],
s = !1;
return o(t, (function(t) {
t.inYRange(r.y) && a.push(t), t.inRange(r.x, r.y) && (s = !0)
})), n.intersect && !s && (a = []), a
}
}
}
}, {
46: 46
}],
30: [function(t, e, n) {
t(26)._set("global", {
responsive: !0,
responsiveAnimationDuration: 0,
maintainAspectRatio: !0,
events: ["mousemove", "mouseout", "click", "touchstart", "touchmove"],
hover: {
onHover: null,
mode: "nearest",
intersect: !0,
animationDuration: 400
},
onClick: null,
defaultColor: "rgba(0,0,0,0.1)",
defaultFontColor: "#666",
defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
defaultFontSize: 12,
defaultFontStyle: "normal",
showLines: !0,
elements: {},
layout: {
padding: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
}
}), e.exports = function() {
var t = function(t, e) {
return this.construct(t, e), this
};
return t.Chart = t, t
}
}, {
26: 26
}],
31: [function(t, e, n) {
var r = t(46);
function i(t, e) {
return r.where(t, (function(t) {
return t.position === e
}))
}
function o(t, e) {
t.forEach((function(t, e) {
return t._tmpIndex_ = e, t
})), t.sort((function(t, n) {
var r = e ? n : t,
i = e ? t : n;
return r.weight === i.weight ? r._tmpIndex_ - i._tmpIndex_ : r.weight - i.weight
})), t.forEach((function(t) {
delete t._tmpIndex_
}))
}
e.exports = {
defaults: {},
addBox: function(t, e) {
t.boxes || (t.boxes = []), e.fullWidth = e.fullWidth || !1, e.position = e.position || "top", e.weight = e.weight || 0, t.boxes.push(e)
},
removeBox: function(t, e) {
var n = t.boxes ? t.boxes.indexOf(e) : -1; - 1 !== n && t.boxes.splice(n, 1)
},
configure: function(t, e, n) {
for (var r, i = ["fullWidth", "position", "weight"], o = i.length, a = 0; a < o; ++a) r = i[a], n.hasOwnProperty(r) && (e[r] = n[r])
},
update: function(t, e, n) {
if (t) {
var a = t.options.layout || {},
s = r.options.toPadding(a.padding),
l = s.left,
u = s.right,
c = s.top,
d = s.bottom,
f = i(t.boxes, "left"),
h = i(t.boxes, "right"),
p = i(t.boxes, "top"),
g = i(t.boxes, "bottom"),
v = i(t.boxes, "chartArea");
o(f, !0), o(h, !1), o(p, !0), o(g, !1);
var m = e - l - u,
y = n - c - d,
b = y / 2,
x = (e - m / 2) / (f.length + h.length),
w = (n - b) / (p.length + g.length),
S = m,
k = y,
C = [];
r.each(f.concat(h, p, g), (function(t) {
var e, n = t.isHorizontal();
n ? (e = t.update(t.fullWidth ? m : S, w), k -= e.height) : (e = t.update(x, k), S -= e.width), C.push({
horizontal: n,
minSize: e,
box: t
})
}));
var M = 0,
A = 0,
P = 0,
_ = 0;
r.each(p.concat(g), (function(t) {
if (t.getPadding) {
var e = t.getPadding();
M = Math.max(M, e.left), A = Math.max(A, e.right)
}
})), r.each(f.concat(h), (function(t) {
if (t.getPadding) {
var e = t.getPadding();
P = Math.max(P, e.top), _ = Math.max(_, e.bottom)
}
}));
var T = l,
I = u,
O = c,
F = d;
r.each(f.concat(h), z), r.each(f, (function(t) {
T += t.width
})), r.each(h, (function(t) {
I += t.width
})), r.each(p.concat(g), z), r.each(p, (function(t) {
O += t.height
})), r.each(g, (function(t) {
F += t.height
})), r.each(f.concat(h), (function(t) {
var e = r.findNextWhere(C, (function(e) {
return e.box === t
})),
n = {
left: 0,
right: 0,
top: O,
bottom: F
};
e && t.update(e.minSize.width, k, n)
})), T = l, I = u, O = c, F = d, r.each(f, (function(t) {
T += t.width
})), r.each(h, (function(t) {
I += t.width
})), r.each(p, (function(t) {
O += t.height
})), r.each(g, (function(t) {
F += t.height
}));
var D = Math.max(M - T, 0);
T += D, I += Math.max(A - I, 0);
var E = Math.max(P - O, 0);
O += E, F += Math.max(_ - F, 0);
var L = n - O - F,
R = e - T - I;
R === S && L === k || (r.each(f, (function(t) {
t.height = L
})), r.each(h, (function(t) {
t.height = L
})), r.each(p, (function(t) {
t.fullWidth || (t.width = R)
})), r.each(g, (function(t) {
t.fullWidth || (t.width = R)
})), k = L, S = R);
var N = l + D,
V = c + E;
r.each(f.concat(p), B), N += S, V += k, r.each(h, B), r.each(g, B), t.chartArea = {
left: T,
top: O,
right: T + S,
bottom: O + k
}, r.each(v, (function(e) {
e.left = t.chartArea.left, e.top = t.chartArea.top, e.right = t.chartArea.right, e.bottom = t.chartArea.bottom, e.update(S, k)
}))
}
function z(t) {
var e = r.findNextWhere(C, (function(e) {
return e.box === t
}));
if (e)
if (t.isHorizontal()) {
var n = {
left: Math.max(T, M),
right: Math.max(I, A),
top: 0,
bottom: 0
};
t.update(t.fullWidth ? m : S, y / 2, n)
} else t.update(e.minSize.width, k)
}
function B(t) {
t.isHorizontal() ? (t.left = t.fullWidth ? l : T, t.right = t.fullWidth ? e - u : T + S, t.top = V, t.bottom = V + t.height, V = t.bottom) : (t.left = N, t.right = N + t.width, t.top = O, t.bottom = O + k, N = t.right)
}
}
}
}, {
46: 46
}],
32: [function(t, e, n) {
var r = t(26),
i = t(46);
r._set("global", {
plugins: {}
}), e.exports = {
_plugins: [],
_cacheId: 0,
register: function(t) {
var e = this._plugins;
[].concat(t).forEach((function(t) {
-1 === e.indexOf(t) && e.push(t)
})), this._cacheId++
},
unregister: function(t) {
var e = this._plugins;
[].concat(t).forEach((function(t) {
var n = e.indexOf(t); - 1 !== n && e.splice(n, 1)
})), this._cacheId++
},
clear: function() {
this._plugins = [], this._cacheId++
},
count: function() {
return this._plugins.length
},
getAll: function() {
return this._plugins
},
notify: function(t, e, n) {
var r, i, o, a, s, l = this.descriptors(t),
u = l.length;
for (r = 0; r < u; ++r)
if ("function" == typeof(s = (o = (i = l[r]).plugin)[e]) && ((a = [t].concat(n || [])).push(i.options), !1 === s.apply(o, a))) return !1;
return !0
},
descriptors: function(t) {
var e = t.$plugins || (t.$plugins = {});
if (e.id === this._cacheId) return e.descriptors;
var n = [],
o = [],
a = t && t.config || {},
s = a.options && a.options.plugins || {};
return this._plugins.concat(a.plugins || []).forEach((function(t) {
if (-1 === n.indexOf(t)) {
var e = t.id,
a = s[e];
!1 !== a && (!0 === a && (a = i.clone(r.global.plugins[e])), n.push(t), o.push({
plugin: t,
options: a || {}
}))
}
})), e.descriptors = o, e.id = this._cacheId, o
},
_invalidate: function(t) {
delete t.$plugins
}
}
}, {
26: 26,
46: 46
}],
33: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46),
a = t(35);
function s(t) {
var e, n, r = [];
for (e = 0, n = t.length; e < n; ++e) r.push(t[e].label);
return r
}
function l(t, e, n) {
var r = t.getPixelForTick(e);
return n && (r -= 0 === e ? (t.getPixelForTick(1) - r) / 2 : (r - t.getPixelForTick(e - 1)) / 2), r
}
function u(t, e, n) {
return o.isArray(e) ? o.longestText(t, n, e) : t.measureText(e).width
}
function c(t) {
var e = o.valueOrDefault,
n = r.global,
i = e(t.fontSize, n.defaultFontSize),
a = e(t.fontStyle, n.defaultFontStyle),
s = e(t.fontFamily, n.defaultFontFamily);
return {
size: i,
style: a,
family: s,
font: o.fontString(i, a, s)
}
}
function d(t) {
return o.options.toLineHeight(o.valueOrDefault(t.lineHeight, 1.2), o.valueOrDefault(t.fontSize, r.global.defaultFontSize))
}
r._set("scale", {
display: !0,
position: "left",
offset: !1,
gridLines: {
display: !0,
color: "rgba(0, 0, 0, 0.1)",
lineWidth: 1,
drawBorder: !0,
drawOnChartArea: !0,
drawTicks: !0,
tickMarkLength: 10,
zeroLineWidth: 1,
zeroLineColor: "rgba(0,0,0,0.25)",
zeroLineBorderDash: [],
zeroLineBorderDashOffset: 0,
offsetGridLines: !1,
borderDash: [],
borderDashOffset: 0
},
scaleLabel: {
display: !1,
labelString: "",
lineHeight: 1.2,
padding: {
top: 4,
bottom: 4
}
},
ticks: {
beginAtZero: !1,
minRotation: 0,
maxRotation: 50,
mirror: !1,
padding: 0,
reverse: !1,
display: !0,
autoSkip: !0,
autoSkipPadding: 0,
labelOffset: 0,
callback: a.formatters.values,
minor: {},
major: {}
}
}), e.exports = i.extend({
getPadding: function() {
return {
left: this.paddingLeft || 0,
top: this.paddingTop || 0,
right: this.paddingRight || 0,
bottom: this.paddingBottom || 0
}
},
getTicks: function() {
return this._ticks
},
mergeTicksOptions: function() {
var t = this.options.ticks;
for (var e in !1 === t.minor && (t.minor = {
display: !1
}), !1 === t.major && (t.major = {
display: !1
}), t) "major" !== e && "minor" !== e && (void 0 === t.minor[e] && (t.minor[e] = t[e]), void 0 === t.major[e] && (t.major[e] = t[e]))
},
beforeUpdate: function() {
o.callback(this.options.beforeUpdate, [this])
},
update: function(t, e, n) {
var r, i, a, s, l, u, c = this;
for (c.beforeUpdate(), c.maxWidth = t, c.maxHeight = e, c.margins = o.extend({
left: 0,
right: 0,
top: 0,
bottom: 0
}, n), c.longestTextCache = c.longestTextCache || {}, c.beforeSetDimensions(), c.setDimensions(), c.afterSetDimensions(), c.beforeDataLimits(), c.determineDataLimits(), c.afterDataLimits(), c.beforeBuildTicks(), l = c.buildTicks() || [], c.afterBuildTicks(), c.beforeTickToLabelConversion(), a = c.convertTicksToLabels(l) || c.ticks, c.afterTickToLabelConversion(), c.ticks = a, r = 0, i = a.length; r < i; ++r) s = a[r], (u = l[r]) ? u.label = s : l.push(u = {
label: s,
major: !1
});
return c._ticks = l, c.beforeCalculateTickRotation(), c.calculateTickRotation(), c.afterCalculateTickRotation(), c.beforeFit(), c.fit(), c.afterFit(), c.afterUpdate(), c.minSize
},
afterUpdate: function() {
o.callback(this.options.afterUpdate, [this])
},
beforeSetDimensions: function() {
o.callback(this.options.beforeSetDimensions, [this])
},
setDimensions: function() {
var t = this;
t.isHorizontal() ? (t.width = t.maxWidth, t.left = 0, t.right = t.width) : (t.height = t.maxHeight, t.top = 0, t.bottom = t.height), t.paddingLeft = 0, t.paddingTop = 0, t.paddingRight = 0, t.paddingBottom = 0
},
afterSetDimensions: function() {
o.callback(this.options.afterSetDimensions, [this])
},
beforeDataLimits: function() {
o.callback(this.options.beforeDataLimits, [this])
},
determineDataLimits: o.noop,
afterDataLimits: function() {
o.callback(this.options.afterDataLimits, [this])
},
beforeBuildTicks: function() {
o.callback(this.options.beforeBuildTicks, [this])
},
buildTicks: o.noop,
afterBuildTicks: function() {
o.callback(this.options.afterBuildTicks, [this])
},
beforeTickToLabelConversion: function() {
o.callback(this.options.beforeTickToLabelConversion, [this])
},
convertTicksToLabels: function() {
var t = this.options.ticks;
this.ticks = this.ticks.map(t.userCallback || t.callback, this)
},
afterTickToLabelConversion: function() {
o.callback(this.options.afterTickToLabelConversion, [this])
},
beforeCalculateTickRotation: function() {
o.callback(this.options.beforeCalculateTickRotation, [this])
},
calculateTickRotation: function() {
var t = this,
e = t.ctx,
n = t.options.ticks,
r = s(t._ticks),
i = c(n);
e.font = i.font;
var a = n.minRotation || 0;
if (r.length && t.options.display && t.isHorizontal())
for (var l, u = o.longestText(e, i.font, r, t.longestTextCache), d = u, f = t.getPixelForTick(1) - t.getPixelForTick(0) - 6; d > f && a < n.maxRotation;) {
var h = o.toRadians(a);
if (l = Math.cos(h), Math.sin(h) * u > t.maxHeight) {
a--;
break
}
a++, d = l * u
}
t.labelRotation = a
},
afterCalculateTickRotation: function() {
o.callback(this.options.afterCalculateTickRotation, [this])
},
beforeFit: function() {
o.callback(this.options.beforeFit, [this])
},
fit: function() {
var t = this,
e = t.minSize = {
width: 0,
height: 0
},
n = s(t._ticks),
r = t.options,
i = r.ticks,
a = r.scaleLabel,
l = r.gridLines,
f = r.display,
h = t.isHorizontal(),
p = c(i),
g = r.gridLines.tickMarkLength;
if (e.width = h ? t.isFullWidth() ? t.maxWidth - t.margins.left - t.margins.right : t.maxWidth : f && l.drawTicks ? g : 0, e.height = h ? f && l.drawTicks ? g : 0 : t.maxHeight, a.display && f) {
var v = d(a) + o.options.toPadding(a.padding).height;
h ? e.height += v : e.width += v
}
if (i.display && f) {
var m = o.longestText(t.ctx, p.font, n, t.longestTextCache),
y = o.numberOfLabelLines(n),
b = .5 * p.size,
x = t.options.ticks.padding;
if (h) {
t.longestLabelWidth = m;
var w = o.toRadians(t.labelRotation),
S = Math.cos(w),
k = Math.sin(w) * m + p.size * y + b * (y - 1) + b;
e.height = Math.min(t.maxHeight, e.height + k + x), t.ctx.font = p.font;
var C = u(t.ctx, n[0], p.font),
M = u(t.ctx, n[n.length - 1], p.font);
0 !== t.labelRotation ? (t.paddingLeft = "bottom" === r.position ? S * C + 3 : S * b + 3, t.paddingRight = "bottom" === r.position ? S * b + 3 : S * M + 3) : (t.paddingLeft = C / 2 + 3, t.paddingRight = M / 2 + 3)
} else i.mirror ? m = 0 : m += x + b, e.width = Math.min(t.maxWidth, e.width + m), t.paddingTop = p.size / 2, t.paddingBottom = p.size / 2
}
t.handleMargins(), t.width = e.width, t.height = e.height
},
handleMargins: function() {
var t = this;
t.margins && (t.paddingLeft = Math.max(t.paddingLeft - t.margins.left, 0), t.paddingTop = Math.max(t.paddingTop - t.margins.top, 0), t.paddingRight = Math.max(t.paddingRight - t.margins.right, 0), t.paddingBottom = Math.max(t.paddingBottom - t.margins.bottom, 0))
},
afterFit: function() {
o.callback(this.options.afterFit, [this])
},
isHorizontal: function() {
return "top" === this.options.position || "bottom" === this.options.position
},
isFullWidth: function() {
return this.options.fullWidth
},
getRightValue: function(t) {
if (o.isNullOrUndef(t)) return NaN;
if ("number" == typeof t && !isFinite(t)) return NaN;
if (t)
if (this.isHorizontal()) {
if (void 0 !== t.x) return this.getRightValue(t.x)
} else if (void 0 !== t.y) return this.getRightValue(t.y);
return t
},
getLabelForIndex: o.noop,
getPixelForValue: o.noop,
getValueForPixel: o.noop,
getPixelForTick: function(t) {
var e = this,
n = e.options.offset;
if (e.isHorizontal()) {
var r = (e.width - (e.paddingLeft + e.paddingRight)) / Math.max(e._ticks.length - (n ? 0 : 1), 1),
i = r * t + e.paddingLeft;
n && (i += r / 2);
var o = e.left + Math.round(i);
return o += e.isFullWidth() ? e.margins.left : 0
}
var a = e.height - (e.paddingTop + e.paddingBottom);
return e.top + t * (a / (e._ticks.length - 1))
},
getPixelForDecimal: function(t) {
var e = this;
if (e.isHorizontal()) {
var n = (e.width - (e.paddingLeft + e.paddingRight)) * t + e.paddingLeft,
r = e.left + Math.round(n);
return r += e.isFullWidth() ? e.margins.left : 0
}
return e.top + t * e.height
},
getBasePixel: function() {
return this.getPixelForValue(this.getBaseValue())
},
getBaseValue: function() {
var t = this.min,
e = this.max;
return this.beginAtZero ? 0 : t < 0 && e < 0 ? e : t > 0 && e > 0 ? t : 0
},
_autoSkip: function(t) {
var e, n, r, i, a = this,
s = a.isHorizontal(),
l = a.options.ticks.minor,
u = t.length,
c = o.toRadians(a.labelRotation),
d = Math.cos(c),
f = a.longestLabelWidth * d,
h = [];
for (l.maxTicksLimit && (i = l.maxTicksLimit), s && (e = !1, (f + l.autoSkipPadding) * u > a.width - (a.paddingLeft + a.paddingRight) && (e = 1 + Math.floor((f + l.autoSkipPadding) * u / (a.width - (a.paddingLeft + a.paddingRight)))), i && u > i && (e = Math.max(e, Math.floor(u / i)))), n = 0; n < u; n++) r = t[n], (e > 1 && n % e > 0 || n % e == 0 && n + e >= u) && n !== u - 1 && delete r.label, h.push(r);
return h
},
draw: function(t) {
var e = this,
n = e.options;
if (n.display) {
var i = e.ctx,
a = r.global,
s = n.ticks.minor,
u = n.ticks.major || s,
f = n.gridLines,
h = n.scaleLabel,
p = 0 !== e.labelRotation,
g = e.isHorizontal(),
v = s.autoSkip ? e._autoSkip(e.getTicks()) : e.getTicks(),
m = o.valueOrDefault(s.fontColor, a.defaultFontColor),
y = c(s),
b = o.valueOrDefault(u.fontColor, a.defaultFontColor),
x = c(u),
w = f.drawTicks ? f.tickMarkLength : 0,
S = o.valueOrDefault(h.fontColor, a.defaultFontColor),
k = c(h),
C = o.options.toPadding(h.padding),
M = o.toRadians(e.labelRotation),
A = [],
P = e.options.gridLines.lineWidth,
_ = "right" === n.position ? e.left : e.right - P - w,
T = "right" === n.position ? e.left + w : e.right,
I = "bottom" === n.position ? e.top + P : e.bottom - w - P,
O = "bottom" === n.position ? e.top + P + w : e.bottom + P;
if (o.each(v, (function(r, i) {
if (!o.isNullOrUndef(r.label)) {
var u, c, d, h, m, y, b, x, S, k, C, F, D, E, L = r.label;
i === e.zeroLineIndex && n.offset === f.offsetGridLines ? (u = f.zeroLineWidth, c = f.zeroLineColor, d = f.zeroLineBorderDash, h = f.zeroLineBorderDashOffset) : (u = o.valueAtIndexOrDefault(f.lineWidth, i), c = o.valueAtIndexOrDefault(f.color, i), d = o.valueOrDefault(f.borderDash, a.borderDash), h = o.valueOrDefault(f.borderDashOffset, a.borderDashOffset));
var R = "middle",
N = "middle",
V = s.padding;
if (g) {
var z = w + V;
"bottom" === n.position ? (N = p ? "middle" : "top", R = p ? "right" : "center", E = e.top + z) : (N = p ? "middle" : "bottom", R = p ? "left" : "center", E = e.bottom - z);
var B = l(e, i, f.offsetGridLines && v.length > 1);
B < e.left && (c = "rgba(0,0,0,0)"), B += o.aliasPixel(u), D = e.getPixelForTick(i) + s.labelOffset, m = b = S = C = B, y = I, x = O, k = t.top, F = t.bottom + P
} else {
var W, j = "left" === n.position;
s.mirror ? (R = j ? "left" : "right", W = V) : (R = j ? "right" : "left", W = w + V), D = j ? e.right - W : e.left + W;
var H = l(e, i, f.offsetGridLines && v.length > 1);
H < e.top && (c = "rgba(0,0,0,0)"), H += o.aliasPixel(u), E = e.getPixelForTick(i) + s.labelOffset, m = _, b = T, S = t.left, C = t.right + P, y = x = k = F = H
}
A.push({
tx1: m,
ty1: y,
tx2: b,
ty2: x,
x1: S,
y1: k,
x2: C,
y2: F,
labelX: D,
labelY: E,
glWidth: u,
glColor: c,
glBorderDash: d,
glBorderDashOffset: h,
rotation: -1 * M,
label: L,
major: r.major,
textBaseline: N,
textAlign: R
})
}
})), o.each(A, (function(t) {
if (f.display && (i.save(), i.lineWidth = t.glWidth, i.strokeStyle = t.glColor, i.setLineDash && (i.setLineDash(t.glBorderDash), i.lineDashOffset = t.glBorderDashOffset), i.beginPath(), f.drawTicks && (i.moveTo(t.tx1, t.ty1), i.lineTo(t.tx2, t.ty2)), f.drawOnChartArea && (i.moveTo(t.x1, t.y1), i.lineTo(t.x2, t.y2)), i.stroke(), i.restore()), s.display) {
i.save(), i.translate(t.labelX, t.labelY), i.rotate(t.rotation), i.font = t.major ? x.font : y.font, i.fillStyle = t.major ? b : m, i.textBaseline = t.textBaseline, i.textAlign = t.textAlign;
var n = t.label;
if (o.isArray(n))
for (var r = n.length, a = 1.5 * y.size, l = e.isHorizontal() ? 0 : -a * (r - 1) / 2, u = 0; u < r; ++u) i.fillText("" + n[u], 0, l), l += a;
else i.fillText(n, 0, 0);
i.restore()
}
})), h.display) {
var F, D, E = 0,
L = d(h) / 2;
if (g) F = e.left + (e.right - e.left) / 2, D = "bottom" === n.position ? e.bottom - L - C.bottom : e.top + L + C.top;
else {
var R = "left" === n.position;
F = R ? e.left + L + C.top : e.right - L - C.top, D = e.top + (e.bottom - e.top) / 2, E = R ? -.5 * Math.PI : .5 * Math.PI
}
i.save(), i.translate(F, D), i.rotate(E), i.textAlign = "center", i.textBaseline = "middle", i.fillStyle = S, i.font = k.font, i.fillText(h.labelString, 0, 0), i.restore()
}
if (f.drawBorder) {
i.lineWidth = o.valueAtIndexOrDefault(f.lineWidth, 0), i.strokeStyle = o.valueAtIndexOrDefault(f.color, 0);
var N = e.left,
V = e.right + P,
z = e.top,
B = e.bottom + P,
W = o.aliasPixel(i.lineWidth);
g ? (z = B = "top" === n.position ? e.bottom : e.top, z += W, B += W) : (N = V = "left" === n.position ? e.right : e.left, N += W, V += W), i.beginPath(), i.moveTo(N, z), i.lineTo(V, B), i.stroke()
}
}
}
})
}, {
26: 26,
27: 27,
35: 35,
46: 46
}],
34: [function(t, e, n) {
var r = t(26),
i = t(46),
o = t(31);
e.exports = {
constructors: {},
defaults: {},
registerScaleType: function(t, e, n) {
this.constructors[t] = e, this.defaults[t] = i.clone(n)
},
getScaleConstructor: function(t) {
return this.constructors.hasOwnProperty(t) ? this.constructors[t] : void 0
},
getScaleDefaults: function(t) {
return this.defaults.hasOwnProperty(t) ? i.merge({}, [r.scale, this.defaults[t]]) : {}
},
updateScaleDefaults: function(t, e) {
this.defaults.hasOwnProperty(t) && (this.defaults[t] = i.extend(this.defaults[t], e))
},
addScalesToLayout: function(t) {
i.each(t.scales, (function(e) {
e.fullWidth = e.options.fullWidth, e.position = e.options.position, e.weight = e.options.weight, o.addBox(t, e)
}))
}
}
}, {
26: 26,
31: 31,
46: 46
}],
35: [function(t, e, n) {
var r = t(46);
e.exports = {
formatters: {
values: function(t) {
return r.isArray(t) ? t : "" + t
},
linear: function(t, e, n) {
var i = n.length > 3 ? n[2] - n[1] : n[1] - n[0];
Math.abs(i) > 1 && t !== Math.floor(t) && (i = t - Math.floor(t));
var o = r.log10(Math.abs(i)),
a = "";
if (0 !== t)
if (Math.max(Math.abs(n[0]), Math.abs(n[n.length - 1])) < 1e-4) {
var s = r.log10(Math.abs(t));
a = t.toExponential(Math.floor(s) - Math.floor(o))
} else {
var l = -1 * Math.floor(o);
l = Math.max(Math.min(l, 20), 0), a = t.toFixed(l)
}
else a = "0";
return a
},
logarithmic: function(t, e, n) {
var i = t / Math.pow(10, Math.floor(r.log10(t)));
return 0 === t ? "0" : 1 === i || 2 === i || 5 === i || 0 === e || e === n.length - 1 ? t.toExponential() : ""
}
}
}
}, {
46: 46
}],
36: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46);
r._set("global", {
tooltips: {
enabled: !0,
custom: null,
mode: "nearest",
position: "average",
intersect: !0,
backgroundColor: "rgba(0,0,0,0.8)",
titleFontStyle: "bold",
titleSpacing: 2,
titleMarginBottom: 6,
titleFontColor: "#fff",
titleAlign: "left",
bodySpacing: 2,
bodyFontColor: "#fff",
bodyAlign: "left",
footerFontStyle: "bold",
footerSpacing: 2,
footerMarginTop: 6,
footerFontColor: "#fff",
footerAlign: "left",
yPadding: 6,
xPadding: 6,
caretPadding: 2,
caretSize: 5,
cornerRadius: 6,
multiKeyBackground: "#fff",
displayColors: !0,
borderColor: "rgba(0,0,0,0)",
borderWidth: 0,
callbacks: {
beforeTitle: o.noop,
title: function(t, e) {
var n = "",
r = e.labels,
i = r ? r.length : 0;
if (t.length > 0) {
var o = t[0];
o.xLabel ? n = o.xLabel : i > 0 && o.index < i && (n = r[o.index])
}
return n
},
afterTitle: o.noop,
beforeBody: o.noop,
beforeLabel: o.noop,
label: function(t, e) {
var n = e.datasets[t.datasetIndex].label || "";
return n && (n += ": "), n += t.yLabel, n
},
labelColor: function(t, e) {
var n = e.getDatasetMeta(t.datasetIndex).data[t.index]._view;
return {
borderColor: n.borderColor,
backgroundColor: n.backgroundColor
}
},
labelTextColor: function() {
return this._options.bodyFontColor
},
afterLabel: o.noop,
afterBody: o.noop,
beforeFooter: o.noop,
footer: o.noop,
afterFooter: o.noop
}
}
});
var a = {
average: function(t) {
if (!t.length) return !1;
var e, n, r = 0,
i = 0,
o = 0;
for (e = 0, n = t.length; e < n; ++e) {
var a = t[e];
if (a && a.hasValue()) {
var s = a.tooltipPosition();
r += s.x, i += s.y, ++o
}
}
return {
x: Math.round(r / o),
y: Math.round(i / o)
}
},
nearest: function(t, e) {
var n, r, i, a = e.x,
s = e.y,
l = Number.POSITIVE_INFINITY;
for (n = 0, r = t.length; n < r; ++n) {
var u = t[n];
if (u && u.hasValue()) {
var c = u.getCenterPoint(),
d = o.distanceBetweenPoints(e, c);
d < l && (l = d, i = u)
}
}
if (i) {
var f = i.tooltipPosition();
a = f.x, s = f.y
}
return {
x: a,
y: s
}
}
};
function s(t, e) {
var n = o.color(t);
return n.alpha(e * n.alpha()).rgbaString()
}
function l(t, e) {
return e && (o.isArray(e) ? Array.prototype.push.apply(t, e) : t.push(e)), t
}
function u(t) {
return ("string" == typeof t || t instanceof String) && t.indexOf("\n") > -1 ? t.split("\n") : t
}
function c(t) {
var e = r.global,
n = o.valueOrDefault;
return {
xPadding: t.xPadding,
yPadding: t.yPadding,
xAlign: t.xAlign,
yAlign: t.yAlign,
bodyFontColor: t.bodyFontColor,
_bodyFontFamily: n(t.bodyFontFamily, e.defaultFontFamily),
_bodyFontStyle: n(t.bodyFontStyle, e.defaultFontStyle),
_bodyAlign: t.bodyAlign,
bodyFontSize: n(t.bodyFontSize, e.defaultFontSize),
bodySpacing: t.bodySpacing,
titleFontColor: t.titleFontColor,
_titleFontFamily: n(t.titleFontFamily, e.defaultFontFamily),
_titleFontStyle: n(t.titleFontStyle, e.defaultFontStyle),
titleFontSize: n(t.titleFontSize, e.defaultFontSize),
_titleAlign: t.titleAlign,
titleSpacing: t.titleSpacing,
titleMarginBottom: t.titleMarginBottom,
footerFontColor: t.footerFontColor,
_footerFontFamily: n(t.footerFontFamily, e.defaultFontFamily),
_footerFontStyle: n(t.footerFontStyle, e.defaultFontStyle),
footerFontSize: n(t.footerFontSize, e.defaultFontSize),
_footerAlign: t.footerAlign,
footerSpacing: t.footerSpacing,
footerMarginTop: t.footerMarginTop,
caretSize: t.caretSize,
cornerRadius: t.cornerRadius,
backgroundColor: t.backgroundColor,
opacity: 0,
legendColorBackground: t.multiKeyBackground,
displayColors: t.displayColors,
borderColor: t.borderColor,
borderWidth: t.borderWidth
}
}
function d(t) {
return l([], u(t))
}(e.exports = i.extend({
initialize: function() {
this._model = c(this._options), this._lastActive = []
},
getTitle: function() {
var t = this,
e = t._options,
n = e.callbacks,
r = n.beforeTitle.apply(t, arguments),
i = n.title.apply(t, arguments),
o = n.afterTitle.apply(t, arguments),
a = [];
return a = l(a, u(r)), a = l(a, u(i)), a = l(a, u(o))
},
getBeforeBody: function() {
return d(this._options.callbacks.beforeBody.apply(this, arguments))
},
getBody: function(t, e) {
var n = this,
r = n._options.callbacks,
i = [];
return o.each(t, (function(t) {
var o = {
before: [],
lines: [],
after: []
};
l(o.before, u(r.beforeLabel.call(n, t, e))), l(o.lines, r.label.call(n, t, e)), l(o.after, u(r.afterLabel.call(n, t, e))), i.push(o)
})), i
},
getAfterBody: function() {
return d(this._options.callbacks.afterBody.apply(this, arguments))
},
getFooter: function() {
var t = this,
e = t._options.callbacks,
n = e.beforeFooter.apply(t, arguments),
r = e.footer.apply(t, arguments),
i = e.afterFooter.apply(t, arguments),
o = [];
return o = l(o, u(n)), o = l(o, u(r)), o = l(o, u(i))
},
update: function(t) {
var e, n, r, i, s, l, u, d = this,
f = d._options,
h = d._model,
p = d._model = c(f),
g = d._active,
v = d._data,
m = {
xAlign: h.xAlign,
yAlign: h.yAlign
},
y = {
x: h.x,
y: h.y
},
b = {
width: h.width,
height: h.height
},
x = {
x: h.caretX,
y: h.caretY
};
if (g.length) {
p.opacity = 1;
var w = [],
S = [];
x = a[f.position].call(d, g, d._eventPosition);
var k = [];
for (e = 0, n = g.length; e < n; ++e) k.push((r = g[e], i = void 0, s = void 0, l = void 0, u = void 0, i = r._xScale, s = r._yScale || r._scale, l = r._index, u = r._datasetIndex, {
xLabel: i ? i.getLabelForIndex(l, u) : "",
yLabel: s ? s.getLabelForIndex(l, u) : "",
index: l,
datasetIndex: u,
x: r._model.x,
y: r._model.y
}));
f.filter && (k = k.filter((function(t) {
return f.filter(t, v)
}))), f.itemSort && (k = k.sort((function(t, e) {
return f.itemSort(t, e, v)
}))), o.each(k, (function(t) {
w.push(f.callbacks.labelColor.call(d, t, d._chart)), S.push(f.callbacks.labelTextColor.call(d, t, d._chart))
})), p.title = d.getTitle(k, v), p.beforeBody = d.getBeforeBody(k, v), p.body = d.getBody(k, v), p.afterBody = d.getAfterBody(k, v), p.footer = d.getFooter(k, v), p.x = Math.round(x.x), p.y = Math.round(x.y), p.caretPadding = f.caretPadding, p.labelColors = w, p.labelTextColors = S, p.dataPoints = k, b = function(t, e) {
var n = t._chart.ctx,
r = 2 * e.yPadding,
i = 0,
a = e.body,
s = a.reduce((function(t, e) {
return t + e.before.length + e.lines.length + e.after.length
}), 0);
s += e.beforeBody.length + e.afterBody.length;
var l = e.title.length,
u = e.footer.length,
c = e.titleFontSize,
d = e.bodyFontSize,
f = e.footerFontSize;
r += l * c, r += l ? (l - 1) * e.titleSpacing : 0, r += l ? e.titleMarginBottom : 0, r += s * d, r += s ? (s - 1) * e.bodySpacing : 0, r += u ? e.footerMarginTop : 0, r += u * f, r += u ? (u - 1) * e.footerSpacing : 0;
var h = 0,
p = function(t) {
i = Math.max(i, n.measureText(t).width + h)
};
return n.font = o.fontString(c, e._titleFontStyle, e._titleFontFamily), o.each(e.title, p), n.font = o.fontString(d, e._bodyFontStyle, e._bodyFontFamily), o.each(e.beforeBody.concat(e.afterBody), p), h = e.displayColors ? d + 2 : 0, o.each(a, (function(t) {
o.each(t.before, p), o.each(t.lines, p), o.each(t.after, p)
})), h = 0, n.font = o.fontString(f, e._footerFontStyle, e._footerFontFamily), o.each(e.footer, p), {
width: i += 2 * e.xPadding,
height: r
}
}(this, p), y = function(t, e, n, r) {
var i = t.x,
o = t.y,
a = t.caretSize,
s = t.caretPadding,
l = t.cornerRadius,
u = n.xAlign,
c = n.yAlign,
d = a + s,
f = l + s;
return "right" === u ? i -= e.width : "center" === u && ((i -= e.width / 2) + e.width > r.width && (i = r.width - e.width), i < 0 && (i = 0)), "top" === c ? o += d : o -= "bottom" === c ? e.height + d : e.height / 2, "center" === c ? "left" === u ? i += d : "right" === u && (i -= d) : "left" === u ? i -= f : "right" === u && (i += f), {
x: i,
y: o
}
}(p, b, m = function(t, e) {
var n, r, i, o, a, s = t._model,
l = t._chart,
u = t._chart.chartArea,
c = "center",
d = "center";
s.y < e.height ? d = "top" : s.y > l.height - e.height && (d = "bottom");
var f = (u.left + u.right) / 2,
h = (u.top + u.bottom) / 2;
"center" === d ? (n = function(t) {
return t <= f
}, r = function(t) {
return t > f
}) : (n = function(t) {
return t <= e.width / 2
}, r = function(t) {
return t >= l.width - e.width / 2
}), i = function(t) {
return t + e.width + s.caretSize + s.caretPadding > l.width
}, o = function(t) {
return t - e.width - s.caretSize - s.caretPadding < 0
}, a = function(t) {
return t <= h ? "top" : "bottom"
}, n(s.x) ? (c = "left", i(s.x) && (c = "center", d = a(s.y))) : r(s.x) && (c = "right", o(s.x) && (c = "center", d = a(s.y)));
var p = t._options;
return {
xAlign: p.xAlign ? p.xAlign : c,
yAlign: p.yAlign ? p.yAlign : d
}
}(this, b), d._chart)
} else p.opacity = 0;
return p.xAlign = m.xAlign, p.yAlign = m.yAlign, p.x = y.x, p.y = y.y, p.width = b.width, p.height = b.height, p.caretX = x.x, p.caretY = x.y, d._model = p, t && f.custom && f.custom.call(d, p), d
},
drawCaret: function(t, e) {
var n = this._chart.ctx,
r = this._view,
i = this.getCaretPosition(t, e, r);
n.lineTo(i.x1, i.y1), n.lineTo(i.x2, i.y2), n.lineTo(i.x3, i.y3)
},
getCaretPosition: function(t, e, n) {
var r, i, o, a, s, l, u = n.caretSize,
c = n.cornerRadius,
d = n.xAlign,
f = n.yAlign,
h = t.x,
p = t.y,
g = e.width,
v = e.height;
if ("center" === f) s = p + v / 2, "left" === d ? (i = (r = h) - u, o = r, a = s + u, l = s - u) : (i = (r = h + g) + u, o = r, a = s - u, l = s + u);
else if ("left" === d ? (r = (i = h + c + u) - u, o = i + u) : "right" === d ? (r = (i = h + g - c - u) - u, o = i + u) : (r = (i = n.caretX) - u, o = i + u), "top" === f) s = (a = p) - u, l = a;
else {
s = (a = p + v) + u, l = a;
var m = o;
o = r, r = m
}
return {
x1: r,
x2: i,
x3: o,
y1: a,
y2: s,
y3: l
}
},
drawTitle: function(t, e, n, r) {
var i = e.title;
if (i.length) {
n.textAlign = e._titleAlign, n.textBaseline = "top";
var a, l, u = e.titleFontSize,
c = e.titleSpacing;
for (n.fillStyle = s(e.titleFontColor, r), n.font = o.fontString(u, e._titleFontStyle, e._titleFontFamily), a = 0, l = i.length; a < l; ++a) n.fillText(i[a], t.x, t.y), t.y += u + c, a + 1 === i.length && (t.y += e.titleMarginBottom - c)
}
},
drawBody: function(t, e, n, r) {
var i = e.bodyFontSize,
a = e.bodySpacing,
l = e.body;
n.textAlign = e._bodyAlign, n.textBaseline = "top", n.font = o.fontString(i, e._bodyFontStyle, e._bodyFontFamily);
var u = 0,
c = function(e) {
n.fillText(e, t.x + u, t.y), t.y += i + a
};
n.fillStyle = s(e.bodyFontColor, r), o.each(e.beforeBody, c);
var d = e.displayColors;
u = d ? i + 2 : 0, o.each(l, (function(a, l) {
var u = s(e.labelTextColors[l], r);
n.fillStyle = u, o.each(a.before, c), o.each(a.lines, (function(o) {
d && (n.fillStyle = s(e.legendColorBackground, r), n.fillRect(t.x, t.y, i, i), n.lineWidth = 1, n.strokeStyle = s(e.labelColors[l].borderColor, r), n.strokeRect(t.x, t.y, i, i), n.fillStyle = s(e.labelColors[l].backgroundColor, r), n.fillRect(t.x + 1, t.y + 1, i - 2, i - 2), n.fillStyle = u), c(o)
})), o.each(a.after, c)
})), u = 0, o.each(e.afterBody, c), t.y -= a
},
drawFooter: function(t, e, n, r) {
var i = e.footer;
i.length && (t.y += e.footerMarginTop, n.textAlign = e._footerAlign, n.textBaseline = "top", n.fillStyle = s(e.footerFontColor, r), n.font = o.fontString(e.footerFontSize, e._footerFontStyle, e._footerFontFamily), o.each(i, (function(r) {
n.fillText(r, t.x, t.y), t.y += e.footerFontSize + e.footerSpacing
})))
},
drawBackground: function(t, e, n, r, i) {
n.fillStyle = s(e.backgroundColor, i), n.strokeStyle = s(e.borderColor, i), n.lineWidth = e.borderWidth;
var o = e.xAlign,
a = e.yAlign,
l = t.x,
u = t.y,
c = r.width,
d = r.height,
f = e.cornerRadius;
n.beginPath(), n.moveTo(l + f, u), "top" === a && this.drawCaret(t, r), n.lineTo(l + c - f, u), n.quadraticCurveTo(l + c, u, l + c, u + f), "center" === a && "right" === o && this.drawCaret(t, r), n.lineTo(l + c, u + d - f), n.quadraticCurveTo(l + c, u + d, l + c - f, u + d), "bottom" === a && this.drawCaret(t, r), n.lineTo(l + f, u + d), n.quadraticCurveTo(l, u + d, l, u + d - f), "center" === a && "left" === o && this.drawCaret(t, r), n.lineTo(l, u + f), n.quadraticCurveTo(l, u, l + f, u), n.closePath(), n.fill(), e.borderWidth > 0 && n.stroke()
},
draw: function() {
var t = this._chart.ctx,
e = this._view;
if (0 !== e.opacity) {
var n = {
width: e.width,
height: e.height
},
r = {
x: e.x,
y: e.y
},
i = Math.abs(e.opacity < .001) ? 0 : e.opacity,
o = e.title.length || e.beforeBody.length || e.body.length || e.afterBody.length || e.footer.length;
this._options.enabled && o && (this.drawBackground(r, e, t, n, i), r.x += e.xPadding, r.y += e.yPadding, this.drawTitle(r, e, t, i), this.drawBody(r, e, t, i), this.drawFooter(r, e, t, i))
}
},
handleEvent: function(t) {
var e, n = this,
r = n._options;
return n._lastActive = n._lastActive || [], "mouseout" === t.type ? n._active = [] : n._active = n._chart.getElementsAtEventForMode(t, r.mode, r), (e = !o.arrayEquals(n._active, n._lastActive)) && (n._lastActive = n._active, (r.enabled || r.custom) && (n._eventPosition = {
x: t.x,
y: t.y
}, n.update(!0), n.pivot())), e
}
})).positioners = a
}, {
26: 26,
27: 27,
46: 46
}],
37: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46);
r._set("global", {
elements: {
arc: {
backgroundColor: r.global.defaultColor,
borderColor: "#fff",
borderWidth: 2
}
}
}), e.exports = i.extend({
inLabelRange: function(t) {
var e = this._view;
return !!e && Math.pow(t - e.x, 2) < Math.pow(e.radius + e.hoverRadius, 2)
},
inRange: function(t, e) {
var n = this._view;
if (n) {
for (var r = o.getAngleFromPoint(n, {
x: t,
y: e
}), i = r.angle, a = r.distance, s = n.startAngle, l = n.endAngle; l < s;) l += 2 * Math.PI;
for (; i > l;) i -= 2 * Math.PI;
for (; i < s;) i += 2 * Math.PI;
var u = i >= s && i <= l,
c = a >= n.innerRadius && a <= n.outerRadius;
return u && c
}
return !1
},
getCenterPoint: function() {
var t = this._view,
e = (t.startAngle + t.endAngle) / 2,
n = (t.innerRadius + t.outerRadius) / 2;
return {
x: t.x + Math.cos(e) * n,
y: t.y + Math.sin(e) * n
}
},
getArea: function() {
var t = this._view;
return Math.PI * ((t.endAngle - t.startAngle) / (2 * Math.PI)) * (Math.pow(t.outerRadius, 2) - Math.pow(t.innerRadius, 2))
},
tooltipPosition: function() {
var t = this._view,
e = t.startAngle + (t.endAngle - t.startAngle) / 2,
n = (t.outerRadius - t.innerRadius) / 2 + t.innerRadius;
return {
x: t.x + Math.cos(e) * n,
y: t.y + Math.sin(e) * n
}
},
draw: function() {
var t = this._chart.ctx,
e = this._view,
n = e.startAngle,
r = e.endAngle;
t.beginPath(), t.arc(e.x, e.y, e.outerRadius, n, r), t.arc(e.x, e.y, e.innerRadius, r, n, !0), t.closePath(), t.strokeStyle = e.borderColor, t.lineWidth = e.borderWidth, t.fillStyle = e.backgroundColor, t.fill(), t.lineJoin = "bevel", e.borderWidth && t.stroke()
}
})
}, {
26: 26,
27: 27,
46: 46
}],
38: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46),
a = r.global;
r._set("global", {
elements: {
line: {
tension: .4,
backgroundColor: a.defaultColor,
borderWidth: 3,
borderColor: a.defaultColor,
borderCapStyle: "butt",
borderDash: [],
borderDashOffset: 0,
borderJoinStyle: "miter",
capBezierPoints: !0,
fill: !0
}
}
}), e.exports = i.extend({
draw: function() {
var t, e, n, r, i = this._view,
s = this._chart.ctx,
l = i.spanGaps,
u = this._children.slice(),
c = a.elements.line,
d = -1;
for (this._loop && u.length && u.push(u[0]), s.save(), s.lineCap = i.borderCapStyle || c.borderCapStyle, s.setLineDash && s.setLineDash(i.borderDash || c.borderDash), s.lineDashOffset = i.borderDashOffset || c.borderDashOffset, s.lineJoin = i.borderJoinStyle || c.borderJoinStyle, s.lineWidth = i.borderWidth || c.borderWidth, s.strokeStyle = i.borderColor || a.defaultColor, s.beginPath(), d = -1, t = 0; t < u.length; ++t) e = u[t], n = o.previousItem(u, t), r = e._view, 0 === t ? r.skip || (s.moveTo(r.x, r.y), d = t) : (n = -1 === d ? n : u[d], r.skip || (d !== t - 1 && !l || -1 === d ? s.moveTo(r.x, r.y) : o.canvas.lineTo(s, n._view, e._view), d = t));
s.stroke(), s.restore()
}
})
}, {
26: 26,
27: 27,
46: 46
}],
39: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46),
a = r.global.defaultColor;
function s(t) {
var e = this._view;
return !!e && Math.abs(t - e.x) < e.radius + e.hitRadius
}
r._set("global", {
elements: {
point: {
radius: 3,
pointStyle: "circle",
backgroundColor: a,
borderColor: a,
borderWidth: 1,
hitRadius: 1,
hoverRadius: 4,
hoverBorderWidth: 1
}
}
}), e.exports = i.extend({
inRange: function(t, e) {
var n = this._view;
return !!n && Math.pow(t - n.x, 2) + Math.pow(e - n.y, 2) < Math.pow(n.hitRadius + n.radius, 2)
},
inLabelRange: s,
inXRange: s,
inYRange: function(t) {
var e = this._view;
return !!e && Math.abs(t - e.y) < e.radius + e.hitRadius
},
getCenterPoint: function() {
var t = this._view;
return {
x: t.x,
y: t.y
}
},
getArea: function() {
return Math.PI * Math.pow(this._view.radius, 2)
},
tooltipPosition: function() {
var t = this._view;
return {
x: t.x,
y: t.y,
padding: t.radius + t.borderWidth
}
},
draw: function(t) {
var e = this._view,
n = this._model,
i = this._chart.ctx,
s = e.pointStyle,
l = e.rotation,
u = e.radius,
c = e.x,
d = e.y;
e.skip || (void 0 === t || n.x >= t.left && 1.01 * t.right >= n.x && n.y >= t.top && 1.01 * t.bottom >= n.y) && (i.strokeStyle = e.borderColor || a, i.lineWidth = o.valueOrDefault(e.borderWidth, r.global.elements.point.borderWidth), i.fillStyle = e.backgroundColor || a, o.canvas.drawPoint(i, s, u, c, d, l))
}
})
}, {
26: 26,
27: 27,
46: 46
}],
40: [function(t, e, n) {
var r = t(26),
i = t(27);
function o(t) {
return void 0 !== t._view.width
}
function a(t) {
var e, n, r, i, a = t._view;
if (o(t)) {
var s = a.width / 2;
e = a.x - s, n = a.x + s, r = Math.min(a.y, a.base), i = Math.max(a.y, a.base)
} else {
var l = a.height / 2;
e = Math.min(a.x, a.base), n = Math.max(a.x, a.base), r = a.y - l, i = a.y + l
}
return {
left: e,
top: r,
right: n,
bottom: i
}
}
r._set("global", {
elements: {
rectangle: {
backgroundColor: r.global.defaultColor,
borderColor: r.global.defaultColor,
borderSkipped: "bottom",
borderWidth: 0
}
}
}), e.exports = i.extend({
draw: function() {
var t, e, n, r, i, o, a, s = this._chart.ctx,
l = this._view,
u = l.borderWidth;
if (l.horizontal ? (t = l.base, e = l.x, n = l.y - l.height / 2, r = l.y + l.height / 2, i = e > t ? 1 : -1, o = 1, a = l.borderSkipped || "left") : (t = l.x - l.width / 2, e = l.x + l.width / 2, n = l.y, i = 1, o = (r = l.base) > n ? 1 : -1, a = l.borderSkipped || "bottom"), u) {
var c = Math.min(Math.abs(t - e), Math.abs(n - r)),
d = (u = u > c ? c : u) / 2,
f = t + ("left" !== a ? d * i : 0),
h = e + ("right" !== a ? -d * i : 0),
p = n + ("top" !== a ? d * o : 0),
g = r + ("bottom" !== a ? -d * o : 0);
f !== h && (n = p, r = g), p !== g && (t = f, e = h)
}
s.beginPath(), s.fillStyle = l.backgroundColor, s.strokeStyle = l.borderColor, s.lineWidth = u;
var v = [
[t, r],
[t, n],
[e, n],
[e, r]
],
m = ["bottom", "left", "top", "right"].indexOf(a, 0);
function y(t) {
return v[(m + t) % 4]
} - 1 === m && (m = 0);
var b = y(0);
s.moveTo(b[0], b[1]);
for (var x = 1; x < 4; x++) b = y(x), s.lineTo(b[0], b[1]);
s.fill(), u && s.stroke()
},
height: function() {
var t = this._view;
return t.base - t.y
},
inRange: function(t, e) {
var n = !1;
if (this._view) {
var r = a(this);
n = t >= r.left && t <= r.right && e >= r.top && e <= r.bottom
}
return n
},
inLabelRange: function(t, e) {
if (!this._view) return !1;
var n = a(this);
return o(this) ? t >= n.left && t <= n.right : e >= n.top && e <= n.bottom
},
inXRange: function(t) {
var e = a(this);
return t >= e.left && t <= e.right
},
inYRange: function(t) {
var e = a(this);
return t >= e.top && t <= e.bottom
},
getCenterPoint: function() {
var t, e, n = this._view;
return o(this) ? (t = n.x, e = (n.y + n.base) / 2) : (t = (n.x + n.base) / 2, e = n.y), {
x: t,
y: e
}
},
getArea: function() {
var t = this._view;
return t.width * Math.abs(t.y - t.base)
},
tooltipPosition: function() {
var t = this._view;
return {
x: t.x,
y: t.y
}
}
})
}, {
26: 26,
27: 27
}],
41: [function(t, e, n) {
e.exports = {}, e.exports.Arc = t(37), e.exports.Line = t(38), e.exports.Point = t(39), e.exports.Rectangle = t(40)
}, {
37: 37,
38: 38,
39: 39,
40: 40
}],
42: [function(t, e, n) {
var r = t(43);
n = e.exports = {
clear: function(t) {
t.ctx.clearRect(0, 0, t.width, t.height)
},
roundedRect: function(t, e, n, r, i, o) {
if (o) {
var a = Math.min(o, i / 2 - 1e-7, r / 2 - 1e-7);
t.moveTo(e + a, n), t.lineTo(e + r - a, n), t.arcTo(e + r, n, e + r, n + a, a), t.lineTo(e + r, n + i - a), t.arcTo(e + r, n + i, e + r - a, n + i, a), t.lineTo(e + a, n + i), t.arcTo(e, n + i, e, n + i - a, a), t.lineTo(e, n + a), t.arcTo(e, n, e + a, n, a), t.closePath(), t.moveTo(e, n)
} else t.rect(e, n, r, i)
},
drawPoint: function(t, e, n, r, i, a) {
var s, l, u, c, d, f;
if (a = a || 0, !e || "object" !== o(e) || "[object HTMLImageElement]" !== (s = e.toString()) && "[object HTMLCanvasElement]" !== s) {
if (!(isNaN(n) || n <= 0)) {
switch (t.save(), t.translate(r, i), t.rotate(a * Math.PI / 180), t.beginPath(), e) {
default:
t.arc(0, 0, n, 0, 2 * Math.PI), t.closePath();
break;
case "triangle":
d = (l = 3 * n / Math.sqrt(3)) * Math.sqrt(3) / 2, t.moveTo(-l / 2, d / 3), t.lineTo(l / 2, d / 3), t.lineTo(0, -2 * d / 3), t.closePath();
break;
case "rect":
f = 1 / Math.SQRT2 * n, t.rect(-f, -f, 2 * f, 2 * f);
break;
case "rectRounded":
var h = n / Math.SQRT2,
p = -h,
g = -h,
v = Math.SQRT2 * n;
this.roundedRect(t, p, g, v, v, .425 * n);
break;
case "rectRot":
f = 1 / Math.SQRT2 * n, t.moveTo(-f, 0), t.lineTo(0, f), t.lineTo(f, 0), t.lineTo(0, -f), t.closePath();
break;
case "cross":
t.moveTo(0, n), t.lineTo(0, -n), t.moveTo(-n, 0), t.lineTo(n, 0);
break;
case "crossRot":
u = Math.cos(Math.PI / 4) * n, c = Math.sin(Math.PI / 4) * n, t.moveTo(-u, -c), t.lineTo(u, c), t.moveTo(-u, c), t.lineTo(u, -c);
break;
case "star":
t.moveTo(0, n), t.lineTo(0, -n), t.moveTo(-n, 0), t.lineTo(n, 0), u = Math.cos(Math.PI / 4) * n, c = Math.sin(Math.PI / 4) * n, t.moveTo(-u, -c), t.lineTo(u, c), t.moveTo(-u, c), t.lineTo(u, -c);
break;
case "line":
t.moveTo(-n, 0), t.lineTo(n, 0);
break;
case "dash":
t.moveTo(0, 0), t.lineTo(n, 0)
}
t.fill(), t.stroke(), t.restore()
}
} else t.drawImage(e, r - e.width / 2, i - e.height / 2, e.width, e.height)
},
clipArea: function(t, e) {
t.save(), t.beginPath(), t.rect(e.left, e.top, e.right - e.left, e.bottom - e.top), t.clip()
},
unclipArea: function(t) {
t.restore()
},
lineTo: function(t, e, n, r) {
if (n.steppedLine) return "after" === n.steppedLine && !r || "after" !== n.steppedLine && r ? t.lineTo(e.x, n.y) : t.lineTo(n.x, e.y), void t.lineTo(n.x, n.y);
n.tension ? t.bezierCurveTo(r ? e.controlPointPreviousX : e.controlPointNextX, r ? e.controlPointPreviousY : e.controlPointNextY, r ? n.controlPointNextX : n.controlPointPreviousX, r ? n.controlPointNextY : n.controlPointPreviousY, n.x, n.y) : t.lineTo(n.x, n.y)
}
};
r.clear = n.clear, r.drawRoundedRectangle = function(t) {
t.beginPath(), n.roundedRect.apply(n, arguments)
}
}, {
43: 43
}],
43: [function(t, e, n) {
var r, i = {
noop: function() {},
uid: (r = 0, function() {
return r++
}),
isNullOrUndef: function(t) {
return null == t
},
isArray: Array.isArray ? Array.isArray : function(t) {
return "[object Array]" === Object.prototype.toString.call(t)
},
isObject: function(t) {
return null !== t && "[object Object]" === Object.prototype.toString.call(t)
},
valueOrDefault: function(t, e) {
return void 0 === t ? e : t
},
valueAtIndexOrDefault: function(t, e, n) {
return i.valueOrDefault(i.isArray(t) ? t[e] : t, n)
},
callback: function(t, e, n) {
if (t && "function" == typeof t.call) return t.apply(n, e)
},
each: function(t, e, n, r) {
var o, a, s;
if (i.isArray(t))
if (a = t.length, r)
for (o = a - 1; o >= 0; o--) e.call(n, t[o], o);
else
for (o = 0; o < a; o++) e.call(n, t[o], o);
else if (i.isObject(t))
for (a = (s = Object.keys(t)).length, o = 0; o < a; o++) e.call(n, t[s[o]], s[o])
},
arrayEquals: function(t, e) {
var n, r, o, a;
if (!t || !e || t.length !== e.length) return !1;
for (n = 0, r = t.length; n < r; ++n)
if (o = t[n], a = e[n], o instanceof Array && a instanceof Array) {
if (!i.arrayEquals(o, a)) return !1
} else if (o !== a) return !1;
return !0
},
clone: function(t) {
if (i.isArray(t)) return t.map(i.clone);
if (i.isObject(t)) {
for (var e = {}, n = Object.keys(t), r = n.length, o = 0; o < r; ++o) e[n[o]] = i.clone(t[n[o]]);
return e
}
return t
},
_merger: function(t, e, n, r) {
var o = e[t],
a = n[t];
i.isObject(o) && i.isObject(a) ? i.merge(o, a, r) : e[t] = i.clone(a)
},
_mergerIf: function(t, e, n) {
var r = e[t],
o = n[t];
i.isObject(r) && i.isObject(o) ? i.mergeIf(r, o) : e.hasOwnProperty(t) || (e[t] = i.clone(o))
},
merge: function(t, e, n) {
var r, o, a, s, l, u = i.isArray(e) ? e : [e],
c = u.length;
if (!i.isObject(t)) return t;
for (r = (n = n || {}).merger || i._merger, o = 0; o < c; ++o)
if (e = u[o], i.isObject(e))
for (l = 0, s = (a = Object.keys(e)).length; l < s; ++l) r(a[l], t, e, n);
return t
},
mergeIf: function(t, e) {
return i.merge(t, e, {
merger: i._mergerIf
})
},
extend: function(t) {
for (var e = function(e, n) {
t[n] = e
}, n = 1, r = arguments.length; n < r; ++n) i.each(arguments[n], e);
return t
},
inherits: function(t) {
var e = this,
n = t && t.hasOwnProperty("constructor") ? t.constructor : function() {
return e.apply(this, arguments)
},
r = function() {
this.constructor = n
};
return r.prototype = e.prototype, n.prototype = new r, n.extend = i.inherits, t && i.extend(n.prototype, t), n.__super__ = e.prototype, n
}
};
e.exports = i, i.callCallback = i.callback, i.indexOf = function(t, e, n) {
return Array.prototype.indexOf.call(t, e, n)
}, i.getValueOrDefault = i.valueOrDefault, i.getValueAtIndexOrDefault = i.valueAtIndexOrDefault
}, {}],
44: [function(t, e, n) {
var r = t(43),
i = {
linear: function(t) {
return t
},
easeInQuad: function(t) {
return t * t
},
easeOutQuad: function(t) {
return -t * (t - 2)
},
easeInOutQuad: function(t) {
return (t /= .5) < 1 ? .5 * t * t : -.5 * (--t * (t - 2) - 1)
},
easeInCubic: function(t) {
return t * t * t
},
easeOutCubic: function(t) {
return (t -= 1) * t * t + 1
},
easeInOutCubic: function(t) {
return (t /= .5) < 1 ? .5 * t * t * t : .5 * ((t -= 2) * t * t + 2)
},
easeInQuart: function(t) {
return t * t * t * t
},
easeOutQuart: function(t) {
return -((t -= 1) * t * t * t - 1)
},
easeInOutQuart: function(t) {
return (t /= .5) < 1 ? .5 * t * t * t * t : -.5 * ((t -= 2) * t * t * t - 2)
},
easeInQuint: function(t) {
return t * t * t * t * t
},
easeOutQuint: function(t) {
return (t -= 1) * t * t * t * t + 1
},
easeInOutQuint: function(t) {
return (t /= .5) < 1 ? .5 * t * t * t * t * t : .5 * ((t -= 2) * t * t * t * t + 2)
},
easeInSine: function(t) {
return 1 - Math.cos(t * (Math.PI / 2))
},
easeOutSine: function(t) {
return Math.sin(t * (Math.PI / 2))
},
easeInOutSine: function(t) {
return -.5 * (Math.cos(Math.PI * t) - 1)
},
easeInExpo: function(t) {
return 0 === t ? 0 : Math.pow(2, 10 * (t - 1))
},
easeOutExpo: function(t) {
return 1 === t ? 1 : 1 - Math.pow(2, -10 * t)
},
easeInOutExpo: function(t) {
return 0 === t ? 0 : 1 === t ? 1 : (t /= .5) < 1 ? .5 * Math.pow(2, 10 * (t - 1)) : .5 * (2 - Math.pow(2, -10 * --t))
},
easeInCirc: function(t) {
return t >= 1 ? t : -(Math.sqrt(1 - t * t) - 1)
},
easeOutCirc: function(t) {
return Math.sqrt(1 - (t -= 1) * t)
},
easeInOutCirc: function(t) {
return (t /= .5) < 1 ? -.5 * (Math.sqrt(1 - t * t) - 1) : .5 * (Math.sqrt(1 - (t -= 2) * t) + 1)
},
easeInElastic: function(t) {
var e = 1.70158,
n = 0,
r = 1;
return 0 === t ? 0 : 1 === t ? 1 : (n || (n = .3), r < 1 ? (r = 1, e = n / 4) : e = n / (2 * Math.PI) * Math.asin(1 / r), -r * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - e) * (2 * Math.PI) / n))
},
easeOutElastic: function(t) {
var e = 1.70158,
n = 0,
r = 1;
return 0 === t ? 0 : 1 === t ? 1 : (n || (n = .3), r < 1 ? (r = 1, e = n / 4) : e = n / (2 * Math.PI) * Math.asin(1 / r), r * Math.pow(2, -10 * t) * Math.sin((t - e) * (2 * Math.PI) / n) + 1)
},
easeInOutElastic: function(t) {
var e = 1.70158,
n = 0,
r = 1;
return 0 === t ? 0 : 2 == (t /= .5) ? 1 : (n || (n = .45), r < 1 ? (r = 1, e = n / 4) : e = n / (2 * Math.PI) * Math.asin(1 / r), t < 1 ? r * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - e) * (2 * Math.PI) / n) * -.5 : r * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - e) * (2 * Math.PI) / n) * .5 + 1)
},
easeInBack: function(t) {
var e = 1.70158;
return t * t * ((e + 1) * t - e)
},
easeOutBack: function(t) {
var e = 1.70158;
return (t -= 1) * t * ((e + 1) * t + e) + 1
},
easeInOutBack: function(t) {
var e = 1.70158;
return (t /= .5) < 1 ? t * t * ((1 + (e *= 1.525)) * t - e) * .5 : .5 * ((t -= 2) * t * ((1 + (e *= 1.525)) * t + e) + 2)
},
easeInBounce: function(t) {
return 1 - i.easeOutBounce(1 - t)
},
easeOutBounce: function(t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375
},
easeInOutBounce: function(t) {
return t < .5 ? .5 * i.easeInBounce(2 * t) : .5 * i.easeOutBounce(2 * t - 1) + .5
}
};
e.exports = {
effects: i
}, r.easingEffects = i
}, {
43: 43
}],
45: [function(t, e, n) {
var r = t(43);
e.exports = {
toLineHeight: function(t, e) {
var n = ("" + t).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
if (!n || "normal" === n[1]) return 1.2 * e;
switch (t = +n[2], n[3]) {
case "px":
return t;
case "%":
t /= 100
}
return e * t
},
toPadding: function(t) {
var e, n, i, o;
return r.isObject(t) ? (e = +t.top || 0, n = +t.right || 0, i = +t.bottom || 0, o = +t.left || 0) : e = n = i = o = +t || 0, {
top: e,
right: n,
bottom: i,
left: o,
height: e + i,
width: o + n
}
},
resolve: function(t, e, n) {
var i, o, a;
for (i = 0, o = t.length; i < o; ++i)
if (void 0 !== (a = t[i]) && (void 0 !== e && "function" == typeof a && (a = a(e)), void 0 !== n && r.isArray(a) && (a = a[n]), void 0 !== a)) return a
}
}
}, {
43: 43
}],
46: [function(t, e, n) {
e.exports = t(43), e.exports.easing = t(44), e.exports.canvas = t(42), e.exports.options = t(45)
}, {
42: 42,
43: 43,
44: 44,
45: 45
}],
47: [function(t, e, n) {
e.exports = {
acquireContext: function(t) {
return t && t.canvas && (t = t.canvas), t && t.getContext("2d") || null
}
}
}, {}],
48: [function(t, e, n) {
var r = t(46),
i = "$chartjs",
o = "chartjs-",
a = o + "render-monitor",
s = o + "render-animation",
l = ["animationstart", "webkitAnimationStart"],
u = {
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup",
pointerenter: "mouseenter",
pointerdown: "mousedown",
pointermove: "mousemove",
pointerup: "mouseup",
pointerleave: "mouseout",
pointerout: "mouseout"
};
function c(t, e) {
var n = r.getStyle(t, e),
i = n && n.match(/^(\d+)(\.\d+)?px$/);
return i ? Number(i[1]) : void 0
}
var d = !! function() {
var t = !1;
try {
var e = Object.defineProperty({}, "passive", {
get: function() {
t = !0
}
});
window.addEventListener("e", null, e)
} catch (t) {}
return t
}() && {
passive: !0
};
function f(t, e, n) {
t.addEventListener(e, n, d)
}
function h(t, e, n) {
t.removeEventListener(e, n, d)
}
function p(t, e, n, r, i) {
return {
type: t,
chart: e,
native: i || null,
x: void 0 !== n ? n : null,
y: void 0 !== r ? r : null
}
}
function g(t, e, n) {
var u, c, d, h, g = t[i] || (t[i] = {}),
v = g.resizer = function(t) {
var e = document.createElement("div"),
n = o + "size-monitor",
r = "position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;";
e.style.cssText = r, e.className = n, e.innerHTML = '<div class="' + n + '-expand" style="' + r + '"><div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div></div><div class="' + n + '-shrink" style="' + r + '"><div style="position:absolute;width:200%;height:200%;left:0; top:0"></div></div>';
var i = e.childNodes[0],
a = e.childNodes[1];
e._reset = function() {
i.scrollLeft = 1e6, i.scrollTop = 1e6, a.scrollLeft = 1e6, a.scrollTop = 1e6
};
var s = function() {
e._reset(), t()
};
return f(i, "scroll", s.bind(i, "expand")), f(a, "scroll", s.bind(a, "shrink")), e
}((u = function() {
if (g.resizer) return e(p("resize", n))
}, d = !1, h = [], function() {
h = Array.prototype.slice.call(arguments), c = c || this, d || (d = !0, r.requestAnimFrame.call(window, (function() {
d = !1, u.apply(c, h)
})))
}));
! function(t, e) {
var n = t[i] || (t[i] = {}),
o = n.renderProxy = function(t) {
t.animationName === s && e()
};
r.each(l, (function(e) {
f(t, e, o)
})), n.reflow = !!t.offsetParent, t.classList.add(a)
}(t, (function() {
if (g.resizer) {
var e = t.parentNode;
e && e !== v.parentNode && e.insertBefore(v, e.firstChild), v._reset()
}
}))
}
function v(t) {
var e = t[i] || {},
n = e.resizer;
delete e.resizer,
function(t) {
var e = t[i] || {},
n = e.renderProxy;
n && (r.each(l, (function(e) {
h(t, e, n)
})), delete e.renderProxy), t.classList.remove(a)
}(t), n && n.parentNode && n.parentNode.removeChild(n)
}
e.exports = {
_enabled: "undefined" != typeof window && "undefined" != typeof document,
initialize: function() {
var t, e, n, r = "from{opacity:0.99}to{opacity:1}";
e = "@-webkit-keyframes " + s + "{" + r + "}@keyframes " + s + "{" + r + "}." + a + "{-webkit-animation:" + s + " 0.001s;animation:" + s + " 0.001s;}", n = (t = this)._style || document.createElement("style"), t._style || (t._style = n, e = "/* Chart.js */\n" + e, n.setAttribute("type", "text/css"), document.getElementsByTagName("head")[0].appendChild(n)), n.appendChild(document.createTextNode(e))
},
acquireContext: function(t, e) {
"string" == typeof t ? t = document.getElementById(t) : t.length && (t = t[0]), t && t.canvas && (t = t.canvas);
var n = t && t.getContext && t.getContext("2d");
return n && n.canvas === t ? (function(t, e) {
var n = t.style,
r = t.getAttribute("height"),
o = t.getAttribute("width");
if (t[i] = {
initial: {
height: r,
width: o,
style: {
display: n.display,
height: n.height,
width: n.width
}
}
}, n.display = n.display || "block", null === o || "" === o) {
var a = c(t, "width");
void 0 !== a && (t.width = a)
}
if (null === r || "" === r)
if ("" === t.style.height) t.height = t.width / (e.options.aspectRatio || 2);
else {
var s = c(t, "height");
void 0 !== a && (t.height = s)
}
}(t, e), n) : null
},
releaseContext: function(t) {
var e = t.canvas;
if (e[i]) {
var n = e[i].initial;
["height", "width"].forEach((function(t) {
var i = n[t];
r.isNullOrUndef(i) ? e.removeAttribute(t) : e.setAttribute(t, i)
})), r.each(n.style || {}, (function(t, n) {
e.style[n] = t
})), e.width = e.width, delete e[i]
}
},
addEventListener: function(t, e, n) {
var o = t.canvas;
if ("resize" !== e) {
var a = n[i] || (n[i] = {});
f(o, e, (a.proxies || (a.proxies = {}))[t.id + "_" + e] = function(e) {
n(function(t, e) {
var n = u[t.type] || t.type,
i = r.getRelativePosition(t, e);
return p(n, e, i.x, i.y, t)
}(e, t))
})
} else g(o, n, t)
},
removeEventListener: function(t, e, n) {
var r = t.canvas;
if ("resize" !== e) {
var o = ((n[i] || {}).proxies || {})[t.id + "_" + e];
o && h(r, e, o)
} else v(r)
}
}, r.addEvent = f, r.removeEvent = h
}, {
46: 46
}],
49: [function(t, e, n) {
var r = t(46),
i = t(47),
o = t(48),
a = o._enabled ? o : i;
e.exports = r.extend({
initialize: function() {},
acquireContext: function() {},
releaseContext: function() {},
addEventListener: function() {},
removeEventListener: function() {}
}, a)
}, {
46: 46,
47: 47,
48: 48
}],
50: [function(t, e, n) {
e.exports = {}, e.exports.filler = t(51), e.exports.legend = t(52), e.exports.title = t(53)
}, {
51: 51,
52: 52,
53: 53
}],
51: [function(t, e, n) {
var r = t(26),
i = t(41),
o = t(46);
r._set("global", {
plugins: {
filler: {
propagate: !0
}
}
});
var a = {
dataset: function(t) {
var e = t.fill,
n = t.chart,
r = n.getDatasetMeta(e),
i = r && n.isDatasetVisible(e) && r.dataset._children || [],
o = i.length || 0;
return o ? function(t, e) {
return e < o && i[e]._view || null
} : null
},
boundary: function(t) {
var e = t.boundary,
n = e ? e.x : null,
r = e ? e.y : null;
return function(t) {
return {
x: null === n ? t.x : n,
y: null === r ? t.y : r
}
}
}
};
function s(t, e, n) {
var r, i = t._model || {},
o = i.fill;
if (void 0 === o && (o = !!i.backgroundColor), !1 === o || null === o) return !1;
if (!0 === o) return "origin";
if (r = parseFloat(o, 10), isFinite(r) && Math.floor(r) === r) return "-" !== o[0] && "+" !== o[0] || (r = e + r), !(r === e || r < 0 || r >= n) && r;
switch (o) {
case "bottom":
return "start";
case "top":
return "end";
case "zero":
return "origin";
case "origin":
case "start":
case "end":
return o;
default:
return !1
}
}
function l(t) {
var e, n = t.el._model || {},
r = t.el._scale || {},
i = t.fill,
o = null;
if (isFinite(i)) return null;
if ("start" === i ? o = void 0 === n.scaleBottom ? r.bottom : n.scaleBottom : "end" === i ? o = void 0 === n.scaleTop ? r.top : n.scaleTop : void 0 !== n.scaleZero ? o = n.scaleZero : r.getBasePosition ? o = r.getBasePosition() : r.getBasePixel && (o = r.getBasePixel()), null != o) {
if (void 0 !== o.x && void 0 !== o.y) return o;
if ("number" == typeof o && isFinite(o)) return {
x: (e = r.isHorizontal()) ? o : null,
y: e ? null : o
}
}
return null
}
function u(t, e, n) {
var r, i = t[e].fill,
o = [e];
if (!n) return i;
for (; !1 !== i && -1 === o.indexOf(i);) {
if (!isFinite(i)) return i;
if (!(r = t[i])) return !1;
if (r.visible) return i;
o.push(i), i = r.fill
}
return !1
}
function c(t) {
var e = t.fill,
n = "dataset";
return !1 === e ? null : (isFinite(e) || (n = "boundary"), a[n](t))
}
function d(t) {
return t && !t.skip
}
function f(t, e, n, r, i) {
var a;
if (r && i) {
for (t.moveTo(e[0].x, e[0].y), a = 1; a < r; ++a) o.canvas.lineTo(t, e[a - 1], e[a]);
for (t.lineTo(n[i - 1].x, n[i - 1].y), a = i - 1; a > 0; --a) o.canvas.lineTo(t, n[a], n[a - 1], !0)
}
}
e.exports = {
id: "filler",
afterDatasetsUpdate: function(t, e) {
var n, r, o, a, d = (t.data.datasets || []).length,
f = e.propagate,
h = [];
for (r = 0; r < d; ++r) a = null, (o = (n = t.getDatasetMeta(r)).dataset) && o._model && o instanceof i.Line && (a = {
visible: t.isDatasetVisible(r),
fill: s(o, r, d),
chart: t,
el: o
}), n.$filler = a, h.push(a);
for (r = 0; r < d; ++r)(a = h[r]) && (a.fill = u(h, r, f), a.boundary = l(a), a.mapper = c(a))
},
beforeDatasetDraw: function(t, e) {
var n = e.meta.$filler;
if (n) {
var i = t.ctx,
a = n.el,
s = a._view,
l = a._children || [],
u = n.mapper,
c = s.backgroundColor || r.global.defaultColor;
u && c && l.length && (o.canvas.clipArea(i, t.chartArea), function(t, e, n, r, i, o) {
var a, s, l, u, c, h, p, g = e.length,
v = r.spanGaps,
m = [],
y = [],
b = 0,
x = 0;
for (t.beginPath(), a = 0, s = g + !!o; a < s; ++a) c = n(u = e[l = a % g]._view, l, r), h = d(u), p = d(c), h && p ? (b = m.push(u), x = y.push(c)) : b && x && (v ? (h && m.push(u), p && y.push(c)) : (f(t, m, y, b, x), b = x = 0, m = [], y = []));
f(t, m, y, b, x), t.closePath(), t.fillStyle = i, t.fill()
}(i, l, u, s, c, a._loop), o.canvas.unclipArea(i))
}
}
}
}, {
26: 26,
41: 41,
46: 46
}],
52: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46),
a = t(31),
s = o.noop;
function l(t, e) {
return t.usePointStyle ? e * Math.SQRT2 : t.boxWidth
}
r._set("global", {
legend: {
display: !0,
position: "top",
fullWidth: !0,
reverse: !1,
weight: 1e3,
onClick: function(t, e) {
var n = e.datasetIndex,
r = this.chart,
i = r.getDatasetMeta(n);
i.hidden = null === i.hidden ? !r.data.datasets[n].hidden : null, r.update()
},
onHover: null,
labels: {
boxWidth: 40,
padding: 10,
generateLabels: function(t) {
var e = t.data;
return o.isArray(e.datasets) ? e.datasets.map((function(e, n) {
return {
text: e.label,
fillStyle: o.isArray(e.backgroundColor) ? e.backgroundColor[0] : e.backgroundColor,
hidden: !t.isDatasetVisible(n),
lineCap: e.borderCapStyle,
lineDash: e.borderDash,
lineDashOffset: e.borderDashOffset,
lineJoin: e.borderJoinStyle,
lineWidth: e.borderWidth,
strokeStyle: e.borderColor,
pointStyle: e.pointStyle,
datasetIndex: n
}
}), this) : []
}
}
},
legendCallback: function(t) {
var e = [];
e.push('<ul class="' + t.id + '-legend">');
for (var n = 0; n < t.data.datasets.length; n++) e.push('<li><span style="background-color:' + t.data.datasets[n].backgroundColor + '"></span>'), t.data.datasets[n].label && e.push(t.data.datasets[n].label), e.push("</li>");
return e.push("</ul>"), e.join("")
}
});
var u = i.extend({
initialize: function(t) {
o.extend(this, t), this.legendHitBoxes = [], this.doughnutMode = !1
},
beforeUpdate: s,
update: function(t, e, n) {
var r = this;
return r.beforeUpdate(), r.maxWidth = t, r.maxHeight = e, r.margins = n, r.beforeSetDimensions(), r.setDimensions(), r.afterSetDimensions(), r.beforeBuildLabels(), r.buildLabels(), r.afterBuildLabels(), r.beforeFit(), r.fit(), r.afterFit(), r.afterUpdate(), r.minSize
},
afterUpdate: s,
beforeSetDimensions: s,
setDimensions: function() {
var t = this;
t.isHorizontal() ? (t.width = t.maxWidth, t.left = 0, t.right = t.width) : (t.height = t.maxHeight, t.top = 0, t.bottom = t.height), t.paddingLeft = 0, t.paddingTop = 0, t.paddingRight = 0, t.paddingBottom = 0, t.minSize = {
width: 0,
height: 0
}
},
afterSetDimensions: s,
beforeBuildLabels: s,
buildLabels: function() {
var t = this,
e = t.options.labels || {},
n = o.callback(e.generateLabels, [t.chart], t) || [];
e.filter && (n = n.filter((function(n) {
return e.filter(n, t.chart.data)
}))), t.options.reverse && n.reverse(), t.legendItems = n
},
afterBuildLabels: s,
beforeFit: s,
fit: function() {
var t = this,
e = t.options,
n = e.labels,
i = e.display,
a = t.ctx,
s = r.global,
u = o.valueOrDefault,
c = u(n.fontSize, s.defaultFontSize),
d = u(n.fontStyle, s.defaultFontStyle),
f = u(n.fontFamily, s.defaultFontFamily),
h = o.fontString(c, d, f),
p = t.legendHitBoxes = [],
g = t.minSize,
v = t.isHorizontal();
if (v ? (g.width = t.maxWidth, g.height = i ? 10 : 0) : (g.width = i ? 10 : 0, g.height = t.maxHeight), i)
if (a.font = h, v) {
var m = t.lineWidths = [0],
y = t.legendItems.length ? c + n.padding : 0;
a.textAlign = "left", a.textBaseline = "top", o.each(t.legendItems, (function(e, r) {
var i = l(n, c) + c / 2 + a.measureText(e.text).width;
m[m.length - 1] + i + n.padding >= t.width && (y += c + n.padding, m[m.length] = t.left), p[r] = {
left: 0,
top: 0,
width: i,
height: c
}, m[m.length - 1] += i + n.padding
})), g.height += y
} else {
var b = n.padding,
x = t.columnWidths = [],
w = n.padding,
S = 0,
k = 0,
C = c + b;
o.each(t.legendItems, (function(t, e) {
var r = l(n, c) + c / 2 + a.measureText(t.text).width;
k + C > g.height && (w += S + n.padding, x.push(S), S = 0, k = 0), S = Math.max(S, r), k += C, p[e] = {
left: 0,
top: 0,
width: r,
height: c
}
})), w += S, x.push(S), g.width += w
} t.width = g.width, t.height = g.height
},
afterFit: s,
isHorizontal: function() {
return "top" === this.options.position || "bottom" === this.options.position
},
draw: function() {
var t = this,
e = t.options,
n = e.labels,
i = r.global,
a = i.elements.line,
s = t.width,
u = t.lineWidths;
if (e.display) {
var c, d = t.ctx,
f = o.valueOrDefault,
h = f(n.fontColor, i.defaultFontColor),
p = f(n.fontSize, i.defaultFontSize),
g = f(n.fontStyle, i.defaultFontStyle),
v = f(n.fontFamily, i.defaultFontFamily),
m = o.fontString(p, g, v);
d.textAlign = "left", d.textBaseline = "middle", d.lineWidth = .5, d.strokeStyle = h, d.fillStyle = h, d.font = m;
var y = l(n, p),
b = t.legendHitBoxes,
x = t.isHorizontal();
c = x ? {
x: t.left + (s - u[0]) / 2,
y: t.top + n.padding,
line: 0
} : {
x: t.left + n.padding,
y: t.top + n.padding,
line: 0
};
var w = p + n.padding;
o.each(t.legendItems, (function(r, l) {
var h = d.measureText(r.text).width,
g = y + p / 2 + h,
v = c.x,
m = c.y;
x ? v + g >= s && (m = c.y += w, c.line++, v = c.x = t.left + (s - u[c.line]) / 2) : m + w > t.bottom && (v = c.x = v + t.columnWidths[c.line] + n.padding, m = c.y = t.top + n.padding, c.line++),
function(t, n, r) {
if (!(isNaN(y) || y <= 0)) {
d.save(), d.fillStyle = f(r.fillStyle, i.defaultColor), d.lineCap = f(r.lineCap, a.borderCapStyle), d.lineDashOffset = f(r.lineDashOffset, a.borderDashOffset), d.lineJoin = f(r.lineJoin, a.borderJoinStyle), d.lineWidth = f(r.lineWidth, a.borderWidth), d.strokeStyle = f(r.strokeStyle, i.defaultColor);
var s = 0 === f(r.lineWidth, a.borderWidth);
if (d.setLineDash && d.setLineDash(f(r.lineDash, a.borderDash)), e.labels && e.labels.usePointStyle) {
var l = p * Math.SQRT2 / 2,
u = l / Math.SQRT2,
c = t + u,
h = n + u;
o.canvas.drawPoint(d, r.pointStyle, l, c, h)
} else s || d.strokeRect(t, n, y, p), d.fillRect(t, n, y, p);
d.restore()
}
}(v, m, r), b[l].left = v, b[l].top = m,
function(t, e, n, r) {
var i = p / 2,
o = y + i + t,
a = e + i;
d.fillText(n.text, o, a), n.hidden && (d.beginPath(), d.lineWidth = 2, d.moveTo(o, a), d.lineTo(o + r, a), d.stroke())
}(v, m, r, h), x ? c.x += g + n.padding : c.y += w
}))
}
},
handleEvent: function(t) {
var e = this,
n = e.options,
r = "mouseup" === t.type ? "click" : t.type,
i = !1;
if ("mousemove" === r) {
if (!n.onHover) return
} else {
if ("click" !== r) return;
if (!n.onClick) return
}
var o = t.x,
a = t.y;
if (o >= e.left && o <= e.right && a >= e.top && a <= e.bottom)
for (var s = e.legendHitBoxes, l = 0; l < s.length; ++l) {
var u = s[l];
if (o >= u.left && o <= u.left + u.width && a >= u.top && a <= u.top + u.height) {
if ("click" === r) {
n.onClick.call(e, t.native, e.legendItems[l]), i = !0;
break
}
if ("mousemove" === r) {
n.onHover.call(e, t.native, e.legendItems[l]), i = !0;
break
}
}
}
return i
}
});
function c(t, e) {
var n = new u({
ctx: t.ctx,
options: e,
chart: t
});
a.configure(t, n, e), a.addBox(t, n), t.legend = n
}
e.exports = {
id: "legend",
_element: u,
beforeInit: function(t) {
var e = t.options.legend;
e && c(t, e)
},
beforeUpdate: function(t) {
var e = t.options.legend,
n = t.legend;
e ? (o.mergeIf(e, r.global.legend), n ? (a.configure(t, n, e), n.options = e) : c(t, e)) : n && (a.removeBox(t, n), delete t.legend)
},
afterEvent: function(t, e) {
var n = t.legend;
n && n.handleEvent(e)
}
}
}, {
26: 26,
27: 27,
31: 31,
46: 46
}],
53: [function(t, e, n) {
var r = t(26),
i = t(27),
o = t(46),
a = t(31),
s = o.noop;
r._set("global", {
title: {
display: !1,
fontStyle: "bold",
fullWidth: !0,
lineHeight: 1.2,
padding: 10,
position: "top",
text: "",
weight: 2e3
}
});
var l = i.extend({
initialize: function(t) {
o.extend(this, t), this.legendHitBoxes = []
},
beforeUpdate: s,
update: function(t, e, n) {
var r = this;
return r.beforeUpdate(), r.maxWidth = t, r.maxHeight = e, r.margins = n, r.beforeSetDimensions(), r.setDimensions(), r.afterSetDimensions(), r.beforeBuildLabels(), r.buildLabels(), r.afterBuildLabels(), r.beforeFit(), r.fit(), r.afterFit(), r.afterUpdate(), r.minSize
},
afterUpdate: s,
beforeSetDimensions: s,
setDimensions: function() {
var t = this;
t.isHorizontal() ? (t.width = t.maxWidth, t.left = 0, t.right = t.width) : (t.height = t.maxHeight, t.top = 0, t.bottom = t.height), t.paddingLeft = 0, t.paddingTop = 0, t.paddingRight = 0, t.paddingBottom = 0, t.minSize = {
width: 0,
height: 0
}
},
afterSetDimensions: s,
beforeBuildLabels: s,
buildLabels: s,
afterBuildLabels: s,
beforeFit: s,
fit: function() {
var t = this,
e = o.valueOrDefault,
n = t.options,
i = n.display,
a = e(n.fontSize, r.global.defaultFontSize),
s = t.minSize,
l = o.isArray(n.text) ? n.text.length : 1,
u = o.options.toLineHeight(n.lineHeight, a),
c = i ? l * u + 2 * n.padding : 0;
t.isHorizontal() ? (s.width = t.maxWidth, s.height = c) : (s.width = c, s.height = t.maxHeight), t.width = s.width, t.height = s.height
},
afterFit: s,
isHorizontal: function() {
var t = this.options.position;
return "top" === t || "bottom" === t
},
draw: function() {
var t = this,
e = t.ctx,
n = o.valueOrDefault,
i = t.options,
a = r.global;
if (i.display) {
var s, l, u, c = n(i.fontSize, a.defaultFontSize),
d = n(i.fontStyle, a.defaultFontStyle),
f = n(i.fontFamily, a.defaultFontFamily),
h = o.fontString(c, d, f),
p = o.options.toLineHeight(i.lineHeight, c),
g = p / 2 + i.padding,
v = 0,
m = t.top,
y = t.left,
b = t.bottom,
x = t.right;
e.fillStyle = n(i.fontColor, a.defaultFontColor), e.font = h, t.isHorizontal() ? (l = y + (x - y) / 2, u = m + g, s = x - y) : (l = "left" === i.position ? y + g : x - g, u = m + (b - m) / 2, s = b - m, v = Math.PI * ("left" === i.position ? -.5 : .5)), e.save(), e.translate(l, u), e.rotate(v), e.textAlign = "center", e.textBaseline = "middle";
var w = i.text;
if (o.isArray(w))
for (var S = 0, k = 0; k < w.length; ++k) e.fillText(w[k], 0, S, s), S += p;
else e.fillText(w, 0, 0, s);
e.restore()
}
}
});
function u(t, e) {
var n = new l({
ctx: t.ctx,
options: e,
chart: t
});
a.configure(t, n, e), a.addBox(t, n), t.titleBlock = n
}
e.exports = {
id: "title",
_element: l,
beforeInit: function(t) {
var e = t.options.title;
e && u(t, e)
},
beforeUpdate: function(t) {
var e = t.options.title,
n = t.titleBlock;
e ? (o.mergeIf(e, r.global.title), n ? (a.configure(t, n, e), n.options = e) : u(t, e)) : n && (a.removeBox(t, n), delete t.titleBlock)
}
}
}, {
26: 26,
27: 27,
31: 31,
46: 46
}],
54: [function(t, e, n) {
var r = t(33),
i = t(34);
e.exports = function() {
var t = r.extend({
getLabels: function() {
var t = this.chart.data;
return this.options.labels || (this.isHorizontal() ? t.xLabels : t.yLabels) || t.labels
},
determineDataLimits: function() {
var t, e = this,
n = e.getLabels();
e.minIndex = 0, e.maxIndex = n.length - 1, void 0 !== e.options.ticks.min && (t = n.indexOf(e.options.ticks.min), e.minIndex = -1 !== t ? t : e.minIndex), void 0 !== e.options.ticks.max && (t = n.indexOf(e.options.ticks.max), e.maxIndex = -1 !== t ? t : e.maxIndex), e.min = n[e.minIndex], e.max = n[e.maxIndex]
},
buildTicks: function() {
var t = this,
e = t.getLabels();
t.ticks = 0 === t.minIndex && t.maxIndex === e.length - 1 ? e : e.slice(t.minIndex, t.maxIndex + 1)
},
getLabelForIndex: function(t, e) {
var n = this,
r = n.chart.data,
i = n.isHorizontal();
return r.yLabels && !i ? n.getRightValue(r.datasets[e].data[t]) : n.ticks[t - n.minIndex]
},
getPixelForValue: function(t, e) {
var n, r = this,
i = r.options.offset,
o = Math.max(r.maxIndex + 1 - r.minIndex - (i ? 0 : 1), 1);
if (null != t && (n = r.isHorizontal() ? t.x : t.y), void 0 !== n || void 0 !== t && isNaN(e)) {
t = n || t;
var a = r.getLabels().indexOf(t);
e = -1 !== a ? a : e
}
if (r.isHorizontal()) {
var s = r.width / o,
l = s * (e - r.minIndex);
return i && (l += s / 2), r.left + Math.round(l)
}
var u = r.height / o,
c = u * (e - r.minIndex);
return i && (c += u / 2), r.top + Math.round(c)
},
getPixelForTick: function(t) {
return this.getPixelForValue(this.ticks[t], t + this.minIndex, null)
},
getValueForPixel: function(t) {
var e = this,
n = e.options.offset,
r = Math.max(e._ticks.length - (n ? 0 : 1), 1),
i = e.isHorizontal(),
o = (i ? e.width : e.height) / r;
return t -= i ? e.left : e.top, n && (t -= o / 2), (t <= 0 ? 0 : Math.round(t / o)) + e.minIndex
},
getBasePixel: function() {
return this.bottom
}
});
i.registerScaleType("category", t, {
position: "bottom"
})
}
}, {
33: 33,
34: 34
}],
55: [function(t, e, n) {
var r = t(26),
i = t(46),
o = t(34),
a = t(35);
e.exports = function(t) {
var e = {
position: "left",
ticks: {
callback: a.formatters.linear
}
},
n = t.LinearScaleBase.extend({
determineDataLimits: function() {
var t = this,
e = t.options,
n = t.chart,
r = n.data.datasets,
o = t.isHorizontal();
function a(e) {
return o ? e.xAxisID === t.id : e.yAxisID === t.id
}
t.min = null, t.max = null;
var s = e.stacked;
if (void 0 === s && i.each(r, (function(t, e) {
if (!s) {
var r = n.getDatasetMeta(e);
n.isDatasetVisible(e) && a(r) && void 0 !== r.stack && (s = !0)
}
})), e.stacked || s) {
var l = {};
i.each(r, (function(r, o) {
var s = n.getDatasetMeta(o),
u = [s.type, void 0 === e.stacked && void 0 === s.stack ? o : "", s.stack].join(".");
void 0 === l[u] && (l[u] = {
positiveValues: [],
negativeValues: []
});
var c = l[u].positiveValues,
d = l[u].negativeValues;
n.isDatasetVisible(o) && a(s) && i.each(r.data, (function(n, r) {
var i = +t.getRightValue(n);
isNaN(i) || s.data[r].hidden || (c[r] = c[r] || 0, d[r] = d[r] || 0, e.relativePoints ? c[r] = 100 : i < 0 ? d[r] += i : c[r] += i)
}))
})), i.each(l, (function(e) {
var n = e.positiveValues.concat(e.negativeValues),
r = i.min(n),
o = i.max(n);
t.min = null === t.min ? r : Math.min(t.min, r), t.max = null === t.max ? o : Math.max(t.max, o)
}))
} else i.each(r, (function(e, r) {
var o = n.getDatasetMeta(r);
n.isDatasetVisible(r) && a(o) && i.each(e.data, (function(e, n) {
var r = +t.getRightValue(e);
isNaN(r) || o.data[n].hidden || (null === t.min ? t.min = r : r < t.min && (t.min = r), null === t.max ? t.max = r : r > t.max && (t.max = r))
}))
}));
t.min = isFinite(t.min) && !isNaN(t.min) ? t.min : 0, t.max = isFinite(t.max) && !isNaN(t.max) ? t.max : 1, this.handleTickRangeOptions()
},
getTickLimit: function() {
var t, e = this.options.ticks;
if (this.isHorizontal()) t = Math.min(e.maxTicksLimit ? e.maxTicksLimit : 11, Math.ceil(this.width / 50));
else {
var n = i.valueOrDefault(e.fontSize, r.global.defaultFontSize);
t = Math.min(e.maxTicksLimit ? e.maxTicksLimit : 11, Math.ceil(this.height / (2 * n)))
}
return t
},
handleDirectionalChanges: function() {
this.isHorizontal() || this.ticks.reverse()
},
getLabelForIndex: function(t, e) {
return +this.getRightValue(this.chart.data.datasets[e].data[t])
},
getPixelForValue: function(t) {
var e = this,
n = e.start,
r = +e.getRightValue(t),
i = e.end - n;
return e.isHorizontal() ? e.left + e.width / i * (r - n) : e.bottom - e.height / i * (r - n)
},
getValueForPixel: function(t) {
var e = this,
n = e.isHorizontal(),
r = n ? e.width : e.height,
i = (n ? t - e.left : e.bottom - t) / r;
return e.start + (e.end - e.start) * i
},
getPixelForTick: function(t) {
return this.getPixelForValue(this.ticksAsNumbers[t])
}
});
o.registerScaleType("linear", n, e)
}
}, {
26: 26,
34: 34,
35: 35,
46: 46
}],
56: [function(t, e, n) {
var r = t(46),
i = t(33);
e.exports = function(t) {
var e = r.noop;
t.LinearScaleBase = i.extend({
getRightValue: function(t) {
return "string" == typeof t ? +t : i.prototype.getRightValue.call(this, t)
},
handleTickRangeOptions: function() {
var t = this,
e = t.options.ticks;
if (e.beginAtZero) {
var n = r.sign(t.min),
i = r.sign(t.max);
n < 0 && i < 0 ? t.max = 0 : n > 0 && i > 0 && (t.min = 0)
}
var o = void 0 !== e.min || void 0 !== e.suggestedMin,
a = void 0 !== e.max || void 0 !== e.suggestedMax;
void 0 !== e.min ? t.min = e.min : void 0 !== e.suggestedMin && (null === t.min ? t.min = e.suggestedMin : t.min = Math.min(t.min, e.suggestedMin)), void 0 !== e.max ? t.max = e.max : void 0 !== e.suggestedMax && (null === t.max ? t.max = e.suggestedMax : t.max = Math.max(t.max, e.suggestedMax)), o !== a && t.min >= t.max && (o ? t.max = t.min + 1 : t.min = t.max - 1), t.min === t.max && (t.max++, e.beginAtZero || t.min--)
},
getTickLimit: e,
handleDirectionalChanges: e,
buildTicks: function() {
var t = this,
e = t.options.ticks,
n = t.getTickLimit(),
i = {
maxTicks: n = Math.max(2, n),
min: e.min,
max: e.max,
precision: e.precision,
stepSize: r.valueOrDefault(e.fixedStepSize, e.stepSize)
},
o = t.ticks = function(t, e) {
var n, i, o, a = [];
if (t.stepSize && t.stepSize > 0) o = t.stepSize;
else {
var s = r.niceNum(e.max - e.min, !1);
o = r.niceNum(s / (t.maxTicks - 1), !0), void 0 !== (i = t.precision) && (n = Math.pow(10, i), o = Math.ceil(o * n) / n)
}
var l = Math.floor(e.min / o) * o,
u = Math.ceil(e.max / o) * o;
r.isNullOrUndef(t.min) || r.isNullOrUndef(t.max) || !t.stepSize || r.almostWhole((t.max - t.min) / t.stepSize, o / 1e3) && (l = t.min, u = t.max);
var c = (u - l) / o;
c = r.almostEquals(c, Math.round(c), o / 1e3) ? Math.round(c) : Math.ceil(c), i = 1, o < 1 && (i = Math.pow(10, 1 - Math.floor(r.log10(o))), l = Math.round(l * i) / i, u = Math.round(u * i) / i), a.push(void 0 !== t.min ? t.min : l);
for (var d = 1; d < c; ++d) a.push(Math.round((l + d * o) * i) / i);
return a.push(void 0 !== t.max ? t.max : u), a
}(i, t);
t.handleDirectionalChanges(), t.max = r.max(o), t.min = r.min(o), e.reverse ? (o.reverse(), t.start = t.max, t.end = t.min) : (t.start = t.min, t.end = t.max)
},
convertTicksToLabels: function() {
var t = this;
t.ticksAsNumbers = t.ticks.slice(), t.zeroLineIndex = t.ticks.indexOf(0), i.prototype.convertTicksToLabels.call(t)
}
})
}
}, {
33: 33,
46: 46
}],
57: [function(t, e, n) {
var r = t(46),
i = t(33),
o = t(34),
a = t(35);
e.exports = function(t) {
var e = {
position: "left",
ticks: {
callback: a.formatters.logarithmic
}
},
n = i.extend({
determineDataLimits: function() {
var t = this,
e = t.options,
n = t.chart,
i = n.data.datasets,
o = t.isHorizontal();
function a(e) {
return o ? e.xAxisID === t.id : e.yAxisID === t.id
}
t.min = null, t.max = null, t.minNotZero = null;
var s = e.stacked;
if (void 0 === s && r.each(i, (function(t, e) {
if (!s) {
var r = n.getDatasetMeta(e);
n.isDatasetVisible(e) && a(r) && void 0 !== r.stack && (s = !0)
}
})), e.stacked || s) {
var l = {};
r.each(i, (function(i, o) {
var s = n.getDatasetMeta(o),
u = [s.type, void 0 === e.stacked && void 0 === s.stack ? o : "", s.stack].join(".");
n.isDatasetVisible(o) && a(s) && (void 0 === l[u] && (l[u] = []), r.each(i.data, (function(e, n) {
var r = l[u],
i = +t.getRightValue(e);
isNaN(i) || s.data[n].hidden || i < 0 || (r[n] = r[n] || 0, r[n] += i)
})))
})), r.each(l, (function(e) {
if (e.length > 0) {
var n = r.min(e),
i = r.max(e);
t.min = null === t.min ? n : Math.min(t.min, n), t.max = null === t.max ? i : Math.max(t.max, i)
}
}))
} else r.each(i, (function(e, i) {
var o = n.getDatasetMeta(i);
n.isDatasetVisible(i) && a(o) && r.each(e.data, (function(e, n) {
var r = +t.getRightValue(e);
isNaN(r) || o.data[n].hidden || r < 0 || (null === t.min ? t.min = r : r < t.min && (t.min = r), null === t.max ? t.max = r : r > t.max && (t.max = r), 0 !== r && (null === t.minNotZero || r < t.minNotZero) && (t.minNotZero = r))
}))
}));
this.handleTickRangeOptions()
},
handleTickRangeOptions: function() {
var t = this,
e = t.options.ticks,
n = r.valueOrDefault;
t.min = n(e.min, t.min), t.max = n(e.max, t.max), t.min === t.max && (0 !== t.min && null !== t.min ? (t.min = Math.pow(10, Math.floor(r.log10(t.min)) - 1), t.max = Math.pow(10, Math.floor(r.log10(t.max)) + 1)) : (t.min = 1, t.max = 10)), null === t.min && (t.min = Math.pow(10, Math.floor(r.log10(t.max)) - 1)), null === t.max && (t.max = 0 !== t.min ? Math.pow(10, Math.floor(r.log10(t.min)) + 1) : 10), null === t.minNotZero && (t.min > 0 ? t.minNotZero = t.min : t.max < 1 ? t.minNotZero = Math.pow(10, Math.floor(r.log10(t.max))) : t.minNotZero = 1)
},
buildTicks: function() {
var t = this,
e = t.options.ticks,
n = !t.isHorizontal(),
i = {
min: e.min,
max: e.max
},
o = t.ticks = function(t, e) {
var n, i, o = [],
a = r.valueOrDefault,
s = a(t.min, Math.pow(10, Math.floor(r.log10(e.min)))),
l = Math.floor(r.log10(e.max)),
u = Math.ceil(e.max / Math.pow(10, l));
0 === s ? (n = Math.floor(r.log10(e.minNotZero)), i = Math.floor(e.minNotZero / Math.pow(10, n)), o.push(s), s = i * Math.pow(10, n)) : (n = Math.floor(r.log10(s)), i = Math.floor(s / Math.pow(10, n)));
var c = n < 0 ? Math.pow(10, Math.abs(n)) : 1;
do {
o.push(s), 10 === ++i && (i = 1, c = ++n >= 0 ? 1 : c), s = Math.round(i * Math.pow(10, n) * c) / c
} while (n < l || n === l && i < u);
var d = a(t.max, s);
return o.push(d), o
}(i, t);
t.max = r.max(o), t.min = r.min(o), e.reverse ? (n = !n, t.start = t.max, t.end = t.min) : (t.start = t.min, t.end = t.max), n && o.reverse()
},
convertTicksToLabels: function() {
this.tickValues = this.ticks.slice(), i.prototype.convertTicksToLabels.call(this)
},
getLabelForIndex: function(t, e) {
return +this.getRightValue(this.chart.data.datasets[e].data[t])
},
getPixelForTick: function(t) {
return this.getPixelForValue(this.tickValues[t])
},
_getFirstTickValue: function(t) {
var e = Math.floor(r.log10(t));
return Math.floor(t / Math.pow(10, e)) * Math.pow(10, e)
},
getPixelForValue: function(e) {
var n, i, o, a, s, l = this,
u = l.options.ticks.reverse,
c = r.log10,
d = l._getFirstTickValue(l.minNotZero),
f = 0;
return e = +l.getRightValue(e), u ? (o = l.end, a = l.start, s = -1) : (o = l.start, a = l.end, s = 1), l.isHorizontal() ? (n = l.width, i = u ? l.right : l.left) : (n = l.height, s *= -1, i = u ? l.top : l.bottom), e !== o && (0 === o && (n -= f = r.getValueOrDefault(l.options.ticks.fontSize, t.defaults.global.defaultFontSize), o = d), 0 !== e && (f += n / (c(a) - c(o)) * (c(e) - c(o))), i += s * f), i
},
getValueForPixel: function(e) {
var n, i, o, a, s = this,
l = s.options.ticks.reverse,
u = r.log10,
c = s._getFirstTickValue(s.minNotZero);
if (l ? (i = s.end, o = s.start) : (i = s.start, o = s.end), s.isHorizontal() ? (n = s.width, a = l ? s.right - e : e - s.left) : (n = s.height, a = l ? e - s.top : s.bottom - e), a !== i) {
if (0 === i) {
var d = r.getValueOrDefault(s.options.ticks.fontSize, t.defaults.global.defaultFontSize);
a -= d, n -= d, i = c
}
a *= u(o) - u(i), a /= n, a = Math.pow(10, u(i) + a)
}
return a
}
});
o.registerScaleType("logarithmic", n, e)
}
}, {
33: 33,
34: 34,
35: 35,
46: 46
}],
58: [function(t, e, n) {
var r = t(26),
i = t(46),
o = t(34),
a = t(35);
e.exports = function(t) {
var e = r.global,
n = {
display: !0,
animate: !0,
position: "chartArea",
angleLines: {
display: !0,
color: "rgba(0, 0, 0, 0.1)",
lineWidth: 1
},
gridLines: {
circular: !1
},
ticks: {
showLabelBackdrop: !0,
backdropColor: "rgba(255,255,255,0.75)",
backdropPaddingY: 2,
backdropPaddingX: 2,
callback: a.formatters.linear
},
pointLabels: {
display: !0,
fontSize: 10,
callback: function(t) {
return t
}
}
};
function s(t) {
var e = t.options;
return e.angleLines.display || e.pointLabels.display ? t.chart.data.labels.length : 0
}
function l(t) {
var n = t.options.pointLabels,
r = i.valueOrDefault(n.fontSize, e.defaultFontSize),
o = i.valueOrDefault(n.fontStyle, e.defaultFontStyle),
a = i.valueOrDefault(n.fontFamily, e.defaultFontFamily);
return {
size: r,
style: o,
family: a,
font: i.fontString(r, o, a)
}
}
function u(t, e, n, r, i) {
return t === r || t === i ? {
start: e - n / 2,
end: e + n / 2
} : t < r || t > i ? {
start: e - n - 5,
end: e
} : {
start: e,
end: e + n + 5
}
}
function c(t) {
return 0 === t || 180 === t ? "center" : t < 180 ? "left" : "right"
}
function d(t, e, n, r) {
if (i.isArray(e))
for (var o = n.y, a = 1.5 * r, s = 0; s < e.length; ++s) t.fillText(e[s], n.x, o), o += a;
else t.fillText(e, n.x, n.y)
}
function f(t, e, n) {
90 === t || 270 === t ? n.y -= e.h / 2 : (t > 270 || t < 90) && (n.y -= e.h)
}
function h(t) {
return i.isNumber(t) ? t : 0
}
var p = t.LinearScaleBase.extend({
setDimensions: function() {
var t = this,
n = t.options,
r = n.ticks;
t.width = t.maxWidth, t.height = t.maxHeight, t.xCenter = Math.round(t.width / 2), t.yCenter = Math.round(t.height / 2);
var o = i.min([t.height, t.width]),
a = i.valueOrDefault(r.fontSize, e.defaultFontSize);
t.drawingArea = n.display ? o / 2 - (a / 2 + r.backdropPaddingY) : o / 2
},
determineDataLimits: function() {
var t = this,
e = t.chart,
n = Number.POSITIVE_INFINITY,
r = Number.NEGATIVE_INFINITY;
i.each(e.data.datasets, (function(o, a) {
if (e.isDatasetVisible(a)) {
var s = e.getDatasetMeta(a);
i.each(o.data, (function(e, i) {
var o = +t.getRightValue(e);
isNaN(o) || s.data[i].hidden || (n = Math.min(o, n), r = Math.max(o, r))
}))
}
})), t.min = n === Number.POSITIVE_INFINITY ? 0 : n, t.max = r === Number.NEGATIVE_INFINITY ? 0 : r, t.handleTickRangeOptions()
},
getTickLimit: function() {
var t = this.options.ticks,
n = i.valueOrDefault(t.fontSize, e.defaultFontSize);
return Math.min(t.maxTicksLimit ? t.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * n)))
},
convertTicksToLabels: function() {
var e = this;
t.LinearScaleBase.prototype.convertTicksToLabels.call(e), e.pointLabels = e.chart.data.labels.map(e.options.pointLabels.callback, e)
},
getLabelForIndex: function(t, e) {
return +this.getRightValue(this.chart.data.datasets[e].data[t])
},
fit: function() {
var t, e;
this.options.pointLabels.display ? function(t) {
var e, n, r, o = l(t),
a = Math.min(t.height / 2, t.width / 2),
c = {
r: t.width,
l: 0,
t: t.height,
b: 0
},
d = {};
t.ctx.font = o.font, t._pointLabelSizes = [];
var f, h, p, g = s(t);
for (e = 0; e < g; e++) {
r = t.getPointPosition(e, a), f = t.ctx, h = o.size, p = t.pointLabels[e] || "", n = i.isArray(p) ? {
w: i.longestText(f, f.font, p),
h: p.length * h + 1.5 * (p.length - 1) * h
} : {
w: f.measureText(p).width,
h: h
}, t._pointLabelSizes[e] = n;
var v = t.getIndexAngle(e),
m = i.toDegrees(v) % 360,
y = u(m, r.x, n.w, 0, 180),
b = u(m, r.y, n.h, 90, 270);
y.start < c.l && (c.l = y.start, d.l = v), y.end > c.r && (c.r = y.end, d.r = v), b.start < c.t && (c.t = b.start, d.t = v), b.end > c.b && (c.b = b.end, d.b = v)
}
t.setReductions(a, c, d)
}(this) : (t = this, e = Math.min(t.height / 2, t.width / 2), t.drawingArea = Math.round(e), t.setCenterPoint(0, 0, 0, 0))
},
setReductions: function(t, e, n) {
var r = e.l / Math.sin(n.l),
i = Math.max(e.r - this.width, 0) / Math.sin(n.r),
o = -e.t / Math.cos(n.t),
a = -Math.max(e.b - this.height, 0) / Math.cos(n.b);
r = h(r), i = h(i), o = h(o), a = h(a), this.drawingArea = Math.min(Math.round(t - (r + i) / 2), Math.round(t - (o + a) / 2)), this.setCenterPoint(r, i, o, a)
},
setCenterPoint: function(t, e, n, r) {
var i = this,
o = i.width - e - i.drawingArea,
a = t + i.drawingArea,
s = n + i.drawingArea,
l = i.height - r - i.drawingArea;
i.xCenter = Math.round((a + o) / 2 + i.left), i.yCenter = Math.round((s + l) / 2 + i.top)
},
getIndexAngle: function(t) {
return t * (2 * Math.PI / s(this)) + (this.chart.options && this.chart.options.startAngle ? this.chart.options.startAngle : 0) * Math.PI * 2 / 360
},
getDistanceFromCenterForValue: function(t) {
var e = this;
if (null === t) return 0;
var n = e.drawingArea / (e.max - e.min);
return e.options.ticks.reverse ? (e.max - t) * n : (t - e.min) * n
},
getPointPosition: function(t, e) {
var n = this.getIndexAngle(t) - Math.PI / 2;
return {
x: Math.round(Math.cos(n) * e) + this.xCenter,
y: Math.round(Math.sin(n) * e) + this.yCenter
}
},
getPointPositionForValue: function(t, e) {
return this.getPointPosition(t, this.getDistanceFromCenterForValue(e))
},
getBasePosition: function() {
var t = this.min,
e = this.max;
return this.getPointPositionForValue(0, this.beginAtZero ? 0 : t < 0 && e < 0 ? e : t > 0 && e > 0 ? t : 0)
},
draw: function() {
var t = this,
n = t.options,
r = n.gridLines,
o = n.ticks,
a = i.valueOrDefault;
if (n.display) {
var u = t.ctx,
h = this.getIndexAngle(0),
p = a(o.fontSize, e.defaultFontSize),
g = a(o.fontStyle, e.defaultFontStyle),
v = a(o.fontFamily, e.defaultFontFamily),
m = i.fontString(p, g, v);
i.each(t.ticks, (function(n, l) {
if (l > 0 || o.reverse) {
var c = t.getDistanceFromCenterForValue(t.ticksAsNumbers[l]);
if (r.display && 0 !== l && function(t, e, n, r) {
var o = t.ctx;
if (o.strokeStyle = i.valueAtIndexOrDefault(e.color, r - 1), o.lineWidth = i.valueAtIndexOrDefault(e.lineWidth, r - 1), t.options.gridLines.circular) o.beginPath(), o.arc(t.xCenter, t.yCenter, n, 0, 2 * Math.PI), o.closePath(), o.stroke();
else {
var a = s(t);
if (0 === a) return;
o.beginPath();
var l = t.getPointPosition(0, n);
o.moveTo(l.x, l.y);
for (var u = 1; u < a; u++) l = t.getPointPosition(u, n), o.lineTo(l.x, l.y);
o.closePath(), o.stroke()
}
}(t, r, c, l), o.display) {
var d = a(o.fontColor, e.defaultFontColor);
if (u.font = m, u.save(), u.translate(t.xCenter, t.yCenter), u.rotate(h), o.showLabelBackdrop) {
var f = u.measureText(n).width;
u.fillStyle = o.backdropColor, u.fillRect(-f / 2 - o.backdropPaddingX, -c - p / 2 - o.backdropPaddingY, f + 2 * o.backdropPaddingX, p + 2 * o.backdropPaddingY)
}
u.textAlign = "center", u.textBaseline = "middle", u.fillStyle = d, u.fillText(n, 0, -c), u.restore()
}
}
})), (n.angleLines.display || n.pointLabels.display) && function(t) {
var n = t.ctx,
r = t.options,
o = r.angleLines,
a = r.pointLabels;
n.lineWidth = o.lineWidth, n.strokeStyle = o.color;
var u = t.getDistanceFromCenterForValue(r.ticks.reverse ? t.min : t.max),
h = l(t);
n.textBaseline = "top";
for (var p = s(t) - 1; p >= 0; p--) {
if (o.display) {
var g = t.getPointPosition(p, u);
n.beginPath(), n.moveTo(t.xCenter, t.yCenter), n.lineTo(g.x, g.y), n.stroke(), n.closePath()
}
if (a.display) {
var v = t.getPointPosition(p, u + 5),
m = i.valueAtIndexOrDefault(a.fontColor, p, e.defaultFontColor);
n.font = h.font, n.fillStyle = m;
var y = t.getIndexAngle(p),
b = i.toDegrees(y);
n.textAlign = c(b), f(b, t._pointLabelSizes[p], v), d(n, t.pointLabels[p] || "", v, h.size)
}
}
}(t)
}
}
});
o.registerScaleType("radialLinear", p, n)
}
}, {
26: 26,
34: 34,
35: 35,
46: 46
}],
59: [function(t, e, n) {
var r = t(1);
r = "function" == typeof r ? r : window.moment;
var i = t(26),
o = t(46),
a = t(33),
s = t(34),
l = Number.MIN_SAFE_INTEGER || -9007199254740991,
u = Number.MAX_SAFE_INTEGER || 9007199254740991,
c = {
millisecond: {
common: !0,
size: 1,
steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
},
second: {
common: !0,
size: 1e3,
steps: [1, 2, 5, 10, 15, 30]
},
minute: {
common: !0,
size: 6e4,
steps: [1, 2, 5, 10, 15, 30]
},
hour: {
common: !0,
size: 36e5,
steps: [1, 2, 3, 6, 12]
},
day: {
common: !0,
size: 864e5,
steps: [1, 2, 5]
},
week: {
common: !1,
size: 6048e5,
steps: [1, 2, 3, 4]
},
month: {
common: !0,
size: 2628e6,
steps: [1, 2, 3]
},
quarter: {
common: !1,
size: 7884e6,
steps: [1, 2, 3, 4]
},
year: {
common: !0,
size: 3154e7
}
},
d = Object.keys(c);
function f(t, e) {
return t - e
}
function h(t) {
var e, n, r, i = {},
o = [];
for (e = 0, n = t.length; e < n; ++e) i[r = t[e]] || (i[r] = !0, o.push(r));
return o
}
function p(t, e, n, r) {
var i = function(t, e, n) {
for (var r, i, o, a = 0, s = t.length - 1; a >= 0 && a <= s;) {
if (i = t[(r = a + s >> 1) - 1] || null, o = t[r], !i) return {
lo: null,
hi: o
};
if (o[e] < n) a = r + 1;
else {
if (!(i[e] > n)) return {
lo: i,
hi: o
};
s = r - 1
}
}
return {
lo: o,
hi: null
}
}(t, e, n),
o = i.lo ? i.hi ? i.lo : t[t.length - 2] : t[0],
a = i.lo ? i.hi ? i.hi : t[t.length - 1] : t[1],
s = a[e] - o[e],
l = s ? (n - o[e]) / s : 0,
u = (a[r] - o[r]) * l;
return o[r] + u
}
function g(t, e) {
var n = e.parser,
i = e.parser || e.format;
return "function" == typeof n ? n(t) : "string" == typeof t && "string" == typeof i ? r(t, i) : (t instanceof r || (t = r(t)), t.isValid() ? t : "function" == typeof i ? i(t) : t)
}
function v(t, e) {
if (o.isNullOrUndef(t)) return null;
var n = e.options.time,
r = g(e.getRightValue(t), n);
return r.isValid() ? (n.round && r.startOf(n.round), r.valueOf()) : null
}
function m(t) {
for (var e = d.indexOf(t) + 1, n = d.length; e < n; ++e)
if (c[d[e]].common) return d[e]
}
function y(t, e, n, i) {
var a, s = i.time,
l = s.unit || function(t, e, n, r) {
var i, o, a, s = d.length;
for (i = d.indexOf(t); i < s - 1; ++i)
if (a = (o = c[d[i]]).steps ? o.steps[o.steps.length - 1] : u, o.common && Math.ceil((n - e) / (a * o.size)) <= r) return d[i];
return d[s - 1]
}(s.minUnit, t, e, n),
f = m(l),
h = o.valueOrDefault(s.stepSize, s.unitStepSize),
p = "week" === l && s.isoWeekday,
g = i.ticks.major.enabled,
v = c[l],
y = r(t),
b = r(e),
x = [];
for (h || (h = function(t, e, n, r) {
var i, o, a, s = e - t,
l = c[n],
u = l.size,
d = l.steps;
if (!d) return Math.ceil(s / (r * u));
for (i = 0, o = d.length; i < o && (a = d[i], !(Math.ceil(s / (u * a)) <= r)); ++i);
return a
}(t, e, l, n)), p && (y = y.isoWeekday(p), b = b.isoWeekday(p)), y = y.startOf(p ? "day" : l), (b = b.startOf(p ? "day" : l)) < e && b.add(1, l), a = r(y), g && f && !p && !s.round && (a.startOf(f), a.add(~~((y - a) / (v.size * h)) * h, l)); a < b; a.add(h, l)) x.push(+a);
return x.push(+a), x
}
e.exports = function() {
var t = a.extend({
initialize: function() {
if (!r) throw new Error("Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com");
this.mergeTicksOptions(), a.prototype.initialize.call(this)
},
update: function() {
var t = this,
e = t.options;
return e.time && e.time.format && console.warn("options.time.format is deprecated and replaced by options.time.parser."), a.prototype.update.apply(t, arguments)
},
getRightValue: function(t) {
return t && void 0 !== t.t && (t = t.t), a.prototype.getRightValue.call(this, t)
},
determineDataLimits: function() {
var t, e, n, i, a, s, c = this,
d = c.chart,
p = c.options.time,
g = p.unit || "day",
m = u,
y = l,
b = [],
x = [],
w = [];
for (t = 0, n = d.data.labels.length; t < n; ++t) w.push(v(d.data.labels[t], c));
for (t = 0, n = (d.data.datasets || []).length; t < n; ++t)
if (d.isDatasetVisible(t))
if (a = d.data.datasets[t].data, o.isObject(a[0]))
for (x[t] = [], e = 0, i = a.length; e < i; ++e) s = v(a[e], c), b.push(s), x[t][e] = s;
else b.push.apply(b, w), x[t] = w.slice(0);
else x[t] = [];
w.length && (w = h(w).sort(f), m = Math.min(m, w[0]), y = Math.max(y, w[w.length - 1])), b.length && (b = h(b).sort(f), m = Math.min(m, b[0]), y = Math.max(y, b[b.length - 1])), m = v(p.min, c) || m, y = v(p.max, c) || y, m = m === u ? +r().startOf(g) : m, y = y === l ? +r().endOf(g) + 1 : y, c.min = Math.min(m, y), c.max = Math.max(m + 1, y), c._horizontal = c.isHorizontal(), c._table = [], c._timestamps = {
data: b,
datasets: x,
labels: w
}
},
buildTicks: function() {
var t, e, n, i = this,
o = i.min,
a = i.max,
s = i.options,
l = s.time,
u = [],
f = [];
switch (s.ticks.source) {
case "data":
u = i._timestamps.data;
break;
case "labels":
u = i._timestamps.labels;
break;
case "auto":
default:
u = y(o, a, i.getLabelCapacity(o), s)
}
for ("ticks" === s.bounds && u.length && (o = u[0], a = u[u.length - 1]), o = v(l.min, i) || o, a = v(l.max, i) || a, t = 0, e = u.length; t < e; ++t)(n = u[t]) >= o && n <= a && f.push(n);
return i.min = o, i.max = a, i._unit = l.unit || function(t, e, n, i) {
var o, a, s = r.duration(r(i).diff(r(n)));
for (o = d.length - 1; o >= d.indexOf(e); o--)
if (a = d[o], c[a].common && s.as(a) >= t.length) return a;
return d[e ? d.indexOf(e) : 0]
}(f, l.minUnit, i.min, i.max), i._majorUnit = m(i._unit), i._table = function(t, e, n, r) {
if ("linear" === r || !t.length) return [{
time: e,
pos: 0
}, {
time: n,
pos: 1
}];
var i, o, a, s, l, u = [],
c = [e];
for (i = 0, o = t.length; i < o; ++i)(s = t[i]) > e && s < n && c.push(s);
for (c.push(n), i = 0, o = c.length; i < o; ++i) l = c[i + 1], a = c[i - 1], s = c[i], void 0 !== a && void 0 !== l && Math.round((l + a) / 2) === s || u.push({
time: s,
pos: i / (o - 1)
});
return u
}(i._timestamps.data, o, a, s.distribution), i._offsets = function(t, e, n, r, i) {
var o, a, s = 0,
l = 0;
return i.offset && e.length && (i.time.min || (o = e.length > 1 ? e[1] : r, a = e[0], s = (p(t, "time", o, "pos") - p(t, "time", a, "pos")) / 2), i.time.max || (o = e[e.length - 1], a = e.length > 1 ? e[e.length - 2] : n, l = (p(t, "time", o, "pos") - p(t, "time", a, "pos")) / 2)), {
left: s,
right: l
}
}(i._table, f, o, a, s), i._labelFormat = function(t, e) {
var n, r, i, o = t.length;
for (n = 0; n < o; n++) {
if (0 !== (r = g(t[n], e)).millisecond()) return "MMM D, YYYY h:mm:ss.SSS a";
0 === r.second() && 0 === r.minute() && 0 === r.hour() || (i = !0)
}
return i ? "MMM D, YYYY h:mm:ss a" : "MMM D, YYYY"
}(i._timestamps.data, l),
function(t, e) {
var n, i, o, a, s = [];
for (n = 0, i = t.length; n < i; ++n) o = t[n], a = !!e && o === +r(o).startOf(e), s.push({
value: o,
major: a
});
return s
}(f, i._majorUnit)
},
getLabelForIndex: function(t, e) {
var n = this.chart.data,
r = this.options.time,
i = n.labels && t < n.labels.length ? n.labels[t] : "",
a = n.datasets[e].data[t];
return o.isObject(a) && (i = this.getRightValue(a)), r.tooltipFormat ? g(i, r).format(r.tooltipFormat) : "string" == typeof i ? i : g(i, r).format(this._labelFormat)
},
tickFormatFunction: function(t, e, n, r) {
var i = this.options,
a = t.valueOf(),
s = i.time.displayFormats,
l = s[this._unit],
u = this._majorUnit,
c = s[u],
d = t.clone().startOf(u).valueOf(),
f = i.ticks.major,
h = f.enabled && u && c && a === d,
p = t.format(r || (h ? c : l)),
g = h ? f : i.ticks.minor,
v = o.valueOrDefault(g.callback, g.userCallback);
return v ? v(p, e, n) : p
},
convertTicksToLabels: function(t) {
var e, n, i = [];
for (e = 0, n = t.length; e < n; ++e) i.push(this.tickFormatFunction(r(t[e].value), e, t));
return i
},
getPixelForOffset: function(t) {
var e = this,
n = e._horizontal ? e.width : e.height,
r = e._horizontal ? e.left : e.top,
i = p(e._table, "time", t, "pos");
return r + n * (e._offsets.left + i) / (e._offsets.left + 1 + e._offsets.right)
},
getPixelForValue: function(t, e, n) {
var r = null;
if (void 0 !== e && void 0 !== n && (r = this._timestamps.datasets[n][e]), null === r && (r = v(t, this)), null !== r) return this.getPixelForOffset(r)
},
getPixelForTick: function(t) {
var e = this.getTicks();
return t >= 0 && t < e.length ? this.getPixelForOffset(e[t].value) : null
},
getValueForPixel: function(t) {
var e = this,
n = e._horizontal ? e.width : e.height,
i = e._horizontal ? e.left : e.top,
o = (n ? (t - i) / n : 0) * (e._offsets.left + 1 + e._offsets.left) - e._offsets.right,
a = p(e._table, "pos", o, "time");
return r(a)
},
getLabelWidth: function(t) {
var e = this.options.ticks,
n = this.ctx.measureText(t).width,
r = o.toRadians(e.maxRotation),
a = Math.cos(r),
s = Math.sin(r);
return n * a + o.valueOrDefault(e.fontSize, i.global.defaultFontSize) * s
},
getLabelCapacity: function(t) {
var e = this,
n = e.options.time.displayFormats.millisecond,
i = e.tickFormatFunction(r(t), 0, [], n),
o = e.getLabelWidth(i),
a = e.isHorizontal() ? e.width : e.height,
s = Math.floor(a / o);
return s > 0 ? s : 1
}
});
s.registerScaleType("time", t, {
position: "bottom",
distribution: "linear",
bounds: "data",
time: {
parser: !1,
format: !1,
unit: !1,
round: !1,
displayFormat: !1,
isoWeekday: !1,
minUnit: "millisecond",
displayFormats: {
millisecond: "h:mm:ss.SSS a",
second: "h:mm:ss a",
minute: "h:mm a",
hour: "hA",
day: "MMM D",
week: "ll",
month: "MMM YYYY",
quarter: "[Q]Q - YYYY",
year: "YYYY"
}
},
ticks: {
autoSkip: !1,
source: "auto",
major: {
enabled: !1
}
}
})
}
}, {
1: 1,
26: 26,
33: 33,
34: 34,
46: 46
}]
}, {}, [7])(7)
}))
}).call(this, n(87)(t), n(59))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(23).findIndex,
o = n(58),
a = !0;
"findIndex" in [] && Array(1).findIndex((function() {
a = !1
})), r({
target: "Array",
proto: !0,
forced: a
}, {
findIndex: function(t) {
return i(this, t, arguments.length > 1 ? arguments[1] : void 0)
}
}), o("findIndex")
}, function(t, e, n) {
var r = n(3),
i = Math.log,
o = Math.LOG10E;
r({
target: "Math",
stat: !0
}, {
log10: function(t) {
return i(t) * o
}
})
}, function(t, e, n) {
n(3)({
target: "Math",
stat: !0
}, {
sign: n(160)
})
}, function(t, e) {
t.exports = Math.sign || function(t) {
return 0 == (t = +t) || t != t ? t : t < 0 ? -1 : 1
}
}, function(t, e, n) {
n(3)({
target: "Number",
stat: !0
}, {
EPSILON: Math.pow(2, -52)
})
}, function(t, e, n) {
"use strict";
(function(t) {
var e, r;
n(78), n(81), n(82), n(102), n(144), n(119), n(91), n(54), n(120), n(96), n(122), n(97), n(123), n(145), n(146), n(147), n(71), n(83), n(84), n(109), n(163), n(125), n(85);
function i(t) {
return (i = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
return typeof t
} : function(t) {
return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
})(t)
}
/*!
* chartjs-plugin-datalabels v0.7.0
* https://chartjs-plugin-datalabels.netlify.com
* (c) 2019 Chart.js Contributors
* Released under the MIT license
*/
e = void 0, r = function(t) {
var e = (t = t && t.hasOwnProperty("default") ? t.default : t).helpers,
n = function() {
if ("undefined" != typeof window) {
if (window.devicePixelRatio) return window.devicePixelRatio;
var t = window.screen;
if (t) return (t.deviceXDPI || 1) / (t.logicalXDPI || 1)
}
return 1
}(),
r = {
toTextLines: function(t) {
var n, r = [];
for (t = [].concat(t); t.length;) "string" == typeof(n = t.pop()) ? r.unshift.apply(r, n.split("\n")) : Array.isArray(n) ? t.push.apply(t, n) : e.isNullOrUndef(t) || r.unshift("" + n);
return r
},
toFontString: function(t) {
return !t || e.isNullOrUndef(t.size) || e.isNullOrUndef(t.family) ? null : (t.style ? t.style + " " : "") + (t.weight ? t.weight + " " : "") + t.size + "px " + t.family
},
textSize: function(t, e, n) {
var r, i = [].concat(e),
o = i.length,
a = t.font,
s = 0;
for (t.font = n.string, r = 0; r < o; ++r) s = Math.max(t.measureText(i[r]).width, s);
return t.font = a, {
height: o * n.lineHeight,
width: s
}
},
parseFont: function(n) {
var i = t.defaults.global,
o = e.valueOrDefault(n.size, i.defaultFontSize),
a = {
family: e.valueOrDefault(n.family, i.defaultFontFamily),
lineHeight: e.options.toLineHeight(n.lineHeight, o),
size: o,
style: e.valueOrDefault(n.style, i.defaultFontStyle),
weight: e.valueOrDefault(n.weight, null),
string: ""
};
return a.string = r.toFontString(a), a
},
bound: function(t, e, n) {
return Math.max(t, Math.min(e, n))
},
arrayDiff: function(t, e) {
var n, r, i, o, a = t.slice(),
s = [];
for (n = 0, i = e.length; n < i; ++n) o = e[n], -1 === (r = a.indexOf(o)) ? s.push([o, 1]) : a.splice(r, 1);
for (n = 0, i = a.length; n < i; ++n) s.push([a[n], -1]);
return s
},
rasterize: function(t) {
return Math.round(t * n) / n
}
};
function i(t, e) {
var n = e.x,
r = e.y;
if (null === n) return {
x: 0,
y: -1
};
if (null === r) return {
x: 1,
y: 0
};
var i = t.x - n,
o = t.y - r,
a = Math.sqrt(i * i + o * o);
return {
x: a ? i / a : 0,
y: a ? o / a : -1
}
}
var o = 0,
a = 1,
s = 2,
l = 4,
u = 8;
function c(t, e, n) {
var r = o;
return t < n.left ? r |= a : t > n.right && (r |= s), e < n.top ? r |= u : e > n.bottom && (r |= l), r
}
function d(t, e) {
var n, r, i = e.anchor,
o = t;
return e.clamp && (o = function(t, e) {
for (var n, r, i, o = t.x0, d = t.y0, f = t.x1, h = t.y1, p = c(o, d, e), g = c(f, h, e); p | g && !(p & g);)(n = p || g) & u ? (r = o + (f - o) * (e.top - d) / (h - d), i = e.top) : n & l ? (r = o + (f - o) * (e.bottom - d) / (h - d), i = e.bottom) : n & s ? (i = d + (h - d) * (e.right - o) / (f - o), r = e.right) : n & a && (i = d + (h - d) * (e.left - o) / (f - o), r = e.left), n === p ? p = c(o = r, d = i, e) : g = c(f = r, h = i, e);
return {
x0: o,
x1: f,
y0: d,
y1: h
}
}(o, e.area)), "start" === i ? (n = o.x0, r = o.y0) : "end" === i ? (n = o.x1, r = o.y1) : (n = (o.x0 + o.x1) / 2, r = (o.y0 + o.y1) / 2),
function(t, e, n, r, i) {
switch (i) {
case "center":
n = r = 0;
break;
case "bottom":
n = 0, r = 1;
break;
case "right":
n = 1, r = 0;
break;
case "left":
n = -1, r = 0;
break;
case "top":
n = 0, r = -1;
break;
case "start":
n = -n, r = -r;
break;
case "end":
break;
default:
i *= Math.PI / 180, n = Math.cos(i), r = Math.sin(i)
}
return {
x: t,
y: e,
vx: n,
vy: r
}
}(n, r, t.vx, t.vy, e.align)
}
var f = {
arc: function(t, e) {
var n = (t.startAngle + t.endAngle) / 2,
r = Math.cos(n),
i = Math.sin(n),
o = t.innerRadius,
a = t.outerRadius;
return d({
x0: t.x + r * o,
y0: t.y + i * o,
x1: t.x + r * a,
y1: t.y + i * a,
vx: r,
vy: i
}, e)
},
point: function(t, e) {
var n = i(t, e.origin),
r = n.x * t.radius,
o = n.y * t.radius;
return d({
x0: t.x - r,
y0: t.y - o,
x1: t.x + r,
y1: t.y + o,
vx: n.x,
vy: n.y
}, e)
},
rect: function(t, e) {
var n = i(t, e.origin),
r = t.x,
o = t.y,
a = 0,
s = 0;
return t.horizontal ? (r = Math.min(t.x, t.base), a = Math.abs(t.base - t.x)) : (o = Math.min(t.y, t.base), s = Math.abs(t.base - t.y)), d({
x0: r,
y0: o + s,
x1: r + a,
y1: o,
vx: n.x,
vy: n.y
}, e)
},
fallback: function(t, e) {
var n = i(t, e.origin);
return d({
x0: t.x,
y0: t.y,
x1: t.x,
y1: t.y,
vx: n.x,
vy: n.y
}, e)
}
},
h = t.helpers,
p = r.rasterize;
function g(t) {
var e = t._model.horizontal,
n = t._scale || e && t._xScale || t._yScale;
if (!n) return null;
if (void 0 !== n.xCenter && void 0 !== n.yCenter) return {
x: n.xCenter,
y: n.yCenter
};
var r = n.getBasePixel();
return e ? {
x: r,
y: null
} : {
x: null,
y: r
}
}
function v(t, e, n) {
var r = t.shadowBlur,
i = n.stroked,
o = p(n.x),
a = p(n.y),
s = p(n.w);
i && t.strokeText(e, o, a, s), n.filled && (r && i && (t.shadowBlur = 0), t.fillText(e, o, a, s), r && i && (t.shadowBlur = r))
}
var m = function(t, e, n, r) {
var i = this;
i._config = t, i._index = r, i._model = null, i._rects = null, i._ctx = e, i._el = n
};
h.extend(m.prototype, {
_modelize: function(e, n, i, o) {
var a, s = this._index,
l = h.options.resolve,
u = r.parseFont(l([i.font, {}], o, s)),
c = l([i.color, t.defaults.global.defaultFontColor], o, s);
return {
align: l([i.align, "center"], o, s),
anchor: l([i.anchor, "center"], o, s),
area: o.chart.chartArea,
backgroundColor: l([i.backgroundColor, null], o, s),
borderColor: l([i.borderColor, null], o, s),
borderRadius: l([i.borderRadius, 0], o, s),
borderWidth: l([i.borderWidth, 0], o, s),
clamp: l([i.clamp, !1], o, s),
clip: l([i.clip, !1], o, s),
color: c,
display: e,
font: u,
lines: n,
offset: l([i.offset, 0], o, s),
opacity: l([i.opacity, 1], o, s),
origin: g(this._el),
padding: h.options.toPadding(l([i.padding, 0], o, s)),
positioner: (a = this._el, a instanceof t.elements.Arc ? f.arc : a instanceof t.elements.Point ? f.point : a instanceof t.elements.Rectangle ? f.rect : f.fallback),
rotation: l([i.rotation, 0], o, s) * (Math.PI / 180),
size: r.textSize(this._ctx, n, u),
textAlign: l([i.textAlign, "start"], o, s),
textShadowBlur: l([i.textShadowBlur, 0], o, s),
textShadowColor: l([i.textShadowColor, c], o, s),
textStrokeColor: l([i.textStrokeColor, c], o, s),
textStrokeWidth: l([i.textStrokeWidth, 0], o, s)
}
},
update: function(t) {
var e, n, i, o = this,
a = null,
s = null,
l = o._index,
u = o._config,
c = h.options.resolve([u.display, !0], t, l);
c && (e = t.dataset.data[l], n = h.valueOrDefault(h.callback(u.formatter, [e, t]), e), (i = h.isNullOrUndef(n) ? [] : r.toTextLines(n)).length && (s = function(t) {
var e = t.borderWidth || 0,
n = t.padding,
r = t.size.height,
i = t.size.width,
o = -i / 2,
a = -r / 2;
return {
frame: {
x: o - n.left - e,
y: a - n.top - e,
w: i + n.width + 2 * e,
h: r + n.height + 2 * e
},
text: {
x: o,
y: a,
w: i,
h: r
}
}
}(a = o._modelize(c, i, u, t)))), o._model = a, o._rects = s
},
geometry: function() {
return this._rects ? this._rects.frame : {}
},
rotation: function() {
return this._model ? this._model.rotation : 0
},
visible: function() {
return this._model && this._model.opacity
},
model: function() {
return this._model
},
draw: function(t, e) {
var n, i = t.ctx,
o = this._model,
a = this._rects;
this.visible() && (i.save(), o.clip && (n = o.area, i.beginPath(), i.rect(n.left, n.top, n.right - n.left, n.bottom - n.top), i.clip()), i.globalAlpha = r.bound(0, o.opacity, 1), i.translate(p(e.x), p(e.y)), i.rotate(o.rotation), function(t, e, n) {
var r = n.backgroundColor,
i = n.borderColor,
o = n.borderWidth;
(r || i && o) && (t.beginPath(), h.canvas.roundedRect(t, p(e.x) + o / 2, p(e.y) + o / 2, p(e.w) - o, p(e.h) - o, n.borderRadius), t.closePath(), r && (t.fillStyle = r, t.fill()), i && o && (t.strokeStyle = i, t.lineWidth = o, t.lineJoin = "miter", t.stroke()))
}(i, a.frame, o), function(t, e, n, r) {
var i, o = r.textAlign,
a = r.color,
s = !!a,
l = r.font,
u = e.length,
c = r.textStrokeColor,
d = r.textStrokeWidth,
f = c && d;
if (u && (s || f))
for (n = function(t, e, n) {
var r = n.lineHeight,
i = t.w,
o = t.x;
return "center" === e ? o += i / 2 : "end" !== e && "right" !== e || (o += i), {
h: r,
w: i,
x: o,
y: t.y + r / 2
}
}(n, o, l), t.font = l.string, t.textAlign = o, t.textBaseline = "middle", t.shadowBlur = r.textShadowBlur, t.shadowColor = r.textShadowColor, s && (t.fillStyle = a), f && (t.lineJoin = "round", t.lineWidth = d, t.strokeStyle = c), i = 0, u = e.length; i < u; ++i) v(t, e[i], {
stroked: f,
filled: s,
w: n.w,
x: n.x,
y: n.y + n.h * i
})
}(i, o.lines, a.text, o), i.restore())
}
});
var y = t.helpers,
b = Number.MIN_SAFE_INTEGER || -9007199254740991,
x = Number.MAX_SAFE_INTEGER || 9007199254740991;
function w(t, e, n) {
var r = Math.cos(n),
i = Math.sin(n),
o = e.x,
a = e.y;
return {
x: o + r * (t.x - o) - i * (t.y - a),
y: a + i * (t.x - o) + r * (t.y - a)
}
}
function S(t, e) {
var n, r, i, o, a, s = x,
l = b,
u = e.origin;
for (n = 0; n < t.length; ++n) i = (r = t[n]).x - u.x, o = r.y - u.y, a = e.vx * i + e.vy * o, s = Math.min(s, a), l = Math.max(l, a);
return {
min: s,
max: l
}
}
function k(t, e) {
var n = e.x - t.x,
r = e.y - t.y,
i = Math.sqrt(n * n + r * r);
return {
vx: (e.x - t.x) / i,
vy: (e.y - t.y) / i,
origin: t,
ln: i
}
}
var C = function() {
this._rotation = 0, this._rect = {
x: 0,
y: 0,
w: 0,
h: 0
}
};
function M(t, e, n) {
var r = e.positioner(t, e),
i = r.vx,
o = r.vy;
if (!i && !o) return {
x: r.x,
y: r.y
};
var a = n.w,
s = n.h,
l = e.rotation,
u = Math.abs(a / 2 * Math.cos(l)) + Math.abs(s / 2 * Math.sin(l)),
c = Math.abs(a / 2 * Math.sin(l)) + Math.abs(s / 2 * Math.cos(l)),
d = 1 / Math.max(Math.abs(i), Math.abs(o));
return u *= i * d, c *= o * d, u += e.offset * i, c += e.offset * o, {
x: r.x + u,
y: r.y + c
}
}
y.extend(C.prototype, {
center: function() {
var t = this._rect;
return {
x: t.x + t.w / 2,
y: t.y + t.h / 2
}
},
update: function(t, e, n) {
this._rotation = n, this._rect = {
x: e.x + t.x,
y: e.y + t.y,
w: e.w,
h: e.h
}
},
contains: function(t) {
var e = this._rect;
return !((t = w(t, this.center(), -this._rotation)).x < e.x - 1 || t.y < e.y - 1 || t.x > e.x + e.w + 2 || t.y > e.y + e.h + 2)
},
intersects: function(t) {
var e, n, r, i = this._points(),
o = t._points(),
a = [k(i[0], i[1]), k(i[0], i[3])];
for (this._rotation !== t._rotation && a.push(k(o[0], o[1]), k(o[0], o[3])), e = 0; e < a.length; ++e)
if (n = S(i, a[e]), r = S(o, a[e]), n.max < r.min || r.max < n.min) return !1;
return !0
},
_points: function() {
var t = this._rect,
e = this._rotation,
n = this.center();
return [w({
x: t.x,
y: t.y
}, n, e), w({
x: t.x + t.w,
y: t.y
}, n, e), w({
x: t.x + t.w,
y: t.y + t.h
}, n, e), w({
x: t.x,
y: t.y + t.h
}, n, e)]
}
});
var A = {
prepare: function(t) {
var e, n, r, i, o, a = [];
for (e = 0, r = t.length; e < r; ++e)
for (n = 0, i = t[e].length; n < i; ++n) o = t[e][n], a.push(o), o.$layout = {
_box: new C,
_hidable: !1,
_visible: !0,
_set: e,
_idx: n
};
return a.sort((function(t, e) {
var n = t.$layout,
r = e.$layout;
return n._idx === r._idx ? r._set - n._set : r._idx - n._idx
})), this.update(a), a
},
update: function(t) {
var e, n, r, i, o, a = !1;
for (e = 0, n = t.length; e < n; ++e) i = (r = t[e]).model(), (o = r.$layout)._hidable = i && "auto" === i.display, o._visible = r.visible(), a |= o._hidable;
a && function(t) {
var e, n, r, i, o, a;
for (e = 0, n = t.length; e < n; ++e)(i = (r = t[e]).$layout)._visible && (o = r.geometry(), a = M(r._el._model, r.model(), o), i._box.update(a, o, r.rotation()));
! function(t, e) {
var n, r, i, o;
for (n = t.length - 1; n >= 0; --n)
for (i = t[n].$layout, r = n - 1; r >= 0 && i._visible; --r)(o = t[r].$layout)._visible && i._box.intersects(o._box) && e(i, o)
}(t, (function(t, e) {
var n = t._hidable,
r = e._hidable;
n && r || r ? e._visible = !1 : n && (t._visible = !1)
}))
}(t)
},
lookup: function(t, e) {
var n, r;
for (n = t.length - 1; n >= 0; --n)
if ((r = t[n].$layout) && r._visible && r._box.contains(e)) return t[n];
return null
},
draw: function(t, e) {
var n, r, i, o, a, s;
for (n = 0, r = e.length; n < r; ++n)(o = (i = e[n]).$layout)._visible && (a = i.geometry(), s = M(i._el._view, i.model(), a), o._box.update(s, a, i.rotation()), i.draw(t, s))
}
},
P = t.helpers,
_ = {
align: "center",
anchor: "center",
backgroundColor: null,
borderColor: null,
borderRadius: 0,
borderWidth: 0,
clamp: !1,
clip: !1,
color: void 0,
display: !0,
font: {
family: void 0,
lineHeight: 1.2,
size: void 0,
style: void 0,
weight: null
},
formatter: function(t) {
if (P.isNullOrUndef(t)) return null;
var e, n, r, i = t;
if (P.isObject(t))
if (P.isNullOrUndef(t.label))
if (P.isNullOrUndef(t.r))
for (i = "", r = 0, n = (e = Object.keys(t)).length; r < n; ++r) i += (0 !== r ? ", " : "") + e[r] + ": " + t[e[r]];
else i = t.r;
else i = t.label;
return "" + i
},
labels: void 0,
listeners: {},
offset: 4,
opacity: 1,
padding: {
top: 4,
right: 4,
bottom: 4,
left: 4
},
rotation: 0,
textAlign: "start",
textStrokeColor: void 0,
textStrokeWidth: 0,
textShadowBlur: 0,
textShadowColor: void 0
},
T = t.helpers,
I = "$datalabels",
O = "$default";
function F(t, e, n) {
if (e) {
var r, i = n.$context,
o = n.$groups;
e[o._set] && (r = e[o._set][o._key]) && !0 === T.callback(r, [i]) && (t[I]._dirty = !0, n.update(i))
}
}
function D(t, e) {
var n, r, i = t[I],
o = i._listeners;
if (o.enter || o.leave) {
if ("mousemove" === e.type) r = A.lookup(i._labels, e);
else if ("mouseout" !== e.type) return;
n = i._hovered, i._hovered = r,
function(t, e, n, r) {
var i, o;
(n || r) && (n ? r ? n !== r && (o = i = !0) : o = !0 : i = !0, o && F(t, e.leave, n), i && F(t, e.enter, r))
}(t, o, n, r)
}
}
t.defaults.global.plugins.datalabels = _;
var E = {
id: "datalabels",
beforeInit: function(t) {
t[I] = {
_actives: []
}
},
beforeUpdate: function(t) {
var e = t[I];
e._listened = !1, e._listeners = {}, e._datasets = [], e._labels = []
},
afterDatasetUpdate: function(t, e, n) {
var r, i, o, a, s, l, u, c, d = e.index,
f = t[I],
h = f._datasets[d] = [],
p = t.isDatasetVisible(d),
g = t.data.datasets[d],
v = function(t, e) {
var n, r, i, o = t.datalabels,
a = [];
return !1 === o ? null : (!0 === o && (o = {}), e = T.merge({}, [e, o]), r = e.labels || {}, i = Object.keys(r), delete e.labels, i.length ? i.forEach((function(t) {
r[t] && a.push(T.merge({}, [e, r[t], {
_key: t
}]))
})) : a.push(e), n = a.reduce((function(t, e) {
return T.each(e.listeners || {}, (function(n, r) {
t[r] = t[r] || {}, t[r][e._key || O] = n
})), delete e.listeners, t
}), {}), {
labels: a,
listeners: n
})
}(g, n),
y = e.meta.data || [],
b = t.ctx;
for (b.save(), r = 0, o = y.length; r < o; ++r)
if ((u = y[r])[I] = [], p && u && !u.hidden && !u._model.skip)
for (i = 0, a = v.labels.length; i < a; ++i) l = (s = v.labels[i])._key, (c = new m(s, b, u, r)).$groups = {
_set: d,
_key: l || O
}, c.$context = {
active: !1,
chart: t,
dataIndex: r,
dataset: g,
datasetIndex: d
}, c.update(c.$context), u[I].push(c), h.push(c);
b.restore(), T.merge(f._listeners, v.listeners, {
merger: function(t, n, r) {
n[t] = n[t] || {}, n[t][e.index] = r[t], f._listened = !0
}
})
},
afterUpdate: function(t, e) {
t[I]._labels = A.prepare(t[I]._datasets, e)
},
afterDatasetsDraw: function(t) {
A.draw(t, t[I]._labels)
},
beforeEvent: function(t, e) {
if (t[I]._listened) switch (e.type) {
case "mousemove":
case "mouseout":
D(t, e);
break;
case "click":
! function(t, e) {
var n = t[I],
r = n._listeners.click,
i = r && A.lookup(n._labels, e);
i && F(t, r, i)
}(t, e)
}
},
afterEvent: function(e) {
var n, i, o, a, s, l, u, c = e[I],
d = c._actives,
f = c._actives = e.lastActive || [],
h = r.arrayDiff(d, f);
for (n = 0, i = h.length; n < i; ++n)
if ((s = h[n])[1])
for (o = 0, a = (u = s[0][I] || []).length; o < a; ++o)(l = u[o]).$context.active = 1 === s[1], l.update(l.$context);
(c._dirty || h.length) && (A.update(c._labels), function(e) {
if (!e.animating) {
for (var n = t.animationService.animations, r = 0, i = n.length; r < i; ++r)
if (n[r].chart === e) return;
e.render({
duration: 1,
lazy: !0
})
}
}(e)), delete c._dirty
}
};
return t.plugins.unregister(E), E
}, "object" === ("undefined" == typeof exports ? "undefined" : i(exports)) && void 0 !== t ? t.exports = r(n(166)) : "function" == typeof define && n(55) ? define(["chart.js"], r) : (e = e || self).ChartDataLabels = r(e.Chart)
}).call(this, n(87)(t))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(164);
r({
target: "String",
proto: !0,
forced: n(165)("anchor")
}, {
anchor: function(t) {
return i(this, "a", "name", t)
}
})
}, function(t, e, n) {
var r = n(13),
i = /"/g;
t.exports = function(t, e, n, o) {
var a = String(r(t)),
s = "<" + e;
return "" !== n && (s += " " + n + '="' + String(o).replace(i, """) + '"'), s + ">" + a + "</" + e + ">"
}
}, function(t, e, n) {
var r = n(1);
t.exports = function(t) {
return r((function() {
var e = "" [t]('"');
return e !== e.toLowerCase() || e.split('"').length > 3
}))
}
}, function(t, e) {
t.exports = chart
}, function(t, e) {
! function(t) {
t("body").on("shown.bs.modal", ".modal", (function() {
t(".modal-backdrop").length || ($modal_dialog = t(this).children(".modal-dialog"), $modal_dialog.hasClass("modal-side") && (t(this).addClass("modal-scrolling"), t("body").addClass("scrollable")), $modal_dialog.hasClass("modal-frame") && (t(this).addClass("modal-content-clickable"), t("body").addClass("scrollable")))
})), t("body").on("hidden.bs.modal", ".modal", (function() {
t("body").removeClass("scrollable")
}))
}(jQuery)
}, function(t, e) {
jQuery.easing.jswing = jQuery.easing.swing, jQuery.extend(jQuery.easing, {
def: "easeOutQuad",
swing: function(t, e, n, r, i) {
return jQuery.easing[jQuery.easing.def](t, e, n, r, i)
},
easeInQuad: function(t, e, n, r, i) {
return r * (e /= i) * e + n
},
easeOutQuad: function(t, e, n, r, i) {
return -r * (e /= i) * (e - 2) + n
},
easeInOutQuad: function(t, e, n, r, i) {
return (e /= i / 2) < 1 ? r / 2 * e * e + n : -r / 2 * (--e * (e - 2) - 1) + n
},
easeInCubic: function(t, e, n, r, i) {
return r * (e /= i) * e * e + n
},
easeOutCubic: function(t, e, n, r, i) {
return r * ((e = e / i - 1) * e * e + 1) + n
},
easeInOutCubic: function(t, e, n, r, i) {
return (e /= i / 2) < 1 ? r / 2 * e * e * e + n : r / 2 * ((e -= 2) * e * e + 2) + n
},
easeInQuart: function(t, e, n, r, i) {
return r * (e /= i) * e * e * e + n
},
easeOutQuart: function(t, e, n, r, i) {
return -r * ((e = e / i - 1) * e * e * e - 1) + n
},
easeInOutQuart: function(t, e, n, r, i) {
return (e /= i / 2) < 1 ? r / 2 * e * e * e * e + n : -r / 2 * ((e -= 2) * e * e * e - 2) + n
},
easeInQuint: function(t, e, n, r, i) {
return r * (e /= i) * e * e * e * e + n
},
easeOutQuint: function(t, e, n, r, i) {
return r * ((e = e / i - 1) * e * e * e * e + 1) + n
},
easeInOutQuint: function(t, e, n, r, i) {
return (e /= i / 2) < 1 ? r / 2 * e * e * e * e * e + n : r / 2 * ((e -= 2) * e * e * e * e + 2) + n
},
easeInSine: function(t, e, n, r, i) {
return -r * Math.cos(e / i * (Math.PI / 2)) + r + n
},
easeOutSine: function(t, e, n, r, i) {
return r * Math.sin(e / i * (Math.PI / 2)) + n
},
easeInOutSine: function(t, e, n, r, i) {
return -r / 2 * (Math.cos(Math.PI * e / i) - 1) + n
},
easeInExpo: function(t, e, n, r, i) {
return 0 == e ? n : r * Math.pow(2, 10 * (e / i - 1)) + n
},
easeOutExpo: function(t, e, n, r, i) {
return e == i ? n + r : r * (1 - Math.pow(2, -10 * e / i)) + n
},
easeInOutExpo: function(t, e, n, r, i) {
return 0 == e ? n : e == i ? n + r : (e /= i / 2) < 1 ? r / 2 * Math.pow(2, 10 * (e - 1)) + n : r / 2 * (2 - Math.pow(2, -10 * --e)) + n
},
easeInCirc: function(t, e, n, r, i) {
return -r * (Math.sqrt(1 - (e /= i) * e) - 1) + n
},
easeOutCirc: function(t, e, n, r, i) {
return r * Math.sqrt(1 - (e = e / i - 1) * e) + n
},
easeInOutCirc: function(t, e, n, r, i) {
return (e /= i / 2) < 1 ? -r / 2 * (Math.sqrt(1 - e * e) - 1) + n : r / 2 * (Math.sqrt(1 - (e -= 2) * e) + 1) + n
},
easeInElastic: function(t, e, n, r, i) {
var o = 1.70158,
a = 0,
s = r;
if (0 == e) return n;
if (1 == (e /= i)) return n + r;
if (a || (a = .3 * i), s < Math.abs(r)) {
s = r;
o = a / 4
} else o = a / (2 * Math.PI) * Math.asin(r / s);
return -s * Math.pow(2, 10 * (e -= 1)) * Math.sin((e * i - o) * (2 * Math.PI) / a) + n
},
easeOutElastic: function(t, e, n, r, i) {
var o = 1.70158,
a = 0,
s = r;
if (0 == e) return n;
if (1 == (e /= i)) return n + r;
if (a || (a = .3 * i), s < Math.abs(r)) {
s = r;
o = a / 4
} else o = a / (2 * Math.PI) * Math.asin(r / s);
return s * Math.pow(2, -10 * e) * Math.sin((e * i - o) * (2 * Math.PI) / a) + r + n
},
easeInOutElastic: function(t, e, n, r, i) {
var o = 1.70158,
a = 0,
s = r;
if (0 == e) return n;
if (2 == (e /= i / 2)) return n + r;
if (a || (a = i * (.3 * 1.5)), s < Math.abs(r)) {
s = r;
o = a / 4
} else o = a / (2 * Math.PI) * Math.asin(r / s);
return e < 1 ? s * Math.pow(2, 10 * (e -= 1)) * Math.sin((e * i - o) * (2 * Math.PI) / a) * -.5 + n : s * Math.pow(2, -10 * (e -= 1)) * Math.sin((e * i - o) * (2 * Math.PI) / a) * .5 + r + n
},
easeInBack: function(t, e, n, r, i, o) {
return null == o && (o = 1.70158), r * (e /= i) * e * ((o + 1) * e - o) + n
},
easeOutBack: function(t, e, n, r, i, o) {
return null == o && (o = 1.70158), r * ((e = e / i - 1) * e * ((o + 1) * e + o) + 1) + n
},
easeInOutBack: function(t, e, n, r, i, o) {
return null == o && (o = 1.70158), (e /= i / 2) < 1 ? r / 2 * (e * e * ((1 + (o *= 1.525)) * e - o)) + n : r / 2 * ((e -= 2) * e * ((1 + (o *= 1.525)) * e + o) + 2) + n
},
easeInBounce: function(t, e, n, r, i) {
return r - jQuery.easing.easeOutBounce(t, i - e, 0, r, i) + n
},
easeOutBounce: function(t, e, n, r, i) {
return (e /= i) < 1 / 2.75 ? r * (7.5625 * e * e) + n : e < 2 / 2.75 ? r * (7.5625 * (e -= 1.5 / 2.75) * e + .75) + n : e < 2.5 / 2.75 ? r * (7.5625 * (e -= 2.25 / 2.75) * e + .9375) + n : r * (7.5625 * (e -= 2.625 / 2.75) * e + .984375) + n
},
easeInOutBounce: function(t, e, n, r, i) {
return e < i / 2 ? .5 * jQuery.easing.easeInBounce(t, 2 * e, 0, r, i) + n : .5 * jQuery.easing.easeOutBounce(t, 2 * e - i, 0, r, i) + .5 * r + n
}
})
}, function(t, e, n) {
"use strict";
(function(t) {
var e;
n(78), n(81), n(82), n(102), n(54), n(101), n(121), n(96), n(170), n(104), n(71), n(105), n(124), n(129), n(83), n(106), n(84), n(113), n(98), n(109), n(172), n(180), n(182), n(183), n(184), n(185), n(186), n(187), n(188), n(189), n(190), n(191), n(192), n(193), n(194), n(195), n(196), n(197), n(198), n(199), n(200), n(201), n(202), n(203), n(85);
function r(t) {
return (r = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
return typeof t
} : function(t) {
return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
})(t)
}
/*! VelocityJS.org (1.2.3). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
/*! Note that this has been modified by Materialize to confirm that Velocity is not already being imported. */
jQuery.Velocity ? console.log("Velocity is already loaded. You may be needlessly importing Velocity again; note that Materialize includes Velocity.") : (function(t) {
function e(t) {
var e = t.length,
r = n.type(t);
return "function" !== r && !n.isWindow(t) && (!(1 !== t.nodeType || !e) || ("array" === r || 0 === e || "number" == typeof e && e > 0 && e - 1 in t))
}
if (!t.jQuery) {
var n = function t(e, n) {
return new t.fn.init(e, n)
};
n.isWindow = function(t) {
return null != t && t == t.window
}, n.type = function(t) {
return null == t ? t + "" : "object" == r(t) || "function" == typeof t ? o[s.call(t)] || "object" : r(t)
}, n.isArray = Array.isArray || function(t) {
return "array" === n.type(t)
}, n.isPlainObject = function(t) {
var e;
if (!t || "object" !== n.type(t) || t.nodeType || n.isWindow(t)) return !1;
try {
if (t.constructor && !a.call(t, "constructor") && !a.call(t.constructor.prototype, "isPrototypeOf")) return !1
} catch (t) {
return !1
}
for (e in t);
return void 0 === e || a.call(t, e)
}, n.each = function(t, n, r) {
var i = 0,
o = t.length,
a = e(t);
if (r) {
if (a)
for (; o > i && !1 !== n.apply(t[i], r); i++);
else
for (i in t)
if (!1 === n.apply(t[i], r)) break
} else if (a)
for (; o > i && !1 !== n.call(t[i], i, t[i]); i++);
else
for (i in t)
if (!1 === n.call(t[i], i, t[i])) break;
return t
}, n.data = function(t, e, r) {
if (void 0 === r) {
var o = (a = t[n.expando]) && i[a];
if (void 0 === e) return o;
if (o && e in o) return o[e]
} else if (void 0 !== e) {
var a = t[n.expando] || (t[n.expando] = ++n.uuid);
return i[a] = i[a] || {}, i[a][e] = r, r
}
}, n.removeData = function(t, e) {
var r = t[n.expando],
o = r && i[r];
o && n.each(e, (function(t, e) {
delete o[e]
}))
}, n.extend = function() {
var t, e, i, o, a, s, l = arguments[0] || {},
u = 1,
c = arguments.length,
d = !1;
for ("boolean" == typeof l && (d = l, l = arguments[u] || {}, u++), "object" != r(l) && "function" !== n.type(l) && (l = {}), u === c && (l = this, u--); c > u; u++)
if (null != (a = arguments[u]))
for (o in a) t = l[o], l !== (i = a[o]) && (d && i && (n.isPlainObject(i) || (e = n.isArray(i))) ? (e ? (e = !1, s = t && n.isArray(t) ? t : []) : s = t && n.isPlainObject(t) ? t : {}, l[o] = n.extend(d, s, i)) : void 0 !== i && (l[o] = i));
return l
}, n.queue = function(t, r, i) {
if (t) {
r = (r || "fx") + "queue";
var o = n.data(t, r);
return i ? (!o || n.isArray(i) ? o = n.data(t, r, function(t, n) {
var r = n || [];
return null != t && (e(Object(t)) ? function(t, e) {
for (var n = +e.length, r = 0, i = t.length; n > r;) t[i++] = e[r++];
if (n != n)
for (; void 0 !== e[r];) t[i++] = e[r++];
t.length = i
}(r, "string" == typeof t ? [t] : t) : [].push.call(r, t)), r
}(i)) : o.push(i), o) : o || []
}
}, n.dequeue = function(t, e) {
n.each(t.nodeType ? [t] : t, (function(t, r) {
e = e || "fx";
var i = n.queue(r, e),
o = i.shift();
"inprogress" === o && (o = i.shift()), o && ("fx" === e && i.unshift("inprogress"), o.call(r, (function() {
n.dequeue(r, e)
})))
}))
}, n.fn = n.prototype = {
init: function(t) {
if (t.nodeType) return this[0] = t, this;
throw new Error("Not a DOM node.")
},
offset: function() {
var e = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : {
top: 0,
left: 0
};
return {
top: e.top + (t.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0),
left: e.left + (t.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0)
}
},
position: function() {
function t() {
for (var t = this.offsetParent || document; t && "html" === !t.nodeType.toLowerCase && "static" === t.style.position;) t = t.offsetParent;
return t || document
}
var e = this[0],
t = t.apply(e),
r = this.offset(),
i = /^(?:body|html)$/i.test(t.nodeName) ? {
top: 0,
left: 0
} : n(t).offset();
return r.top -= parseFloat(e.style.marginTop) || 0, r.left -= parseFloat(e.style.marginLeft) || 0, t.style && (i.top += parseFloat(t.style.borderTopWidth) || 0, i.left += parseFloat(t.style.borderLeftWidth) || 0), {
top: r.top - i.top,
left: r.left - i.left
}
}
};
var i = {};
n.expando = "velocity" + (new Date).getTime(), n.uuid = 0;
for (var o = {}, a = o.hasOwnProperty, s = o.toString, l = "Boolean Number String Function Array Date RegExp Object Error".split(" "), u = 0; u < l.length; u++) o["[object " + l[u] + "]"] = l[u].toLowerCase();
n.fn.init.prototype = n.fn, t.Velocity = {
Utilities: n
}
}
}(window), e = function() {
return function(t, e, n, i) {
function o(t) {
return g.isWrapped(t) ? t = [].slice.call(t) : g.isNode(t) && (t = [t]), t
}
function a(t) {
var e = f.data(t, "velocity");
return null === e ? i : e
}
function s(t) {
return function(e) {
return Math.round(e * t) * (1 / t)
}
}
function l(t, n, r, i) {
function o(t, e) {
return 1 - 3 * e + 3 * t
}
function a(t, e) {
return 3 * e - 6 * t
}
function s(t) {
return 3 * t
}
function l(t, e, n) {
return ((o(e, n) * t + a(e, n)) * t + s(e)) * t
}
function u(t, e, n) {
return 3 * o(e, n) * t * t + 2 * a(e, n) * t + s(e)
}
function c(e, n) {
for (var i = 0; h > i; ++i) {
var o = u(n, t, r);
if (0 === o) return n;
n -= (l(n, t, r) - e) / o
}
return n
}
function d(e, n, i) {
var o, a, s = 0;
do {
(o = l(a = n + (i - n) / 2, t, r) - e) > 0 ? i = a : n = a
} while (Math.abs(o) > g && ++s < v);
return a
}
function f() {
S = !0, (t != n || r != i) && function() {
for (var e = 0; m > e; ++e) w[e] = l(e * y, t, r)
}()
}
var h = 4,
p = .001,
g = 1e-7,
v = 10,
m = 11,
y = 1 / (m - 1),
b = "Float32Array" in e;
if (4 !== arguments.length) return !1;
for (var x = 0; 4 > x; ++x)
if ("number" != typeof arguments[x] || isNaN(arguments[x]) || !isFinite(arguments[x])) return !1;
t = Math.min(t, 1), r = Math.min(r, 1), t = Math.max(t, 0), r = Math.max(r, 0);
var w = b ? new Float32Array(m) : new Array(m),
S = !1,
k = function(e) {
return S || f(), t === n && r === i ? e : 0 === e ? 0 : 1 === e ? 1 : l(function(e) {
for (var n = 0, i = 1, o = m - 1; i != o && w[i] <= e; ++i) n += y;
var a = n + (e - w[--i]) / (w[i + 1] - w[i]) * y,
s = u(a, t, r);
return s >= p ? c(e, a) : 0 == s ? a : d(e, n, n + y)
}(e), n, i)
};
k.getControlPoints = function() {
return [{
x: t,
y: n
}, {
x: r,
y: i
}]
};
var C = "generateBezier(" + [t, n, r, i] + ")";
return k.toString = function() {
return C
}, k
}
function u(t, e) {
var n = t;
return g.isString(t) ? b.Easings[t] || (n = !1) : n = g.isArray(t) && 1 === t.length ? s.apply(null, t) : g.isArray(t) && 2 === t.length ? x.apply(null, t.concat([e])) : !(!g.isArray(t) || 4 !== t.length) && l.apply(null, t), !1 === n && (n = b.Easings[b.defaults.easing] ? b.defaults.easing : y), n
}
function c(t) {
if (t) {
var e = (new Date).getTime(),
n = b.State.calls.length;
n > 1e4 && (b.State.calls = function(t) {
for (var e = -1, n = t ? t.length : 0, r = []; ++e < n;) {
var i = t[e];
i && r.push(i)
}
return r
}(b.State.calls));
for (var r = 0; n > r; r++)
if (b.State.calls[r]) {
var o = b.State.calls[r],
s = o[0],
l = o[2],
u = o[3],
h = !!u,
p = null;
u || (u = b.State.calls[r][3] = e - 16);
for (var v = Math.min((e - u) / l.duration, 1), m = 0, y = s.length; y > m; m++) {
var x = s[m],
S = x.element;
if (a(S)) {
var C = !1;
for (var M in l.display !== i && null !== l.display && "none" !== l.display && ("flex" === l.display && f.each(["-webkit-box", "-moz-box", "-ms-flexbox", "-webkit-flex"], (function(t, e) {
w.setPropertyValue(S, "display", e)
})), w.setPropertyValue(S, "display", l.display)), l.visibility !== i && "hidden" !== l.visibility && w.setPropertyValue(S, "visibility", l.visibility), x)
if ("element" !== M) {
var A, P = x[M],
_ = g.isString(P.easing) ? b.Easings[P.easing] : P.easing;
if (1 === v) A = P.endValue;
else {
var T = P.endValue - P.startValue;
if (A = P.startValue + T * _(v, l, T), !h && A === P.currentValue) continue
}
if (P.currentValue = A, "tween" === M) p = A;
else {
if (w.Hooks.registered[M]) {
var I = w.Hooks.getRoot(M),
O = a(S).rootPropertyValueCache[I];
O && (P.rootPropertyValue = O)
}
var F = w.setPropertyValue(S, M, P.currentValue + (0 === parseFloat(A) ? "" : P.unitType), P.rootPropertyValue, P.scrollData);
w.Hooks.registered[M] && (a(S).rootPropertyValueCache[I] = w.Normalizations.registered[I] ? w.Normalizations.registered[I]("extract", null, F[1]) : F[1]), "transform" === F[0] && (C = !0)
}
} l.mobileHA && a(S).transformCache.translate3d === i && (a(S).transformCache.translate3d = "(0px, 0px, 0px)", C = !0), C && w.flushTransformCache(S)
}
}
l.display !== i && "none" !== l.display && (b.State.calls[r][2].display = !1), l.visibility !== i && "hidden" !== l.visibility && (b.State.calls[r][2].visibility = !1), l.progress && l.progress.call(o[1], o[1], v, Math.max(0, u + l.duration - e), u, p), 1 === v && d(r)
}
}
b.State.isTicking && k(c)
}
function d(t, e) {
if (!b.State.calls[t]) return !1;
for (var n = b.State.calls[t][0], r = b.State.calls[t][1], o = b.State.calls[t][2], s = b.State.calls[t][4], l = !1, u = 0, c = n.length; c > u; u++) {
var d = n[u].element;
if (e || o.loop || ("none" === o.display && w.setPropertyValue(d, "display", o.display), "hidden" === o.visibility && w.setPropertyValue(d, "visibility", o.visibility)), !0 !== o.loop && (f.queue(d)[1] === i || !/\.velocityQueueEntryFlag/i.test(f.queue(d)[1])) && a(d)) {
a(d).isAnimating = !1, a(d).rootPropertyValueCache = {};
var h = !1;
f.each(w.Lists.transforms3D, (function(t, e) {
var n = /^scale/.test(e) ? 1 : 0,
r = a(d).transformCache[e];
a(d).transformCache[e] !== i && new RegExp("^\\(" + n + "[^.]").test(r) && (h = !0, delete a(d).transformCache[e])
})), o.mobileHA && (h = !0, delete a(d).transformCache.translate3d), h && w.flushTransformCache(d), w.Values.removeClass(d, "velocity-animating")
}
if (!e && o.complete && !o.loop && u === c - 1) try {
o.complete.call(r, r)
} catch (t) {
setTimeout((function() {
throw t
}), 1)
}
s && !0 !== o.loop && s(r), a(d) && !0 === o.loop && !e && (f.each(a(d).tweensContainer, (function(t, e) {
/^rotate/.test(t) && 360 === parseFloat(e.endValue) && (e.endValue = 0, e.startValue = 360), /^backgroundPosition/.test(t) && 100 === parseFloat(e.endValue) && "%" === e.unitType && (e.endValue = 0, e.startValue = 100)
})), b(d, "reverse", {
loop: !0,
delay: o.delay
})), !1 !== o.queue && f.dequeue(d, o.queue)
}
b.State.calls[t] = !1;
for (var p = 0, g = b.State.calls.length; g > p; p++)
if (!1 !== b.State.calls[p]) {
l = !0;
break
}! 1 === l && (b.State.isTicking = !1, delete b.State.calls, b.State.calls = [])
}
var f, h = function() {
if (n.documentMode) return n.documentMode;
for (var t = 7; t > 4; t--) {
var e = n.createElement("div");
if (e.innerHTML = "\x3c!--[if IE " + t + "]><span></span><![endif]--\x3e", e.getElementsByTagName("span").length) return e = null, t
}
return i
}(),
p = function() {
var t = 0;
return e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || function(e) {
var n, r = (new Date).getTime();
return n = Math.max(0, 16 - (r - t)), t = r + n, setTimeout((function() {
e(r + n)
}), n)
}
}(),
g = {
isString: function(t) {
return "string" == typeof t
},
isArray: Array.isArray || function(t) {
return "[object Array]" === Object.prototype.toString.call(t)
},
isFunction: function(t) {
return "[object Function]" === Object.prototype.toString.call(t)
},
isNode: function(t) {
return t && t.nodeType
},
isNodeList: function(t) {
return "object" == r(t) && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(t)) && t.length !== i && (0 === t.length || "object" == r(t[0]) && t[0].nodeType > 0)
},
isWrapped: function(t) {
return t && (t.jquery || e.Zepto && e.Zepto.zepto.isZ(t))
},
isSVG: function(t) {
return e.SVGElement && t instanceof e.SVGElement
},
isEmptyObject: function(t) {
for (var e in t) return !1;
return !0
}
},
v = !1;
if (t.fn && t.fn.jquery ? (f = t, v = !0) : f = e.Velocity.Utilities, 8 >= h && !v) throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");
if (!(7 >= h)) {
var m = 400,
y = "swing",
b = {
State: {
isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
isAndroid: /Android/i.test(navigator.userAgent),
isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent),
isChrome: e.chrome,
isFirefox: /Firefox/i.test(navigator.userAgent),
prefixElement: n.createElement("div"),
prefixMatches: {},
scrollAnchor: null,
scrollPropertyLeft: null,
scrollPropertyTop: null,
isTicking: !1,
calls: []
},
CSS: {},
Utilities: f,
Redirects: {},
Easings: {},
Promise: e.Promise,
defaults: {
queue: "",
duration: m,
easing: y,
begin: i,
complete: i,
progress: i,
display: i,
visibility: i,
loop: !1,
delay: !1,
mobileHA: !0,
_cacheValues: !0
},
init: function(t) {
f.data(t, "velocity", {
isSVG: g.isSVG(t),
isAnimating: !1,
computedStyle: null,
tweensContainer: null,
rootPropertyValueCache: {},
transformCache: {}
})
},
hook: null,
mock: !1,
version: {
major: 1,
minor: 2,
patch: 2
},
debug: !1
};
e.pageYOffset !== i ? (b.State.scrollAnchor = e, b.State.scrollPropertyLeft = "pageXOffset", b.State.scrollPropertyTop = "pageYOffset") : (b.State.scrollAnchor = n.documentElement || n.body.parentNode || n.body, b.State.scrollPropertyLeft = "scrollLeft", b.State.scrollPropertyTop = "scrollTop");
var x = function() {
function t(t) {
return -t.tension * t.x - t.friction * t.v
}
function e(e, n, r) {
var i = {
x: e.x + r.dx * n,
v: e.v + r.dv * n,
tension: e.tension,
friction: e.friction
};
return {
dx: i.v,
dv: t(i)
}
}
function n(n, r) {
var i = {
dx: n.v,
dv: t(n)
},
o = e(n, .5 * r, i),
a = e(n, .5 * r, o),
s = e(n, r, a),
l = 1 / 6 * (i.dx + 2 * (o.dx + a.dx) + s.dx),
u = 1 / 6 * (i.dv + 2 * (o.dv + a.dv) + s.dv);
return n.x = n.x + l * r, n.v = n.v + u * r, n
}
return function t(e, r, i) {
var o, a, s, l = {
x: -1,
v: 0,
tension: null,
friction: null
},
u = [0],
c = 0;
for (e = parseFloat(e) || 500, r = parseFloat(r) || 20, i = i || null, l.tension = e, l.friction = r, a = (o = null !== i) ? (c = t(e, r)) / i * .016 : .016; s = n(s || l, a), u.push(1 + s.x), c += 16, Math.abs(s.x) > 1e-4 && Math.abs(s.v) > 1e-4;);
return o ? function(t) {
return u[t * (u.length - 1) | 0]
} : c
}
}();
b.Easings = {
linear: function(t) {
return t
},
swing: function(t) {
return .5 - Math.cos(t * Math.PI) / 2
},
spring: function(t) {
return 1 - Math.cos(4.5 * t * Math.PI) * Math.exp(6 * -t)
}
}, f.each([
["ease", [.25, .1, .25, 1]],
["ease-in", [.42, 0, 1, 1]],
["ease-out", [0, 0, .58, 1]],
["ease-in-out", [.42, 0, .58, 1]],
["easeInSine", [.47, 0, .745, .715]],
["easeOutSine", [.39, .575, .565, 1]],
["easeInOutSine", [.445, .05, .55, .95]],
["easeInQuad", [.55, .085, .68, .53]],
["easeOutQuad", [.25, .46, .45, .94]],
["easeInOutQuad", [.455, .03, .515, .955]],
["easeInCubic", [.55, .055, .675, .19]],
["easeOutCubic", [.215, .61, .355, 1]],
["easeInOutCubic", [.645, .045, .355, 1]],
["easeInQuart", [.895, .03, .685, .22]],
["easeOutQuart", [.165, .84, .44, 1]],
["easeInOutQuart", [.77, 0, .175, 1]],
["easeInQuint", [.755, .05, .855, .06]],
["easeOutQuint", [.23, 1, .32, 1]],
["easeInOutQuint", [.86, 0, .07, 1]],
["easeInExpo", [.95, .05, .795, .035]],
["easeOutExpo", [.19, 1, .22, 1]],
["easeInOutExpo", [1, 0, 0, 1]],
["easeInCirc", [.6, .04, .98, .335]],
["easeOutCirc", [.075, .82, .165, 1]],
["easeInOutCirc", [.785, .135, .15, .86]]
], (function(t, e) {
b.Easings[e[0]] = l.apply(null, e[1])
}));
var w = b.CSS = {
RegEx: {
isHex: /^#([A-f\d]{3}){1,2}$/i,
valueUnwrap: /^[A-z]+\((.*)\)$/i,
wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,
valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi
},
Lists: {
colors: ["fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor", "borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor"],
transformsBase: ["translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ"],
transforms3D: ["transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY"]
},
Hooks: {
templates: {
textShadow: ["Color X Y Blur", "black 0px 0px 0px"],
boxShadow: ["Color X Y Blur Spread", "black 0px 0px 0px 0px"],
clip: ["Top Right Bottom Left", "0px 0px 0px 0px"],
backgroundPosition: ["X Y", "0% 0%"],
transformOrigin: ["X Y Z", "50% 50% 0px"],
perspectiveOrigin: ["X Y", "50% 50%"]
},
registered: {},
register: function() {
for (var t = 0; t < w.Lists.colors.length; t++) {
var e = "color" === w.Lists.colors[t] ? "0 0 0 1" : "255 255 255 1";
w.Hooks.templates[w.Lists.colors[t]] = ["Red Green Blue Alpha", e]
}
var n, r, i;
if (h)
for (n in w.Hooks.templates) {
i = (r = w.Hooks.templates[n])[0].split(" ");
var o = r[1].match(w.RegEx.valueSplit);
"Color" === i[0] && (i.push(i.shift()), o.push(o.shift()), w.Hooks.templates[n] = [i.join(" "), o.join(" ")])
}
for (n in w.Hooks.templates)
for (var t in i = (r = w.Hooks.templates[n])[0].split(" ")) {
var a = n + i[t],
s = t;
w.Hooks.registered[a] = [n, s]
}
},
getRoot: function(t) {
var e = w.Hooks.registered[t];
return e ? e[0] : t
},
cleanRootPropertyValue: function(t, e) {
return w.RegEx.valueUnwrap.test(e) && (e = e.match(w.RegEx.valueUnwrap)[1]), w.Values.isCSSNullValue(e) && (e = w.Hooks.templates[t][1]), e
},
extractValue: function(t, e) {
var n = w.Hooks.registered[t];
if (n) {
var r = n[0],
i = n[1];
return (e = w.Hooks.cleanRootPropertyValue(r, e)).toString().match(w.RegEx.valueSplit)[i]
}
return e
},
injectValue: function(t, e, n) {
var r = w.Hooks.registered[t];
if (r) {
var i, o = r[0],
a = r[1];
return (i = (n = w.Hooks.cleanRootPropertyValue(o, n)).toString().match(w.RegEx.valueSplit))[a] = e, i.join(" ")
}
return n
}
},
Normalizations: {
registered: {
clip: function(t, e, n) {
switch (t) {
case "name":
return "clip";
case "extract":
var r;
return r = w.RegEx.wrappedValueAlreadyExtracted.test(n) ? n : (r = n.toString().match(w.RegEx.valueUnwrap)) ? r[1].replace(/,(\s+)?/g, " ") : n;
case "inject":
return "rect(" + n + ")"
}
},
blur: function(t, e, n) {
switch (t) {
case "name":
return b.State.isFirefox ? "filter" : "-webkit-filter";
case "extract":
var r = parseFloat(n);
if (!r && 0 !== r) {
var i = n.toString().match(/blur\(([0-9]+[A-z]+)\)/i);
r = i ? i[1] : 0
}
return r;
case "inject":
return parseFloat(n) ? "blur(" + n + ")" : "none"
}
},
opacity: function(t, e, n) {
if (8 >= h) switch (t) {
case "name":
return "filter";
case "extract":
var r = n.toString().match(/alpha\(opacity=(.*)\)/i);
return r ? r[1] / 100 : 1;
case "inject":
return e.style.zoom = 1, parseFloat(n) >= 1 ? "" : "alpha(opacity=" + parseInt(100 * parseFloat(n), 10) + ")"
} else switch (t) {
case "name":
return "opacity";
case "extract":
case "inject":
return n
}
}
},
register: function() {
9 >= h || b.State.isGingerbread || (w.Lists.transformsBase = w.Lists.transformsBase.concat(w.Lists.transforms3D));
for (var t = 0; t < w.Lists.transformsBase.length; t++) ! function() {
var e = w.Lists.transformsBase[t];
w.Normalizations.registered[e] = function(t, n, r) {
switch (t) {
case "name":
return "transform";
case "extract":
return a(n) === i || a(n).transformCache[e] === i ? /^scale/i.test(e) ? 1 : 0 : a(n).transformCache[e].replace(/[()]/g, "");
case "inject":
var o = !1;
switch (e.substr(0, e.length - 1)) {
case "translate":
o = !/(%|px|em|rem|vw|vh|\d)$/i.test(r);
break;
case "scal":
case "scale":
b.State.isAndroid && a(n).transformCache[e] === i && 1 > r && (r = 1), o = !/(\d)$/i.test(r);
break;
case "skew":
o = !/(deg|\d)$/i.test(r);
break;
case "rotate":
o = !/(deg|\d)$/i.test(r)
}
return o || (a(n).transformCache[e] = "(" + r + ")"), a(n).transformCache[e]
}
}
}();
for (t = 0; t < w.Lists.colors.length; t++) ! function() {
var e = w.Lists.colors[t];
w.Normalizations.registered[e] = function(t, n, r) {
switch (t) {
case "name":
return e;
case "extract":
var o;
if (w.RegEx.wrappedValueAlreadyExtracted.test(r)) o = r;
else {
var a, s = {
black: "rgb(0, 0, 0)",
blue: "rgb(0, 0, 255)",
gray: "rgb(128, 128, 128)",
green: "rgb(0, 128, 0)",
red: "rgb(255, 0, 0)",
white: "rgb(255, 255, 255)"
};
/^[A-z]+$/i.test(r) ? a = s[r] !== i ? s[r] : s.black : w.RegEx.isHex.test(r) ? a = "rgb(" + w.Values.hexToRgb(r).join(" ") + ")" : /^rgba?\(/i.test(r) || (a = s.black), o = (a || r).toString().match(w.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " ")
}
return 8 >= h || 3 !== o.split(" ").length || (o += " 1"), o;
case "inject":
return 8 >= h ? 4 === r.split(" ").length && (r = r.split(/\s+/).slice(0, 3).join(" ")) : 3 === r.split(" ").length && (r += " 1"), (8 >= h ? "rgb" : "rgba") + "(" + r.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")"
}
}
}()
}
},
Names: {
camelCase: function(t) {
return t.replace(/-(\w)/g, (function(t, e) {
return e.toUpperCase()
}))
},
SVGAttribute: function(t) {
var e = "width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";
return (h || b.State.isAndroid && !b.State.isChrome) && (e += "|transform"), new RegExp("^(" + e + ")$", "i").test(t)
},
prefixCheck: function(t) {
if (b.State.prefixMatches[t]) return [b.State.prefixMatches[t], !0];
for (var e = ["", "Webkit", "Moz", "ms", "O"], n = 0, r = e.length; r > n; n++) {
var i;
if (i = 0 === n ? t : e[n] + t.replace(/^\w/, (function(t) {
return t.toUpperCase()
})), g.isString(b.State.prefixElement.style[i])) return b.State.prefixMatches[t] = i, [i, !0]
}
return [t, !1]
}
},
Values: {
hexToRgb: function(t) {
var e;
return t = t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (function(t, e, n, r) {
return e + e + n + n + r + r
})), (e = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t)) ? [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)] : [0, 0, 0]
},
isCSSNullValue: function(t) {
return 0 == t || /^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(t)
},
getUnitType: function(t) {
return /^(rotate|skew)/i.test(t) ? "deg" : /(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(t) ? "" : "px"
},
getDisplayType: function(t) {
var e = t && t.tagName.toString().toLowerCase();
return /^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(e) ? "inline" : /^(li)$/i.test(e) ? "list-item" : /^(tr)$/i.test(e) ? "table-row" : /^(table)$/i.test(e) ? "table" : /^(tbody)$/i.test(e) ? "table-row-group" : "block"
},
addClass: function(t, e) {
t.classList ? t.classList.add(e) : t.className += (t.className.length ? " " : "") + e
},
removeClass: function(t, e) {
t.classList ? t.classList.remove(e) : t.className = t.className.toString().replace(new RegExp("(^|\\s)" + e.split(" ").join("|") + "(\\s|$)", "gi"), " ")
}
},
getPropertyValue: function(t, n, r, o) {
function s(t, n) {
function r() {
c && w.setPropertyValue(t, "display", "none")
}
var l = 0;
if (8 >= h) l = f.css(t, n);
else {
var u, c = !1;
if (/^(width|height)$/.test(n) && 0 === w.getPropertyValue(t, "display") && (c = !0, w.setPropertyValue(t, "display", w.Values.getDisplayType(t))), !o) {
if ("height" === n && "border-box" !== w.getPropertyValue(t, "boxSizing").toString().toLowerCase()) {
var d = t.offsetHeight - (parseFloat(w.getPropertyValue(t, "borderTopWidth")) || 0) - (parseFloat(w.getPropertyValue(t, "borderBottomWidth")) || 0) - (parseFloat(w.getPropertyValue(t, "paddingTop")) || 0) - (parseFloat(w.getPropertyValue(t, "paddingBottom")) || 0);
return r(), d
}
if ("width" === n && "border-box" !== w.getPropertyValue(t, "boxSizing").toString().toLowerCase()) {
var p = t.offsetWidth - (parseFloat(w.getPropertyValue(t, "borderLeftWidth")) || 0) - (parseFloat(w.getPropertyValue(t, "borderRightWidth")) || 0) - (parseFloat(w.getPropertyValue(t, "paddingLeft")) || 0) - (parseFloat(w.getPropertyValue(t, "paddingRight")) || 0);
return r(), p
}
}
u = a(t) === i ? e.getComputedStyle(t, null) : a(t).computedStyle ? a(t).computedStyle : a(t).computedStyle = e.getComputedStyle(t, null), "borderColor" === n && (n = "borderTopColor"), ("" === (l = 9 === h && "filter" === n ? u.getPropertyValue(n) : u[n]) || null === l) && (l = t.style[n]), r()
}
if ("auto" === l && /^(top|right|bottom|left)$/i.test(n)) {
var g = s(t, "position");
("fixed" === g || "absolute" === g && /top|left/i.test(n)) && (l = f(t).position()[n] + "px")
}
return l
}
var l;
if (w.Hooks.registered[n]) {
var u = n,
c = w.Hooks.getRoot(u);
r === i && (r = w.getPropertyValue(t, w.Names.prefixCheck(c)[0])), w.Normalizations.registered[c] && (r = w.Normalizations.registered[c]("extract", t, r)), l = w.Hooks.extractValue(u, r)
} else if (w.Normalizations.registered[n]) {
var d, p;
"transform" !== (d = w.Normalizations.registered[n]("name", t)) && (p = s(t, w.Names.prefixCheck(d)[0]), w.Values.isCSSNullValue(p) && w.Hooks.templates[n] && (p = w.Hooks.templates[n][1])), l = w.Normalizations.registered[n]("extract", t, p)
}
if (!/^[\d-]/.test(l))
if (a(t) && a(t).isSVG && w.Names.SVGAttribute(n))
if (/^(height|width)$/i.test(n)) try {
l = t.getBBox()[n]
} catch (t) {
l = 0
} else l = t.getAttribute(n);
else l = s(t, w.Names.prefixCheck(n)[0]);
return w.Values.isCSSNullValue(l) && (l = 0), b.debug >= 2 && console.log("Get " + n + ": " + l), l
},
setPropertyValue: function(t, n, r, i, o) {
var s = n;
if ("scroll" === n) o.container ? o.container["scroll" + o.direction] = r : "Left" === o.direction ? e.scrollTo(r, o.alternateValue) : e.scrollTo(o.alternateValue, r);
else if (w.Normalizations.registered[n] && "transform" === w.Normalizations.registered[n]("name", t)) w.Normalizations.registered[n]("inject", t, r), s = "transform", r = a(t).transformCache[n];
else {
if (w.Hooks.registered[n]) {
var l = n,
u = w.Hooks.getRoot(n);
i = i || w.getPropertyValue(t, u), r = w.Hooks.injectValue(l, r, i), n = u
}
if (w.Normalizations.registered[n] && (r = w.Normalizations.registered[n]("inject", t, r), n = w.Normalizations.registered[n]("name", t)), s = w.Names.prefixCheck(n)[0], 8 >= h) try {
t.style[s] = r
} catch (t) {
b.debug && console.log("Browser does not support [" + r + "] for [" + s + "]")
} else a(t) && a(t).isSVG && w.Names.SVGAttribute(n) ? t.setAttribute(n, r) : t.style[s] = r;
b.debug >= 2 && console.log("Set " + n + " (" + s + "): " + r)
}
return [s, r]
},
flushTransformCache: function(t) {
function e(e) {
return parseFloat(w.getPropertyValue(t, e))
}
var n = "";
if ((h || b.State.isAndroid && !b.State.isChrome) && a(t).isSVG) {
var r = {
translate: [e("translateX"), e("translateY")],
skewX: [e("skewX")],
skewY: [e("skewY")],
scale: 1 !== e("scale") ? [e("scale"), e("scale")] : [e("scaleX"), e("scaleY")],
rotate: [e("rotateZ"), 0, 0]
};
f.each(a(t).transformCache, (function(t) {
/^translate/i.test(t) ? t = "translate" : /^scale/i.test(t) ? t = "scale" : /^rotate/i.test(t) && (t = "rotate"), r[t] && (n += t + "(" + r[t].join(" ") + ") ", delete r[t])
}))
} else {
var i, o;
f.each(a(t).transformCache, (function(e) {
return i = a(t).transformCache[e], "transformPerspective" === e ? (o = i, !0) : (9 === h && "rotateZ" === e && (e = "rotate"), void(n += e + i + " "))
})), o && (n = "perspective" + o + " " + n)
}
w.setPropertyValue(t, "transform", n)
}
};
w.Hooks.register(), w.Normalizations.register(), b.hook = function(t, e, n) {
var r = i;
return t = o(t), f.each(t, (function(t, o) {
if (a(o) === i && b.init(o), n === i) r === i && (r = b.CSS.getPropertyValue(o, e));
else {
var s = b.CSS.setPropertyValue(o, e, n);
"transform" === s[0] && b.CSS.flushTransformCache(o), r = s
}
})), r
};
var S = function t() {
function r() {
return l ? _.promise || null : h
}
function s() {
function t(t) {
function d(t, e) {
var n = i,
r = i,
a = i;
return g.isArray(t) ? (n = t[0], !g.isArray(t[1]) && /^[\d-]/.test(t[1]) || g.isFunction(t[1]) || w.RegEx.isHex.test(t[1]) ? a = t[1] : (g.isString(t[1]) && !w.RegEx.isHex.test(t[1]) || g.isArray(t[1])) && (r = e ? t[1] : u(t[1], s.duration), t[2] !== i && (a = t[2]))) : n = t, e || (r = r || s.easing), g.isFunction(n) && (n = n.call(o, C, k)), g.isFunction(a) && (a = a.call(o, C, k)), [n || 0, r, a]
}
function h(t, e) {
var n, r;
return r = (e || "0").toString().toLowerCase().replace(/[%A-z]+$/, (function(t) {
return n = t, ""
})), n || (n = w.Values.getUnitType(t)), [r, n]
}
function p() {
var t = {
myParent: o.parentNode || n.body,
position: w.getPropertyValue(o, "position"),
fontSize: w.getPropertyValue(o, "fontSize")
},
r = t.position === L.lastPosition && t.myParent === L.lastParent,
i = t.fontSize === L.lastFontSize;
L.lastParent = t.myParent, L.lastPosition = t.position, L.lastFontSize = t.fontSize;
var s = 100,
l = {};
if (i && r) l.emToPx = L.lastEmToPx, l.percentToPxWidth = L.lastPercentToPxWidth, l.percentToPxHeight = L.lastPercentToPxHeight;
else {
var u = a(o).isSVG ? n.createElementNS("http://www.w3.org/2000/svg", "rect") : n.createElement("div");
b.init(u), t.myParent.appendChild(u), f.each(["overflow", "overflowX", "overflowY"], (function(t, e) {
b.CSS.setPropertyValue(u, e, "hidden")
})), b.CSS.setPropertyValue(u, "position", t.position), b.CSS.setPropertyValue(u, "fontSize", t.fontSize), b.CSS.setPropertyValue(u, "boxSizing", "content-box"), f.each(["minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height"], (function(t, e) {
b.CSS.setPropertyValue(u, e, s + "%")
})), b.CSS.setPropertyValue(u, "paddingLeft", s + "em"), l.percentToPxWidth = L.lastPercentToPxWidth = (parseFloat(w.getPropertyValue(u, "width", null, !0)) || 1) / s, l.percentToPxHeight = L.lastPercentToPxHeight = (parseFloat(w.getPropertyValue(u, "height", null, !0)) || 1) / s, l.emToPx = L.lastEmToPx = (parseFloat(w.getPropertyValue(u, "paddingLeft")) || 1) / s, t.myParent.removeChild(u)
}
return null === L.remToPx && (L.remToPx = parseFloat(w.getPropertyValue(n.body, "fontSize")) || 16), null === L.vwToPx && (L.vwToPx = parseFloat(e.innerWidth) / 100, L.vhToPx = parseFloat(e.innerHeight) / 100), l.remToPx = L.remToPx, l.vwToPx = L.vwToPx, l.vhToPx = L.vhToPx, b.debug >= 1 && console.log("Unit ratios: " + JSON.stringify(l), o), l
}
if (s.begin && 0 === C) try {
s.begin.call(v, v)
} catch (t) {
setTimeout((function() {
throw t
}), 1)
}
if ("scroll" === P) {
var m, S, M, A = /^x$/i.test(s.axis) ? "Left" : "Top",
T = parseFloat(s.offset) || 0;
s.container ? g.isWrapped(s.container) || g.isNode(s.container) ? (s.container = s.container[0] || s.container, M = (m = s.container["scroll" + A]) + f(o).position()[A.toLowerCase()] + T) : s.container = null : (m = b.State.scrollAnchor[b.State["scrollProperty" + A]], S = b.State.scrollAnchor[b.State["scrollProperty" + ("Left" === A ? "Top" : "Left")]], M = f(o).offset()[A.toLowerCase()] + T), l = {
scroll: {
rootPropertyValue: !1,
startValue: m,
currentValue: m,
endValue: M,
unitType: "",
easing: s.easing,
scrollData: {
container: s.container,
direction: A,
alternateValue: S
}
},
element: o
}, b.debug && console.log("tweensContainer (scroll): ", l.scroll, o)
} else if ("reverse" === P) {
if (!a(o).tweensContainer) return void f.dequeue(o, s.queue);
"none" === a(o).opts.display && (a(o).opts.display = "auto"), "hidden" === a(o).opts.visibility && (a(o).opts.visibility = "visible"), a(o).opts.loop = !1, a(o).opts.begin = null, a(o).opts.complete = null, x.easing || delete s.easing, x.duration || delete s.duration, s = f.extend({}, a(o).opts, s);
var I = f.extend(!0, {}, a(o).tweensContainer);
for (var O in I)
if ("element" !== O) {
var F = I[O].startValue;
I[O].startValue = I[O].currentValue = I[O].endValue, I[O].endValue = F, g.isEmptyObject(x) || (I[O].easing = s.easing), b.debug && console.log("reverse tweensContainer (" + O + "): " + JSON.stringify(I[O]), o)
} l = I
} else if ("start" === P) {
for (var D in a(o).tweensContainer && !0 === a(o).isAnimating && (I = a(o).tweensContainer), f.each(y, (function(t, e) {
if (RegExp("^" + w.Lists.colors.join("$|^") + "$").test(t)) {
var n = d(e, !0),
r = n[0],
o = n[1],
a = n[2];
if (w.RegEx.isHex.test(r)) {
for (var s = ["Red", "Green", "Blue"], l = w.Values.hexToRgb(r), u = a ? w.Values.hexToRgb(a) : i, c = 0; c < s.length; c++) {
var f = [l[c]];
o && f.push(o), u !== i && f.push(u[c]), y[t + s[c]] = f
}
delete y[t]
}
}
})), y) {
var E = d(y[D]),
N = E[0],
V = E[1],
z = E[2];
D = w.Names.camelCase(D);
var B = w.Hooks.getRoot(D),
W = !1;
if (a(o).isSVG || "tween" === B || !1 !== w.Names.prefixCheck(B)[1] || w.Normalizations.registered[B] !== i) {
(s.display !== i && null !== s.display && "none" !== s.display || s.visibility !== i && "hidden" !== s.visibility) && /opacity|filter/.test(D) && !z && 0 !== N && (z = 0), s._cacheValues && I && I[D] ? (z === i && (z = I[D].endValue + I[D].unitType), W = a(o).rootPropertyValueCache[B]) : w.Hooks.registered[D] ? z === i ? (W = w.getPropertyValue(o, B), z = w.getPropertyValue(o, D, W)) : W = w.Hooks.templates[B][1] : z === i && (z = w.getPropertyValue(o, D));
var j, H, q, U = !1;
if (z = (j = h(D, z))[0], q = j[1], N = (j = h(D, N))[0].replace(/^([+-\/*])=/, (function(t, e) {
return U = e, ""
})), H = j[1], z = parseFloat(z) || 0, N = parseFloat(N) || 0, "%" === H && (/^(fontSize|lineHeight)$/.test(D) ? (N /= 100, H = "em") : /^scale/.test(D) ? (N /= 100, H = "") : /(Red|Green|Blue)$/i.test(D) && (N = N / 100 * 255, H = "")), /[\/*]/.test(U)) H = q;
else if (q !== H && 0 !== z)
if (0 === N) H = q;
else {
r = r || p();
var $ = /margin|padding|left|right|width|text|word|letter/i.test(D) || /X$/.test(D) || "x" === D ? "x" : "y";
switch (q) {
case "%":
z *= "x" === $ ? r.percentToPxWidth : r.percentToPxHeight;
break;
case "px":
break;
default:
z *= r[q + "ToPx"]
}
switch (H) {
case "%":
z *= 1 / ("x" === $ ? r.percentToPxWidth : r.percentToPxHeight);
break;
case "px":
break;
default:
z *= 1 / r[H + "ToPx"]
}
} switch (U) {
case "+":
N = z + N;
break;
case "-":
N = z - N;
break;
case "*":
N *= z;
break;
case "/":
N = z / N
}
l[D] = {
rootPropertyValue: W,
startValue: z,
currentValue: z,
endValue: N,
unitType: H,
easing: V
}, b.debug && console.log("tweensContainer (" + D + "): " + JSON.stringify(l[D]), o)
} else b.debug && console.log("Skipping [" + B + "] due to a lack of browser support.")
}
l.element = o
}
l.element && (w.Values.addClass(o, "velocity-animating"), R.push(l), "" === s.queue && (a(o).tweensContainer = l, a(o).opts = s), a(o).isAnimating = !0, C === k - 1 ? (b.State.calls.push([R, v, s, null, _.resolver]), !1 === b.State.isTicking && (b.State.isTicking = !0, c())) : C++)
}
var r, o = this,
s = f.extend({}, b.defaults, x),
l = {};
switch (a(o) === i && b.init(o), parseFloat(s.delay) && !1 !== s.queue && f.queue(o, s.queue, (function(t) {
b.velocityQueueEntryFlag = !0, a(o).delayTimer = {
setTimeout: setTimeout(t, parseFloat(s.delay)),
next: t
}
})), s.duration.toString().toLowerCase()) {
case "fast":
s.duration = 200;
break;
case "normal":
s.duration = m;
break;
case "slow":
s.duration = 600;
break;
default:
s.duration = parseFloat(s.duration) || 1
}!1 !== b.mock && (!0 === b.mock ? s.duration = s.delay = 1 : (s.duration *= parseFloat(b.mock) || 1, s.delay *= parseFloat(b.mock) || 1)), s.easing = u(s.easing, s.duration), s.begin && !g.isFunction(s.begin) && (s.begin = null), s.progress && !g.isFunction(s.progress) && (s.progress = null), s.complete && !g.isFunction(s.complete) && (s.complete = null), s.display !== i && null !== s.display && (s.display = s.display.toString().toLowerCase(), "auto" === s.display && (s.display = b.CSS.Values.getDisplayType(o))), s.visibility !== i && null !== s.visibility && (s.visibility = s.visibility.toString().toLowerCase()), s.mobileHA = s.mobileHA && b.State.isMobile && !b.State.isGingerbread, !1 === s.queue ? s.delay ? setTimeout(t, s.delay) : t() : f.queue(o, s.queue, (function(e, n) {
return !0 === n ? (_.promise && _.resolver(v), !0) : (b.velocityQueueEntryFlag = !0, void t())
})), "" !== s.queue && "fx" !== s.queue || "inprogress" === f.queue(o)[0] || f.dequeue(o)
}
var l, h, p, v, y, x, S = arguments[0] && (arguments[0].p || f.isPlainObject(arguments[0].properties) && !arguments[0].properties.names || g.isString(arguments[0].properties));
if (g.isWrapped(this) ? (l = !1, p = 0, v = this, h = this) : (l = !0, p = 1, v = S ? arguments[0].elements || arguments[0].e : arguments[0]), v = o(v)) {
S ? (y = arguments[0].properties || arguments[0].p, x = arguments[0].options || arguments[0].o) : (y = arguments[p], x = arguments[p + 1]);
var k = v.length,
C = 0;
if (!/^(stop|finish)$/i.test(y) && !f.isPlainObject(x)) {
var M = p + 1;
x = {};
for (var A = M; A < arguments.length; A++) g.isArray(arguments[A]) || !/^(fast|normal|slow)$/i.test(arguments[A]) && !/^\d/.test(arguments[A]) ? g.isString(arguments[A]) || g.isArray(arguments[A]) ? x.easing = arguments[A] : g.isFunction(arguments[A]) && (x.complete = arguments[A]) : x.duration = arguments[A]
}
var P, _ = {
promise: null,
resolver: null,
rejecter: null
};
switch (l && b.Promise && (_.promise = new b.Promise((function(t, e) {
_.resolver = t, _.rejecter = e
}))), y) {
case "scroll":
P = "scroll";
break;
case "reverse":
P = "reverse";
break;
case "finish":
case "stop":
f.each(v, (function(t, e) {
a(e) && a(e).delayTimer && (clearTimeout(a(e).delayTimer.setTimeout), a(e).delayTimer.next && a(e).delayTimer.next(), delete a(e).delayTimer)
}));
var T = [];
return f.each(b.State.calls, (function(t, e) {
e && f.each(e[1], (function(n, r) {
var o = x === i ? "" : x;
return !0 !== o && e[2].queue !== o && (x !== i || !1 !== e[2].queue) || void f.each(v, (function(n, i) {
i === r && ((!0 === x || g.isString(x)) && (f.each(f.queue(i, g.isString(x) ? x : ""), (function(t, e) {
g.isFunction(e) && e(null, !0)
})), f.queue(i, g.isString(x) ? x : "", [])), "stop" === y ? (a(i) && a(i).tweensContainer && !1 !== o && f.each(a(i).tweensContainer, (function(t, e) {
e.endValue = e.currentValue
})), T.push(t)) : "finish" === y && (e[2].duration = 1))
}))
}))
})), "stop" === y && (f.each(T, (function(t, e) {
d(e, !0)
})), _.promise && _.resolver(v)), r();
default:
if (!f.isPlainObject(y) || g.isEmptyObject(y)) {
if (g.isString(y) && b.Redirects[y]) {
var I = (E = f.extend({}, x)).duration,
O = E.delay || 0;
return !0 === E.backwards && (v = f.extend(!0, [], v).reverse()), f.each(v, (function(t, e) {
parseFloat(E.stagger) ? E.delay = O + parseFloat(E.stagger) * t : g.isFunction(E.stagger) && (E.delay = O + E.stagger.call(e, t, k)), E.drag && (E.duration = parseFloat(I) || (/^(callout|transition)/.test(y) ? 1e3 : m), E.duration = Math.max(E.duration * (E.backwards ? 1 - t / k : (t + 1) / k), .75 * E.duration, 200)), b.Redirects[y].call(e, e, E || {}, t, k, v, _.promise ? _ : i)
})), r()
}
var F = "Velocity: First argument (" + y + ") was not a property map, a known action, or a registered redirect. Aborting.";
return _.promise ? _.rejecter(new Error(F)) : console.log(F), r()
}
P = "start"
}
var D, E, L = {
lastParent: null,
lastPosition: null,
lastFontSize: null,
lastPercentToPxWidth: null,
lastPercentToPxHeight: null,
lastEmToPx: null,
remToPx: null,
vwToPx: null,
vhToPx: null
},
R = [];
if (f.each(v, (function(t, e) {
g.isNode(e) && s.call(e)
})), (E = f.extend({}, b.defaults, x)).loop = parseInt(E.loop), D = 2 * E.loop - 1, E.loop)
for (var N = 0; D > N; N++) {
var V = {
delay: E.delay,
progress: E.progress
};
N === D - 1 && (V.display = E.display, V.visibility = E.visibility, V.complete = E.complete), t(v, "reverse", V)
}
return r()
}
};
(b = f.extend(S, b)).animate = S;
var k = e.requestAnimationFrame || p;
return b.State.isMobile || n.hidden === i || n.addEventListener("visibilitychange", (function() {
n.hidden ? (k = function(t) {
return setTimeout((function() {
t(!0)
}), 16)
}, c()) : k = e.requestAnimationFrame || p
})), t.Velocity = b, t !== e && (t.fn.velocity = S, t.fn.velocity.defaults = b.defaults), f.each(["Down", "Up"], (function(t, e) {
b.Redirects["slide" + e] = function(t, n, r, o, a, s) {
var l = f.extend({}, n),
u = l.begin,
c = l.complete,
d = {
height: "",
marginTop: "",
marginBottom: "",
paddingTop: "",
paddingBottom: ""
},
h = {};
l.display === i && (l.display = "Down" === e ? "inline" === b.CSS.Values.getDisplayType(t) ? "inline-block" : "block" : "none"), l.begin = function() {
for (var n in u && u.call(a, a), d) {
h[n] = t.style[n];
var r = b.CSS.getPropertyValue(t, n);
d[n] = "Down" === e ? [r, 0] : [0, r]
}
h.overflow = t.style.overflow, t.style.overflow = "hidden"
}, l.complete = function() {
for (var e in h) t.style[e] = h[e];
c && c.call(a, a), s && s.resolver(a)
}, b(t, d, l)
}
})), f.each(["In", "Out"], (function(t, e) {
b.Redirects["fade" + e] = function(t, n, r, o, a, s) {
var l = f.extend({}, n),
u = {
opacity: "In" === e ? 1 : 0
},
c = l.complete;
l.complete = r !== o - 1 ? l.begin = null : function() {
c && c.call(a, a), s && s.resolver(a)
}, l.display === i && (l.display = "In" === e ? "auto" : "none"), b(this, u, l)
}
})), b
}
jQuery.fn.velocity = jQuery.fn.animate
}(window.jQuery || window.Zepto || window, window, document)
}, "object" == r(t) && "object" == r(t.exports) ? t.exports = e() : "function" == typeof define && n(55) ? define(e) : e())
}).call(this, n(87)(t))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(1),
o = n(148),
a = n(7),
s = n(32),
l = n(11),
u = n(103),
c = o.ArrayBuffer,
d = o.DataView,
f = c.prototype.slice;
r({
target: "ArrayBuffer",
proto: !0,
unsafe: !0,
forced: i((function() {
return !new c(2).slice(1, void 0).byteLength
}))
}, {
slice: function(t, e) {
if (void 0 !== f && void 0 === e) return f.call(a(this), t);
for (var n = a(this).byteLength, r = s(t, n), i = s(void 0 === e ? n : e, n), o = new(u(this, c))(l(i - r)), h = new d(this), p = new d(o), g = 0; r < i;) p.setUint8(g++, h.getUint8(r++));
return o
}
})
}, function(t, e, n) {
var r = n(14);
t.exports = function(t, e, n) {
for (var i in e) r(t, i, e[i], n);
return t
}
}, function(t, e, n) {
n(173)("Float32", 4, (function(t) {
return function(e, n, r) {
return t(this, e, n, r)
}
}))
}, function(t, e, n) {
"use strict";
var r = n(3),
i = n(0),
o = n(9),
a = n(174),
s = n(56),
l = n(148),
u = n(149),
c = n(17),
d = n(6),
f = n(11),
h = n(150),
p = n(151),
g = n(19),
v = n(4),
m = n(76),
y = n(5),
b = n(34),
x = n(70),
w = n(27).f,
S = n(177),
k = n(23).forEach,
C = n(126),
M = n(8),
A = n(26),
P = n(21),
_ = P.get,
T = P.set,
I = M.f,
O = A.f,
F = Math.round,
D = i.RangeError,
E = l.ArrayBuffer,
L = l.DataView,
R = s.NATIVE_ARRAY_BUFFER_VIEWS,
N = s.TYPED_ARRAY_TAG,
V = s.TypedArray,
z = s.TypedArrayPrototype,
B = s.aTypedArrayConstructor,
W = s.isTypedArray,
j = function(t, e) {
for (var n = 0, r = e.length, i = new(B(t))(r); r > n;) i[n] = e[n++];
return i
},
H = function(t, e) {
I(t, e, {
get: function() {
return _(this)[e]
}
})
},
q = function(t) {
var e;
return t instanceof E || "ArrayBuffer" == (e = m(t)) || "SharedArrayBuffer" == e
},
U = function(t, e) {
return W(t) && "symbol" != typeof e && e in t && String(+e) == String(e)
},
$ = function(t, e) {
return U(t, e = g(e, !0)) ? c(2, t[e]) : O(t, e)
},
Y = function(t, e, n) {
return !(U(t, e = g(e, !0)) && y(n) && v(n, "value")) || v(n, "get") || v(n, "set") || n.configurable || v(n, "writable") && !n.writable || v(n, "enumerable") && !n.enumerable ? I(t, e, n) : (t[e] = n.value, t)
};
o ? (R || (A.f = $, M.f = Y, H(z, "buffer"), H(z, "byteOffset"), H(z, "byteLength"), H(z, "length")), r({
target: "Object",
stat: !0,
forced: !R
}, {
getOwnPropertyDescriptor: $,
defineProperty: Y
}), t.exports = function(t, e, n, o) {
var s = t + (o ? "Clamped" : "") + "Array",
l = "get" + t,
c = "set" + t,
g = i[s],
v = g,
m = v && v.prototype,
M = {},
A = function(t, n) {
I(t, n, {
get: function() {
return function(t, n) {
var r = _(t);
return r.view[l](n * e + r.byteOffset, !0)
}(this, n)
},
set: function(t) {
return function(t, n, r) {
var i = _(t);
o && (r = (r = F(r)) < 0 ? 0 : r > 255 ? 255 : 255 & r), i.view[c](n * e + i.byteOffset, r, !0)
}(this, n, t)
},
enumerable: !0
})
};
R ? a && (v = n((function(t, n, r, i) {
return u(t, v, s), y(n) ? q(n) ? void 0 !== i ? new g(n, p(r, e), i) : void 0 !== r ? new g(n, p(r, e)) : new g(n) : W(n) ? j(v, n) : S.call(v, n) : new g(h(n))
})), x && x(v, V), k(w(g), (function(t) {
t in v || d(v, t, g[t])
})), v.prototype = m) : (v = n((function(t, n, r, i) {
u(t, v, s);
var o, a, l, c = 0,
d = 0;
if (y(n)) {
if (!q(n)) return W(n) ? j(v, n) : S.call(v, n);
o = n, d = p(r, e);
var g = n.byteLength;
if (void 0 === i) {
if (g % e) throw D("Wrong length");
if ((a = g - d) < 0) throw D("Wrong length")
} else if ((a = f(i) * e) + d > g) throw D("Wrong length");
l = a / e
} else l = h(n), o = new E(a = l * e);
for (T(t, {
buffer: o,
byteOffset: d,
byteLength: a,
length: l,
view: new L(o)
}); c < l;) A(t, c++)
})), x && x(v, V), m = v.prototype = b(z)), m.constructor !== v && d(m, "constructor", v), N && d(m, N, s), M[s] = v, r({
global: !0,
forced: v != g,
sham: !R
}, M), "BYTES_PER_ELEMENT" in v || d(v, "BYTES_PER_ELEMENT", e), "BYTES_PER_ELEMENT" in m || d(m, "BYTES_PER_ELEMENT", e), C(s)
}) : t.exports = function() {}
}, function(t, e, n) {
var r = n(0),
i = n(1),
o = n(175),
a = n(56).NATIVE_ARRAY_BUFFER_VIEWS,
s = r.ArrayBuffer,
l = r.Int8Array;
t.exports = !a || !i((function() {
l(1)
})) || !i((function() {
new l(-1)
})) || !o((function(t) {
new l, new l(null), new l(1.5), new l(t)
}), !0) || i((function() {
return 1 !== new l(new s(2), 1, void 0).length
}))
}, function(t, e, n) {
var r = n(2)("iterator"),
i = !1;
try {
var o = 0,
a = {
next: function() {
return {
done: !!o++
}
},
return: function() {
i = !0
}
};
a[r] = function() {
return this
}, Array.from(a, (function() {
throw 2
}))
} catch (t) {}
t.exports = function(t, e) {
if (!e && !i) return !1;
var n = !1;
try {
var o = {};
o[r] = function() {
return {
next: function() {
return {
done: n = !0
}
}
}
}, t(o)
} catch (t) {}
return n
}
}, function(t, e, n) {
var r = n(12);
t.exports = function(t) {
var e = r(t);
if (e < 0) throw RangeError("The argument can't be less than 0");
return e
}
}, function(t, e, n) {
var r = n(16),
i = n(11),
o = n(178),
a = n(179),
s = n(75),
l = n(56).aTypedArrayConstructor;
t.exports = function(t) {
var e, n, u, c, d, f, h = r(t),
p = arguments.length,
g = p > 1 ? arguments[1] : void 0,
v = void 0 !== g,
m = o(h);
if (null != m && !a(m))
for (f = (d = m.call(h)).next, h = []; !(c = f.call(d)).done;) h.push(c.value);
for (v && p > 2 && (g = s(g, arguments[2], 2)), n = i(h.length), u = new(l(this))(n), e = 0; n > e; e++) u[e] = v ? g(h[e], e) : h[e];
return u
}
}, function(t, e, n) {
var r = n(76),
i = n(40),
o = n(2)("iterator");
t.exports = function(t) {
if (null != t) return t[o] || t["@@iterator"] || i[r(t)]
}
}, function(t, e, n) {
var r = n(2),
i = n(40),
o = r("iterator"),
a = Array.prototype;
t.exports = function(t) {
return void 0 !== t && (i.Array === t || a[o] === t)
}
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(181),
o = r.aTypedArray;
r.exportProto("copyWithin", (function(t, e) {
return i.call(o(this), t, e, arguments.length > 2 ? arguments[2] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(16),
i = n(32),
o = n(11),
a = Math.min;
t.exports = [].copyWithin || function(t, e) {
var n = r(this),
s = o(n.length),
l = i(t, s),
u = i(e, s),
c = arguments.length > 2 ? arguments[2] : void 0,
d = a((void 0 === c ? s : i(c, s)) - u, s - l),
f = 1;
for (u < l && l < u + d && (f = -1, u += d - 1, l += d - 1); d-- > 0;) u in n ? n[l] = n[u] : delete n[l], l += f, u += f;
return n
}
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).every,
o = r.aTypedArray;
r.exportProto("every", (function(t) {
return i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(132),
o = r.aTypedArray;
r.exportProto("fill", (function(t) {
return i.apply(o(this), arguments)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).filter,
o = n(103),
a = r.aTypedArray,
s = r.aTypedArrayConstructor;
r.exportProto("filter", (function(t) {
for (var e = i(a(this), t, arguments.length > 1 ? arguments[1] : void 0), n = o(this, this.constructor), r = 0, l = e.length, u = new(s(n))(l); l > r;) u[r] = e[r++];
return u
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).find,
o = r.aTypedArray;
r.exportProto("find", (function(t) {
return i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).findIndex,
o = r.aTypedArray;
r.exportProto("findIndex", (function(t) {
return i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).forEach,
o = r.aTypedArray;
r.exportProto("forEach", (function(t) {
i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(41).includes,
o = r.aTypedArray;
r.exportProto("includes", (function(t) {
return i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(41).indexOf,
o = r.aTypedArray;
r.exportProto("indexOf", (function(t) {
return i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(0),
i = n(56),
o = n(54),
a = n(2)("iterator"),
s = r.Uint8Array,
l = o.values,
u = o.keys,
c = o.entries,
d = i.aTypedArray,
f = i.exportProto,
h = s && s.prototype[a],
p = !!h && ("values" == h.name || null == h.name),
g = function() {
return l.call(d(this))
};
f("entries", (function() {
return c.call(d(this))
})), f("keys", (function() {
return u.call(d(this))
})), f("values", g, !p), f(a, g, !p)
}, function(t, e, n) {
"use strict";
var r = n(56),
i = r.aTypedArray,
o = [].join;
r.exportProto("join", (function(t) {
return o.apply(i(this), arguments)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(130),
o = r.aTypedArray;
r.exportProto("lastIndexOf", (function(t) {
return i.apply(o(this), arguments)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).map,
o = n(103),
a = r.aTypedArray,
s = r.aTypedArrayConstructor;
r.exportProto("map", (function(t) {
return i(a(this), t, arguments.length > 1 ? arguments[1] : void 0, (function(t, e) {
return new(s(o(t, t.constructor)))(e)
}))
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(107).left,
o = r.aTypedArray;
r.exportProto("reduce", (function(t) {
return i(o(this), t, arguments.length, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(107).right,
o = r.aTypedArray;
r.exportProto("reduceRight", (function(t) {
return i(o(this), t, arguments.length, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = r.aTypedArray,
o = Math.floor;
r.exportProto("reverse", (function() {
for (var t, e = i(this).length, n = o(e / 2), r = 0; r < n;) t = this[r], this[r++] = this[--e], this[e] = t;
return this
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(11),
o = n(151),
a = n(16),
s = n(1),
l = r.aTypedArray,
u = s((function() {
new Int8Array(1).set({})
}));
r.exportProto("set", (function(t) {
l(this);
var e = o(arguments.length > 1 ? arguments[1] : void 0, 1),
n = this.length,
r = a(t),
s = i(r.length),
u = 0;
if (s + e > n) throw RangeError("Wrong length");
for (; u < s;) this[e + u] = r[u++]
}), u)
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(103),
o = n(1),
a = r.aTypedArray,
s = r.aTypedArrayConstructor,
l = [].slice,
u = o((function() {
new Int8Array(1).slice()
}));
r.exportProto("slice", (function(t, e) {
for (var n = l.call(a(this), t, e), r = i(this, this.constructor), o = 0, u = n.length, c = new(s(r))(u); u > o;) c[o] = n[o++];
return c
}), u)
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(23).some,
o = r.aTypedArray;
r.exportProto("some", (function(t) {
return i(o(this), t, arguments.length > 1 ? arguments[1] : void 0)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = r.aTypedArray,
o = [].sort;
r.exportProto("sort", (function(t) {
return o.call(i(this), t)
}))
}, function(t, e, n) {
"use strict";
var r = n(56),
i = n(11),
o = n(32),
a = n(103),
s = r.aTypedArray;
r.exportProto("subarray", (function(t, e) {
var n = s(this),
r = n.length,
l = o(t, r);
return new(a(n, n.constructor))(n.buffer, n.byteOffset + l * n.BYTES_PER_ELEMENT, i((void 0 === e ? r : o(e, r)) - l))
}))
}, function(t, e, n) {
"use strict";
var r = n(0),
i = n(56),
o = n(1),
a = r.Int8Array,
s = i.aTypedArray,
l = [].toLocaleString,
u = [].slice,
c = !!a && o((function() {
l.call(new a(1))
})),
d = o((function() {
return [1, 2].toLocaleString() != new a([1, 2]).toLocaleString()
})) || !o((function() {
a.prototype.toLocaleString.call([1, 2])
}));
i.exportProto("toLocaleString", (function() {
return l.apply(c ? u.call(s(this)) : s(this), arguments)
}), d)
}, function(t, e, n) {
"use strict";
var r = n(0),
i = n(56),
o = n(1),
a = r.Uint8Array,
s = a && a.prototype,
l = [].toString,
u = [].join;
o((function() {
l.call({})
})) && (l = function() {
return u.call(this)
}), i.exportProto("toString", l, (s || {}).toString != l)
}, function(t, e, n) {
"use strict";
(function(t) {
n(78), n(81), n(82), n(91), n(54), n(101), n(104), n(123), n(71), n(106), n(84), n(85);
function e(t) {
return (e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
return typeof t
} : function(t) {
return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t
})(t)
}
/*!
* Waves v0.7.6
* http://fian.my.id/Waves
*
* Copyright 2014-2018 Alfiana E. Sibuea and other contributors
* Released under the MIT license
* https://github.com/fians/Waves/blob/master/LICENSE
*/
! function(r, i) {
"function" == typeof define && n(55) ? define([], (function() {
return r.Waves = i.call(r), r.Waves
})) : "object" === ("undefined" == typeof exports ? "undefined" : e(exports)) ? t.exports = i.call(r) : r.Waves = i.call(r)
}("object" === ("undefined" == typeof window ? "undefined" : e(window)) ? window : void 0, (function() {
var t = t || {},
n = document.querySelectorAll.bind(document),
r = Object.prototype.toString,
i = "ontouchstart" in window;
function o(t) {
var n = e(t);
return "function" === n || "object" === n && !!t
}
function a(t) {
var e, i = r.call(t);
return "[object String]" === i ? n(t) : o(t) && /^\[object (Array|HTMLCollection|NodeList|Object)\]$/.test(i) && t.hasOwnProperty("length") ? t : o(e = t) && e.nodeType > 0 ? [t] : []
}
function s(t) {
var n, r, i = {
top: 0,
left: 0
},
o = t && t.ownerDocument;
return n = o.documentElement, "undefined" !== e(t.getBoundingClientRect) && (i = t.getBoundingClientRect()), r = function(t) {
return null !== (e = t) && e === e.window ? t : 9 === t.nodeType && t.defaultView;
var e
}(o), {
top: i.top + r.pageYOffset - n.clientTop,
left: i.left + r.pageXOffset - n.clientLeft
}
}
function l(t) {
var e = "";
for (var n in t) t.hasOwnProperty(n) && (e += n + ":" + t[n] + ";");
return e
}
var u = {
duration: 750,
delay: 200,
show: function(t, e, n) {
if (2 === t.button) return !1;
e = e || this;
var r = document.createElement("div");
r.className = "waves-ripple waves-rippling", e.appendChild(r);
var i = s(e),
o = 0,
a = 0;
"touches" in t && t.touches.length ? (o = t.touches[0].pageY - i.top, a = t.touches[0].pageX - i.left) : (o = t.pageY - i.top, a = t.pageX - i.left), a = a >= 0 ? a : 0, o = o >= 0 ? o : 0;
var c = "scale(" + e.clientWidth / 100 * 3 + ")",
d = "translate(0,0)";
n && (d = "translate(" + n.x + "px, " + n.y + "px)"), r.setAttribute("data-hold", Date.now()), r.setAttribute("data-x", a), r.setAttribute("data-y", o), r.setAttribute("data-scale", c), r.setAttribute("data-translate", d);
var f = {
top: o + "px",
left: a + "px"
};
r.classList.add("waves-notransition"), r.setAttribute("style", l(f)), r.classList.remove("waves-notransition"), f["-webkit-transform"] = c + " " + d, f["-moz-transform"] = c + " " + d, f["-ms-transform"] = c + " " + d, f["-o-transform"] = c + " " + d, f.transform = c + " " + d, f.opacity = "1";
var h = "mousemove" === t.type ? 2500 : u.duration;
f["-webkit-transition-duration"] = h + "ms", f["-moz-transition-duration"] = h + "ms", f["-o-transition-duration"] = h + "ms", f["transition-duration"] = h + "ms", r.setAttribute("style", l(f))
},
hide: function(t, e) {
for (var n = (e = e || this).getElementsByClassName("waves-rippling"), r = 0, o = n.length; r < o; r++) d(t, e, n[r]);
i && (e.removeEventListener("touchend", u.hide), e.removeEventListener("touchcancel", u.hide)), e.removeEventListener("mouseup", u.hide), e.removeEventListener("mouseleave", u.hide)
}
},
c = {
input: function(t) {
var e = t.parentNode;
if ("span" !== e.tagName.toLowerCase() || !e.classList.contains("waves-effect")) {
var n = document.createElement("span");
n.className = "waves-input-wrapper", e.replaceChild(n, t), n.appendChild(t)
}
},
img: function(t) {
var e = t.parentNode;
if ("i" !== e.tagName.toLowerCase() || !e.classList.contains("waves-effect")) {
var n = document.createElement("i");
e.replaceChild(n, t), n.appendChild(t)
}
}
};
function d(t, e, n) {
if (n) {
n.classList.remove("waves-rippling");
var r = n.getAttribute("data-x"),
i = n.getAttribute("data-y"),
o = n.getAttribute("data-scale"),
a = n.getAttribute("data-translate"),
s = 350 - (Date.now() - Number(n.getAttribute("data-hold")));
s < 0 && (s = 0), "mousemove" === t.type && (s = 150);
var c = "mousemove" === t.type ? 2500 : u.duration;
setTimeout((function() {
var t = {
top: i + "px",
left: r + "px",
opacity: "0",
"-webkit-transition-duration": c + "ms",
"-moz-transition-duration": c + "ms",
"-o-transition-duration": c + "ms",
"transition-duration": c + "ms",
"-webkit-transform": o + " " + a,
"-moz-transform": o + " " + a,
"-ms-transform": o + " " + a,
"-o-transform": o + " " + a,
transform: o + " " + a
};
n.setAttribute("style", l(t)), setTimeout((function() {
try {
e.removeChild(n)
} catch (t) {
return !1
}
}), c)
}), s)
}
}
var f = {
touches: 0,
allowEvent: function(t) {
var e = !0;
return /^(mousedown|mousemove)$/.test(t.type) && f.touches && (e = !1), e
},
registerEvent: function(t) {
var e = t.type;
"touchstart" === e ? f.touches += 1 : /^(touchend|touchcancel)$/.test(e) && setTimeout((function() {
f.touches && (f.touches -= 1)
}), 500)
}
};
function h(t) {
var e = function(t) {
if (!1 === f.allowEvent(t)) return null;
for (var e = null, n = t.target || t.srcElement; n.parentElement;) {
if (!(n instanceof SVGElement) && n.classList.contains("waves-effect")) {
e = n;
break
}
n = n.parentElement
}
return e
}(t);
if (null !== e) {
if (e.disabled || e.getAttribute("disabled") || e.classList.contains("disabled")) return;
if (f.registerEvent(t), "touchstart" === t.type && u.delay) {
var n = !1,
r = setTimeout((function() {
r = null, u.show(t, e)
}), u.delay),
o = function(i) {
r && (clearTimeout(r), r = null, u.show(t, e)), n || (n = !0, u.hide(i, e)), s()
},
a = function(t) {
r && (clearTimeout(r), r = null), o(t), s()
};
e.addEventListener("touchmove", a, !1), e.addEventListener("touchend", o, !1), e.addEventListener("touchcancel", o, !1);
var s = function() {
e.removeEventListener("touchmove", a), e.removeEventListener("touchend", o), e.removeEventListener("touchcancel", o)
}
} else u.show(t, e), i && (e.addEventListener("touchend", u.hide, !1), e.addEventListener("touchcancel", u.hide, !1)), e.addEventListener("mouseup", u.hide, !1), e.addEventListener("mouseleave", u.hide, !1)
}
}
return t.init = function(t) {
var e = document.body;
"duration" in (t = t || {}) && (u.duration = t.duration), "delay" in t && (u.delay = t.delay), i && (e.addEventListener("touchstart", h, !1), e.addEventListener("touchcancel", f.registerEvent, !1), e.addEventListener("touchend", f.registerEvent, !1)), e.addEventListener("mousedown", h, !1)
}, t.attach = function(t, e) {
var n, i;
t = a(t), "[object Array]" === r.call(e) && (e = e.join(" ")), e = e ? " " + e : "";
for (var o = 0, s = t.length; o < s; o++) i = (n = t[o]).tagName.toLowerCase(), -1 !== ["input", "img"].indexOf(i) && (c[i](n), n = n.parentElement), -1 === n.className.indexOf("waves-effect") && (n.className += " waves-effect" + e)
}, t.ripple = function(t, e) {
var n = (t = a(t)).length;
if ((e = e || {}).wait = e.wait || 0, e.position = e.position || null, n)
for (var r, i, o, l = {}, c = 0, d = {
type: "mousedown",
button: 1
}, f = function(t, e) {
return function() {
u.hide(t, e)
}
}; c < n; c++)
if (r = t[c], i = e.position || {
x: r.clientWidth / 2,
y: r.clientHeight / 2
}, o = s(r), l.x = o.left + i.x, l.y = o.top + i.y, d.pageX = l.x, d.pageY = l.y, u.show(d, r), e.wait >= 0 && null !== e.wait) {
setTimeout(f({
type: "mouseup",
button: 1
}, r), e.wait)
}
}, t.calm = function(t) {
for (var e = {
type: "mouseup",
button: 1
}, n = 0, r = (t = a(t)).length; n < r; n++) u.hide(e, t[n])
}, t.displayEffect = function(e) {
console.error("Waves.displayEffect() has been deprecated and will be removed in future version. Please use Waves.init() to initialize Waves effect"), t.init(e)
}, t
})), $(document).ready((function() {
Waves.attach(".btn:not(.btn-flat), .btn-floating", ["waves-light"]), Waves.attach(".btn-flat", ["waves-effect"]), Waves.attach(".chip", ["waves-effect"]), Waves.attach(".view a .mask", ["waves-light"]), Waves.attach(".waves-light", ["waves-light"]), Waves.attach(".navbar-nav a:not(.navbar-brand), .nav-icons li a, .nav-tabs .nav-item:not(.dropdown)", ["waves-light"]), Waves.attach(".pager li a", ["waves-light"]), Waves.attach(".pagination .page-item .page-link", ["waves-effect"]), Waves.init()
}))
}).call(this, n(87)(t))
}]);
//# sourceMappingURL=mdb.min.js.map |
var parse = {
/*
* 解析模板为执行函数
*/
get: (function() {
var regmap = [
// if语句开始
{reg: /^if\s+(.+)/i, val: function(all, condition) {return 'if(' + condition + ') {';}},
// elseif 语句开始
{reg: /^elseif\s+(.+)/i, val: function(all, condition) {return '} else if(' + condition + ') {';}},
// else语句结束
{reg: /^else/i, val: '} else {'},
// if语句结束
{reg: /^\/\s*if/i, val: '}'},
// list语句开始
{reg: /^list\s+([\S]+)\s+as\s+([\S]+)/i, val: function(all, arr, item) {return 'for(var __INDEX__=0;__INDEX__<' + arr + '.length;__INDEX__++) {var ' + item + '=' + arr + '[__INDEX__];var ' + item + '_index=__INDEX__;';}},
// list语句结束
{reg: /^\/\s*list/i, val: '}'},
// var 语句
{reg: /^var\s+(.+)/i, val: function(all, expr) {return 'var ' + expr + ';';}}
];
/*
* 转换模板语句
*/
var transStm = function(stmJs) {
stmJs = stmJs.trim();
for(var i=0; i<regmap.length; i++) {
var item = regmap[i];
if(item.reg.test(stmJs)) {
return (typeof item.val === 'function') ? stmJs.replace(item.reg, item.val) : item.val;
}
}
};
/*
* 解析模板
*/
var doParseTemplate = function(content, data) {
content = content.replace(/\t/g, ' ').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
// 初始化模板生成器结构
var struct = [
'try { var OUT = [];',
'', //放置模板生成器占位符
'return OUT.join(\'\'); } catch(e) { throw new Error("parse template error!"); }'
];
// 初始化模板变量
var vars = [];
Object.keys(data).forEach(function(name) {
if(typeof data[name] === 'string') {
data[name] = '\'' + data[name] + '\'';
}
var tmp = typeof data[name] === 'object' ? JSON.stringify(data[name]) : data[name];
vars.push('var ' + name + ' = ' + tmp + ';');
});
vars = vars.join('');
// 解析模板内容
var out = [];
var beg = 0; // 解析文段起始位置
var stmbeg = 0; // 表达式起始位置
var stmend = 0; // 表达式结束位置
var len = content.length;
var preCode = ''; // 表达式前的代码
var endCode = ''; // 最后一段代码
var stmJs = ''; // 表达式
while(beg < len) {
/* 开始符 */
stmbeg = content.indexOf('{', beg);
while(content.charAt(stmbeg - 1) === '\\') {
// 遇到转义的情况
stmbeg = content.indexOf('{', stmbeg + 1);
}
if(stmbeg === -1) {
// 到达最后一段代码
endCode = content.substr(beg);
out.push('OUT.push(\'' + endCode + '\');');
break;
}
/* 结束符 */
stmend = content.indexOf('}', stmbeg);
while(content.charAt(stmend - 1) === '\\') {
// 遇到转义的情况
stmend = content.indexOf('}', stmend + 1);
}
if(stmend === -1) {
// 没有结束符
break;
}
// 开始符之前代码
preCode = content.substring(beg, stmbeg);
if(content.charAt(stmbeg - 1) === '$') {
// 针对变量取值
out.push('OUT.push(\'' + preCode.substr(0, preCode.length-1) + '\');');
stmJs = content.substring(stmbeg + 1, stmend);
out.push('OUT.push((' + stmJs + ').toString());');
} else {
// 针对js语句
out.push('OUT.push(\'' + preCode + '\');');
stmJs = content.substring(stmbeg + 1, stmend);
out.push(transStm(stmJs));
}
beg = stmend + 1;
}
out.unshift(vars);
struct[1] = out.join('');
return new Function('DATA', struct.join(''));
};
/**`
* 根据模板数据生成代码
* @method
*/
return function(content, data){
try{
data = data||{};
// 解析模板生成代码生成器
var f = doParseTemplate(content, data);
return f(data);
}catch(ex){
return -1;
}
};
})()
};
module.exports = parse.get; |
// detect node for conditional import for jsonToFormData
const isNode = typeof process !== 'undefined' && process.versions && !!process.versions.node
if (isNode) {
// TODO : deal with node.js side for example using https://www.npmjs.com/package/form-data: fake one for now
}
export function jsonToFormData (jsonData) {
jsonData = JSON.parse(JSON.stringify(jsonData))
let formData
if (isNode) {
formData = {append: function (fieldName, value) {}} // FIXME: hack for tests/nodes.js
} else {
formData = new FormData()
}
for (let fieldName in jsonData) {
let value = jsonData[fieldName]
// value = encodeURIComponent(JSON.stringify(value))
// value = JSON.stringify(value)
// value = value.replace(/\"/g, '')
if (Object.prototype.toString.call(value) === '[object Object]') {
value = JSON.stringify(value)
// console.log("value",value)
}
if (Object.prototype.toString.call(value) === '[object Array]') {
// value = //JSON.stringify(value)
// value = 'arr[]', arr[i]//value.reduce()
// console.log("value",value)
value = `{ ${value.join(',')} }`
}
if (typeof value === 'boolean') {
value = '' + value
}
// console.log("append",fieldName, value)
formData.append(fieldName, value)
}
return formData
}
|
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return Ember.A([{
name: 'Frozen yogurt',
calories: 159,
fat: 6.0,
carbs: 24,
protein: 4.0,
sodium: 87,
calcium: 14,
iron: 1
}, {
name: 'Ice cream sandwich',
calories: 237,
fat: 9.0,
carbs: 37,
protein: 4.3,
sodium: 129,
calcium: 8,
iron: 1
}, {
name: 'Eclair',
calories: 262,
fat: 16.0,
carbs: 24,
protein: 6.0,
sodium: 337,
calcium: 6,
iron: 7
}]);
}
});
|
'use strict';
var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _utilsDomUtils = require('../../utils/dom-utils');
var _utilsAssert = require('../../utils/assert');
var _modelsMarker = require('../../models/marker');
var _utilsSelectionUtils = require('../../utils/selection-utils');
var _utilsKey = require('../../utils/key');
var _range = require('./range');
var FORWARD = _utilsKey.DIRECTION.FORWARD;
var BACKWARD = _utilsKey.DIRECTION.BACKWARD;
var WORD_CHAR_REGEX = /\w|_|:/;
function findParentSectionFromNode(renderTree, node) {
var renderNode = renderTree.findRenderNodeFromElement(node, function (renderNode) {
return renderNode.postNode.isSection;
});
return renderNode && renderNode.postNode;
}
function findOffsetInMarkerable(markerable, node, offset) {
var offsetInSection = 0;
var marker = markerable.markers.head;
while (marker) {
var markerNode = marker.renderNode.element;
if (markerNode === node) {
return offsetInSection + offset;
} else if (marker.isAtom) {
if (marker.renderNode.headTextNode === node) {
return offsetInSection;
} else if (marker.renderNode.tailTextNode === node) {
return offsetInSection + 1;
}
}
offsetInSection += marker.length;
marker = marker.next;
}
return offsetInSection;
}
function findOffsetInSection(section, node, offset) {
if (section.isMarkerable) {
return findOffsetInMarkerable(section, node, offset);
} else {
(0, _utilsAssert['default'])('findOffsetInSection must be called with markerable or card section', section.isCardSection);
var wrapperNode = section.renderNode.element;
var endTextNode = wrapperNode.lastChild;
if (node === endTextNode) {
return 1;
}
return 0;
}
}
var Position = undefined,
BlankPosition = undefined;
Position = (function () {
/**
* A position is a logical location (zero-width, or "collapsed") in a post,
* typically between two characters in a section.
* Two positions (a head and a tail) make up a {@link Range}.
* @constructor
*/
function Position(section) {
var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
var isBlank = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
_classCallCheck(this, Position);
if (!isBlank) {
(0, _utilsAssert['default'])('Position must have a section that is addressable by the cursor', section && section.isLeafSection);
(0, _utilsAssert['default'])('Position must have numeric offset', typeof offset === 'number');
}
this.section = section;
this.offset = offset;
this.isBlank = isBlank;
}
/**
* @param {integer} x x-position in current viewport
* @param {integer} y y-position in current viewport
* @param {Editor} editor
* @return {Position|null}
*/
_createClass(Position, [{
key: 'toRange',
/**
* Returns a range from this position to the given tail. If no explicit
* tail is given this returns a collapsed range focused on this position.
* @param {Position} [tail=this] The ending position
* @return {Range}
* @public
*/
value: function toRange() {
var tail = arguments.length <= 0 || arguments[0] === undefined ? this : arguments[0];
return new _range['default'](this, tail);
}
}, {
key: 'markerIn',
/**
* Returns the marker in `direction` from this position.
* If the position is in the middle of a marker, the direction is irrelevant.
* Otherwise, if the position is at a boundary between two markers, returns the
* marker to the left if `direction` === BACKWARD and the marker to the right
* if `direction` === FORWARD (assuming left-to-right text direction).
* @param {Direction}
* @return {Marker|undefined}
*/
value: function markerIn(direction) {
if (!this.isMarkerable) {
return;
}
var marker = this.marker;
var offsetInMarker = this.offsetInMarker;
if (!marker) {
return;
}
if (offsetInMarker > 0 && offsetInMarker < marker.length) {
return marker;
} else if (offsetInMarker === 0) {
return direction === BACKWARD ? marker : marker.prev;
} else if (offsetInMarker === marker.length) {
return direction === FORWARD ? marker.next : marker;
}
}
}, {
key: 'isEqual',
value: function isEqual(position) {
return this.section === position.section && this.offset === position.offset;
}
/**
* @return {Boolean} If this position is at the head of the post
*/
}, {
key: 'isHeadOfPost',
value: function isHeadOfPost() {
return this.move(BACKWARD).isEqual(this);
}
/**
* @return {Boolean} If this position is at the tail of the post
*/
}, {
key: 'isTailOfPost',
value: function isTailOfPost() {
return this.move(FORWARD).isEqual(this);
}
/**
* @return {Boolean} If this position is at the head of its section
*/
}, {
key: 'isHead',
value: function isHead() {
return this.isEqual(this.section.headPosition());
}
/**
* @return {Boolean} If this position is at the head of its section
*/
}, {
key: 'isTail',
value: function isTail() {
return this.isEqual(this.section.tailPosition());
}
/**
* Move the position 1 unit in `direction`.
*
* @param {Number} units to move. > 0 moves right, < 0 moves left
* @return {Position} Return a new position one unit in the given
* direction. If the position is moving left and at the beginning of the post,
* the same position will be returned. Same if the position is moving right and
* at the end of the post.
*/
}, {
key: 'move',
value: function move(units) {
(0, _utilsAssert['default'])('Must pass integer to Position#move', typeof units === 'number');
if (units < 0) {
return this.moveLeft().move(++units);
} else if (units > 0) {
return this.moveRight().move(--units);
} else {
return this;
}
}
/**
* @param {Number} direction (FORWARD or BACKWARD)
* @return {Position} The result of moving 1 "word" unit in `direction`
*/
}, {
key: 'moveWord',
value: function moveWord(direction) {
var isPostBoundary = direction === BACKWARD ? this.isHeadOfPost() : this.isTailOfPost();
if (isPostBoundary) {
return this;
}
if (!this.isMarkerable) {
return this.move(direction);
}
var pos = this;
// Helper fn to check if the pos is at the `dir` boundary of its section
var isBoundary = function isBoundary(pos, dir) {
return dir === BACKWARD ? pos.isHead() : pos.isTail();
};
// Get the char at this position (looking forward/right)
var getChar = function getChar(pos) {
var marker = pos.marker;
var offsetInMarker = pos.offsetInMarker;
return marker.charAt(offsetInMarker);
};
// Get the char in `dir` at this position
var peekChar = function peekChar(pos, dir) {
return dir === BACKWARD ? getChar(pos.move(BACKWARD)) : getChar(pos);
};
// Whether there is an atom in `dir` from this position
var isAtom = function isAtom(pos, dir) {
// Special case when position is at end, the marker associated with it is
// the marker to its left. Normally `pos#marker` is the marker to the right of the pos's offset.
if (dir === BACKWARD && pos.isTail() && pos.marker.isAtom) {
return true;
}
return dir === BACKWARD ? pos.move(BACKWARD).marker.isAtom : pos.marker.isAtom;
};
if (isBoundary(pos, direction)) {
// extend movement into prev/next section
return pos.move(direction).moveWord(direction);
}
var seekWord = function seekWord(pos) {
return !isBoundary(pos, direction) && !isAtom(pos, direction) && !WORD_CHAR_REGEX.test(peekChar(pos, direction));
};
// move(dir) while we are seeking the first word char
while (seekWord(pos)) {
pos = pos.move(direction);
}
if (isAtom(pos, direction)) {
return pos.move(direction);
}
var seekBoundary = function seekBoundary(pos) {
return !isBoundary(pos, direction) && !isAtom(pos, direction) && WORD_CHAR_REGEX.test(peekChar(pos, direction));
};
// move(dir) while we are seeking the first boundary position
while (seekBoundary(pos)) {
pos = pos.move(direction);
}
return pos;
}
/**
* The position to the left of this position.
* If this position is the post's headPosition it returns itself.
* @return {Position}
* @private
*/
}, {
key: 'moveLeft',
value: function moveLeft() {
if (this.isHead()) {
var prev = this.section.previousLeafSection();
return prev ? prev.tailPosition() : this;
} else {
var offset = this.offset - 1;
if (this.isMarkerable && this.marker) {
var code = this.marker.value.charCodeAt(offset);
if (code >= _modelsMarker.LOW_SURROGATE_RANGE[0] && code <= _modelsMarker.LOW_SURROGATE_RANGE[1]) {
offset = offset - 1;
}
}
return new Position(this.section, offset);
}
}
/**
* The position to the right of this position.
* If this position is the post's tailPosition it returns itself.
* @return {Position}
* @private
*/
}, {
key: 'moveRight',
value: function moveRight() {
if (this.isTail()) {
var next = this.section.nextLeafSection();
return next ? next.headPosition() : this;
} else {
var offset = this.offset + 1;
if (this.isMarkerable && this.marker) {
var code = this.marker.value.charCodeAt(offset - 1);
if (code >= _modelsMarker.HIGH_SURROGATE_RANGE[0] && code <= _modelsMarker.HIGH_SURROGATE_RANGE[1]) {
offset = offset + 1;
}
}
return new Position(this.section, offset);
}
}
}, {
key: 'leafSectionIndex',
get: function get() {
var _this = this;
var post = this.section.post;
var leafSectionIndex = undefined;
post.walkAllLeafSections(function (section, index) {
if (section === _this.section) {
leafSectionIndex = index;
}
});
return leafSectionIndex;
}
}, {
key: 'isMarkerable',
get: function get() {
return this.section && this.section.isMarkerable;
}
/**
* Returns the marker at this position, in the backward direction
* (i.e., the marker to the left of the cursor if the cursor is on a marker boundary and text is left-to-right)
* @return {Marker|undefined}
*/
}, {
key: 'marker',
get: function get() {
return this.isMarkerable && this.markerPosition.marker;
}
}, {
key: 'offsetInMarker',
get: function get() {
return this.markerPosition.offset;
}
}, {
key: 'markerPosition',
/**
* @private
*/
get: function get() {
(0, _utilsAssert['default'])('Cannot get markerPosition without a section', !!this.section);
(0, _utilsAssert['default'])('cannot get markerPosition of a non-markerable', !!this.section.isMarkerable);
return this.section.markerPositionAtOffset(this.offset);
}
}], [{
key: 'atPoint',
value: function atPoint(x, y, editor) {
var _renderTree = editor._renderTree;
var rootElement = editor.element;
var elementFromPoint = document.elementFromPoint(x, y);
if (!(0, _utilsDomUtils.containsNode)(rootElement, elementFromPoint)) {
return;
}
var _findOffsetInNode = (0, _utilsSelectionUtils.findOffsetInNode)(elementFromPoint, { left: x, top: y });
var node = _findOffsetInNode.node;
var offset = _findOffsetInNode.offset;
return Position.fromNode(_renderTree, node, offset);
}
}, {
key: 'blankPosition',
value: function blankPosition() {
return new BlankPosition();
}
}, {
key: 'fromNode',
value: function fromNode(renderTree, node, offset) {
if ((0, _utilsDomUtils.isTextNode)(node)) {
return Position.fromTextNode(renderTree, node, offset);
} else {
return Position.fromElementNode(renderTree, node, offset);
}
}
}, {
key: 'fromTextNode',
value: function fromTextNode(renderTree, textNode, offsetInNode) {
var renderNode = renderTree.getElementRenderNode(textNode);
var section = undefined,
offsetInSection = undefined;
if (renderNode) {
var marker = renderNode.postNode;
section = marker.section;
(0, _utilsAssert['default'])('Could not find parent section for mapped text node "' + textNode.textContent + '"', !!section);
offsetInSection = section.offsetOfMarker(marker, offsetInNode);
} else {
// all text nodes should be rendered by markers except:
// * text nodes inside cards
// * text nodes created by the browser during text input
// both of these should have rendered parent sections, though
section = findParentSectionFromNode(renderTree, textNode);
(0, _utilsAssert['default'])('Could not find parent section for un-mapped text node "' + textNode.textContent + '"', !!section);
offsetInSection = findOffsetInSection(section, textNode, offsetInNode);
}
return new Position(section, offsetInSection);
}
}, {
key: 'fromElementNode',
value: function fromElementNode(renderTree, elementNode, offset) {
var position = undefined;
// The browser may change the reported selection to equal the editor's root
// element if the user clicks an element that is immediately removed,
// which can happen when clicking to remove a card.
if (elementNode === renderTree.rootElement) {
var post = renderTree.rootNode.postNode;
position = offset === 0 ? post.headPosition() : post.tailPosition();
} else {
var section = findParentSectionFromNode(renderTree, elementNode);
(0, _utilsAssert['default'])('Could not find parent section from element node', !!section);
if (section.isCardSection) {
// Selections in cards are usually made on a text node
// containing a ‌ on one side or the other of the card but
// some scenarios (Firefox) will result in selecting the
// card's wrapper div. If the offset is 2 we've selected
// the final zwnj and should consider the cursor at the
// end of the card (offset 1). Otherwise, the cursor is at
// the start of the card
position = offset < 2 ? section.headPosition() : section.tailPosition();
} else {
// In Firefox it is possible for the cursor to be on an atom's wrapper
// element. (In Chrome/Safari, the browser corrects this to be on
// one of the text nodes surrounding the wrapper).
// This code corrects for when the browser reports the cursor position
// to be on the wrapper element itself
var renderNode = renderTree.getElementRenderNode(elementNode);
var postNode = renderNode && renderNode.postNode;
if (postNode && postNode.isAtom) {
var sectionOffset = section.offsetOfMarker(postNode);
if (offset > 1) {
// we are on the tail side of the atom
sectionOffset += postNode.length;
}
position = new Position(section, sectionOffset);
} else {
// The offset is 0 if the cursor is on a non-atom-wrapper element node
// (e.g., a <br> tag in a blank markup section)
position = section.headPosition();
}
}
}
return position;
}
}]);
return Position;
})();
BlankPosition = (function (_Position) {
_inherits(BlankPosition, _Position);
function BlankPosition() {
_classCallCheck(this, BlankPosition);
_get(Object.getPrototypeOf(BlankPosition.prototype), 'constructor', this).call(this, null, 0, true);
}
_createClass(BlankPosition, [{
key: 'isEqual',
value: function isEqual(other) {
return other && other.isBlank;
}
}, {
key: 'toRange',
value: function toRange() {
return _range['default'].blankRange();
}
}, {
key: 'isHeadOfPost',
value: function isHeadOfPost() {
return false;
}
}, {
key: 'isTailOfPost',
value: function isTailOfPost() {
return false;
}
}, {
key: 'isHead',
value: function isHead() {
return false;
}
}, {
key: 'isTail',
value: function isTail() {
return false;
}
}, {
key: 'move',
value: function move() {
return this;
}
}, {
key: 'moveWord',
value: function moveWord() {
return this;
}
}, {
key: 'leafSectionIndex',
get: function get() {
(0, _utilsAssert['default'])('must implement get leafSectionIndex', false);
}
}, {
key: 'isMarkerable',
get: function get() {
return false;
}
}, {
key: 'marker',
get: function get() {
return false;
}
}, {
key: 'markerPosition',
get: function get() {
return {};
}
}]);
return BlankPosition;
})(Position);
exports['default'] = Position; |
'use strict';
describe('myApp.items module', function() {
beforeEach(module('myApp.items'));
describe('items controller', function(){
it('should ....', inject(function($controller) {
//spec body
}));
});
}); |
/**
* Created by hbzhang on 10/5/15.
*/
//http://stackoverflow.com/questions/26523093/sync-control-flow-using-nodejs-async-waterfall-each-and-mysql
'use strict';
var najax = require('najax');
//var _ = require('lodash');
var async = require('async');
//var Agenda = require('agenda');
var schedule = require('node-schedule');
exports.create_new_versus = function(req, res) {
najax({
url:'http://localhost:9999/users',
method:'POST',
data:{role:'admin',passport:'905400231',fname:'test hongbo',lname:'test zhang'}
}).
success(
function(resp){
console.log('add suessful');
res.jsonp(resp);
}
)
.error(
function(err){
console.log('failed');
return res.jsonp(500, {
error: 'Cannot update versus'
});
}
);
};
//var json = JSON.parse(resp);//JSON.stringify(eval("(" + resp + ")"));
/*async.map(json, function iterator(model) {
console.log(model.id);
make_update_versus(model.id);
});*/
// _.each(json, function iterator(model) {
// make_update_versus(model.id);
// async.setImmediate(function (model) {
//});
// });
/* _.each(json, function(model){
//console.log(model.techid);
get_notcheckedin_id_in_versus(model.techid);
// console.log(_.size(json));
for(var key in model){
// check also if property is not inherited from prototype
if (myObject.options.hasOwnProperty(key)) {
var value = model[key];
}
}
}); */
//res.jsonp(response);
/*var make_update_versus = function(id) {
var condition = '/'+ id;
var url = 'http://128.173.128.195:9999/people'+condition;
//console.log(url);
najax({
url:url,
method:'put',
data:{eligible:1}
}).
success(
function(resp){
//console.log(resp);
console.log('add suessful');
}
)
.error(
function(err){
console.log('failed to make real update to versus');
}
);
}; */
var all_notcheckedin_in_signup = function(req, res) {
//var result = [];
var response = {sucessful:'ajax signup not checked in read finished'};
var eachCounter = 0;
najax({
url:'http://aquaman.recsports.vt.edu:6901/registrationdetails',
method:'get'}
).success(
function(resp){
var json = JSON.parse(resp);//JSON.stringify(eval("(" + resp + ")"));
//console.log(json);
json = json.slice(1, 30);
//console.log(json);
async.eachSeries(json, function(model,eachcallback) {
var condition = '?where={passport:"'+model.techid+'"}';
var url = 'http://128.173.128.195:9999/people'+condition;
async.waterfall([
function(callback){
najax({
url: url,
method: 'get'
}).
success(
function (resp) {
callback(null, resp);
}).error(
function(err){
console.log(url);
console.log('failed to get persom from versus');
callback(null, resp);
});
},
function(resp, callback) {
// arg1 is equals 'a' and arg2 is 'b'
// Code c
var json = JSON.parse(resp);//JSON.stringify(eval("(" + resp + ")"));
async.eachSeries(json, function (model, eachcallback1) {
var url = 'http://128.173.128.195:9999/people/' + model.id;
najax({
url: url,
method: 'put',
data: {eligible: 1}
}).
success(
function (resp) {
//console.log(resp);
console.log('add sucessful');
eachcallback1();
}
)
.error(
function (err) {
console.log('failed to make real update to versus');
eachcallback1();
}
);
}, function done() {
callback();
});
}
], function (err, result) {
eachCounter = eachCounter + 1;
//console.log('waterfall done');
eachcallback();
}
);
//callback();
},function(err){
// if any of the file processing produced an error, err would equal that error
if( err ) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('error to fetch data from signup' + err);
} else {
console.log(eachCounter + ' records has been updated');
console.log(response);
}
});
}
)
.error(
function(err){
console.log('failed');
return res.jsonp(500, {
error: 'Cannot list all not checkedin signup '
});
}
);
};
exports.update_versus = function(req, res) {
/*var agenda = new Agenda({db: { address: 'localhost:27017/intramuralsignupintegration'}});
agenda.define('update versus from signup', function(job) {
all_notcheckedin_in_signup(req, res);
});
agenda.every('3 minutes', 'update versus from signup');
agenda.start();*/
schedule.scheduleJob('*/5 * * * *', function(){
all_notcheckedin_in_signup(req, res);
});
};
exports.item = function(req, res, next, id) {
};
//najax('http://www.google.com', { type:'POST' }, function(html){ console.log(html); }); // "awesome"
//najax({ url:'http://www.google.com', type:'POST' }).success(function(resp){}).error(function(err){}); // "awesome"
|
@task *pollForChanges() {
while(true) {
yield pollServerForChanges();
if (Ember.testing) { return; }
yield timeout(5000);
}
}
|
/**
* Created by joehua on 7/6/15.
*/
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var baseModelPlugin = require('./../../utilities/base-model-plugin');
var ArticleSpintax = require('./article-spintax.model.js');
var ArticleSchema = new Schema({
code: String,
title: String,
summary: String, // Plain Text
body: String, // Markdown
niche: {
_id: {type: Schema.ObjectId, ref: 'Niche'},
code: String,
name: String
},
quality: Number,
tags: [{
text: String,
_id: {type: Schema.ObjectId, ref: 'Tag'}
}],
approach: {type: String, "enum": ['HowTo', 'Sale', 'Story']},
canBeUsedForContent: [{type: String, "enum": ['Presentation', 'Video', 'Infographic', 'AutoResponse']}],
uniqueness: {},
spintaxes: [ArticleSpintax],
_creatorId: {type: Schema.ObjectId, ref: 'User'}
});
ArticleSchema.plugin(baseModelPlugin);
var Article = mongoose.model('Article', ArticleSchema);
module.exports = Article;
|
'use strict';
/* jasmine specs for filters go here */
describe('filter', function() {
beforeEach(module('opennms.filters'));
describe('interpolate', function() {
beforeEach(module(function($provide) {
$provide.value('version', 'TEST_VER');
}));
it('should replace VERSION', inject(function(interpolateFilter) {
expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after');
}));
});
});
|
import moment from 'moment';
export const calHeight = 270;
export const cellHeight = 20;
export const yearHeight = 32;
export const yearLength = +moment.duration(1, 'year');
export function linear(x0, y0, a) {
return {
y(x) {
return +y0 + (x - x0) * a;
},
x(y) {
return +x0 + (y - y0) / a;
},
};
}
export function scheduleRAF() {
let scheduledCb;
let RAF;
return function schedule(cb) {
scheduledCb = cb;
if (!RAF) {
RAF = window.requestAnimationFrame(() => {
scheduledCb();
RAF = null;
scheduledCb = null;
});
}
};
}
|
let config;
config = {
apiUrl: 'http://ergast.com/api/f1/',
dateFormat: 'yyyy/MM/dd'
};
export default config;
|
(function(){
/**
An Environment object holds <variable,value> pairs and
it has a link to the rest of the objects in the environment
chain. This link is used to look up "non-local" variable
references.
The Environment interface has methods for
1) Adding new <variable,value> pairs to this environment object.
2) Looking up a variable to see if it is in the Environment chain.
2) Looking up a variable to see if it is in this Environment object.
3) Looking up a variable's value from the variable's <variable,value> pair.
4) Mutating the value part of a varaible's <variable,value> pair.
*/
"use strict";
angular
.module('astInterpreter')
.factory('l8.environmentFactory', function () {
var envId = 0;
function Environment(scope, env, label ) {
var self = this;
this.variables = [];
this.values = [];
this.id = envId++;
this.label = null; //label is used for debugging purposes; Update: use the label property for naming an env <div> on a webpage
if (label !== undefined) {
this.label = label;
}
this.nonLocalLink = null;
if (env !== undefined) {
this.nonLocalLink = env;
}
/**
Add a <variable, value> pair to this environment object.
*/
this.add = function (variable, value) {
this.variables.push(variable);
this.values.push(value);
//emit an "envAdd" event
//pass along the proper env id when creating the associated <div> on a webpage
//text to be displayed in <div> on web pages should be formatted like so:
// "var" + [variable name] + "=" + [ VALUE | "function" ]
// where 'VALUE' := 'INTEGER' | 'BOOLEAN'
scope.main.addAnimationData({'name': "envAdd",
data: {
'id': self.id,
'label': self.label, //this will name the environment; e.g. 'Global Env'
'value': variable + " = " + value, //this will be the text in the new p element
}
});
};
this.defined = function (variable, emitEvents) {
return (null !== this.lookUp(variable, emitEvents));
};
//I need to set a parameter to tell the lookUp function if it should emit events or not
this.lookUp = function (variable, emitEvents) {
//when emitting events an id to the current env ( represented as a div) will need to be passed along
var i = 0;
for (; i < this.variables.length; i++) {
if (variable.trim() === this.variables[i].trim()) {
//if emitEvents is undefined assume the user wants events emitted
if (emitEvents) {
// set the color to be green i.e found the variable we are looking for
//emit an "envSearch" event
scope.main.addAnimationData({'name': "envSearch",
data: {
'id': self.id,
'label': self.label,
'childRank': i + 1,
'color': "#5FAD00", //green; color code from color.adobe.com
}
});
}
break;
}
//if emitEvents is undefined assume the user wants events emitted
if (emitEvents) {
//set the color to be red (i.e the variable currently looked up is not the one we want)
//emit an "envSearch" event
scope.main.addAnimationData({'name': "envSearch",
data: {
'id': self.id,
'label': self.label,
'childRank': i + 1,
'color': "#FF4", //yellow; color code from color.adobe.com
}
});
}
}
if (i < this.variables.length) {
return this.values[i];
}
else {
if (null === this.nonLocalLink) {
return null; //variable cannot be found
}
else {
// recursively search the rest of the environment chain
return this.nonLocalLink.lookUp(variable, emitEvents);
}
}
};
this.definedLocal = function (variable) {
var i = 0;
for (; i < this.variables.length; i++) {
if (variable.trim() === this.variables[i].trim()) {
break;
}
}
if (i < this.variables.length) {
return true;
}
else {
return false;
}
};
this.update = function (variable, value) {
//when emitting events an id to the current env ( represented as a div) will need to be passed along
var i = 0;
for (; i < this.variables.length; i++) {
if (variable.trim() === this.variables[i].trim()) {
// set the color to be green i.e found the variable we are looking for
//emit an "envSearch" event
scope.main.addAnimationData({'name': "envSearch",
data: {
'id': self.id,
'label': self.label,
'childRank': i + 1,
'color': "#5FAD00", //green; color code from color.adobe.com
}
});
break;
}
//set the color to be red (i.e the variable currently looked up is not the one we want)
//emit an "envSearch" event
scope.main.addAnimationData({'name': "envSearch",
data: {
'id': self.id,
'label': self.label,
'childRank': i + 1,
'color': "#FF4", //yellow; color code from color.adobe.com "#FF4"
}
});
}
if (i < this.variables.length) {
this.values[i] = value;
scope.main.addAnimationData({'name': "envUpdate",
data: {
'id': self.id,
'label': self.label,
'childRank': i + 1,
'value': variable + " = " + value,
'color': "#FF0302", //red; I want the user to note the change made
}
});
return true;
}
else {
if (null === this.nonLocalLink) {
return false; // variable cannot be found
}
else {
// recursively search the rest of the environment chain
return this.nonLocalLink.update(variable, value);
}
}
};
/**
Convert the contents of the environment chain into a string.
This is mainly for debugging purposes.
In this JS version I will never need to use the toString() method
*/
this.toString = function () {
var result = "";
if (null !== this.nonLocalLink) {
result = this.nonLocalLink.toString() + "\n/\\\n||\n[" + this.label + " Environment";
}
else {
result += "[Global Environment";
}
// Now convert this Environment object.
for (var i = 0; i < this.variables.length; i++) {
result += "\n[ " + this.variables[i] + " = " + this.values[i];
}
return result;
};
}
return {
"Environment": Environment
};
});
})(); |
var expect = require('expect.js')
, storageModule = require('../lib/storage/inMemory/storage');
describe('Storage', function() {
var storage;
describe('beeing not connected', function() {
describe('calling createStorage', function() {
describe('without a callback', function() {
before(function() {
storage = storageModule.createStorage({ dbName: 'testeventstore' });
});
describe('calling connect', function() {
it('it should connect successfully', function(done) {
storage.connect(function(err) {
expect(err).not.to.be.ok();
done();
});
});
});
});
describe('with a callback', function() {
it('it should connect successfully', function(done) {
storageModule.createStorage({ dbName: 'testeventstore' }, function(err, str) {
storage = str;
expect(err).not.to.be.ok();
expect(str).to.not.eql(null);
done();
});
});
});
});
});
describe('beeing connected', function() {
describe('calling getId', function() {
it('it should callback with a new id', function(done) {
storage.getId(function(err, id) {
expect(err).not.to.be.ok();
expect(id).to.be.an('string');
done();
});
});
});
describe('calling addEvents', function() {
var event = {
streamId: 'id1',
streamRevision: 0,
commitId: '10',
dispatched: false,
payload: {
event:'bla'
}
};
it('it should save the events', function(done) {
storage.addEvents([event], function(err) {
expect(err).not.to.be.ok();
storage.getEvents('id1', -1, function(err, evts) {
expect(err).not.to.be.ok();
expect(evts).to.be.an('array');
expect(evts).to.have.length(1);
done();
});
});
});
describe('calling getUndispatchedEvents', function() {
it('it should be in the array', function(done) {
storage.getUndispatchedEvents(function(err, evts) {
expect(err).not.to.be.ok();
expect(evts).to.be.an('array');
expect(evts).to.have.length(1);
expect(event).to.eql(evts[0]);
done();
});
});
describe('calling setEventToDispatched', function() {
it('it should not be in the undispatched array anymore', function(done) {
storage.setEventToDispatched(event, function(err) {
expect(err).not.to.be.ok();
storage.getUndispatchedEvents(function(err, evts) {
expect(err).not.to.be.ok();
expect(evts).to.be.an('array');
expect(evts).to.have.length(0);
done();
});
});
});
});
});
});
describe('calling addSnapshot', function() {
it('it should save the snapshot', function(done) {
var snapshot = {
snapshotId: '1',
streamId: '3',
revision: 1,
data: 'data'
};
storage.addSnapshot(snapshot, function(err) {
expect(err).not.to.be.ok();
storage.getSnapshot('3', function(err, snap) {
expect(err).not.to.be.ok();
expect(snap.data).to.eql(snapshot.data);
expect(snap.snapshotId).to.eql(snapshot.snapshotId);
expect(snap.revision).to.eql(snapshot.revision);
expect(snap.streamId).to.eql(snapshot.streamId);
done();
});
});
});
});
describe('having a filled store with example data', function() {
before(function(done) {
storage.addEvents([
{streamId: '2', streamRevision: 0, commitId: 0, commitStamp: new Date(2012, 3, 14, 8, 0, 0), payload: {id: '1', event:'blaaaaaaaaaaa'}, dispatched: false},
{streamId: '2', streamRevision: 1, commitId: 1, commitStamp: new Date(2012, 3, 14, 9, 0, 0), payload: {id: '2', event:'blaaaaaaaaaaa'}, dispatched: false},
{streamId: '2', streamRevision: 2, commitId: 2, commitStamp: new Date(2012, 3, 14, 10, 0, 0), payload: {id: '3', event:'blaaaaaaaaaaa'}, dispatched: false},
{streamId: '2', streamRevision: 3, commitId: 3, commitStamp: new Date(2012, 3, 15, 8, 0, 0), payload: {id: '4', event:'blaaaaaaaaaaa'}, dispatched: false}
],
function (err) {
storage.addEvents([
{streamId: '3', streamRevision: 0, commitId: 4, commitStamp: new Date(2012, 3, 16, 8, 0, 0), payload: {id: '5', event:'blaaaaaaaaaaa'}, dispatched: false},
{streamId: '3', streamRevision: 1, commitId: 5, commitStamp: new Date(2012, 3, 17, 8, 0, 0), payload: {id: '6', event:'blaaaaaaaaaaa'}, dispatched: false}
],
function (err) {
storage.addSnapshot({snapshotId: '1', streamId: '3', revision: 1, data: 'data'}, function() {
storage.addSnapshot({snapshotId: '2', streamId: '3', revision: 2, data: 'dataPlus'}, done);
});
}
);
});
});
describe('calling getEvents for id 2', function() {
it('it should callback with the correct values', function(done) {
storage.getEvents('2', 0, -1, function(err, events) {
expect(err).not.to.be.ok();
expect(events).to.have.length(4);
expect(events[0].commitId).to.eql('0');
expect(events[1].commitId).to.eql('1');
expect(events[3].commitId).to.eql('3');
done();
});
});
});
describe('calling getEvents for id 3', function() {
it('it should callback with the correct values', function(done) {
storage.getEvents('3', 0, -1, function(err, events) {
expect(err).not.to.be.ok();
expect(events).to.have.length(2);
done();
});
});
});
describe('calling getEvents for id 2 from 1 to 3', function() {
it('it should callback with the correct values', function(done) {
storage.getEvents('2', 1, 3, function(err, events) {
expect(err).not.to.be.ok();
expect(events).to.have.length(2);
done();
});
});
});
describe('calling getUndispatchedEvents', function() {
it('it should callback with the correct values', function(done) {
storage.getUndispatchedEvents(function(err, events) {
expect(err).not.to.be.ok();
expect(events).to.have.length(6);
expect(events[0].commitId).to.eql('0');
expect(events[2].commitId).to.eql('2');
expect(events[5].commitId).to.eql('5');
done();
});
});
});
describe('calling getEventRange searching by event id', function() {
it('it should callback with the correct values', function(done) {
storage.getEventRange({id: '2'}, 2, function(err, events) {
expect(err).not.to.be.ok();
expect(events).to.have.length(2);
expect(events[0].commitId).to.eql('2');
expect(events[1].commitId).to.eql('3');
done();
});
});
});
describe('calling getSnapshot for id 3', function() {
it('it should callback with the correct values', function(done) {
storage.getSnapshot('3', -1, function(err, snap) {
expect(err).not.to.be.ok();
expect(snap.data).to.eql('dataPlus');
expect(snap.snapshotId).to.eql('2');
expect(snap.streamId).to.eql('3');
expect(snap.revision).to.eql('2');
done();
});
});
});
describe('calling getSnapshot for id 3 with maxRev 1', function() {
it('it should callback with the correct values', function(done) {
storage.getSnapshot('3', 1, function(err, snap) {
expect(err).not.to.be.ok();
expect(snap.data).to.eql('data');
expect(snap.snapshotId).to.eql('1');
expect(snap.streamId).to.eql('3');
expect(snap.revision).to.eql('1');
done();
});
});
});
});
});
}); |
import Promise from 'pinkie';
import TestRun from '../test-run';
import TEST_RUN_STATE from './test-run-state';
import COMMAND_TYPE from '../test-run/commands/type';
import { UnlockPageCommand } from '../test-run/commands/service';
const TEST_RUN_ABORTED_MESSAGE = 'The test run has been aborted.';
export const TestRunCtorFactory = function (callbacks) {
const { created, done, readyToNext } = callbacks;
return class LiveModeTestRun extends TestRun {
constructor (test, browserConnection, screenshotCapturer, warningLog, opts) {
super(test, browserConnection, screenshotCapturer, warningLog, opts);
created(this, test);
this.state = TEST_RUN_STATE.created;
this.finish = null;
this.stopping = false;
this.isInRoleInitializing = false;
this.stopped = false;
}
stop () {
this.stopped = true;
}
_useRole (...args) {
this.isInRoleInitializing = true;
return super._useRole.apply(this, args)
.then(res => {
this.isInRoleInitializing = false;
return res;
})
.catch(err => {
this.isInRoleInitializing = false;
throw err;
});
}
executeCommand (commandToExec, callsite, forced) {
// NOTE: don't close the page and the session when the last test in the queue is done
if (commandToExec.type === COMMAND_TYPE.testDone && !forced) {
done(this, this.stopped)
.then(() => this.executeCommand(commandToExec, callsite, true))
.then(() => readyToNext(this));
this.executeCommand(new UnlockPageCommand(), null);
return Promise.resolve();
}
if (this.stopped && !this.stopping &&
!this.isInRoleInitializing) {
this.stopping = true;
return Promise.reject(new Error(TEST_RUN_ABORTED_MESSAGE));
}
return super.executeCommand(commandToExec, callsite);
}
};
};
|
const _ = require('underscore');
const XlsxPopulate = require('xlsx-populate');
const tracesService = require('./traces.service')
const cfgService = require('./config.service');
const EXCEL_PATH = cfgService.getProperty('node').templates.excel;
exports.trxToExcel = trxToExcel;
/**
* @desc En base a una salida de una transacción lee
* de una ruta predefinida un excel y sustituye los (Nombres Definidos) por lo que se corresponda con el campo de salida
* de dicha transacción.
* @param {string} fileTemplate Nombre del archivo donde va a estar la plantilla de excel
* @param {any} trxData Datos de la transacción
*/
function trxToExcel(fileTemplate, trxData) {
return XlsxPopulate.fromFileAsync(`${EXCEL_PATH}${fileTemplate}.xlsx`)
.then((workbook) => {
for (var trxFormat in trxData) {
// Si no es un Array lo igualamos para tratar a todas las entradas por igual
if (!_.isArray(trxData[trxFormat])) {
trxData[trxFormat] = [trxData[trxFormat]];
}
// Recorremos cada objeto del array
for (var format in trxData[trxFormat]) {
// Luego recorremos las claves de cada objeto
for (var key in trxData[trxFormat][format]) {
// Si el nombre del nombre del formato mas clave PEM9804.SURNAM2 existe
// Obtenemos la celda
var cell = workbook.definedName(`${trxFormat}.${key}`);
if (cell != null) {
var sheet = cell.sheet().name();
var row = cell.rowNumber();
var column = cell.columnNumber()
// A la columna le añadimos la posición en el Array
workbook.sheet(sheet).cell(row + Number(format), column).value(trxData[trxFormat][format][key])
}
}
}
}
return workbook.outputAsync();
})
} |
'use strict'
var tap = require('tap')
var testVersion = '4'
process.env.API_VERSION = testVersion
var config = require('../config')
tap.equal(config.API_VERSION, testVersion, 'It supports API_VERSION through env')
|
/* setup.js */
import "babel-polyfill";
import JSDOM from "jsdom";
const Adapter = require("enzyme-adapter-react-15");
const { configure } = require("enzyme");
require("jsdom-global")();
configure({ adapter: new Adapter() });
|
/**
* Module dependencies
*/
var fs = require('fs');
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('config');
var app = express();
var port = process.env.PORT || 3001;
// Connect to mongodb
var connect = function () {
var options = { server: { socketOptions: { keepAlive: 1 } } };
mongoose.connect(config.db, options);
};
connect();
mongoose.connection.on('error', console.log);
mongoose.connection.on('disconnected', connect);
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file);
});
// Bootstrap passport config
require('./config/passport')(passport, config);
// Bootstrap application settings
require('./config/express')(app, passport);
// Bootstrap routes
require('./config/routes')(app, passport);
app.listen(port);
console.log('Express app started on port ' + port);
|
!function(){"use strict";module.exports=require("./lib/React"),module.exports=require("./lib/ReactDOM")}(); |
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
NavigatorIOS,
} = React;
var Dashboard = require('./App/Views/Dashboard/index.ios.js');
var HackerNews = React.createClass({
render: function() {
return (
<NavigatorIOS
style={styles.container}
tintColor='#FF6600'
initialRoute={{
title: 'Hacker News',
component: Dashboard,
}}/>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F6F6EF',
},
});
AppRegistry.registerComponent('HackerNews', () => HackerNews);
module.exports = HackerNews;
|
/*Sorting an array means to arrange its elements in increasing order.
Write a script to sort an array.
Use the selection sort algorithm: Find the smallest element, move it at the first position,
find the smallest from the rest, move it at the second position, etc.
Hint: Use a second array */
console.log('=====================================');
console.log('05.Selection sort');
console.log('-------------------------');
var array = [2, 11, 1, 23, 3, 8, 12, 4, 4, 5],
sortedArray = [],
minIndex,
i;
console.log('Initial array= [' + array + ']');
while (array.length !== 0) {
minIndex = 0;
for (i = 0; i < array.length; i += 1) {
if (array[minIndex] > array[i]) {
minIndex = i;
}
}
sortedArray.push(array[minIndex]);
array.splice(minIndex, 1);
}
array.push(sortedArray);
console.log('Sorted array= [' + array + ']');
|
/**
* Created by qcplay on 7/9/15.
*/
var BlendTexture = defineFilter('qc.Filter.BlendTexture', qc.Filter, function(game) {
this.mixing = 0.5;
this.otherTexture = null;
this.vertexSrc = [
'attribute vec2 aVertexPosition;',
'attribute vec2 aTextureCoord;',
'attribute vec2 aOtherTextureCoord;',
'attribute vec4 aColor;',
'uniform vec2 projectionVector;',
'uniform vec2 offsetVector;',
'varying vec2 vTextureCoord;',
'varying vec2 vOtherTextureCoord;',
'varying vec4 vColor;',
'const vec2 center = vec2(-1.0, 1.0);',
'void main(void) {',
' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);',
' vTextureCoord = aTextureCoord;',
' vOtherTextureCoord = aOtherTextureCoord;',
' vColor = vec4(aColor.rgb * aColor.a, aColor.a);',
'}'
];
this.fragmentSrc = [
'precision mediump float;',
'varying vec2 vTextureCoord;',
'varying vec2 vOtherTextureCoord;',
'varying vec4 vColor;',
'uniform sampler2D uSampler;',
'uniform sampler2D otherTexture;',
'uniform float mixing;',
'void main(void) {',
' vec4 original = texture2D(uSampler, vTextureCoord);',
' vec4 add = texture2D(otherTexture, vOtherTextureCoord);',
' gl_FragColor = mixing * add + (1.0 - mixing) * original;',
'}'
];
},{
otherTexture : qc.Filter.SAMPLER2D,
mixing : qc.Filter.F1
}); |
import {
GraphQLEnumType,
} from 'graphql';
export default new GraphQLEnumType({
name: 'MeteorMetricResolution',
description: 'TODO description',
values: {
RES_1MIN: {value: '1min'},
RES_30MIN: {value: '30min'},
RES_3HOUR: {value: '3hour'},
}
});
|
"use strict";
var should = require('should');
var rarity = require('../lib/');
describe('rarity.pad()', function() {
var EXPECTED_RESULT = "expectedResult";
var noop = function() {};
var shittyFunction = function(cb) {
process.nextTick(function() {
cb(EXPECTED_RESULT);
});
};
it("should fail with non array", function(done) {
try {
rarity.pad("nope", noop);
}
catch(e) {
e.toString().should.containDeep('must be an array');
return done();
}
done(new Error("Should not be working"));
});
it("should fail without function as second argument", function(done) {
try {
rarity.pad([], 4);
}
catch(e) {
e.toString().should.containDeep('must be a function');
return done();
}
done(new Error("Should not be working"));
});
it("should pad argument", function(done) {
shittyFunction(rarity.pad([null], function(err, result) {
should(err).eql(null);
result.should.eql(EXPECTED_RESULT);
arguments.should.have.lengthOf(2);
done();
}));
});
it("should pad multiple arguments", function(done) {
shittyFunction(rarity.pad([1, 2, 3], function(c1, c2, c3, result) {
c1.should.eql(1);
c2.should.eql(2);
c3.should.eql(3);
result.should.eql(EXPECTED_RESULT);
arguments.should.have.lengthOf(4);
done();
}));
});
});
|
/**
* Various generic JavaScripts for Anqh.
*
* @package Anqh
* @author Antti Qvickström
* @copyright (c) 2010-2014 Antti Qvickström
* @license http://www.opensource.org/licenses/mit-license.php MIT license
*/
Anqh = Anqh || {};
// Google Maps Geocoder
Anqh.geocoder = null;
// Google Maps Map
Anqh.map = null;
// Ajax loader
$.fn.loading = function(loaded) {
if (loaded) {
$(this).find('div.loading').remove();
} else {
$(this).append('<div class="loading"></div>');
}
return this;
};
// Initialize
$(function() {
var
hoverTimeout,
hovercards = {};
$(document).on({
'mouseenter.hoverable': function() {
var
$this = $(this),
href = $this.attr('href');
function popover(element, title, content) {
element
.removeClass('hoverable')
.popover({
trigger: 'hover',
delay: 500,
html: true,
title: title,
content: content,
container: 'body',
placement: 'auto right'
})
.popover('show')
.on('hide.bs.popover', function() {
// Don't hide hovercard if hovering it
var
$this = $(this),
$tip = $this.data('bs.popover').tip();
if ($tip.is(':hover')) {
$tip.mouseleave(function() {
$this.popover('hide')
});
return false;
}
});
}
hoverTimeout = setTimeout(function () {
if (hovercards[href]) {
popover($this, hovercards[href].title, hovercards[href].content);
} else {
// Load hovercard contents with ajax
$.get(href + '/hover', function (response) {
var $card = $(response);
hovercards[href] = {
title: $card.find('header').remove().text().replace('<', '<').replace('>', '>'),
content: $card.html()
};
popover($this, hovercards[href].title, hovercards[href].content);
});
}
}, 500);
},
'mouseleave.hoverable': function() {
clearTimeout(hoverTimeout);
}
}, 'a.hoverable');
// Delete comment
$('a.comment-delete').each(function deleteComment() {
var $this = $(this);
$this.data('action', function deleteAction() {
var comment = $this.attr('href').match(/([0-9]*)\/delete/);
if (comment) {
$.get($this.attr('href'), function deleted() {
$('#comment-' + comment[1]).slideUp();
});
}
});
});
// Set comment as private
$(document).delegate('a.comment-private', 'click', function privateComment(e) {
e.preventDefault();
var href = $(this).attr('href');
var comment = href.match(/([0-9]*)\/private/);
if (comment) {
$.get(href, function() {
$('#comment-' + comment[1]).addClass('private');
});
$(this).fadeOut();
}
return false;
});
$(document).delegate('button[name=private-toggle]', 'click', function privateComment() {
$('input[name=private]').val(~~$(this).hasClass('active'));
$('input[name=comment]').toggleClass('private', ~~$(this).hasClass('active')).focus();
});
// Submit comment with ajax
$(document).delegate('section.comments form', 'submit', function sendComment(e) {
e.preventDefault();
var comment = $(this).closest('section.comments');
$.post($(this).attr('action'), $(this).serialize(), function onSend(data) {
comment.replaceWith(data);
});
return false;
});
// Delete item confirmation
$(document).on('click', 'a[class*="-delete"]', function(e) {
e.preventDefault();
var
$this = $(this),
title = $this.data('confirm') || $this.attr('title') || $this.text() || 'Are you sure you want to do this?',
$modal = $('#dialog-confirm'),
callback;
if ($this.data('action')) {
callback = function() { $this.data('action')(); $modal.modal('hide'); };
} else if ($this.is('a')) {
callback = function() { window.location = $this.attr('href'); };
} else {
callback = function() { $this.parent('form').submit(); $modal.modal('hide'); };
}
// Clear old modal
if ($modal.length) {
$modal.remove();
}
// Create new modal
var $header = $('<div class="modal-header" />')
.append('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>')
.append('<h4 class="modal-title" id="dialog-confirm-title">' + title + '</h4>');
var $body = $('<div class="modal-body" />')
.append('Are you sure?');
var $confirm = $('<button type="button" class="btn btn-danger" />')
.append('Yes, do it!')
.on('click', callback);
var $footer = $('<div class="modal-footer" />')
.append($confirm)
.append('<button type="button" class="btn btn-default" data-dismiss="modal">No, cancel</button>');
$modal = $('<div class="modal fade" id="dialog-confirm" tabindex="-1" role="dialog" aria-labelledby="dialog-confirm-title" aria-hidden="true" />')
.append($('<div class="modal-dialog modal-sm" />')
.append($('<div class="modal-content" />')
.append($header)
.append($body)
.append($footer)));
$('body').append($modal);
$modal.modal('show');
});
// Preview post
$(document).on('click', 'button[name=preview]', function _preview(e) {
e.preventDefault();
var $this = $(this)
, $form = $this.closest('form')
, form = $form.serialize() + '&preview=1'
, $post = $this.closest('article')
, preClass = $this.attr('data-content-class') || 'media-body'
, addClass = $this.attr('data-preview-class') || 'post'
, prepend = $this.attr('data-prepend') || '.post-edit';
// Add ajax loader
$post.loading();
// Remove previous preview
$post.find('.preview').remove();
// Submit form
$.post($form.attr('action'), form, function _response(data) {
// Find preview data from result
var $preview = preClass !== '*' ? $(data).find('.' + preClass) : $(data);
// Mangle
$preview
.removeClass(preClass).addClass('preview ' + addClass)
.find('header small.pull-right').remove();
// Add to view
$post.find(prepend).prepend($preview);
// Scroll
var $header = $('#header');
$('html, body').animate({
scrollTop: $post.find(prepend).offset().top - ($header ? $header.height() : 0)
}, 250);
// Remove loader
$post.loading(true);
});
});
// Ajaxify actions
$(document).on('click', 'a.ajaxify', function _ajaxify() {
var parent = $(this).attr('data-ajaxify-target');
$(this).closest('section, article, aside' + (parent ? ', ' + parent : '')).ajaxify($(this).attr('href'));
return false;
});
$(document).on('submit', 'form.ajaxify', function() {
var $form = $(this);
$(this).closest('section, aside').ajaxify($form.attr('action'), $form.serialize(), $form.attr('method'));
return false;
});
// Ajaxify nofitications
$(document).on('click', 'a.notification', function _ajaxify() {
var parent = $(this).attr('data-ajaxify-target');
$(this).closest('section, article, aside' + (parent ? ', ' + parent : ''))
.ajaxify($(this).attr('href'), null, 'get', function _counter(response) {
var notifications = $(response).find('li').length
, $notifications = $('#visitor a.notifications');
if ($notifications) {
if (notifications) {
$notifications.find('span').text(notifications);
} else {
$notifications.remove();
}
}
});
return false;
});
// Ajax dialogs
$(document).on('click', 'a.dialogify', function(e) {
e.preventDefault();
$(this).dialogify();
});
// Keyboard pagination navigation
$(document).on('keydown', function onKeydown(event) {
if (event.target.type === undefined) {
var link;
switch (event.which) {
case $.ui.keyCode.LEFT: link = $('.pager .previous:not(.disabled) a').first().attr('href'); break;
case $.ui.keyCode.RIGHT: link = $('.pager .next:not(.disabled) a').first().attr('href'); break;
}
if (link) {
event.preventDefault();
window.location = link;
}
}
});
// User default picture
$('section.image-slideshow a[data-image-id]').on('click', function() {
var $changes = $('a.image-change');
var $image = $(this);
if ($changes.length) {
$changes.each(function(i) {
var $link = $(this);
var change = $link.attr('data-change');
$link.toggleClass('disabled', $image.hasClass(change));
$link.attr('href', $link.attr('href').replace(new RegExp(change + '.*$'), change + '=' + $image.attr('data-image-id')));
});
}
var $delete = $('a.image-delete');
if ($delete.length) {
$delete.toggleClass('disabled', $(this).hasClass('default'));
$delete.attr('href', $delete.attr('href').replace(/delete.*$/, 'delete=' + $(this).attr('data-image-id')));
}
});
// Carousels
$('.carousel').carousel({ interval: false });
// Lady load images
$('img.lazy').lazyload({
failure_limit: 100
});
// Notifications
$('a.notifications').on('click', function _notifications(e) {
var $this = $(this);
$.get($this.attr('href'), function _loadNotifications(response) {
$this.off('click').popover({
content: response,
html: true,
placement: 'bottom',
trigger: 'click'
}).popover('show');
});
return false;
});
// Element visibility toggle
$('[data-toggle=show]').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var selector = $this.data('target');
var parent = $this.data('parent') || 'body';
var $parent = $(parent);
$parent.find('.show').removeClass('show').addClass('hidden');
$parent.find(selector).removeClass('hidden').addClass('show');
});
// Theme selector
$('[data-toggle=theme]').on('click', function(e) {
e.preventDefault();
var theme = $(this).data('theme') || 'mixed';
$('body').removeClass('theme-light theme-mixed theme-dark').addClass('theme-' + theme);
$.post('/set', { theme: theme });
});
});
|
//Because Browserify encapsulates every module, use strict won't apply to the global scope and break everything
'use strict';
//Require necessary modules
var System = require('./core/system.js');
//The initialize Module
var Intialize = function initializeSystem() {
var options = {
//Empty for now
};
//Create a new system
var system = new System(options);
};
// shim layer with setTimeout fallback
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
//Initialize when fully loaded
window.addEventListener("load", Intialize);
//Export the Browserify module
module.exports = Intialize;
|
define([], function() {
return function() {
var container = document.querySelector( ".video-container" ),
baseFontSize = 14,
baseContainerWidth = 560;
container.style.fontSize = ( baseFontSize * ( container.offsetWidth / baseContainerWidth ) ) + "px";
};
});
|
var MediaFilter = function ($mdMedia) {
'use strict';
return function (input) {
return $mdMedia(input);
};
};
MediaFilter.$inject = ['$mdMedia'];
module.exports = MediaFilter;
|
'use strict';
/* eslint no-new-func: "off" */
const upperFirst = require('upper-case-first');
const { CAMEL_CASE_CONVENTION, PASCAL_CASE_CONVENTION, SNAKE_CASE_CONVENTION } = require('./fieldConventions/constants');
const conventionsFactory = require('./fieldConventions/conventionsFactory');
const BaseMapInstance = require('./mapInstances/base');
const MapInstance = require('./mapInstances/mapInstance');
const AsyncMapInstance = require('./mapInstances/asyncMapInstance');
const checkMapperArgs = Symbol('_checkMapperArgs');
const getMapInstanceConstructor = Symbol('_getMapInstance');
class Mapper {
constructor() {
this.conventionsFactory = conventionsFactory;
this.BaseMapInstance = BaseMapInstance;
this.MapInstance = MapInstance;
this.AsyncMapInstance = AsyncMapInstance;
}
register(convention, methodName, SourceType, DestType, cb) {
const self = this;
self[checkMapperArgs](convention, methodName, SourceType, DestType);
const MapInstanceConstructor = self[getMapInstanceConstructor](methodName);
const mapInstance = new MapInstanceConstructor(self.conventionsFactory.get(convention), SourceType, DestType, cb);
this[methodName] = mapInstance.map.bind(mapInstance);
}
generateType(typeName, fields) {
return new Function(`
return function ${upperFirst(typeName)}() {
${fields.map(field => `this['${field}'] = undefined;`).join('\n')}
}
`)();
}
registerConvention(name, convention) {
this.conventionsFactory.register(name, convention);
}
extendMap(methodName, implementation) {
this.BaseMapInstance.prototype[methodName] = implementation;
}
get CAMEL_CASE_CONVENTION() {
return CAMEL_CASE_CONVENTION;
}
get PASCAL_CASE_CONVENTION() {
return PASCAL_CASE_CONVENTION;
}
get SNAKE_CASE_CONVENTION() {
return SNAKE_CASE_CONVENTION;
}
[checkMapperArgs](convention, methodName, SourceType, DestType) {
const invalidConstructors = [
String, Number, Boolean, Date, RegExp, Array
];
if (!this.conventionsFactory.has(convention)) {
throw new Error('Unsupported convention.');
}
if (typeof methodName !== 'string' || methodName.length === 0) {
throw new Error('Method name should be specified.');
}
if (typeof SourceType !== 'function' || invalidConstructors.includes(SourceType)) {
throw new Error('Unsupported source type. Source type should be constructor function (Object or custom)');
}
if (typeof DestType !== 'function' || invalidConstructors.includes(DestType)) {
throw new Error('Unsupported destination type. Destination type should be constructor function (Object or custom)');
}
}
[getMapInstanceConstructor](methodName) {
const self = this;
if (methodName.endsWith('Async')) {
return self.AsyncMapInstance;
} else {
return self.MapInstance;
}
}
}
module.exports = Mapper; |
var mongooseConnection = require('../../../config/mongoose-connection').open('test'),
mongoose = require('mongoose'),
ObjectID = require('mongodb').ObjectID,
TextLog = require('../../../models/textLog'),
should = require('should');
/*
* Mocha Test
*
* Tests are organized by having a "describe" and "it" method. Describe
* basically creates a "section" that you are testing and the "it" method
* is what runs your test code.
*
* For asynchronous tests you need to have a done method that you call after
* your code should be done executing so Mocha runs to test properly.
*/
describe('TextLog', function(){
it('uses only friendly property names in toObject result', function(){
var log = new TextLog.model({
gpi : new ObjectID(),
ts : Date.now(),
logs : [
{
val : "my garden journal entry",
tags: ["journal"]
}
]
});
var result = log.toObject();
// only friendly 'logs' should exist
result.should.not.have.property('l');
result.should.have.property('logs');
// only friendly 'timestamp' should exist
result.should.not.have.property('ts');
result.should.have.property('timestamp');
result.logs.forEach(function(log){
log.should.not.have.property('v');
log.should.not.have.property('t');
log.should.have.property('val');
log.should.have.property('tags');
log.tags.should.include("journal");
});
});
it('uses only friendly property names in toJSON result', function(){
var log = new TextLog.model({
gpi : new ObjectID(),
ts : Date.now(),
logs : [
{
val : "my garden journal entry",
tags: ["journal"]
}
]
});
var result = log.toJSON();
// only friendly 'logs' should exist
result.should.not.have.property('l');
result.should.have.property('logs');
// only friendly 'timestamp' should exist
result.should.not.have.property('ts');
result.should.have.property('timestamp');
result.logs.forEach(function(log){
log.should.not.have.property('v');
log.should.not.have.property('t');
log.should.have.property('val');
log.should.have.property('tags');
log.tags.should.include("journal");
});
});
});
|
var proxy = require('../../model/linkProxy.js');
export function get(req, res, next) {
proxy.get(req,res);
}
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __assign = (this && this.__assign) || Object.assign || function(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;
};
var _ = require('underscore');
var React = require('react');
var react_bootstrap_1 = require('react-bootstrap');
var group_1 = require('./group');
var fileinput_1 = require('./fileinput');
exports.FileInput = fileinput_1.FileInput;
var FormForm = (function (_super) {
__extends(FormForm, _super);
function FormForm(props) {
_super.call(this, props);
this.handleChange = this.handleChange.bind(this);
this.handleMultiChange = this.handleMultiChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleOnFocus = this.handleOnFocus.bind(this);
}
/**
* Merge an object with validation errors into an existing field-configuration-array.
* The FieldConfig-objects are cloned for safe use with the React.Component.setState method.
*/
FormForm.mergeValidationMsg = function (fields, messages) {
var arr = [];
_.each(fields, function (field) {
var msg, _field = _.clone(field);
msg = messages[field.name];
if (msg) {
if (_.isArray(msg)) {
msg = msg[0];
}
_.extend(_field, {
helpText: msg,
validationState: 'error',
});
}
else {
// clear previous validation errors
_.extend(_field, {
helpText: null,
validationState: null,
});
}
arr.push(_field);
});
return arr;
};
FormForm.clearFieldError = function (fields, name) {
var field, clonedFields;
clonedFields = _.clone(fields);
field = FormForm.getFieldByName(clonedFields, name);
field.helpText = null;
field.validationState = null;
return clonedFields;
};
FormForm.getFieldByName = function (fields, name) {
return _.find(fields, function (field) {
return field.name === name;
});
};
FormForm.prototype.handleChange = function (event) {
// console.log('handleChange', event.target)
this.callOnChange(event.target.name, event.target.value);
};
FormForm.prototype.handleMultiChange = function (event) {
var values, options;
// console.log('handleMultiChange', event.target)
options = event.target.options;
values = [];
_.each(event.target.options, function (option) {
if (option.selected) {
values.push(option.value);
}
});
this.callOnChange(event.target.name, values);
};
FormForm.prototype.handleClick = function (event) {
var value;
// console.log('handleClick', event.target)
if (this.props.values) {
value = this.props.values[event.target.name];
}
else {
value = false;
}
this.callOnChange(event.target.name, !value);
};
FormForm.prototype.callOnChange = function (name, newValue) {
var clonedValues = {};
_.each(this.props.values, function (value, key) {
clonedValues[key] = _.clone(value);
});
clonedValues[name] = newValue;
this.props.onChange(clonedValues);
};
FormForm.prototype.handleSubmit = function (event) {
if (this.props.onSubmit) {
event.preventDefault();
this.props.onSubmit();
}
};
FormForm.prototype.handleOnFocus = function (event) {
if (this.props.onFocus) {
this.props.onFocus(event.target.name);
}
};
/*
* Get the display string of a choice value.
*/
FormForm.getChoiceDisplay = function (value, choices) {
var option;
_.find(choices, function (choice) {
if (choice[0] == value) {
option = choice;
return true;
}
if (_.isArray(choice[1])) {
return _.find(choice[1], function (c) {
if (c[0] == value) {
option = c;
return true;
}
});
}
});
return option ? option[1] : '';
};
FormForm.getMultiChoiceDisplay = function (values, choices) {
var labels;
if (!_.isArray(values)) {
return '';
}
labels = [];
_.each(values, function (value) {
var label;
label = FormForm.getChoiceDisplay(value, choices);
if (label) {
labels.push(label);
}
});
return labels.join(', ');
};
FormForm.prototype.render = function () {
var _this = this;
var fields = [];
_.each(this.props.fields, function (fieldConfig, index) {
var field, props, value;
if (_.has(_this.props.values, fieldConfig.name)) {
value = _this.props.values[fieldConfig.name];
}
else {
value = null;
}
props = {
isHorizontal: _this.props.isHorizontal,
key: fieldConfig.name || fieldConfig.label,
col1: _this.props.col1,
col2: _this.props.col2,
controlId: index.toString(),
onChange: _this.handleChange,
checked: value == true,
type: fieldConfig.type,
value: value,
name: fieldConfig.name,
choices: fieldConfig.choices,
label: fieldConfig.label,
addonPrepend: fieldConfig.addonPrepend,
addonAppend: fieldConfig.addonAppend,
placeholder: fieldConfig.placeholder,
helpText: fieldConfig.helpText,
validationState: fieldConfig.validationState,
};
// isStatic override
if (_this.props.isStatic) {
switch (props.type) {
case 'select':
props.value = FormForm.getChoiceDisplay(props.value, props.choices);
break;
case 'multiselect':
props.value = FormForm.getMultiChoiceDisplay(props.value, props.choices);
break;
case 'checkbox':
props.value = props.value ? React.createElement(react_bootstrap_1.Glyphicon, {glyph: "check"}) : React.createElement(react_bootstrap_1.Glyphicon, {glyph: "unchecked"});
}
props.type = 'static';
}
switch (props.type) {
case 'text':
case 'password':
case 'number':
case 'hidden':
case 'textarea':
if (props.value === null) {
props.value = '';
}
if (props.type === 'textarea') {
props.componentClass = 'textarea';
}
field = (React.createElement(group_1.Group, __assign({}, props), React.createElement(react_bootstrap_1.FormControl, __assign({}, props, {onFocus: _this.handleOnFocus}))));
break;
case 'select':
case 'multiselect':
if (props.type === 'multiselect') {
props.multiple = true;
props.onChange = _this.handleMultiChange;
if (props.value === null) {
props.value = [];
}
}
else {
if (props.value === null) {
props.value = '';
}
}
field = (React.createElement(group_1.Group, __assign({}, props), React.createElement(react_bootstrap_1.FormControl, __assign({}, props, {componentClass: "select"}), props.choices.map(function (choice) {
if (_.isArray(choice[1])) {
// Nested optgroup choices
return (React.createElement("optgroup", {label: choice[0], key: choice[0]}, choice[1].map(function (c) {
return React.createElement("option", {key: c[0], value: c[0]}, c[1]);
})));
}
return React.createElement("option", {key: choice[0], value: choice[0]}, choice[1]);
}))));
break;
case 'checkbox':
props.onClick = _this.handleClick;
props.onChange = function () { };
props.value = '';
field = (React.createElement(react_bootstrap_1.Checkbox, __assign({}, props), props.label));
if (_this.props.isHorizontal) {
field = (React.createElement(react_bootstrap_1.FormGroup, {key: props.key}, React.createElement(react_bootstrap_1.Col, {smOffset: _this.props.col1, sm: _this.props.col2}, field)));
}
break;
case 'file':
field = (React.createElement(group_1.Group, __assign({}, props), React.createElement(fileinput_1.FileInput, __assign({}, props))));
break;
case 'static':
field = (React.createElement(group_1.Group, __assign({}, props), React.createElement(react_bootstrap_1.FormControl.Static, null, props.value)));
break;
}
fields.push(field);
});
if (!this.props.isHorizontal) {
return (React.createElement("form", {onSubmit: this.handleSubmit}, fields, this.props.children));
}
else {
return (React.createElement(react_bootstrap_1.Form, {horizontal: true, onSubmit: this.handleSubmit}, fields, React.createElement(react_bootstrap_1.FormGroup, null, React.createElement(react_bootstrap_1.Col, {smOffset: this.props.col1, sm: this.props.col2}, this.props.children))));
}
};
return FormForm;
}(React.Component));
exports.FormForm = FormForm;
//# sourceMappingURL=formform.js.map |
'use strict'
/*****************************************************************
*
* Declare app level module which depends on views, and components
*
******************************************************************/
angular.module('app', [
'btford.socket-io',
'sqwk'
])
/*****************************************************************
*
* Ansi
*
******************************************************************/
.constant('Ansi', window.ansi_up)
/*****************************************************************
*
* Socket Factory
*
******************************************************************/
.factory('Socket', function(socketFactory) {
return socketFactory()
})
|
/**
* Copyright (c) 2017-present, Liu Jinyong
* All rights reserved.
*
* https://github.com/huanxsd/MeiTuan
* @flow
*/
import React, { PureComponent } from 'react'
import { View, Text, StyleSheet, InteractionManager } from 'react-native'
import { WebView } from 'react-native-webview'
type Props = {
navigation: any,
}
type State = {
source: Object,
}
class WebScene extends PureComponent<Props, State> {
static navigationOptions = ({ navigation }: any) => ({
headerStyle: { backgroundColor: 'white' },
title: navigation.state.params.title,
})
constructor(props: Props) {
super(props)
this.state = {
source: {}
}
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
this.props.navigation.setParams({ title: '加载中' })
this.setState({ source: { uri: this.props.navigation.state.params.url } })
})
}
render() {
return (
<View style={styles.container}>
<WebView
automaticallyAdjustContentInsets={false}
style={styles.webView}
source={this.state.source}
onLoadEnd={(e) => this.onLoadEnd(e)}
scalesPageToFit
/>
</View>
)
}
onLoadEnd(e: any) {
if (e.nativeEvent.title.length > 0) {
this.props.navigation.setParams({ title: e.nativeEvent.title })
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#2c3e50',
},
webView: {
flex: 1,
backgroundColor: 'white',
}
})
export default WebScene
|
NetInfo = new Mongo.Collection("networking");
var pythonPath = "/path/to/bin/python";
var scriptPath = "/path/to/nettop.py";
var bytesToSize = function (bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
bytes = parseInt(bytes);
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
if (Meteor.isClient) {
Template.netinfo.helpers({
netInfo: function () {
var netInfo = [];
// Meteor's mongodb api doesn't seem to support deduping, so I'll list some interfaces manually.
// Otherwise I would do something like:
// NetInfo.find({}).distinct(ifname) and get an array of ifnames
var ifaces = ['all','en0','en1','en2','lo0','bridge0','p2p0','awd10'];
for (var i in ifaces) {
var ifaceName = ifaces[i];
ifInfo = NetInfo.find({ifname: ifaceName}, {sort: {timestamp: -1}, limit: 2}).fetch();
if (ifInfo.length > 1){
var info = {};
info.ifname = ifaceName;
info.sent = bytesToSize(ifInfo[0].bytes_sent);
info.receieved = bytesToSize(ifInfo[0].bytes_received);
info.sentRate = bytesToSize((ifInfo[0].bytes_sent - ifInfo[1].bytes_sent));
info.recvRate = bytesToSize((ifInfo[0].bytes_received - ifInfo[1].bytes_received));
netInfo.push(info);
}
}
return netInfo;
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// Run a network info python psutil script as a subprocess
var spawn = Npm.require('child_process').spawn;
var child = spawn(pythonPath, ['-u',scriptPath]);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
console.log("Python client started, pid: " + child.pid);
});
}
|
/** Copy own-properties from `props` onto `obj`.
* @returns obj
* @private
*/
/* global ReactEventBridge:false, internalInstanceKey:false */
// m-start
import options from './options';
import { ATTR_KEY } from './constants';
function getInternalInstanceKey() {
if (typeof internalInstanceKey !== 'undefined') {
return internalInstanceKey;
}
}
export function loseup(inst, node) {
let key = getInternalInstanceKey();
if (key) {
ReactEventBridge.precacheNode(inst, node);
}
}
export function recycle(node) {
let key = getInternalInstanceKey();
if (node[key]) {
ReactEventBridge.recycle(node, key);
}
}
export function resetNode(node) {
if (node && node.style) {
options.processStyle(node, 'name', '', node[ATTR_KEY].style || '') // reset style
// node.className = '' // only reset style
}
}
// m-end
export function extend(obj, props) {
if (props) {
for (let i in props) obj[i] = props[i];
}
return obj;
}
/** Fast clone. Note: does not filter out non-own properties.
* @see https://esbench.com/bench/56baa34f45df6895002e03b6
*/
export function clone(obj) {
return extend({}, obj);
}
/** Get a deep property value from the given object, expressed in dot-notation.
* @private
*/
export function delve(obj, key) {
for (let p=key.split('.'), i=0; i<p.length && obj; i++) {
obj = obj[p[i]];
}
return obj;
}
/** @private is the given object a Function? */
export function isFunction(obj) {
return 'function'===typeof obj;
}
/** @private is the given object a String? */
export function isString(obj) {
return 'string'===typeof obj;
}
/** Convert a hashmap of CSS classes to a space-delimited className string
* @private
*/
export function hashToClassName(c) {
let str = '';
for (let prop in c) {
if (c[prop]) {
if (str) str += ' ';
str += prop;
}
}
return str;
}
/** Just a memoized String#toLowerCase */
let lcCache = {};
export const toLowerCase = s => lcCache[s] || (lcCache[s] = s.toLowerCase());
/** Call a function asynchronously, as soon as possible.
* @param {Function} callback
*/
let resolved = typeof Promise!=='undefined' && Promise.resolve();
export const defer = resolved ? (f => { resolved.then(f); }) : setTimeout;
|
export const ic_grade_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M17.11 10.83l-2.47-.21-1.2-.1-.47-1.11L12 7.13l-.97 2.28-.47 1.11-1.2.1-2.47.21 1.88 1.63.91.79-.27 1.17-.57 2.42 2.13-1.28 1.03-.63 1.03.63 2.13 1.28-.57-2.42-.27-1.17.91-.79z","opacity":".3"},"children":[]},{"name":"path","attribs":{"d":"M22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.64-7.03L22 9.24zm-7.41 5.18l.56 2.41-2.12-1.28-1.03-.62-1.03.62-2.12 1.28.56-2.41.27-1.18-.91-.79-1.88-1.63 2.47-.21 1.2-.1.47-1.11.97-2.27.97 2.29.47 1.11 1.2.1 2.47.21-1.88 1.63-.91.79.27 1.16z"},"children":[]}]}; |
// var Promise = require('bluebird');
// var request = require('request');
//
//
// var address = "https://api.github.com/repos/jThreeJS/jThree-Example";
//
// var co = require('co');
// co(function *() {
// var branchesUrl = address + "/branches"
//
// var masterUrl = (yield p(branchesUrl)).filter(function (o) {
// return o.name === "master"
// })[0].commit.url;
// console.log(masterUrl);
//
// });
//
// function p(url) {
// var result;
// return new Promise(function (resolve, reject) {
// request.get({
// url: url,
// json: true,
// headers: { 'User-Agent': 'request' }
// }, function(error, response, body) {
// resolve(body);
// });
// })
// }
|
var elixir = require('laravel-elixir');
require('laravel-elixir-angular');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
//mix.sass('app.scss');
mix.scripts([
"app.js",
"dashboard/dashboard.config.js",
"dashboard/dashboard.controller.js"
], "public/js/app.js", "resources/assets/angular");
mix.copy('resources/assets/angular/**/*.html', 'public/build');
// Angular mix recipe.
// @params: (string: input path, string: output path, string: compiled file name)
//mix.angular('resources/assets/angular/', 'public/js', 'app.js');
});
|
var TestResponses = {
generic: {
status: 200,
responseText: 'ok'
},
events: {
status: 200,
responseText: JSON.stringify({
events: {
event1: 1,
event2: ['a','b','c']
}
})
},
messages: {
status: 200,
responseText: JSON.stringify({
events: {
statusmessage: [
{content:"Test 1", type:'good'},
{content:"Test 2", type:'bad'}
]
}
})
},
pushRegion: {
status: 200,
responseText: JSON.stringify({
regions: {
SideCart: '<div id="region1">Replaced:1</div>'
}
})
},
pushManyRegions: {
status: 200,
responseText: JSON.stringify({
regions: {
SideCart: '<div id="region1">Replaced:1</div>',
Other: '<div class="replaceme">Replaced:<span>2+3</span></div>'
}
})
},
pushImplicitly: {
status: 200,
responseText: '<div id="region1">Sneaky:1</div>'
},
pullLocal: {
status: 200,
responseText: JSON.stringify({
regions: {
Test2: '<div class="replaceme">Replaced:2</div>'
}
})
},
pullDataAttribute: {
status: 200,
responseText: JSON.stringify({
regions: {
Test3: '<div class="replaceme">Replaced:3</div>',
Test4: '<div>Replaced:4</div>'
}
})
},
errorEmpty: {
status: 400,
responseText: ''
},
errorStringResponse: {
status: 400,
responseText: 'Test Error Message'
},
errorHtmlResponse: {
status: 400,
responseText: '<p>Test <strong>Error</strong> Message</p>'
},
errorPageResponse: {
status: 400,
responseText: '<html><body>Test Error Message</body></html>'
}
};
|
/*
Re: NSColor to CGColor by j o a r
http://www.cocoabuilder.com/archive/message/cocoa/2006/11/12/174339
static CGColorRef CGColorCreateFromNSColor (CGColorSpaceRef
colorSpace, NSColor *color)
NSColor *deviceColor = [color colorUsingColorSpaceName:
NSDeviceRGBColorSpace];
float components[4];
[deviceColor getRed: &components[0] green: &components[1] blue:
&components[2] alpha: &components[3]];
return CGColorCreate (colorSpace, components);
*/
// Split call disabled by default since ObjJ syntax
var useSplitCall = __jsc__.useSplitCall
__jsc__.useSplitCall = true
function floatsEq(a, b)
{
if (Math.abs(a-b) < 0.001) return true
return false
}
//
// Test get : allocate a memory buffer and have Cocoa fill it
//
// 32bit only
// var encoding = 'ffff'
// 32 and 64 bit : get size of CGFloat by inspecting a signature of method returning CGFloat (##dirty)
var signature = JSCocoa.typeEncodingOfMethod_class('whiteComponent', 'NSColor')
var CGFloatEncoding = signature.charAt(0)
var buffer = new memoryBuffer(CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding)
var r = 0.9
var g = 0.8
var b = 0.7
var a = 0.6
var color = NSColor.colorWithDevice({ red : r, green : g, blue : b, alpha : a })
// Use scrambled pattern 2 3 0 1 instead of 0 1 2 3 to test
color.get({ red : new outArgument(buffer, 2),
green : new outArgument(buffer, 3),
blue : new outArgument(buffer, 0),
alpha : new outArgument(buffer, 1) })
/*
log('color=' + color)
log('buffer[0]=' + buffer[0])
log('buffer[1]=' + buffer[1])
log('buffer[2]=' + buffer[2])
log('buffer[3]=' + buffer[3])
*/
if (!floatsEq(buffer[2], r)) throw 'pointer handling get failed (1)'
if (!floatsEq(buffer[3], g)) throw 'pointer handling get failed (2)'
if (!floatsEq(buffer[0], b)) throw 'pointer handling get failed (3)'
if (!floatsEq(buffer[1], a)) throw 'pointer handling get failed (4)'
//
// Test set with the same buffer
//
var a = 123.456
var b = -87.6
var c = 563.1
var d = -1.1
buffer[0] = a
buffer[1] = b
buffer[2] = c
buffer[3] = d
if (!floatsEq(buffer[0], a)) throw 'pointer handling set failed (5)'
if (!floatsEq(buffer[1], b)) throw 'pointer handling set failed (6)'
if (!floatsEq(buffer[2], c)) throw 'pointer handling set failed (7)'
if (!floatsEq(buffer[3], d)) throw 'pointer handling set failed (8)'
buffer = null
//
// Test raw buffer
//
var path = NSBezierPath.bezierPath
path.moveToPoint(new NSPoint(0, 0))
path.curve({ toPoint : new NSPoint(10, 20), controlPoint1 : new NSPoint(30, 40), controlPoint2 : new NSPoint(50, 60) })
// Allocate room for 3 points
var buffer = new memoryBuffer(CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding)
// Copy points into our buffer
path.element({ atIndex : 1, associatedPoints : new outArgument(buffer, 0) })
// Check points were copied OK (controlPoint1, controlPoint2, toPoint)
if (!floatsEq(buffer[0], 30)) throw 'pointer handling raw get failed (9)'
if (!floatsEq(buffer[1], 40)) throw 'pointer handling raw get failed (10)'
if (!floatsEq(buffer[2], 50)) throw 'pointer handling raw get failed (11)'
if (!floatsEq(buffer[3], 60)) throw 'pointer handling raw get failed (12)'
if (!floatsEq(buffer[4], 10)) throw 'pointer handling raw get failed (13)'
if (!floatsEq(buffer[5], 20)) throw 'pointer handling raw get failed (14)'
/*
log(buffer[0])
log(buffer[1])
log(buffer[2])
log(buffer[3])
log(buffer[4])
log(buffer[5])
*/
// Change point values
buffer[0] = 123
buffer[1] = 456
buffer[2] = 789
buffer[3] = 0.123
buffer[4] = 0.456
buffer[5] = 0.789
path.set({ associatedPoints : buffer, atIndex : 1 })
// Overwrite existing points
path.setAssociatedPoints_atIndex(buffer, 1)
// Copy points into a new buffer
var buffer2 = new memoryBuffer(CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding+CGFloatEncoding)
path.element({ atIndex : 1, associatedPoints : new outArgument(buffer2, 0) })
if (!floatsEq(buffer2[0], 123)) throw 'pointer handling raw get failed (15)'
if (!floatsEq(buffer2[1], 456)) throw 'pointer handling raw get failed (16)'
if (!floatsEq(buffer2[2], 789)) throw 'pointer handling raw get failed (17)'
if (!floatsEq(buffer2[3], 0.123)) throw 'pointer handling raw get failed (18)'
if (!floatsEq(buffer2[4], 0.456)) throw 'pointer handling raw get failed (19)'
if (!floatsEq(buffer2[5], 0.789)) throw 'pointer handling raw get failed (20)'
buffer = null
buffer2 = null
__jsc__.useSplitCall = useSplitCall
|
/**
* Uses wintersmith programatically to create a build.
*
* Duplicated here so the wintersmith version can be easily controlled
* via npm (and wintersmith does not need to be installed globally).
*/
var wintersmith = require('wintersmith')
var env = wintersmith('config.json')
env.build(function (err) {
if (err) {
throw err
}
console.log('Build Completed')
})
|
import 'babel-polyfill';
import { AppContainer } from 'react-hot-loader';
import React from 'react';
import {render} from 'react-dom';
import { browserHistory } from 'react-router';
import App from './app';
import './styles/main.scss';
import {buildCheckIfAuthed} from 'helpers/auth';
var configureStore = require('./store/configureStore');
const {store, history} = configureStore({}, browserHistory);
const checkIfAuthed = buildCheckIfAuthed(store);
var rootEl = document.getElementById('app');
render(
<AppContainer>
<App store={store} history={history} checkIfAuthed={checkIfAuthed} />
</AppContainer>, rootEl
);
if (module.hot) {
module.hot.accept('./app', () => {
const NextApp = require('./app').default;
render(
<AppContainer>
<NextApp store={store} history={history} checkIfAuthed={checkIfAuthed} />
</AppContainer>,
rootEl
);
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.