code
stringlengths 2
1.05M
|
---|
'use strict';
backAndControllers.controller('filterDashboardController', ['$scope', 'dataListService',
function ($scope, dataListService) {
$scope.dashboardId = '1';
$scope.filterOptions = [{ fieldName: 'First_Name', operator: 'contains', value: '' }, { fieldName: 'Job_Title', operator: 'in', value: '' }];
$scope.loadSelectOptions = function () {
dataListService.read({
dataType: "view",
viewName: "EmployeesJob_Title",
withSelectOptions: null,
filter: null,
sort: JSON.stringify([{fieldName:"Ordinal", order: "asc"}]),
search: null
}, function (data) {
$scope.Job_TitleOptions = data.data;
});
}
$scope.loadSelectOptions();
}
])
|
Template.mugenRoleCollectionsView.events = {
'click #btnRemove': function(e) {
e.preventDefault();
var recordId = this._id;
MeteorisAlert.confirm("confirm_remove", function() {
Router.current().remove(recordId);
Router.go("mugenRoleCollectionsIndex")
});
}
};
Template.mugenRoleCollectionsView.helpers({
});
|
'use strict';
var App = require('../app');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var _ = require('underscore');
var keyboardShortcuts = require('./keyboardShortcuts.json');
var marked = require('marked');
var controller = {
showHelp: function () {
var HelpView = require('./views/HelpView');
_.each(keyboardShortcuts, function (category) {
_.each(category.shortcuts, function (shortcut) {
shortcut.description = marked(shortcut.description);
});
});
var helpModel = new Backbone.Model({keyboardShortcuts: keyboardShortcuts});
App.mainRegion.show(new HelpView({model: helpModel}));
App.navigationRegion.currentView.options.collection.deselect();
}
};
App.addInitializer(function () {
new Marionette.AppRouter({
controller: controller,
appRoutes: {
'help': 'showHelp'
}
});
});
|
GS.MeshPhongGlowMaterial = function(map, glow, normal, emissive, glowIntensity) {
this.shader = GS.PhongGlowShader;
this.uniforms = THREE.UniformsUtils.clone(this.shader.uniforms);
this.uniforms["map"].value = map;
this.uniforms["glowMap"].value = glow;
this.uniforms["normalMap"].value = normal;
this.uniforms["emissive"].value = new THREE.Color(emissive || 0);
this.uniforms["glowIntensity"].value = (glowIntensity !== undefined) ? glowIntensity : 1;
THREE.ShaderMaterial.call(this, {
uniforms: this.uniforms,
fragmentShader: this.shader.fragmentShader,
vertexShader: this.shader.vertexShader,
lights: true,
});
this.map = true;
this.normalMap = (normal !== undefined && normal !== null);
};
GS.MeshPhongGlowMaterial.prototype = GS.inherit(THREE.ShaderMaterial, {
constructor: GS.MeshPhongGlowMaterial,
clone: function() {
var material = new GS.MeshPhongGlowMaterial(
this.uniforms["map"].value,
this.uniforms["glowMap"].value,
this.uniforms["normalMap"].value,
this.uniforms["emissive"].value,
this.uniforms["glowIntensity"].value
);
return material;
},
get emissive() {
return this.uniforms["emissive"].value;
},
set glowIntensity(value) {
this.uniforms["glowIntensity"].value = value;
},
get glowIntensity() {
return this.uniforms["glowIntensity"].value
},
});
|
/* */
require('../modules/es7.string.at');
require('../modules/es7.string.pad-start');
require('../modules/es7.string.pad-end');
require('../modules/es7.string.trim-left');
require('../modules/es7.string.trim-right');
module.exports = require('../modules/_core').String;
|
(function() {
var rgb_to_hsl = function(r,g,b){
// Input colors are in 0-255, calculations are between 0-1
r /= 255; g /= 255; b /= 255;
// http://en.wikipedia.org/wiki/HSL_and_HSV
// Convert to HSL
var max = Math.max(r,g,b),
min = Math.min(r,g,b),
chroma = max - min,
luminance = chroma / 2,
saturation = chroma / (1 - Math.abs(2*luminance-1)),
hue = 0;
if( max == r ){ hue = ((g-b)/chroma) % 6; }else
if( max == g ){ hue = (b-r)/chroma + 2; }else
if( max == b ){ hue = (r-g)/chroma + 4; }
return [(hue*60+360) % 360, saturation, luminance];
};
var pixelShiftHue = function(r,g,b,deg){
// Input colors are in 0-255, calculations are between 0-1
r /= 255; g /= 255; b /= 255;
// http://en.wikipedia.org/wiki/HSL_and_HSV
// Convert to HSL
var max = Math.max(r,g,b),
min = Math.min(r,g,b),
chroma = max - min,
luminance = chroma / 2,
saturation = chroma / (1 - Math.abs(2*luminance-1)),
hue = 0;
if( max == r ){ hue = ((g-b)/chroma) % 6; }else
if( max == g ){ hue = (b-r)/chroma + 2; }else
if( max == b ){ hue = (r-g)/chroma + 4; }
hue *= 60;
hue %= 360;
// Shift hue
hue += deg;
hue %= 360;
//hue /= 360;
// hsl to rgb:
hue /= 60;
var rR = 0, rG = 0, rB = 0,
//chroma = saturation*(1 - Math.abs(2*luminance - 1)),
tmp = chroma * (1-Math.abs(hue % 2 - 1)),
m = luminance - chroma/2;
if( 0 <= hue && hue < 1 ){ rR = chroma; rG = tmp; }else
if( 1 <= hue && hue < 2 ){ rG = chroma; rR = tmp; }else
if( 2 <= hue && hue < 3 ){ rG = chroma; rB = tmp; }else
if( 3 <= hue && hue < 4 ){ rB = chroma; rG = tmp; }else
if( 4 <= hue && hue < 5 ){ rB = chroma; rR = tmp; }else
if( 5 <= hue && hue < 6 ){ rR = chroma; rB = tmp; }
rR += m; rG += m; rB += m;
rR = (255*rR);
rG = (255*rG);
rB = (255*rB);
return [rR,rG,rB];
};
var shift_hue = function(imageData,deg){
var data = imageData.data,
pixel;
for(var i = 0; i < data.length; i += 4) {
pixel = pixelShiftHue(data[i+0],data[i+1],data[i+2],deg);
data[i+0] = pixel[0];
data[i+1] = pixel[1];
data[i+2] = pixel[2];
}
};
/**
* Shift Hue Filter.
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.ShiftHue = function(imageData) {
shift_hue(imageData, this.getFilterHueShiftDeg() % 360 );
};
Kinetic.Factory.addFilterGetterSetter(Kinetic.Image, 'filterHueShiftDeg', 0);
/**
* get hue shift amount. The shift amount is a number between 0 and 360.
* @name getFilterBrightness
* @method
* @memberof Kinetic.Image.prototype
*/
/**
* set hue shift amount
* @name setFilterBrightness
* @method
* @memberof Kinetic.Image.prototype
*/
/**
* Colorize Filter.
* colorizes the image so that it is just varying shades of the specified color
* @function
* @memberof Kinetic.Filters
* @param {Object} imageData
* @author ippo615
*/
Kinetic.Filters.Colorize = function(imageData) {
var data = imageData.data;
// First we'll colorize it red, then shift by the hue specified
var color = this.getFilterColorizeColor(),
hsl = rgb_to_hsl(color[0],color[1],color[2]),
hue = hsl[0];
// Color it red, by removing green and blue
for(var i = 0; i < data.length; i += 4) {
data[i + 1] = 0;
data[i + 2] = 0;
}
// Shift by the hue
shift_hue(imageData,hue);
};
Kinetic.Factory.addFilterGetterSetter(Kinetic.Image, 'filterColorizeColor', [255,0,0] );
/**
* Gets the colorizing color.
* @name getFilterColorizeColor
* @method
* @memberof Kinetic.Image.prototype
*/
/**
* Gets the colorizing color. Should be an array [r,g,b] ie [255,0,128].
* note that white [255,255,255] black [0,0,0] and greys [r,r,r] get treated as red.
* @name setFilterColorizeColor
* @method
* @memberof Kinetic.Image.prototype
*/
})();
|
angular.module('ionic-pullup', [])
.constant('ionPullUpFooterState', {
COLLAPSED: 'COLLAPSED',
MINIMIZED: 'MINIMIZED',
EXPANDED: 'EXPANDED'
})
.constant('ionPullUpFooterBehavior', {
HIDE: 'HIDE',
EXPAND: 'EXPAND'
})
.directive('ionPullUpFooter', ['$timeout', '$rootScope', '$window', function($timeout, $rootScope, $window) {
return {
restrict: 'AE',
scope: {
onExpand: '&',
onCollapse: '&',
onMinimize: '&'
},
controller: ['$scope', '$element', '$attrs', 'ionPullUpFooterState', 'ionPullUpFooterBehavior', function($scope, $element, $attrs, FooterState, FooterBehavior) {
var
tabs = document.querySelector('.tabs'),
hasBottomTabs = document.querySelector('.tabs-bottom'),
header = document.querySelector('.bar-header'),
tabsHeight = tabs ? tabs.offsetHeight : 0,
headerHeight = header ? header.offsetHeight : 0,
handleHeight = 0,
footer = {
height: 0,
posY: 0,
lastPosY: 0,
state: FooterState.COLLAPSED,
defaultHeight : $element[0].offsetHeight,
maxHeight: parseInt($attrs.maxHeight, 10) || 0,
initialState: $attrs.initialState ? $attrs.initialState.toUpperCase() : FooterState.COLLAPSED,
defaultBehavior: $attrs.defaultBehavior ? $attrs.defaultBehavior.toUpperCase() : FooterBehavior.EXPAND
};
function init() {
$element.css({'-webkit-backface-visibility': 'hidden', 'backface-visibility': 'hidden', 'transition': '300ms ease-in-out', 'padding': 0});
if (tabs && hasBottomTabs) {
$element.css('bottom', tabs.offsetHeight + 'px');
}
}
function computeHeights() {
footer.height = footer.maxHeight > 0 ? footer.maxHeight : $window.innerHeight - headerHeight - handleHeight - tabsHeight;
$element.css({'height': footer.height + 'px'});
if (footer.initialState == FooterState.MINIMIZED) {
minimize();
} else {
collapse();
}
}
function expand() {
footer.lastPosY = 0;
$element.css({'-webkit-transform': 'translate3d(0, 0, 0)', 'transform': 'translate3d(0, 0, 0)'});
$scope.onExpand();
footer.state = FooterState.EXPANDED;
}
function collapse() {
footer.lastPosY = (tabs && hasBottomTabs) ? footer.height - tabsHeight : footer.height - footer.defaultHeight;
$element.css({'-webkit-transform': 'translate3d(0, ' + footer.lastPosY + 'px, 0)', 'transform': 'translate3d(0, ' + footer.lastPosY + 'px, 0)'});
$scope.onCollapse();
footer.state = FooterState.COLLAPSED
}
function minimize() {
footer.lastPosY = footer.height;
$element.css({'-webkit-transform': 'translate3d(0, ' + footer.lastPosY + 'px, 0)', 'transform': 'translate3d(0, ' + footer.lastPosY + 'px, 0)'});
$scope.onMinimize();
footer.state = FooterState.MINIMIZED;
}
this.setHandleHeight = function(height) {
handleHeight = height;
computeHeights();
};
this.getHeight = function() {
return $element[0].offsetHeight;
};
this.getBackground = function() {
return $window.getComputedStyle($element[0]).background;
};
this.onTap = function(e) {
e.gesture.srcEvent.preventDefault();
e.gesture.preventDefault();
if (footer.state == FooterState.COLLAPSED) {
if (footer.defaultBehavior == FooterBehavior.HIDE) {
minimize();
} else {
expand();
}
} else {
if (footer.state == FooterState.MINIMIZED) {
if (footer.defaultBehavior == FooterBehavior.HIDE)
collapse();
else
expand();
} else {
// footer is expanded
footer.initialState == FooterState.MINIMIZED ? minimize() : collapse();
}
}
$rootScope.$broadcast('ionPullUp:tap', footer.state);
};
this.onDrag = function(e) {
e.gesture.srcEvent.preventDefault();
e.gesture.preventDefault();
switch (e.type) {
case 'dragstart':
$element.css('transition', 'none');
break;
case 'drag':
footer.posY = Math.round(e.gesture.deltaY) + footer.lastPosY;
if (footer.posY < 0 || footer.posY > footer.height) return;
$element.css({'-webkit-transform': 'translate3d(0, ' + footer.posY + 'px, 0)', 'transform': 'translate3d(0, ' + footer.posY + 'px, 0)'});
break;
case 'dragend':
$element.css({'transition': '300ms ease-in-out'});
footer.lastPosY = footer.posY;
break;
}
};
$window.addEventListener('orientationchange', function() {
$timeout(function() {
computeHeights();
}, 500);
});
init();
}],
compile: function(element, attrs) {
attrs.defaultHeight && element.css('height', parseInt(attrs.defaultHeight, 10) + 'px');
element.addClass('bar bar-footer');
}
}
}])
.directive('ionPullUpContent', [function() {
return {
restrict: 'AE',
require: '^ionPullUpFooter',
link: function (scope, element, attrs, controller) {
var
footerHeight = controller.getHeight();
element.css({'display': 'block', 'margin-top': footerHeight + 'px', width: '100%'});
// add scrolling if needed
if (attrs.scroll && attrs.scroll.toUpperCase() == 'TRUE') {
element.css({'overflow-y': 'scroll', 'overflow-x': 'hidden'});
}
}
}
}])
.directive('ionPullUpBar', [function() {
return {
restrict: 'AE',
require: '^ionPullUpFooter',
link: function (scope, element, attrs, controller) {
var
footerHeight = controller.getHeight();
element.css({'display': 'flex', 'height': footerHeight + 'px', position: 'absolute', right: '0', left: '0'});
}
}
}])
.directive('ionPullUpTrigger', ['$ionicGesture', function($ionicGesture) {
return {
restrict: 'AE',
require: '^ionPullUpFooter',
link: function (scope, element, attrs, controller) {
// add gesture
$ionicGesture.on('tap', controller.onTap, element);
$ionicGesture.on('drag dragstart dragend', controller.onDrag, element);
}
}
}])
.directive('ionPullUpHandle', ['$ionicGesture', '$timeout', '$window', function($ionicGesture, $timeout, $window) {
return {
restrict: 'AE',
require: '^ionPullUpFooter',
link: function (scope, element, attrs, controller) {
var height = parseInt(attrs.height,10) || 25, width = parseInt(attrs.width, 10) || 100,
background = controller.getBackground(),
toggleClasses = attrs.toggle;
controller.setHandleHeight(height);
element.css({
display: 'block',
background: background,
position: 'absolute',
top: 1-height + 'px',
left: (($window.innerWidth - width) / 2) + 'px',
height: height + 'px',
width: width + 'px',
//margin: '0 auto',
'text-align': 'center'
});
// add gesture
$ionicGesture.on('tap', controller.onTap, element);
$ionicGesture.on('drag dragstart dragend', controller.onDrag, element);
scope.$on('ionPullUp:tap', function() {
element.find('i').toggleClass(toggleClasses);
});
$window.addEventListener('orientationchange', function() {
$timeout(function() {
element.css('left', (($window.innerWidth - width) / 2) + 'px');
}, 500);
});
}
}
}]);
|
/**
* @overview datejs
* @version 1.0.0-rc1
* @author Gregory Wild-Smith <gregory@wild-smith.com>
* @copyright 2014 Gregory Wild-Smith
* @license MIT
* @homepage https://github.com/abritinthebay/datejs
*/
/*
2014 Gregory Wild-Smith
@license MIT
@homepage https://github.com/abritinthebay/datejs
2014 Gregory Wild-Smith
@license MIT
@homepage https://github.com/abritinthebay/datejs
*/
Date.CultureStrings=Date.CultureStrings||{};
Date.CultureStrings["xh-ZA"]={name:"xh-ZA",englishName:"Xhosa (South Africa)",nativeName:"isiXhosa (uMzantsi Afrika)",Sunday:"iCawa",Monday:"uMvulo",Tuesday:"uLwesibini",Wednesday:"uLwesithathu",Thursday:"uLwesine",Friday:"uLwesihlanu",Saturday:"uMgqibelo",Sun:"Sun",Mon:"Mon",Tue:"Tue",Wed:"Wed",Thu:"Thu",Fri:"Fri",Sat:"Sat",Su:"Sun",Mo:"Mon",Tu:"Tue",We:"Wed",Th:"Thu",Fr:"Fri",Sa:"Sat",S_Sun_Initial:"S",M_Mon_Initial:"M",T_Tue_Initial:"T",W_Wed_Initial:"W",T_Thu_Initial:"T",F_Fri_Initial:"F",S_Sat_Initial:"S",
January:"eyoMqungu",February:"eyoMdumba",March:"eyoKwindla",April:"Tshazimpuzi",May:"Canzibe",June:"eyeSilimela",July:"eyeKhala",August:"eyeThupha",September:"eyoMsintsi",October:"eyeDwara",November:"eyeNkanga",December:"eyoMnga",Jan_Abbr:"Jan",Feb_Abbr:"Feb",Mar_Abbr:"Mar",Apr_Abbr:"Apr",May_Abbr:"May",Jun_Abbr:"Jun",Jul_Abbr:"Jul",Aug_Abbr:"Aug",Sep_Abbr:"Sep",Oct_Abbr:"Oct",Nov_Abbr:"Nov",Dec_Abbr:"Dec",AM:"AM",PM:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,mdy:"ymd","M/d/yyyy":"yyyy/MM/dd","dddd, MMMM dd, yyyy":"dd MMMM yyyy",
"h:mm tt":"hh:mm:ss tt","h:mm:ss tt":"hh:mm:ss tt","dddd, MMMM dd, yyyy h:mm:ss tt":"dd MMMM yyyy hh:mm:ss tt","yyyy-MM-ddTHH:mm:ss":"yyyy-MM-ddTHH:mm:ss","yyyy-MM-dd HH:mm:ssZ":"yyyy-MM-dd HH:mm:ssZ","ddd, dd MMM yyyy HH:mm:ss":"ddd, dd MMM yyyy HH:mm:ss","MMMM dd":"MMMM dd","MMMM, yyyy":"MMMM yyyy","/jan(uary)?/":"eyomqungu","/feb(ruary)?/":"eyomdumba","/mar(ch)?/":"eyokwindla","/apr(il)?/":"tshazimpuzi","/may/":"canzibe","/jun(e)?/":"eyesilimela","/jul(y)?/":"eyekhala","/aug(ust)?/":"eyethupha",
"/sep(t(ember)?)?/":"eyomsintsi","/oct(ober)?/":"eyedwara","/nov(ember)?/":"eyenkanga","/dec(ember)?/":"eyomnga","/^su(n(day)?)?/":"^icawa","/^mo(n(day)?)?/":"^umvulo","/^tu(e(s(day)?)?)?/":"^ulwesibini","/^we(d(nesday)?)?/":"^ulwesithathu","/^th(u(r(s(day)?)?)?)?/":"^ulwesine","/^fr(i(day)?)?/":"^ulwesihlanu","/^sa(t(urday)?)?/":"^umgqibelo","/^next/":"^next","/^last|past|prev(ious)?/":"^last|past|prev(ious)?","/^(\\+|aft(er)?|from|hence)/":"^(\\+|aft(er)?|from|hence)","/^(\\-|bef(ore)?|ago)/":"^(\\-|bef(ore)?|ago)",
"/^yes(terday)?/":"^yes(terday)?","/^t(od(ay)?)?/":"^t(od(ay)?)?","/^tom(orrow)?/":"^tom(orrow)?","/^n(ow)?/":"^n(ow)?","/^ms|milli(second)?s?/":"^ms|milli(second)?s?","/^sec(ond)?s?/":"^sec(ond)?s?","/^mn|min(ute)?s?/":"^mn|min(ute)?s?","/^h(our)?s?/":"^h(our)?s?","/^w(eek)?s?/":"^w(eek)?s?","/^m(onth)?s?/":"^m(onth)?s?","/^d(ay)?s?/":"^d(ay)?s?","/^y(ear)?s?/":"^y(ear)?s?","/^(a|p)/":"^(a|p)","/^(a\\.?m?\\.?|p\\.?m?\\.?)/":"^(a\\.?m?\\.?|p\\.?m?\\.?)","/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/":"^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)",
"/^\\s*(st|nd|rd|th)/":"^\\s*(st|nd|rd|th)","/^\\s*(\\:|a(?!u|p)|p)/":"^\\s*(\\:|a(?!u|p)|p)",LINT:"LINT",TOT:"TOT",CHAST:"CHAST",NZST:"NZST",NFT:"NFT",SBT:"SBT",AEST:"AEST",ACST:"ACST",JST:"JST",CWST:"CWST",CT:"CT",ICT:"ICT",MMT:"MMT",BIOT:"BST",NPT:"NPT",IST:"IST",PKT:"PKT",AFT:"AFT",MSK:"MSK",IRST:"IRST",FET:"FET",EET:"EET",CET:"CET",UTC:"UTC",GMT:"GMT",CVT:"CVT",GST:"GST",BRT:"BRT",NST:"NST",AST:"AST",EST:"EST",CST:"CST",MST:"MST",PST:"PST",AKST:"AKST",MIT:"MIT",HST:"HST",SST:"SST",BIT:"BIT",
CHADT:"CHADT",NZDT:"NZDT",AEDT:"AEDT",ACDT:"ACDT",AZST:"AZST",IRDT:"IRDT",EEST:"EEST",CEST:"CEST",BST:"BST",PMDT:"PMDT",ADT:"ADT",NDT:"NDT",EDT:"EDT",CDT:"CDT",MDT:"MDT",PDT:"PDT",AKDT:"AKDT",HADT:"HADT"};Date.CultureStrings.lang="xh-ZA";
(function(){var g=Date,e=Date.CultureStrings?Date.CultureStrings.lang:null,b={},d={getFromKey:function(a,h){var k;k=Date.CultureStrings&&Date.CultureStrings[h]&&Date.CultureStrings[h][a]?Date.CultureStrings[h][a]:d.buildFromDefault(a);"/"===a.charAt(0)&&(k=d.buildFromRegex(a,h));return k},getFromObjectValues:function(a,h){var k,c={};for(k in a)a.hasOwnProperty(k)&&(c[k]=d.getFromKey(a[k],h));return c},getFromObjectKeys:function(a,h){var c,f={};for(c in a)a.hasOwnProperty(c)&&(f[d.getFromKey(c,h)]=
a[c]);return f},getFromArray:function(a,h){for(var c=[],f=0;f<a.length;f++)f in a&&(c[f]=d.getFromKey(a[f],h));return c},buildFromDefault:function(a){var h,c,f;switch(a){case "name":h="en-US";break;case "englishName":h="English (United States)";break;case "nativeName":h="English (United States)";break;case "twoDigitYearMax":h=2049;break;case "firstDayOfWeek":h=0;break;default:if(h=a,f=a.split("_"),c=f.length,1<c&&"/"!==a.charAt(0)&&(a=f[c-1].toLowerCase(),"initial"===a||"abbr"===a))h=f[0]}return h},
buildFromRegex:function(a,h){return Date.CultureStrings&&Date.CultureStrings[h]&&Date.CultureStrings[h][a]?RegExp(Date.CultureStrings[h][a],"i"):RegExp(a.replace(RegExp("/","g"),""),"i")}},a=function(a,h){var c=h?h:e;b[a]=a;return"object"===typeof a?a instanceof Array?d.getFromArray(a,c):d.getFromObjectKeys(a,c):d.getFromKey(a,c)},c=function(a){a=Date.Config.i18n+a+".js";var h=document.getElementsByTagName("head")[0]||document.documentElement,c=document.createElement("script");c.src=a;var f={done:function(){}};
c.onload=c.onreadystatechange=function(){this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(f.done(),h.removeChild(c))};setTimeout(function(){h.insertBefore(c,h.firstChild)},0);return{done:function(h){f.done=function(){h&&setTimeout(h,0)}}}},f={buildFromMethodHash:function(a){for(var h in a)a.hasOwnProperty(h)&&(a[h]=f[a[h]]());return a},timeZoneDST:function(){return a({CHADT:"+1345",NZDT:"+1300",AEDT:"+1100",ACDT:"+1030",AZST:"+0500",IRDT:"+0430",EEST:"+0300",CEST:"+0200",
BST:"+0100",PMDT:"-0200",ADT:"-0300",NDT:"-0230",EDT:"-0400",CDT:"-0500",MDT:"-0600",PDT:"-0700",AKDT:"-0800",HADT:"-0900"})},timeZoneStandard:function(){return a({LINT:"+1400",TOT:"+1300",CHAST:"+1245",NZST:"+1200",NFT:"+1130",SBT:"+1100",AEST:"+1000",ACST:"+0930",JST:"+0900",CWST:"+0845",CT:"+0800",ICT:"+0700",MMT:"+0630",BST:"+0600",NPT:"+0545",IST:"+0530",PKT:"+0500",AFT:"+0430",MSK:"+0400",IRST:"+0330",FET:"+0300",EET:"+0200",CET:"+0100",GMT:"+0000",UTC:"+0000",CVT:"-0100",GST:"-0200",BRT:"-0300",
NST:"-0330",AST:"-0400",EST:"-0500",CST:"-0600",MST:"-0700",PST:"-0800",AKST:"-0900",MIT:"-0930",HST:"-1000",SST:"-1100",BIT:"-1200"})},timeZones:function(a){var h;a.timezones=[];for(h in a.abbreviatedTimeZoneStandard)a.abbreviatedTimeZoneStandard.hasOwnProperty(h)&&a.timezones.push({name:h,offset:a.abbreviatedTimeZoneStandard[h]});for(h in a.abbreviatedTimeZoneDST)a.abbreviatedTimeZoneDST.hasOwnProperty(h)&&a.timezones.push({name:h,offset:a.abbreviatedTimeZoneDST[h],dst:!0});return a.timezones},
days:function(){return a("Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "))},dayAbbr:function(){return a("Sun Mon Tue Wed Thu Fri Sat".split(" "))},dayShortNames:function(){return a("Su Mo Tu We Th Fr Sa".split(" "))},dayFirstLetters:function(){return a("S_Sun_Initial M_Mon_Initial T_Tues_Initial W_Wed_Initial T_Thu_Initial F_Fri_Initial S_Sat_Initial".split(" "))},months:function(){return a("January February March April May June July August September October November December".split(" "))},
monthAbbr:function(){return a("Jan_Abbr Feb_Abbr Mar_Abbr Apr_Abbr May_Abbr Jun_Abbr Jul_Abbr Aug_Abbr Sep_Abbr Oct_Abbr Nov_Abbr Dec_Abbr".split(" "))},formatPatterns:function(){return d.getFromObjectValues({shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},
Date.i18n.currentLanguage())},regex:function(){return d.getFromObjectValues({inTheMorning:"/( in the )(morn(ing)?)\\b/",thisMorning:"/(this )(morn(ing)?)\\b/",amThisMorning:"/(\b\\d(am)? )(this )(morn(ing)?)/",inTheEvening:"/( in the )(even(ing)?)\\b/",thisEvening:"/(this )(even(ing)?)\\b/",pmThisEvening:"/(\b\\d(pm)? )(this )(even(ing)?)/",jan:"/jan(uary)?/",feb:"/feb(ruary)?/",mar:"/mar(ch)?/",apr:"/apr(il)?/",may:"/may/",jun:"/jun(e)?/",jul:"/jul(y)?/",aug:"/aug(ust)?/",sep:"/sep(t(ember)?)?/",
oct:"/oct(ober)?/",nov:"/nov(ember)?/",dec:"/dec(ember)?/",sun:"/^su(n(day)?)?/",mon:"/^mo(n(day)?)?/",tue:"/^tu(e(s(day)?)?)?/",wed:"/^we(d(nesday)?)?/",thu:"/^th(u(r(s(day)?)?)?)?/",fri:"/fr(i(day)?)?/",sat:"/^sa(t(urday)?)?/",future:"/^next/",past:"/^last|past|prev(ious)?/",add:"/^(\\+|aft(er)?|from|hence)/",subtract:"/^(\\-|bef(ore)?|ago)/",yesterday:"/^yes(terday)?/",today:"/^t(od(ay)?)?/",tomorrow:"/^tom(orrow)?/",now:"/^n(ow)?/",millisecond:"/^ms|milli(second)?s?/",second:"/^sec(ond)?s?/",
minute:"/^mn|min(ute)?s?/",hour:"/^h(our)?s?/",week:"/^w(eek)?s?/",month:"/^m(onth)?s?/",day:"/^d(ay)?s?/",year:"/^y(ear)?s?/",shortMeridian:"/^(a|p)/",longMeridian:"/^(a\\.?m?\\.?|p\\.?m?\\.?)/",timezone:"/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/",ordinalSuffix:"/^\\s*(st|nd|rd|th)/",timeContext:"/^\\s*(\\:|a(?!u|p)|p)/"},Date.i18n.currentLanguage())}},l=function(){var a=d.getFromObjectValues({name:"name",englishName:"englishName",nativeName:"nativeName",
amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:"firstDayOfWeek",twoDigitYearMax:"twoDigitYearMax",dateElementOrder:"mdy"},Date.i18n.currentLanguage()),h=f.buildFromMethodHash({dayNames:"days",abbreviatedDayNames:"dayAbbr",shortestDayNames:"dayShortNames",firstLetterDayNames:"dayFirstLetters",monthNames:"months",abbreviatedMonthNames:"monthAbbr",formatPatterns:"formatPatterns",regexPatterns:"regex",abbreviatedTimeZoneDST:"timeZoneDST",abbreviatedTimeZoneStandard:"timeZoneStandard"}),c;for(c in h)h.hasOwnProperty(c)&&
(a[c]=h[c]);f.timeZones(a);return a};g.i18n={__:function(c,h){return a(c,h)},currentLanguage:function(){return e||"en-US"},setLanguage:function(a,h,f){var d=!1;if(h||"en-US"===a||Date.CultureStrings&&Date.CultureStrings[a])e=a,Date.CultureStrings=Date.CultureStrings||{},Date.CultureStrings.lang=a,Date.CultureInfo=new l;else if(!Date.CultureStrings||!Date.CultureStrings[a])if("undefined"!==typeof exports&&this.exports!==exports)try{require("../i18n/"+a+".js"),e=a,Date.CultureStrings.lang=a,Date.CultureInfo=
new l}catch(b){throw Error("The DateJS IETF language tag '"+a+"' could not be loaded by Node. It likely does not exist.");}else Date.Config&&Date.Config.i18n?(d=!0,c(a).done(function(){e=a;Date.CultureStrings=Date.CultureStrings||{};Date.CultureStrings.lang=a;Date.CultureInfo=new l;g.Parsing.Normalizer.buildReplaceData();g.Grammar&&g.Grammar.buildGrammarFormats();f&&setTimeout(f,0)})):Date.console.error("The DateJS IETF language tag '"+a+"' is not available and has not been loaded.");g.Parsing.Normalizer.buildReplaceData();
g.Grammar&&g.Grammar.buildGrammarFormats();!d&&f&&setTimeout(f,0)},getLoggedKeys:function(){return b},updateCultureInfo:function(){Date.CultureInfo=new l}};g.i18n.updateCultureInfo()})();
(function(){var g=Date,e=g.prototype,b=function(a,c){c||(c=2);return("000"+a).slice(-1*c)};g.console="undefined"!==typeof window&&"undefined"!==typeof window.console&&"undefined"!==typeof window.console.log?console:{log:function(){},error:function(){}};g.Config=g.Config||{};g.initOverloads=function(){g.now?g._now||(g._now=g.now):g._now=function(){return(new Date).getTime()};g.now=function(a){return a?g.present():g._now()};e.toISOString||(e.toISOString=function(){return this.getUTCFullYear()+"-"+b(this.getUTCMonth()+
1)+"-"+b(this.getUTCDate())+"T"+b(this.getUTCHours())+":"+b(this.getUTCMinutes())+":"+b(this.getUTCSeconds())+"."+String((this.getUTCMilliseconds()/1E3).toFixed(3)).slice(2,5)+"Z"});void 0===e._toString&&(e._toString=e.toString)};g.initOverloads();e.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this};e.setTimeToNow=function(){var a=new Date;this.setHours(a.getHours());this.setMinutes(a.getMinutes());this.setSeconds(a.getSeconds());this.setMilliseconds(a.getMilliseconds());
return this};g.today=function(){return(new Date).clearTime()};g.present=function(){return new Date};g.compare=function(a,c){if(isNaN(a)||isNaN(c))throw Error(a+" - "+c);if(a instanceof Date&&c instanceof Date)return a<c?-1:a>c?1:0;throw new TypeError(a+" - "+c);};g.equals=function(a,c){return 0===a.compareTo(c)};g.getDayName=function(a){return Date.CultureInfo.dayNames[a]};g.getDayNumberFromName=function(a){var c=Date.CultureInfo.dayNames,f=Date.CultureInfo.abbreviatedDayNames,d=Date.CultureInfo.shortestDayNames;
a=a.toLowerCase();for(var b=0;b<c.length;b++)if(c[b].toLowerCase()===a||f[b].toLowerCase()===a||d[b].toLowerCase()===a)return b;return-1};g.getMonthNumberFromName=function(a){var c=Date.CultureInfo.monthNames,f=Date.CultureInfo.abbreviatedMonthNames;a=a.toLowerCase();for(var b=0;b<c.length;b++)if(c[b].toLowerCase()===a||f[b].toLowerCase()===a)return b;return-1};g.getMonthName=function(a){return Date.CultureInfo.monthNames[a]};g.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};g.getDaysInMonth=
function(a,c){!c&&g.validateMonth(a)&&(c=a,a=Date.today().getFullYear());return[31,g.isLeapYear(a)?29:28,31,30,31,30,31,31,30,31,30,31][c]};e.getDaysInMonth=function(){return g.getDaysInMonth(this.getFullYear(),this.getMonth())};g.getTimezoneAbbreviation=function(a,c){var f,b=c?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard;for(f in b)if(b.hasOwnProperty(f)&&b[f]===a)return f;return null};g.getTimezoneOffset=function(a,c){var f,b=[],d=Date.CultureInfo.timezones;
a||(a=(new Date).getTimezone());for(f=0;f<d.length;f++)d[f].name===a.toUpperCase()&&b.push(f);if(!d[b[0]])return null;if(1!==b.length&&c)for(f=0;f<b.length;f++){if(d[b[f]].dst)return d[b[f]].offset}else return d[b[0]].offset};g.getQuarter=function(a){a=a||new Date;return[1,2,3,4][Math.floor(a.getMonth()/3)]};g.getDaysLeftInQuarter=function(a){a=a||new Date;var c=new Date(a);c.setMonth(c.getMonth()+3-c.getMonth()%3,0);return Math.floor((c-a)/864E5)};e.clone=function(){return new Date(this.getTime())};
e.compareTo=function(a){return Date.compare(this,a)};e.equals=function(a){return Date.equals(this,void 0!==a?a:new Date)};e.between=function(a,c){return this.getTime()>=a.getTime()&&this.getTime()<=c.getTime()};e.isAfter=function(a){return 1===this.compareTo(a||new Date)};e.isBefore=function(a){return-1===this.compareTo(a||new Date)};e.isToday=e.isSameDay=function(a){return this.clone().clearTime().equals((a||new Date).clone().clearTime())};e.addMilliseconds=function(a){if(!a)return this;this.setTime(this.getTime()+
1*a);return this};e.addSeconds=function(a){return a?this.addMilliseconds(1E3*a):this};e.addMinutes=function(a){return a?this.addMilliseconds(6E4*a):this};e.addHours=function(a){return a?this.addMilliseconds(36E5*a):this};e.addDays=function(a){if(!a)return this;this.setDate(this.getDate()+1*a);return this};e.addWeekdays=function(a){if(!a)return this;var c=this.getDay(),f=Math.ceil(Math.abs(a)/7);(0===c||6===c)&&0<a&&(this.next().monday(),this.addDays(-1));if(0>a){for(;0>a;)this.addDays(-1),c=this.getDay(),
0!==c&&6!==c&&a++;return this}if(5<a||6-c<=a)a+=2*f;return this.addDays(a)};e.addWeeks=function(a){return a?this.addDays(7*a):this};e.addMonths=function(a){if(!a)return this;var c=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+1*a);this.setDate(Math.min(c,g.getDaysInMonth(this.getFullYear(),this.getMonth())));return this};e.addQuarters=function(a){return a?this.addMonths(3*a):this};e.addYears=function(a){return a?this.addMonths(12*a):this};e.add=function(a){if("number"===typeof a)return this._orient=
a,this;a.day&&0!==a.day-this.getDate()&&this.setDate(a.day);a.milliseconds&&this.addMilliseconds(a.milliseconds);a.seconds&&this.addSeconds(a.seconds);a.minutes&&this.addMinutes(a.minutes);a.hours&&this.addHours(a.hours);a.weeks&&this.addWeeks(a.weeks);a.months&&this.addMonths(a.months);a.years&&this.addYears(a.years);a.days&&this.addDays(a.days);return this};e.getWeek=function(a){var c=new Date(this.valueOf());a?(c.addMinutes(c.getTimezoneOffset()),a=c.clone()):a=this;a=(a.getDay()+6)%7;c.setDate(c.getDate()-
a+3);a=c.valueOf();c.setMonth(0,1);4!==c.getDay()&&c.setMonth(0,1+(4-c.getDay()+7)%7);return 1+Math.ceil((a-c)/6048E5)};e.getISOWeek=function(){return b(this.getWeek(!0))};e.setWeek=function(a){return 0===a-this.getWeek()?1!==this.getDay()?this.moveToDayOfWeek(1,1<this.getDay()?-1:1):this:this.moveToDayOfWeek(1,1<this.getDay()?-1:1).addWeeks(a-this.getWeek())};e.setQuarter=function(a){a=Math.abs(3*(a-1)+1);return this.setMonth(a,1)};e.getQuarter=function(){return Date.getQuarter(this)};e.getDaysLeftInQuarter=
function(){return Date.getDaysLeftInQuarter(this)};var d=function(a,c,f,b){if("undefined"===typeof a)return!1;if("number"!==typeof a)throw new TypeError(a+" is not a Number.");return a<c||a>f?!1:!0};g.validateMillisecond=function(a){return d(a,0,999,"millisecond")};g.validateSecond=function(a){return d(a,0,59,"second")};g.validateMinute=function(a){return d(a,0,59,"minute")};g.validateHour=function(a){return d(a,0,23,"hour")};g.validateDay=function(a,c,f){return void 0===c||null===c||void 0===f||
null===f?!1:d(a,1,g.getDaysInMonth(c,f),"day")};g.validateWeek=function(a){return d(a,0,53,"week")};g.validateMonth=function(a){return d(a,0,11,"month")};g.validateYear=function(a){return d(a,-271822,275760,"year")};g.validateTimezone=function(a){return 1==={ACDT:1,ACST:1,ACT:1,ADT:1,AEDT:1,AEST:1,AFT:1,AKDT:1,AKST:1,AMST:1,AMT:1,ART:1,AST:1,AWDT:1,AWST:1,AZOST:1,AZT:1,BDT:1,BIOT:1,BIT:1,BOT:1,BRT:1,BST:1,BTT:1,CAT:1,CCT:1,CDT:1,CEDT:1,CEST:1,CET:1,CHADT:1,CHAST:1,CHOT:1,ChST:1,CHUT:1,CIST:1,CIT:1,
CKT:1,CLST:1,CLT:1,COST:1,COT:1,CST:1,CT:1,CVT:1,CWST:1,CXT:1,DAVT:1,DDUT:1,DFT:1,EASST:1,EAST:1,EAT:1,ECT:1,EDT:1,EEDT:1,EEST:1,EET:1,EGST:1,EGT:1,EIT:1,EST:1,FET:1,FJT:1,FKST:1,FKT:1,FNT:1,GALT:1,GAMT:1,GET:1,GFT:1,GILT:1,GIT:1,GMT:1,GST:1,GYT:1,HADT:1,HAEC:1,HAST:1,HKT:1,HMT:1,HOVT:1,HST:1,ICT:1,IDT:1,IOT:1,IRDT:1,IRKT:1,IRST:1,IST:1,JST:1,KGT:1,KOST:1,KRAT:1,KST:1,LHST:1,LINT:1,MAGT:1,MART:1,MAWT:1,MDT:1,MET:1,MEST:1,MHT:1,MIST:1,MIT:1,MMT:1,MSK:1,MST:1,MUT:1,MVT:1,MYT:1,NCT:1,NDT:1,NFT:1,NPT:1,
NST:1,NT:1,NUT:1,NZDT:1,NZST:1,OMST:1,ORAT:1,PDT:1,PET:1,PETT:1,PGT:1,PHOT:1,PHT:1,PKT:1,PMDT:1,PMST:1,PONT:1,PST:1,PYST:1,PYT:1,RET:1,ROTT:1,SAKT:1,SAMT:1,SAST:1,SBT:1,SCT:1,SGT:1,SLST:1,SRT:1,SST:1,SYOT:1,TAHT:1,THA:1,TFT:1,TJT:1,TKT:1,TLT:1,TMT:1,TOT:1,TVT:1,UCT:1,ULAT:1,UTC:1,UYST:1,UYT:1,UZT:1,VET:1,VLAT:1,VOLT:1,VOST:1,VUT:1,WAKT:1,WAST:1,WAT:1,WEDT:1,WEST:1,WET:1,WST:1,YAKT:1,YEKT:1,Z:1}[a]};g.validateTimezoneOffset=function(a){return-841<a&&721>a};var a=function(a){var c={},f=this,b,d;d=function(c,
b,d){if("day"===c){c=void 0!==a.month?a.month-f.getMonth():f.getMonth();var e=void 0!==a.year?a.year-f.getFullYear():f.getFullYear();return g[b](d,e,c)}return g[b](d)};for(b in a)if(hasOwnProperty.call(a,b)){var e="validate"+b.charAt(0).toUpperCase()+b.slice(1);g[e]&&null!==a[b]&&d(b,e,a[b])&&(c[b]=a[b])}return c};e.set=function(c){c=a.call(this,c);for(var f in c)if(hasOwnProperty.call(c,f)){var b=f.charAt(0).toUpperCase()+f.slice(1),d,e;"week"!==f&&"month"!==f&&"timezone"!==f&&"timezoneOffset"!==
f&&(b+="s");d="add"+b;e="get"+b;"month"===f?d+="s":"year"===f&&(e="getFullYear");if("day"!==f&&"timezone"!==f&&"timezoneOffset"!==f&&"week"!==f)this[d](c[f]-this[e]());else if("timezone"===f||"timezoneOffset"===f||"week"===f)this["set"+b](c[f])}c.day&&this.addDays(c.day-this.getDate());return this};e.moveToFirstDayOfMonth=function(){return this.set({day:1})};e.moveToLastDayOfMonth=function(){return this.set({day:g.getDaysInMonth(this.getFullYear(),this.getMonth())})};e.moveToNthOccurrence=function(a,
c){if("Weekday"===a){if(0<c)this.moveToFirstDayOfMonth(),this.is().weekday()&&(c-=1);else if(0>c)this.moveToLastDayOfMonth(),this.is().weekday()&&(c+=1);else return this;return this.addWeekdays(c)}var f=0;if(0<c)f=c-1;else if(-1===c)return this.moveToLastDayOfMonth(),this.getDay()!==a&&this.moveToDayOfWeek(a,-1),this;return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(a,1).addWeeks(f)};var c=function(a,c,f){return function(b,d){var e=(b-this[a]()+f*(d||1))%f;return this[c](0===e?e+f*(d||
1):e)}};e.moveToDayOfWeek=c("getDay","addDays",7);e.moveToMonth=c("getMonth","addMonths",12);e.getOrdinate=function(){var a=this.getDate();return f(a)};e.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/864E5)+1};e.getTimezone=function(){return g.getTimezoneAbbreviation(this.getUTCOffset(),this.isDaylightSavingTime())};e.setTimezoneOffset=function(a){var c=this.getTimezoneOffset();return(a=-6*Number(a)/10)||0===a?this.addMinutes(a-c):this};e.setTimezone=
function(a){return this.setTimezoneOffset(g.getTimezoneOffset(a))};e.hasDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset()};e.isDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==this.getTimezoneOffset()};e.getUTCOffset=function(a){a=-10*(a||this.getTimezoneOffset())/6;if(0>a)return a=(a-1E4).toString(),a.charAt(0)+a.substr(2);a=(a+1E4).toString();return"+"+a.substr(1)};
e.getElapsed=function(a){return(a||new Date)-this};var f=function(a){switch(1*a){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},l=function(a){var c=Date.CultureInfo.formatPatterns;switch(a){case "d":return this.toString(c.shortDate);case "D":return this.toString(c.longDate);case "F":return this.toString(c.fullDateTime);case "m":return this.toString(c.monthDay);case "r":case "R":return a=this.clone().addMinutes(this.getTimezoneOffset()),a.toString(c.rfc1123)+
" GMT";case "s":return this.toString(c.sortableDateTime);case "t":return this.toString(c.shortTime);case "T":return this.toString(c.longTime);case "u":return a=this.clone().addMinutes(this.getTimezoneOffset()),a.toString(c.universalSortableDateTime);case "y":return this.toString(c.yearMonth);default:return!1}},m=function(a){return function(c){if("\\"===c.charAt(0))return c.replace("\\","");switch(c){case "hh":return b(13>a.getHours()?0===a.getHours()?12:a.getHours():a.getHours()-12);case "h":return 13>
a.getHours()?0===a.getHours()?12:a.getHours():a.getHours()-12;case "HH":return b(a.getHours());case "H":return a.getHours();case "mm":return b(a.getMinutes());case "m":return a.getMinutes();case "ss":return b(a.getSeconds());case "s":return a.getSeconds();case "yyyy":return b(a.getFullYear(),4);case "yy":return b(a.getFullYear());case "y":return a.getFullYear();case "dddd":return Date.CultureInfo.dayNames[a.getDay()];case "ddd":return Date.CultureInfo.abbreviatedDayNames[a.getDay()];case "dd":return b(a.getDate());
case "d":return a.getDate();case "MMMM":return Date.CultureInfo.monthNames[a.getMonth()];case "MMM":return Date.CultureInfo.abbreviatedMonthNames[a.getMonth()];case "MM":return b(a.getMonth()+1);case "M":return a.getMonth()+1;case "t":return 12>a.getHours()?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case "tt":return 12>a.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case "S":return f(a.getDate());case "W":return a.getWeek();case "WW":return a.getISOWeek();
case "Q":return"Q"+a.getQuarter();case "q":return String(a.getQuarter());default:return c}}};e.toString=function(a,c){if(!c&&a&&1===a.length&&(output=l.call(this,a)))return output;var f=m(this);return a?a.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g,f).replace(/\[|\]/g,""):this._toString()}})();
(function(){var g=Date,e=g.prototype,b=Number.prototype;e._orient=1;e._nth=null;e._is=!1;e._same=!1;e._isSecond=!1;b._dateElement="days";e.next=function(){this._move=!0;this._orient=1;return this};g.next=function(){return g.today().next()};e.last=e.prev=e.previous=function(){this._move=!0;this._orient=-1;return this};g.last=g.prev=g.previous=function(){return g.today().last()};e.is=function(){this._is=!0;return this};e.same=function(){this._same=!0;this._isSecond=!1;return this};e.today=function(){return this.same().day()};
e.weekday=function(){return this._nth?m("Weekday").call(this):this._move?this.addWeekdays(this._orient):this._is?(this._is=!1,!this.is().sat()&&!this.is().sun()):!1};e.weekend=function(){return this._is?(this._is=!1,this.is().sat()||this.is().sun()):!1};e.at=function(a){return"string"===typeof a?g.parse(this.toString("d")+" "+a):this.set(a)};b.fromNow=b.after=function(a){var c={};c[this._dateElement]=this;return(a?a.clone():new Date).add(c)};b.ago=b.before=function(a){var c={};c["s"!==this._dateElement[this._dateElement.length-
1]?this._dateElement+"s":this._dateElement]=-1*this;return(a?a.clone():new Date).add(c)};var d="sunday monday tuesday wednesday thursday friday saturday".split(/\s/),a="january february march april may june july august september october november december".split(/\s/),c="Millisecond Second Minute Hour Day Week Month Year Quarter Weekday".split(/\s/),f="Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter".split(/\s/),l="final first second third fourth fifth".split(/\s/);e.toObject=function(){for(var a=
{},b=0;b<c.length;b++)this["get"+f[b]]&&(a[c[b].toLowerCase()]=this["get"+f[b]]());return a};g.fromObject=function(a){a.week=null;return Date.today().set(a)};var m=function(a){return function(){if(this._is)return this._is=!1,this.getDay()===a;this._move&&(this._move=null);if(null!==this._nth){this._isSecond&&this.addSeconds(-1*this._orient);this._isSecond=!1;var c=this._nth;this._nth=null;var f=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(a,c);if(this>f)throw new RangeError(g.getDayName(a)+
" does not occur "+c+" times in the month of "+g.getMonthName(f.getMonth())+" "+f.getFullYear()+".");return this}return this.moveToDayOfWeek(a,this._orient)}},h=function(a,c,f){for(var b=0;b<a.length;b++)g[a[b].toUpperCase()]=g[a[b].toUpperCase().substring(0,3)]=b,g[a[b]]=g[a[b].substring(0,3)]=c(b),e[a[b]]=e[a[b].substring(0,3)]=f(b)};h(d,function(a){return function(){var c=g.today(),f=a-c.getDay();0===a&&1===Date.CultureInfo.firstDayOfWeek&&0!==c.getDay()&&(f+=7);return c.addDays(f)}},m);h(a,function(a){return function(){return g.today().set({month:a,
day:1})}},function(a){return function(){return this._is?(this._is=!1,this.getMonth()===a):this.moveToMonth(a,this._orient)}});for(var a=function(a){return function(f){if(this._isSecond)return this._isSecond=!1,this;if(this._same){this._same=this._is=!1;var b=this.toObject();f=(f||new Date).toObject();for(var d="",e=a.toLowerCase(),e="s"===e[e.length-1]?e.substring(0,e.length-1):e,l=c.length-1;-1<l;l--){d=c[l].toLowerCase();if(b[d]!==f[d])return!1;if(e===d)break}return!0}"s"!==a.substring(a.length-
1)&&(a+="s");this._move&&(this._move=null);return this["add"+a](this._orient)}},h=function(a){return function(){this._dateElement=a;return this}},k=0;k<c.length;k++)d=c[k].toLowerCase(),"weekday"!==d&&(e[d]=e[d+"s"]=a(c[k]),b[d]=b[d+"s"]=h(d+"s"));e._ss=a("Second");b=function(a){return function(c){if(this._same)return this._ss(c);if(c||0===c)return this.moveToNthOccurrence(c,a);this._nth=a;return 2!==a||void 0!==c&&null!==c?this:(this._isSecond=!0,this.addSeconds(this._orient))}};for(d=0;d<l.length;d++)e[l[d]]=
0===d?b(-1):b(d)})();
(function(){Date.Parsing={Exception:function(a){this.message="Parse error at '"+a.substring(0,10)+" ...'"}};var g=Date.Parsing,e=[0,31,59,90,120,151,181,212,243,273,304,334],b=[0,31,60,91,121,152,182,213,244,274,305,335];g.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};var d={multiReplace:function(a,c){for(var f in c)if(Object.prototype.hasOwnProperty.call(c,f)){var b;"function"!==typeof c[f]&&(b=c[f]instanceof RegExp?c[f]:RegExp(c[f],"g"));a=a.replace(b,f)}return a},getDayOfYearFromWeek:function(a){var c;
a.weekDay=a.weekDay||0===a.weekDay?a.weekDay:1;c=new Date(a.year,0,4);c=(0===c.getDay()?7:c.getDay())+3;a.dayOfYear=7*a.week+(0===a.weekDay?7:a.weekDay)-c;return a},getDayOfYear:function(a,c){a.dayOfYear||(a=d.getDayOfYearFromWeek(a));for(var f=0;f<=c.length;f++)if(a.dayOfYear<c[f]||f===c.length){a.day=a.day?a.day:a.dayOfYear-c[f-1];break}else a.month=f;return a},adjustForTimeZone:function(a,c){var f;"Z"===a.zone.toUpperCase()||0===a.zone_hours&&0===a.zone_minutes?f=-c.getTimezoneOffset():(f=60*a.zone_hours+
(a.zone_minutes||0),"+"===a.zone_sign&&(f*=-1),f-=c.getTimezoneOffset());c.setMinutes(c.getMinutes()+f);return c},setDefaults:function(a){a.year=a.year||Date.today().getFullYear();a.hours=a.hours||0;a.minutes=a.minutes||0;a.seconds=a.seconds||0;a.milliseconds=a.milliseconds||0;if(a.month||!a.week&&!a.dayOfYear)a.month=a.month||0,a.day=a.day||1;return a},dataNum:function(a,c,f,b){var d=1*a;return c?b?a?1*c(a):a:a?c(d):a:f?a&&"undefined"!==typeof a?d:a:a?d:a},timeDataProcess:function(a){var c={},f;
for(f in a.data)a.data.hasOwnProperty(f)&&(c[f]=a.ignore[f]?a.data[f]:d.dataNum(a.data[f],a.mods[f],a.explict[f],a.postProcess[f]));a.data.secmins&&(a.data.secmins=60*a.data.secmins.replace(",","."),c.minutes?c.seconds||(c.seconds=a.data.secmins):c.minutes=a.data.secmins,delete a.secmins);return c},buildTimeObjectFromData:function(a){return d.timeDataProcess({data:{year:a[1],month:a[5],day:a[7],week:a[8],dayOfYear:a[10],hours:a[15],zone_hours:a[23],zone_minutes:a[24],zone:a[21],zone_sign:a[22],weekDay:a[9],
minutes:a[16],seconds:a[19],milliseconds:a[20],secmins:a[18]},mods:{month:function(a){return a-1},weekDay:function(a){a=Math.abs(a);return 7===a?0:a},minutes:function(a){return a.replace(":","")},seconds:function(a){return Math.floor(1*a.replace(":","").replace(",","."))},milliseconds:function(a){return 1E3*a.replace(",",".")}},postProcess:{minutes:!0,seconds:!0,milliseconds:!0},explict:{zone_hours:!0,zone_minutes:!0},ignore:{zone:!0,zone_sign:!0,secmins:!0}})},addToHash:function(a,c,f){for(var b=
c.length,d=0;d<b;d++)a[c[d]]=f[d];return a},combineRegex:function(a,c){return RegExp("(("+a.source+")\\s("+c.source+"))")},getDateNthString:function(a,c,f){if(a)return Date.today().addDays(f).toString("d");if(c)return Date.today().last()[f]().toString("d")},buildRegexData:function(a){for(var c=[],f=a.length,b=0;b<f;b++)Array.isArray(a[b])?c.push(this.combineRegex(a[b][0],a[b][1])):c.push(a[b]);return c}};g.processTimeObject=function(a){var c;d.setDefaults(a);c=g.isLeapYear(a.year)?b:e;a.month||!a.week&&
!a.dayOfYear?a.dayOfYear=c[a.month]+a.day:d.getDayOfYear(a,c);c=new Date(a.year,a.month,a.day,a.hours,a.minutes,a.seconds,a.milliseconds);a.zone&&d.adjustForTimeZone(a,c);return c};g.ISO={regex:/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,parse:function(a){a=
a.match(this.regex);if(!a||!a.length)return null;a=d.buildTimeObjectFromData(a);return a.year&&(a.year||a.month||a.day||a.week||a.dayOfYear)?g.processTimeObject(a):null}};g.Numeric={isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},regex:/\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i,parse:function(a){var c,f={},b=Date.CultureInfo.dateElementOrder.split("");if(!this.isNumeric(a)||"+"===a[0]&&"-"===a[0])return null;if(5>a.length)return f.year=a,g.processTimeObject(f);a=a.match(this.regex);
if(!a||!a.length)return null;for(c=0;c<b.length;c++)switch(b[c]){case "d":f.day=a[c+1];break;case "m":f.month=a[c+1]-1;break;case "y":f.year=a[c+1]}return g.processTimeObject(f)}};g.Normalizer={regexData:function(){var a=Date.CultureInfo.regexPatterns;return d.buildRegexData([a.tomorrow,a.yesterday,[a.past,a.mon],[a.past,a.tue],[a.past,a.wed],[a.past,a.thu],[a.past,a.fri],[a.past,a.sat],[a.past,a.sun]])},basicReplaceHash:function(){var a=Date.CultureInfo.regexPatterns;return{January:a.jan.source,
February:a.feb,March:a.mar,April:a.apr,May:a.may,June:a.jun,July:a.jul,August:a.aug,September:a.sep,October:a.oct,November:a.nov,December:a.dec,"":/\bat\b/gi," ":/\s{2,}/,am:a.inTheMorning,"9am":a.thisMorning,pm:a.inTheEvening,"7pm":a.thisEvening}},keys:function(){return[d.getDateNthString(!0,!1,1),d.getDateNthString(!0,!1,-1),d.getDateNthString(!1,!0,"monday"),d.getDateNthString(!1,!0,"tuesday"),d.getDateNthString(!1,!0,"wednesday"),d.getDateNthString(!1,!0,"thursday"),d.getDateNthString(!1,!0,"friday"),
d.getDateNthString(!1,!0,"saturday"),d.getDateNthString(!1,!0,"sunday")]},buildRegexFunctions:function(){var a=Date.CultureInfo.regexPatterns,c=Date.i18n.__;this.replaceFuncs=[[RegExp("(\\b\\d\\d?("+c("AM")+"|"+c("PM")+")? )("+a.tomorrow.source.slice(1)+")","i"),function(a,c){return Date.today().addDays(1).toString("d")+" "+c}],[a.amThisMorning,function(a,c){return c}],[a.pmThisEvening,function(a,c){return c}]]},buildReplaceData:function(){this.buildRegexFunctions();this.replaceHash=d.addToHash(this.basicReplaceHash(),
this.keys(),this.regexData())},stringReplaceFuncs:function(a){for(var c=0;c<this.replaceFuncs.length;c++)a=a.replace(this.replaceFuncs[c][0],this.replaceFuncs[c][1]);return a},parse:function(a){a=this.stringReplaceFuncs(a);a=d.multiReplace(a,this.replaceHash);try{var c=a.split(/([\s\-\.\,\/\x27]+)/);3===c.length&&g.Numeric.isNumeric(c[0])&&g.Numeric.isNumeric(c[2])&&4<=c[2].length&&"d"===Date.CultureInfo.dateElementOrder[0]&&(a="1/"+c[0]+"/"+c[2])}catch(f){}return a}};g.Normalizer.buildReplaceData()})();
(function(){for(var g=Date.Parsing,e=g.Operators={rtoken:function(a){return function(f){var b=f.match(a);if(b)return[b[0],f.substring(b[0].length)];throw new g.Exception(f);}},token:function(){return function(a){return e.rtoken(RegExp("^\\s*"+a+"\\s*"))(a)}},stoken:function(a){return e.rtoken(RegExp("^"+a))},until:function(a){return function(f){for(var b=[],d=null;f.length;){try{d=a.call(this,f)}catch(e){b.push(d[0]);f=d[1];continue}break}return[b,f]}},many:function(a){return function(f){for(var b=
[],d=null;f.length;){try{d=a.call(this,f)}catch(e){break}b.push(d[0]);f=d[1]}return[b,f]}},optional:function(a){return function(f){var b=null;try{b=a.call(this,f)}catch(d){return[null,f]}return[b[0],b[1]]}},not:function(a){return function(f){try{a.call(this,f)}catch(b){return[null,f]}throw new g.Exception(f);}},ignore:function(a){return a?function(b){var d=null,d=a.call(this,b);return[null,d[1]]}:null},product:function(){for(var a=arguments[0],b=Array.prototype.slice.call(arguments,1),d=[],g=0;g<
a.length;g++)d.push(e.each(a[g],b));return d},cache:function(a){var b={},d=null;return function(e){try{d=b[e]=b[e]||a.call(this,e)}catch(h){d=b[e]=h}if(d instanceof g.Exception)throw d;return d}},any:function(){var a=arguments;return function(b){for(var d=null,e=0;e<a.length;e++)if(null!=a[e]){try{d=a[e].call(this,b)}catch(h){d=null}if(d)return d}throw new g.Exception(b);}},each:function(){var a=arguments;return function(b){for(var d=[],e=null,h=0;h<a.length;h++)if(null!=a[h]){try{e=a[h].call(this,
b)}catch(k){throw new g.Exception(b);}d.push(e[0]);b=e[1]}return[d,b]}},all:function(){var a=a;return a.each(a.optional(arguments))},sequence:function(a,b,d){b=b||e.rtoken(/^\s*/);d=d||null;return 1===a.length?a[0]:function(e){for(var h=null,k=null,n=[],p=0;p<a.length;p++){try{h=a[p].call(this,e)}catch(q){break}n.push(h[0]);try{k=b.call(this,h[1])}catch(s){k=null;break}e=k[1]}if(!h)throw new g.Exception(e);if(k)throw new g.Exception(k[1]);if(d)try{h=d.call(this,h[1])}catch(t){throw new g.Exception(h[1]);
}return[n,h?h[1]:e]}},between:function(a,b,d){d=d||a;var g=e.each(e.ignore(a),b,e.ignore(d));return function(a){a=g.call(this,a);return[[a[0][0],r[0][2]],a[1]]}},list:function(a,b,d){b=b||e.rtoken(/^\s*/);d=d||null;return a instanceof Array?e.each(e.product(a.slice(0,-1),e.ignore(b)),a.slice(-1),e.ignore(d)):e.each(e.many(e.each(a,e.ignore(b))),px,e.ignore(d))},set:function(a,b,d){b=b||e.rtoken(/^\s*/);d=d||null;return function(m){for(var h=null,k=h=null,n=null,p=[[],m],q=!1,s=0;s<a.length;s++){h=
k=null;q=1===a.length;try{h=a[s].call(this,m)}catch(t){continue}n=[[h[0]],h[1]];if(0<h[1].length&&!q)try{k=b.call(this,h[1])}catch(u){q=!0}else q=!0;q||0!==k[1].length||(q=!0);if(!q){h=[];for(q=0;q<a.length;q++)s!==q&&h.push(a[q]);h=e.set(h,b).call(this,k[1]);0<h[0].length&&(n[0]=n[0].concat(h[0]),n[1]=h[1])}n[1].length<p[1].length&&(p=n);if(0===p[1].length)break}if(0===p[0].length)return p;if(d){try{k=d.call(this,p[1])}catch(v){throw new g.Exception(p[1]);}p[1]=k[1]}return p}},forward:function(a,
b){return function(d){return a[b].call(this,d)}},replace:function(a,b){return function(d){d=a.call(this,d);return[b,d[1]]}},process:function(a,b){return function(d){d=a.call(this,d);return[b.call(this,d[0]),d[1]]}},min:function(a,b){return function(d){var e=b.call(this,d);if(e[0].length<a)throw new g.Exception(d);return e}}},b=function(a){return function(){var b=null,d=[],e;1<arguments.length?b=Array.prototype.slice.call(arguments):arguments[0]instanceof Array&&(b=arguments[0]);if(b){if(e=b.shift(),
0<e.length)return b.unshift(e[void 0]),d.push(a.apply(null,b)),b.shift(),d}else return a.apply(null,arguments)}},d="optional not ignore cache".split(/\s/),a=0;a<d.length;a++)e[d[a]]=b(e[d[a]]);b=function(a){return function(){return arguments[0]instanceof Array?a.apply(null,arguments[0]):a.apply(null,arguments)}};d="each any all".split(/\s/);for(a=0;a<d.length;a++)e[d[a]]=b(e[d[a]])})();
(function(){var g=Date,e=function(b){for(var a=[],c=0;c<b.length;c++)b[c]instanceof Array?a=a.concat(e(b[c])):b[c]&&a.push(b[c]);return a},b=function(){if(this.meridian&&(this.hour||0===this.hour)){if("a"===this.meridian&&11<this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";if("p"===this.meridian&&12>this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";"p"===this.meridian&&12>this.hour?this.hour+=12:"a"===this.meridian&&12===this.hour&&(this.hour=
0)}};g.Translator={hour:function(b){return function(){this.hour=Number(b)}},minute:function(b){return function(){this.minute=Number(b)}},second:function(b){return function(){this.second=Number(b)}},secondAndMillisecond:function(b){return function(){var a=b.match(/^([0-5][0-9])\.([0-9]{1,3})/);this.second=Number(a[1]);this.millisecond=Number(a[2])}},meridian:function(b){return function(){this.meridian=b.slice(0,1).toLowerCase()}},timezone:function(b){return function(){var a=b.replace(/[^\d\+\-]/g,
"");a.length?this.timezoneOffset=Number(a):this.timezone=b.toLowerCase()}},day:function(b){var a=b[0];return function(){this.day=Number(a.match(/\d+/)[0]);if(1>this.day)throw"invalid day";}},month:function(b){return function(){this.month=3===b.length?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(b)/4:Number(b)-1;if(0>this.month)throw"invalid month";}},year:function(b){return function(){var a=Number(b);this.year=2<b.length?a:a+(a+2E3<Date.CultureInfo.twoDigitYearMax?2E3:1900)}},rday:function(b){return function(){switch(b){case "yesterday":this.days=
-1;break;case "tomorrow":this.days=1;break;case "today":this.days=0;break;case "now":this.days=0,this.now=!0}}},finishExact:function(d){d=d instanceof Array?d:[d];for(var a=0;a<d.length;a++)d[a]&&d[a].call(this);d=new Date;!this.hour&&!this.minute||this.month||this.year||this.day||(this.day=d.getDate());this.year||(this.year=d.getFullYear());this.month||0===this.month||(this.month=d.getMonth());this.day||(this.day=1);this.hour||(this.hour=0);this.minute||(this.minute=0);this.second||(this.second=
0);this.millisecond||(this.millisecond=0);b.call(this);if(this.day>g.getDaysInMonth(this.year,this.month))throw new RangeError(this.day+" is not a valid value for days.");d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);100>this.year&&d.setFullYear(this.year);this.timezone?d.set({timezone:this.timezone}):this.timezoneOffset&&d.set({timezoneOffset:this.timezoneOffset});return d},finish:function(d){var a,c,f;d=d instanceof Array?e(d):[d];if(0===d.length)return null;
for(a=0;a<d.length;a++)"function"===typeof d[a]&&d[a].call(this);if(!this.now||this.unit||this.operator)d=this.now||-1!=="hour minute second".indexOf(this.unit)?new Date:g.today();else return new Date;a=!!(this.days&&null!==this.days||this.orient||this.operator);c="past"===this.orient||"subtract"===this.operator?-1:1;this.month&&"week"===this.unit&&(this.value=this.month+1,delete this.month,delete this.day);!this.month&&0!==this.month||-1==="year day hour minute second".indexOf(this.unit)||(this.value||
(this.value=this.month+1),this.month=null,a=!0);a||!this.weekday||this.day||this.days||(f=Date[this.weekday](),this.day=f.getDate(),this.month||(this.month=f.getMonth()),this.year=f.getFullYear());!this.weekday||"week"===this.unit||this.day||this.days||(f=Date[this.weekday](),this.day=f.getDate(),f.getMonth()!==d.getMonth()&&(this.month=f.getMonth()));a&&this.weekday&&"month"!==this.unit&&"week"!==this.unit&&(f=d,this.unit="day",this.days=(f=g.getDayNumberFromName(this.weekday)-f.getDay())?(f+7*orient)%
7:7*orient);this.month&&"day"===this.unit&&this.operator&&(this.value||(this.value=this.month+1),this.month=null);null!=this.value&&null!=this.month&&null!=this.year&&(this.day=1*this.value);this.month&&!this.day&&this.value&&(d.set({day:1*this.value}),a||(this.day=1*this.value));this.month||!this.value||"month"!==this.unit||this.now||(this.month=this.value,a=!0);a&&(this.month||0===this.month)&&"year"!==this.unit&&(this.unit="month",this.months=(f=this.month-d.getMonth())?(f+12*c)%12:12*c,this.month=
null);this.unit||(this.unit="day");if(!this.value&&this.operator&&null!==this.operator&&this[this.unit+"s"]&&null!==this[this.unit+"s"])this[this.unit+"s"]=this[this.unit+"s"]+("add"===this.operator?1:-1)+(this.value||0)*c;else if(null==this[this.unit+"s"]||null!=this.operator)this.value||(this.value=1),this[this.unit+"s"]=this.value*c;b.call(this);!this.month&&0!==this.month||this.day||(this.day=1);if(!this.orient&&!this.operator&&"week"===this.unit&&this.value&&!this.day&&!this.month)return Date.today().setWeek(this.value);
if("week"===this.unit&&this.weeks&&!this.day&&!this.month)return d=Date[void 0!==this.weekday?this.weekday:"today"]().addWeeks(this.weeks),this.now&&d.setTimeToNow(),d;a&&this.timezone&&this.day&&this.days&&(this.day=this.days);return a?d.add(this):d.set(this)}}})();
(function(){var g=Date;g.Grammar={};var e=g.Parsing.Operators,b=g.Grammar,d=g.Translator,a;b.datePartDelimiter=e.rtoken(/^([\s\-\.\,\/\x27]+)/);b.timePartDelimiter=e.stoken(":");b.whiteSpace=e.rtoken(/^\s*/);b.generalDelimiter=e.rtoken(/^(([\s\,]|at|@|on)+)/);var c={};b.ctoken=function(a){var b=c[a];if(!b){for(var b=Date.CultureInfo.regexPatterns,d=a.split(/\s+/),f=[],g=0;g<d.length;g++)f.push(e.replace(e.rtoken(b[d[g]]),d[g]));b=c[a]=e.any.apply(null,f)}return b};b.ctoken2=function(a){return e.rtoken(Date.CultureInfo.regexPatterns[a])};
var f=function(a,c,d){return d?e.cache(e.process(e.each(e.rtoken(a),e.optional(b.ctoken2(d))),c)):e.cache(e.process(e.rtoken(a),c))},l={},m=function(a){l[a]=l[a]||b.format(a)[0];return l[a]};b.allformats=function(a){var b=[];if(a instanceof Array)for(var c=0;c<a.length;c++)b.push(m(a[c]));else b.push(m(a));return b};b.formats=function(a){if(a instanceof Array){for(var b=[],c=0;c<a.length;c++)b.push(m(a[c]));return e.any.apply(null,b)}return m(a)};b.buildGrammarFormats=function(){c={};b.h=f(/^(0[0-9]|1[0-2]|[1-9])/,
d.hour);b.hh=f(/^(0[0-9]|1[0-2])/,d.hour);b.H=f(/^([0-1][0-9]|2[0-3]|[0-9])/,d.hour);b.HH=f(/^([0-1][0-9]|2[0-3])/,d.hour);b.m=f(/^([0-5][0-9]|[0-9])/,d.minute);b.mm=f(/^[0-5][0-9]/,d.minute);b.s=f(/^([0-5][0-9]|[0-9])/,d.second);b.ss=f(/^[0-5][0-9]/,d.second);b["ss.s"]=f(/^[0-5][0-9]\.[0-9]{1,3}/,d.secondAndMillisecond);b.hms=e.cache(e.sequence([b.H,b.m,b.s],b.timePartDelimiter));b.t=e.cache(e.process(b.ctoken2("shortMeridian"),d.meridian));b.tt=e.cache(e.process(b.ctoken2("longMeridian"),d.meridian));
b.z=f(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/,d.timezone);b.zz=f(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/,d.timezone);b.zzz=e.cache(e.process(b.ctoken2("timezone"),d.timezone));b.timeSuffix=e.each(e.ignore(b.whiteSpace),e.set([b.tt,b.zzz]));b.time=e.each(e.optional(e.ignore(e.stoken("T"))),b.hms,b.timeSuffix);b.d=f(/^([0-2]\d|3[0-1]|\d)/,d.day,"ordinalSuffix");b.dd=f(/^([0-2]\d|3[0-1])/,d.day,"ordinalSuffix");b.ddd=b.dddd=e.cache(e.process(b.ctoken("sun mon tue wed thu fri sat"),function(a){return function(){this.weekday=
a}}));b.M=f(/^(1[0-2]|0\d|\d)/,d.month);b.MM=f(/^(1[0-2]|0\d)/,d.month);b.MMM=b.MMMM=e.cache(e.process(b.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),d.month));b.y=f(/^(\d+)/,d.year);b.yy=f(/^(\d\d)/,d.year);b.yyy=f(/^(\d\d?\d?\d?)/,d.year);b.yyyy=f(/^(\d\d\d\d)/,d.year);a=function(){return e.each(e.any.apply(null,arguments),e.not(b.ctoken2("timeContext")))};b.day=a(b.d,b.dd);b.month=a(b.M,b.MMM);b.year=a(b.yyyy,b.yy);b.orientation=e.process(b.ctoken("past future"),function(a){return function(){this.orient=
a}});b.operator=e.process(b.ctoken("add subtract"),function(a){return function(){this.operator=a}});b.rday=e.process(b.ctoken("yesterday tomorrow today now"),d.rday);b.unit=e.process(b.ctoken("second minute hour day week month year"),function(a){return function(){this.unit=a}});b.value=e.process(e.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/),function(a){return function(){this.value=a.replace(/\D/g,"")}});b.expression=e.set([b.rday,b.operator,b.value,b.unit,b.orientation,b.ddd,b.MMM]);a=function(){return e.set(arguments,
b.datePartDelimiter)};b.mdy=a(b.ddd,b.month,b.day,b.year);b.ymd=a(b.ddd,b.year,b.month,b.day);b.dmy=a(b.ddd,b.day,b.month,b.year);b.date=function(a){return(b[Date.CultureInfo.dateElementOrder]||b.mdy).call(this,a)};b.format=e.process(e.many(e.any(e.process(e.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(a){if(b[a])return b[a];throw g.Parsing.Exception(a);}),e.process(e.rtoken(/^[^dMyhHmstz]+/),function(a){return e.ignore(e.stoken(a))}))),function(a){return e.process(e.each.apply(null,
a),d.finishExact)});b._start=e.process(e.set([b.date,b.time,b.expression],b.generalDelimiter,b.whiteSpace),d.finish)};b.buildGrammarFormats();b._formats=b.formats('"yyyy-MM-ddTHH:mm:ssZ";yyyy-MM-ddTHH:mm:ss.sz;yyyy-MM-ddTHH:mm:ssZ;yyyy-MM-ddTHH:mm:ssz;yyyy-MM-ddTHH:mm:ss;yyyy-MM-ddTHH:mmZ;yyyy-MM-ddTHH:mmz;yyyy-MM-ddTHH:mm;ddd, MMM dd, yyyy H:mm:ss tt;ddd MMM d yyyy HH:mm:ss zzz;MMddyyyy;ddMMyyyy;Mddyyyy;ddMyyyy;Mdyyyy;dMyyyy;yyyy;Mdyy;dMyy;d'.split(";"));b.start=function(a){try{var c=b._formats.call({},
a);if(0===c[1].length)return c}catch(d){}return b._start.call({},a)}})();
(function(){var g=Date,e={removeOrds:function(b){return b=(ords=b.match(/\b(\d+)(?:st|nd|rd|th)\b/))&&2===ords.length?b.replace(ords[0],ords[1]):b},grammarParser:function(b){var d=null;try{d=g.Grammar.start.call({},b.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"))}catch(a){return null}return 0===d[1].length?d[0]:null},nativeFallback:function(b){var d;try{return(d=Date._parse(b))||0===d?new Date(d):null}catch(a){return null}}};g._parse||(g._parse=g.parse);g.parse=function(b){var d;if(!b)return null;if(b instanceof
Date)return b.clone();4<=b.length&&"0"!==b.charAt(0)&&"+"!==b.charAt(0)&&"-"!==b.charAt(0)&&(d=g.Parsing.ISO.parse(b)||g.Parsing.Numeric.parse(b));if(d instanceof Date&&!isNaN(d.getTime()))return d;b=g.Parsing.Normalizer.parse(e.removeOrds(b));d=e.grammarParser(b);return null!==d?d:e.nativeFallback(b)};Date.getParseFunction=function(b){var d=Date.Grammar.allformats(b);return function(a){for(var b=null,f=0;f<d.length;f++){try{b=d[f].call({},a)}catch(e){continue}if(0===b[1].length)return b[0]}return null}};
g.parseExact=function(b,d){return g.getParseFunction(d)(b)}})();
(function(){var g=Date,e=g.prototype,b=function(a,b){b||(b=2);return("000"+a).slice(-1*b)};g.normalizeFormat=function(a){return a};g.strftime=function(a,b){return(new Date(1E3*b)).$format(a)};g.strtotime=function(a){a=g.parse(a);a.addMinutes(-1*a.getTimezoneOffset());return Math.round(g.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds())/1E3)};var d=function(a){var c;return function(d){var e,m=!1;if("\\"===d.charAt(0)||
"%%"===d.substring(0,2))return d.replace("\\","").replace("%%","%");switch(d){case "d":case "%d":e="dd";break;case "D":case "%a":e="ddd";break;case "j":case "l":case "%A":e="dddd";break;case "N":case "%u":return a.getDay()+1;case "S":e="S";break;case "w":case "%w":return a.getDay();case "z":return a.getOrdinalNumber();case "%j":return b(a.getOrdinalNumber(),3);case "%U":return d=a.clone().set({month:0,day:1}).addDays(-1).moveToDayOfWeek(0),e=a.clone().addDays(1).moveToDayOfWeek(0,-1),e<d?"00":b((e.getOrdinalNumber()-
d.getOrdinalNumber())/7+1);case "W":case "%V":return a.getISOWeek();case "%W":return b(a.getWeek());case "F":case "%B":e="MMMM";break;case "m":case "%m":e="MM";break;case "M":case "%b":case "%h":e="MMM";break;case "n":e="M";break;case "t":return g.getDaysInMonth(a.getFullYear(),a.getMonth());case "L":return g.isLeapYear(a.getFullYear())?1:0;case "o":case "%G":return a.setWeek(a.getISOWeek()).toString("yyyy");case "%g":return a.$format("%G").slice(-2);case "Y":case "%Y":e="yyyy";break;case "y":case "%y":e=
"yy";break;case "a":case "%p":return a.toString("tt",void 0).toLowerCase();case "A":return a.toString("tt",void 0).toUpperCase();case "g":case "%I":e="h";break;case "G":e="H";break;case "h":e="hh";break;case "H":case "%H":e="HH";break;case "i":case "%M":e="mm";break;case "s":case "%S":e="ss";break;case "u":return b(a.getMilliseconds(),3);case "I":return a.isDaylightSavingTime()?1:0;case "O":return a.getUTCOffset();case "P":return c=a.getUTCOffset(),c.substring(0,c.length-2)+":"+c.substring(c.length-
2);case "e":case "T":case "%z":case "%Z":return a.getTimezone();case "Z":return-60*a.getTimezoneOffset();case "B":return d=new Date,Math.floor((3600*d.getHours()+60*d.getMinutes()+d.getSeconds()+60*(d.getTimezoneOffset()+60))/86.4);case "c":return a.toISOString().replace(/\"/g,"");case "U":return g.strtotime("now");case "%c":return a.toString("d",void 0)+" "+a.toString("t",void 0);case "%C":return Math.floor(a.getFullYear()/100+1);case "%D":e="MM/dd/yy";break;case "%n":return"\\n";case "%t":return"\\t";
case "%r":e="hh:mm tt";break;case "%R":e="H:mm";break;case "%T":e="H:mm:ss";break;case "%e":e="d";m=!0;break;case "%x":m=!1;break;case "%X":e="t";break;default:return d}if(e)return a.toString(e,m)}};e.$format=function(a){var b=d(this);if(a)a.replace(/(%|\\)?.|%%/g,b);else return this._toString()};e.format||(e.format=e.$format)})();
(function(){var g=function(b){return function(){return this[b]}},e=function(b){return function(a){this[b]=a;return this}},b=function(d,a,c,e,g){if(1===arguments.length&&"number"===typeof d){var m=0>d?-1:1,h=Math.abs(d);this.setDays(Math.floor(h/864E5)*m);h%=864E5;this.setHours(Math.floor(h/36E5)*m);h%=36E5;this.setMinutes(Math.floor(h/6E4)*m);h%=6E4;this.setSeconds(Math.floor(h/1E3)*m);this.setMilliseconds(h%1E3*m)}else this.set(d,a,c,e,g);this.getTotalMilliseconds=function(){return 864E5*this.getDays()+
36E5*this.getHours()+6E4*this.getMinutes()+1E3*this.getSeconds()};this.compareTo=function(a){var b=new Date(1970,1,1,this.getHours(),this.getMinutes(),this.getSeconds());a=null===a?new Date(1970,1,1,0,0,0):new Date(1970,1,1,a.getHours(),a.getMinutes(),a.getSeconds());return b<a?-1:b>a?1:0};this.equals=function(a){return 0===this.compareTo(a)};this.add=function(a){return null===a?this:this.addSeconds(a.getTotalMilliseconds()/1E3)};this.subtract=function(a){return null===a?this:this.addSeconds(-a.getTotalMilliseconds()/
1E3)};this.addDays=function(a){return new b(this.getTotalMilliseconds()+864E5*a)};this.addHours=function(a){return new b(this.getTotalMilliseconds()+36E5*a)};this.addMinutes=function(a){return new b(this.getTotalMilliseconds()+6E4*a)};this.addSeconds=function(a){return new b(this.getTotalMilliseconds()+1E3*a)};this.addMilliseconds=function(a){return new b(this.getTotalMilliseconds()+a)};this.get12HourHour=function(){return 12<this.getHours()?this.getHours()-12:0===this.getHours()?12:this.getHours()};
this.getDesignator=function(){return 12>this.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator};this.toString=function(a){this._toString=function(){return null!==this.getDays()&&0<this.getDays()?this.getDays()+"."+this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds()):this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds())};this.p=function(a){return 2>a.toString().length?"0"+a:a};var b=this;return a?a.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g,
function(a){switch(a){case "d":return b.getDays();case "dd":return b.p(b.getDays());case "H":return b.getHours();case "HH":return b.p(b.getHours());case "h":return b.get12HourHour();case "hh":return b.p(b.get12HourHour());case "m":return b.getMinutes();case "mm":return b.p(b.getMinutes());case "s":return b.getSeconds();case "ss":return b.p(b.getSeconds());case "t":return(12>b.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator).substring(0,1);case "tt":return 12>b.getHours()?Date.CultureInfo.amDesignator:
Date.CultureInfo.pmDesignator}}):this._toString()};return this};(function(b,a){for(var c=0;c<a.length;c++){var f=a[c],l=f.slice(0,1).toUpperCase()+f.slice(1);b.prototype[f]=0;b.prototype["get"+l]=g(f);b.prototype["set"+l]=e(f)}})(b,"years months days hours minutes seconds milliseconds".split(" ").slice(2));b.prototype.set=function(b,a,c,e,g){this.setDays(b||this.getDays());this.setHours(a||this.getHours());this.setMinutes(c||this.getMinutes());this.setSeconds(e||this.getSeconds());this.setMilliseconds(g||
this.getMilliseconds())};Date.prototype.getTimeOfDay=function(){return new b(0,this.getHours(),this.getMinutes(),this.getSeconds(),this.getMilliseconds())};Date.TimeSpan=b;"undefined"!==typeof window&&(window.TimeSpan=b)})();
(function(){var g=function(a){return function(){return this[a]}},e=function(a){return function(b){this[a]=b;return this}},b=function(a,b,d,e){function g(){b.addMonths(-a);e.months++;12===e.months&&(e.years++,e.months=0)}if(1===a)for(;b>d;)g();else for(;b<d;)g();e.months--;e.months*=a;e.years*=a},d=function(a,c,d,e,g,h,k){if(7===arguments.length)this.set(a,c,d,e,g,h,k);else if(2===arguments.length&&arguments[0]instanceof Date&&arguments[1]instanceof Date){var n=arguments[0].clone(),p=arguments[1].clone(),
q=n>p?1:-1;this.dates={start:arguments[0].clone(),end:arguments[1].clone()};b(q,n,p,this);var s=!1===(n.isDaylightSavingTime()===p.isDaylightSavingTime());s&&1===q?n.addHours(-1):s&&n.addHours(1);n=p-n;0!==n&&(n=new TimeSpan(n),this.set(this.years,this.months,n.getDays(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()))}return this};(function(a,b){for(var d=0;d<b.length;d++){var l=b[d],m=l.slice(0,1).toUpperCase()+l.slice(1);a.prototype[l]=0;a.prototype["get"+m]=g(l);a.prototype["set"+
m]=e(l)}})(d,"years months days hours minutes seconds milliseconds".split(" "));d.prototype.set=function(a,b,d,e,g,h,k){this.setYears(a||this.getYears());this.setMonths(b||this.getMonths());this.setDays(d||this.getDays());this.setHours(e||this.getHours());this.setMinutes(g||this.getMinutes());this.setSeconds(h||this.getSeconds());this.setMilliseconds(k||this.getMilliseconds())};Date.TimePeriod=d;"undefined"!==typeof window&&(window.TimePeriod=d)})();
|
module.exports={title:"AOL",slug:"aol",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>AOL icon</title><path d="M13.07 9.334c2.526 0 3.74 1.997 3.74 3.706 0 1.709-1.214 3.706-3.74 3.706-2.527 0-3.74-1.997-3.74-3.706 0-1.709 1.213-3.706 3.74-3.706m0 5.465c.9 0 1.663-.741 1.663-1.759 0-1.018-.763-1.759-1.663-1.759s-1.664.741-1.664 1.759c0 1.018.764 1.76 1.664 1.76m4.913-7.546h2.104v9.298h-2.104zm4.618 6.567a1.398 1.398 0 1 0 .002 2.796 1.398 1.398 0 0 0-.002-2.796M5.536 7.254H3.662L0 16.55h2.482l.49-1.343h3.23l.452 1.343H9.16zm-1.91 6.068L4.6 10.08l.974 3.242H3.626z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.aol.com/",hex:"3399FF"};
|
/**
* IBAN is the international bank account number.
* It has a country - specific format, that is checked here too
*/
$.validator.addMethod( "iban", function( value, element ) {
// some quick simple tests to prevent needless work
if ( this.optional( element ) ) {
return true;
}
// remove spaces and to upper case
var iban = value.replace( / /g, "" ).toUpperCase(),
ibancheckdigits = "",
leadingZeroes = true,
cRest = "",
cOperator = "",
countrycode, ibancheck, charAt, cChar, bbanpattern, bbancountrypatterns, ibanregexp, i, p;
// check the country code and find the country specific format
countrycode = iban.substring( 0, 2 );
bbancountrypatterns = {
"AL": "\\d{8}[\\dA-Z]{16}",
"AD": "\\d{8}[\\dA-Z]{12}",
"AT": "\\d{16}",
"AZ": "[\\dA-Z]{4}\\d{20}",
"BE": "\\d{12}",
"BH": "[A-Z]{4}[\\dA-Z]{14}",
"BA": "\\d{16}",
"BR": "\\d{23}[A-Z][\\dA-Z]",
"BG": "[A-Z]{4}\\d{6}[\\dA-Z]{8}",
"CR": "\\d{17}",
"HR": "\\d{17}",
"CY": "\\d{8}[\\dA-Z]{16}",
"CZ": "\\d{20}",
"DK": "\\d{14}",
"DO": "[A-Z]{4}\\d{20}",
"EE": "\\d{16}",
"FO": "\\d{14}",
"FI": "\\d{14}",
"FR": "\\d{10}[\\dA-Z]{11}\\d{2}",
"GE": "[\\dA-Z]{2}\\d{16}",
"DE": "\\d{18}",
"GI": "[A-Z]{4}[\\dA-Z]{15}",
"GR": "\\d{7}[\\dA-Z]{16}",
"GL": "\\d{14}",
"GT": "[\\dA-Z]{4}[\\dA-Z]{20}",
"HU": "\\d{24}",
"IS": "\\d{22}",
"IE": "[\\dA-Z]{4}\\d{14}",
"IL": "\\d{19}",
"IT": "[A-Z]\\d{10}[\\dA-Z]{12}",
"KZ": "\\d{3}[\\dA-Z]{13}",
"KW": "[A-Z]{4}[\\dA-Z]{22}",
"LV": "[A-Z]{4}[\\dA-Z]{13}",
"LB": "\\d{4}[\\dA-Z]{20}",
"LI": "\\d{5}[\\dA-Z]{12}",
"LT": "\\d{16}",
"LU": "\\d{3}[\\dA-Z]{13}",
"MK": "\\d{3}[\\dA-Z]{10}\\d{2}",
"MT": "[A-Z]{4}\\d{5}[\\dA-Z]{18}",
"MR": "\\d{23}",
"MU": "[A-Z]{4}\\d{19}[A-Z]{3}",
"MC": "\\d{10}[\\dA-Z]{11}\\d{2}",
"MD": "[\\dA-Z]{2}\\d{18}",
"ME": "\\d{18}",
"NL": "[A-Z]{4}\\d{10}",
"NO": "\\d{11}",
"PK": "[\\dA-Z]{4}\\d{16}",
"PS": "[\\dA-Z]{4}\\d{21}",
"PL": "\\d{24}",
"PT": "\\d{21}",
"RO": "[A-Z]{4}[\\dA-Z]{16}",
"SM": "[A-Z]\\d{10}[\\dA-Z]{12}",
"SA": "\\d{2}[\\dA-Z]{18}",
"RS": "\\d{18}",
"SK": "\\d{20}",
"SI": "\\d{15}",
"ES": "\\d{20}",
"SE": "\\d{20}",
"CH": "\\d{5}[\\dA-Z]{12}",
"TN": "\\d{20}",
"TR": "\\d{5}[\\dA-Z]{17}",
"AE": "\\d{3}\\d{16}",
"GB": "[A-Z]{4}\\d{14}",
"VG": "[\\dA-Z]{4}\\d{16}"
};
bbanpattern = bbancountrypatterns[countrycode];
// As new countries will start using IBAN in the
// future, we only check if the countrycode is known.
// This prevents false negatives, while almost all
// false positives introduced by this, will be caught
// by the checksum validation below anyway.
// Strict checking should return FALSE for unknown
// countries.
if ( typeof bbanpattern !== "undefined" ) {
ibanregexp = new RegExp( "^[A-Z]{2}\\d{2}" + bbanpattern + "$", "" );
if ( !( ibanregexp.test( iban ) ) ) {
return false; // invalid country specific format
}
}
// now check the checksum, first convert to digits
ibancheck = iban.substring( 4, iban.length ) + iban.substring( 0, 4 );
for ( i = 0; i < ibancheck.length; i++ ) {
charAt = ibancheck.charAt( i );
if ( charAt !== "0" ) {
leadingZeroes = false;
}
if ( !leadingZeroes ) {
ibancheckdigits += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( charAt );
}
}
// calculate the result of: ibancheckdigits % 97
for ( p = 0; p < ibancheckdigits.length; p++ ) {
cChar = ibancheckdigits.charAt( p );
cOperator = "" + cRest + "" + cChar;
cRest = cOperator % 97;
}
return cRest === 1;
}, "Please specify a valid IBAN" );
|
function solve(lines) {
return lines[0];
}
|
angular.module('sliderDemo1', ['ngMaterial'])
.controller('AppCtrl', function($scope) {
$scope.color = {
red: Math.floor(Math.random() * 255),
green: Math.floor(Math.random() * 255),
blue: Math.floor(Math.random() * 255)
};
$scope.rating = 3;
$scope.disabled1 = 0;
$scope.disabled2 = 70;
});
|
var _ = require('lodash');
var async = require('async');
var crypto = require('crypto');
var nodemailer = require('nodemailer');
var passport = require('passport');
var User = require('../models/User');
var secrets = require('../config/secrets');
/**
* GET /login
* Login page.
*/
exports.getLogin = function(req, res) {
if (req.user) return res.redirect('/');
res.render('account/login', {
title: 'Login'
});
};
/**
* POST /login
* Sign in using email and password.
* @param email
* @param password
*/
exports.postLogin = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/login');
}
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) {
req.flash('errors', { msg: info.message });
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) return next(err);
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect(req.session.returnTo || '/');
});
})(req, res, next);
};
/**
* GET /logout
* Log out.
*/
exports.logout = function(req, res) {
req.logout();
res.redirect('/');
};
/**
* GET /signup
* Signup page.
*/
exports.getSignup = function(req, res) {
if (req.user) return res.redirect('/');
res.render('account/signup', {
title: 'Create Account'
});
};
/**
* POST /signup
* Create a new local account.
* @param email
* @param password
*/
exports.postSignup = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/signup');
}
var user = new User({
email: req.body.email,
password: req.body.password
});
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
req.flash('errors', { msg: 'Account with that email address already exists.' });
return res.redirect('/signup');
}
user.save(function(err) {
if (err) return next(err);
req.logIn(user, function(err) {
if (err) return next(err);
res.redirect('/');
});
});
});
};
/**
* GET /account
* Profile page.
*/
exports.getAccount = function(req, res) {
res.render('account/profile', {
title: 'Account Management'
});
};
/**
* POST /account/profile
* Update profile information.
*/
exports.postUpdateProfile = function(req, res, next) {
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
user.email = req.body.email || '';
user.profile.name = req.body.name || '';
user.profile.gender = req.body.gender || '';
user.profile.location = req.body.location || '';
user.profile.website = req.body.website || '';
user.save(function(err) {
if (err) return next(err);
req.flash('success', { msg: 'Profile information updated.' });
res.redirect('/account');
});
});
};
/**
* POST /account/password
* Update current password.
* @param password
*/
exports.postUpdatePassword = function(req, res, next) {
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
user.password = req.body.password;
user.save(function(err) {
if (err) return next(err);
req.flash('success', { msg: 'Password has been changed.' });
res.redirect('/account');
});
});
};
/**
* POST /account/delete
* Delete user account.
*/
exports.postDeleteAccount = function(req, res, next) {
User.remove({ _id: req.user.id }, function(err) {
if (err) return next(err);
req.logout();
req.flash('info', { msg: 'Your account has been deleted.' });
res.redirect('/');
});
};
/**
* GET /account/unlink/:provider
* Unlink OAuth provider.
* @param provider
*/
exports.getOauthUnlink = function(req, res, next) {
var provider = req.params.provider;
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
user[provider] = undefined;
user.tokens = _.reject(user.tokens, function(token) { return token.kind === provider; });
user.save(function(err) {
if (err) return next(err);
req.flash('info', { msg: provider + ' account has been unlinked.' });
res.redirect('/account');
});
});
};
/**
* GET /reset/:token
* Reset Password page.
*/
exports.getReset = function(req, res) {
if (req.isAuthenticated()) {
return res.redirect('/');
}
User
.findOne({ resetPasswordToken: req.params.token })
.where('resetPasswordExpires').gt(Date.now())
.exec(function(err, user) {
if (!user) {
req.flash('errors', { msg: 'Password reset token is invalid or has expired.' });
return res.redirect('/forgot');
}
res.render('account/reset', {
title: 'Password Reset'
});
});
};
/**
* POST /reset/:token
* Process the reset password request.
* @param token
*/
exports.postReset = function(req, res, next) {
req.assert('password', 'Password must be at least 4 characters long.').len(4);
req.assert('confirm', 'Passwords must match.').equals(req.body.password);
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('back');
}
async.waterfall([
function(done) {
User
.findOne({ resetPasswordToken: req.params.token })
.where('resetPasswordExpires').gt(Date.now())
.exec(function(err, user) {
if (!user) {
req.flash('errors', { msg: 'Password reset token is invalid or has expired.' });
return res.redirect('back');
}
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
if (err) return next(err);
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
var transporter = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: secrets.sendgrid.user,
pass: secrets.sendgrid.password
}
});
var mailOptions = {
to: user.email,
from: 'hackathon@starter.com',
subject: 'Your Hackathon Starter password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
transporter.sendMail(mailOptions, function(err) {
req.flash('success', { msg: 'Success! Your password has been changed.' });
done(err);
});
}
], function(err) {
if (err) return next(err);
res.redirect('/');
});
};
/**
* GET /forgot
* Forgot Password page.
*/
exports.getForgot = function(req, res) {
if (req.isAuthenticated()) {
return res.redirect('/');
}
res.render('account/forgot', {
title: 'Forgot Password'
});
};
/**
* POST /forgot
* Create a random token, then the send user an email with a reset link.
* @param email
*/
exports.postForgot = function(req, res, next) {
req.assert('email', 'Please enter a valid email address.').isEmail();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/forgot');
}
async.waterfall([
function(done) {
crypto.randomBytes(16, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email.toLowerCase() }, function(err, user) {
if (!user) {
req.flash('errors', { msg: 'No account with that email address exists.' });
return res.redirect('/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var transporter = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: secrets.sendgrid.user,
pass: secrets.sendgrid.password
}
});
var mailOptions = {
to: user.email,
from: 'hackathon@starter.com',
subject: 'Reset your password on Hackathon Starter',
text: 'You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
transporter.sendMail(mailOptions, function(err) {
req.flash('info', { msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' });
done(err, 'done');
});
}
], function(err) {
if (err) return next(err);
res.redirect('/forgot');
});
};
|
import { win, doc, vendors } from './environment';
export let visible;
let hidden = 'hidden';
if ( doc ) {
let prefix;
if ( hidden in doc ) {
prefix = '';
} else {
let i = vendors.length;
while ( i-- ) {
const vendor = vendors[i];
hidden = vendor + 'Hidden';
if ( hidden in doc ) {
prefix = vendor;
break;
}
}
}
if ( prefix !== undefined ) {
doc.addEventListener( prefix + 'visibilitychange', onChange );
onChange();
} else {
// gah, we're in an old browser
if ( 'onfocusout' in doc ) {
doc.addEventListener( 'focusout', onHide );
doc.addEventListener( 'focusin', onShow );
}
else {
win.addEventListener( 'pagehide', onHide );
win.addEventListener( 'blur', onHide );
win.addEventListener( 'pageshow', onShow );
win.addEventListener( 'focus', onShow );
}
visible = true; // until proven otherwise. Not ideal but hey
}
}
function onChange () {
visible = !doc[ hidden ];
}
function onHide () {
visible = false;
}
function onShow () {
visible = true;
}
|
// flag to cancel keyup event if already handled by click event (pressing Enter on a focusted button).
var cancelKeyup = false;
/**
* Helper: triggers a button callback
*
* @param {Object} The dilog instance.
* @param {Function} Callback to check which button triggered the event.
*
* @return {undefined}
*/
function triggerCallback(instance, check) {
for (var idx = 0; idx < instance.__internal.buttons.length; idx += 1) {
var button = instance.__internal.buttons[idx];
if (!button.element.disabled && check(button)) {
var closeEvent = createCloseEvent(idx, button);
if (typeof instance.callback === 'function') {
instance.callback.apply(instance, [closeEvent]);
}
//close the dialog only if not canceled.
if (closeEvent.cancel === false) {
instance.close();
}
break;
}
}
}
/**
* Clicks event handler, attached to the dialog footer.
*
* @param {Event} DOM event object.
* @param {Object} The dilog instance.
*
* @return {undefined}
*/
function buttonsClickHandler(event, instance) {
var target = event.srcElement || event.target;
triggerCallback(instance, function (button) {
// if this button caused the click, cancel keyup event
return button.element === target && (cancelKeyup = true);
});
}
/**
* Keyup event handler, attached to the document.body
*
* @param {Event} DOM event object.
* @param {Object} The dilog instance.
*
* @return {undefined}
*/
function keyupHandler(event) {
//hitting enter while button has focus will trigger keyup too.
//ignore if handled by clickHandler
if (cancelKeyup) {
cancelKeyup = false;
return;
}
var instance = openDialogs[openDialogs.length - 1];
var keyCode = event.keyCode;
if (instance.__internal.buttons.length === 0 && keyCode === keys.ESC && instance.get('closable') === true) {
triggerClose(instance);
return false;
}else if (usedKeys.indexOf(keyCode) > -1) {
triggerCallback(instance, function (button) {
return button.key === keyCode;
});
return false;
}
}
/**
* Keydown event handler, attached to the document.body
*
* @param {Event} DOM event object.
* @param {Object} The dilog instance.
*
* @return {undefined}
*/
function keydownHandler(event) {
var instance = openDialogs[openDialogs.length - 1];
var keyCode = event.keyCode;
if (keyCode === keys.LEFT || keyCode === keys.RIGHT) {
var buttons = instance.__internal.buttons;
for (var x = 0; x < buttons.length; x += 1) {
if (document.activeElement === buttons[x].element) {
switch (keyCode) {
case keys.LEFT:
buttons[(x || buttons.length) - 1].element.focus();
return;
case keys.RIGHT:
buttons[(x + 1) % buttons.length].element.focus();
return;
}
}
}
}else if (keyCode < keys.F12 + 1 && keyCode > keys.F1 - 1 && usedKeys.indexOf(keyCode) > -1) {
event.preventDefault();
event.stopPropagation();
triggerCallback(instance, function (button) {
return button.key === keyCode;
});
return false;
}
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.6.2_A4_T5;
* @section: 11.6.2, 11.6.3;
* @assertion: Operator x - y produces the same result as x + (-y);
* @description: Using the rule of sum of two zeroes and the fact that a - b = a + (-b);
*/
//CHECK#1
if (-0 - -0 !== 0 ) {
$ERROR('#1.1: -0 - -0 === 0. Actual: ' + (-0 - -0));
} else {
if (1 / (-0 - -0) !== Number.POSITIVE_INFINITY) {
$ERROR('#1.2: -0 - -0 === + 0. Actual: -0');
}
}
//CHECK#2
if (0 - -0 !== 0 ) {
$ERROR('#2.1: 0 - -0 === 0. Actual: ' + (0 - -0));
} else {
if (1 / (0 - -0) !== Number.POSITIVE_INFINITY) {
$ERROR('#2.2: 0 - -0 === + 0. Actual: -0');
}
}
//CHECK#3
if (-0 - 0 !== -0 ) {
$ERROR('#3.1: -0 - 0 === 0. Actual: ' + (-0 - 0));
} else {
if (1 / (-0 - 0) !== Number.NEGATIVE_INFINITY) {
$ERROR('#3.2: -0 - 0 === - 0. Actual: +0');
}
}
//CHECK#4
if (0 - 0 !== 0 ) {
$ERROR('#4.1: 0 - 0 === 0. Actual: ' + (0 - 0));
} else {
if (1 / (0 - 0) !== Number.POSITIVE_INFINITY) {
$ERROR('#4.2: 0 - 0 === + 0. Actual: -0');
}
}
|
import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import createMiddleware from './middleware/clientMiddleware';
import transitionMiddleware from './middleware/transitionMiddleware';
export default function createStore(reduxReactRouter, getRoutes, createHistory, client, data) {
const middleware = [createMiddleware(client)];
if (__CLIENT__) {
middleware.push(transitionMiddleware);
}
let finalCreateStore;
if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
const { devTools, persistState } = require('redux-devtools');
finalCreateStore = compose(
applyMiddleware(...middleware),
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(_createStore);
} else {
finalCreateStore = applyMiddleware(...middleware)(_createStore);
}
finalCreateStore = reduxReactRouter({ getRoutes, createHistory })(finalCreateStore);
const reducer = require('./modules/reducer');
const store = finalCreateStore(reducer, data);
store.client = client;
if (__DEVELOPMENT__ && module.hot) {
module.hot.accept('./modules/reducer', () => {
store.replaceReducer(require('./modules/reducer'));
});
}
return store;
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.3.1_A1.1_T4;
* @section: 11.3.1, 11.6.3, 7.3;
* @assertion: Line Terminator between LeftHandSideExpression and "++" is not allowed;
* @description: Checking Paragraph separator;
* @negative
*/
//CHECK#1
eval("var x = 1; x\u2029++");
|
/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
function Tooltip() {
this.init.apply(this, arguments);
}
Tooltip.prototype = {
init: function (chart, options) {
var borderWidth = options.borderWidth,
style = options.style,
padding = pInt(style.padding);
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = UNDEFINED;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = { x: 0, y: 0 };
// The tooltip is initially hidden
this.isHidden = true;
// create the label
this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip')
.attr({
padding: padding,
fill: options.backgroundColor,
'stroke-width': borderWidth,
r: options.borderRadius,
zIndex: 8
})
.css(style)
.css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
.add()
.attr({ y: -999 }); // #2301
// When using canVG the shadow shows up as a gray circle
// even if the tooltip is hidden.
if (!useCanVG) {
this.label.shadow(options.shadow);
}
// Public property for getting the shared state.
this.shared = options.shared;
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function () {
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function (x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden;
// get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// move to the intermediate value
tooltip.label.attr(now);
// run on next tick of the mouse tracker
if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
// never allow two timeouts
clearTimeout(this.tooltipTimeout);
// set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function () {
// The interval function may still be running during destroy, so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function () {
var tooltip = this,
hoverPoints;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
if (!this.isHidden) {
hoverPoints = this.chart.hoverPoints;
this.hideTimer = setTimeout(function () {
tooltip.label.fadeOut();
tooltip.isHidden = true;
}, pick(this.options.hideDelay, 500));
// hide previous hoverPoints and set new
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
this.chart.hoverPoints = null;
}
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function (points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotX = 0,
plotY = 0,
yAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === UNDEFINED) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function (point) {
yAxis = point.series.yAxis;
plotX += point.plotX;
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, mathRound);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function (boxWidth, boxHeight, point) {
// Set up the variables
var chart = this.chart,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
distance = pick(this.options.distance, 12),
pointX = point.plotX,
pointY = point.plotY,
x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance),
y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip
alignedRight;
// It is too far to the left, adjust it
if (x < 7) {
x = plotLeft + mathMax(pointX, 0) + distance;
}
// Test to see if the tooltip is too far to the right,
// if it is, move it back to be inside and then up to not cover the point.
if ((x + boxWidth) > (plotLeft + plotWidth)) {
x -= (x + boxWidth) - (plotLeft + plotWidth);
y = pointY - boxHeight + plotTop - distance;
alignedRight = true;
}
// If it is now above the plot area, align it to the top of the plot area
if (y < plotTop + 5) {
y = plotTop + 5;
// If the tooltip is still covering the point, move it below instead
if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
y = pointY + plotTop + distance; // below
}
}
// Now if the tooltip is below the chart, move it up. It's better to cover the
// point than to disappear outside the chart. #834.
if (y + boxHeight > plotTop + plotHeight) {
y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below
}
return {x: x, y: y};
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*/
defaultFormatter: function (tooltip) {
var items = this.points || splat(this),
series = items[0].series,
s;
// build the header
s = [series.tooltipHeaderFormatter(items[0])];
// build the values
each(items, function (item) {
series = item.series;
s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
});
// footer
s.push(tooltip.options.footerFormat || '');
return s.join('');
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function (point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.label,
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
borderColor,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(point, function (item) {
item.setState(HOVER_STATE);
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr('opacity', 1).show();
}
// update text
label.attr({
text: text
});
// set the stroke color of the box
borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
label.attr({
stroke: borderColor
});
tooltip.updatePosition({ plotX: x, plotY: y });
this.isHidden = false;
}
fireEvent(chart, 'tooltipRefresh', {
text: text,
x: x + chart.plotLeft,
y: y + chart.plotTop,
borderColor: borderColor
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function (point) {
var chart = this.chart,
label = this.label,
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
mathRound(pos.x),
mathRound(pos.y),
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
}
};
|
import {computed} from "ember-metal/computed";
import EmberObject from "ember-runtime/system/object";
import {testBoth} from "ember-runtime/tests/props_helper";
QUnit.module('CP macros');
testBoth('Ember.computed.empty', function (get, set) {
var obj = EmberObject.extend({
bestLannister: null,
lannisters: null,
bestLannisterUnspecified: computed.empty('bestLannister'),
noLannistersKnown: computed.empty('lannisters')
}).create({
lannisters: Ember.A([])
});
equal(get(obj, 'bestLannisterUnspecified'), true, "bestLannister initially empty");
equal(get(obj, 'noLannistersKnown'), true, "lannisters initially empty");
get(obj, 'lannisters').pushObject('Tyrion');
set(obj, 'bestLannister', 'Tyrion');
equal(get(obj, 'bestLannisterUnspecified'), false, "empty respects strings");
equal(get(obj, 'noLannistersKnown'), false, "empty respects array mutations");
});
testBoth('Ember.computed.notEmpty', function(get, set) {
var obj = EmberObject.extend({
bestLannister: null,
lannisters: null,
bestLannisterSpecified: computed.notEmpty('bestLannister'),
LannistersKnown: computed.notEmpty('lannisters')
}).create({
lannisters: Ember.A([])
});
equal(get(obj, 'bestLannisterSpecified'), false, "bestLannister initially empty");
equal(get(obj, 'LannistersKnown'), false, "lannisters initially empty");
get(obj, 'lannisters').pushObject('Tyrion');
set(obj, 'bestLannister', 'Tyrion');
equal(get(obj, 'bestLannisterSpecified'), true, "empty respects strings");
equal(get(obj, 'LannistersKnown'), true, "empty respects array mutations");
});
|
// twbs/bootstrap is included in the webpack.config.js
// as multi-module entry
$("#myModal").modal({
show: false
});
$("#save-button").click(function() {
alert("Saved");
$("#myModal").modal("hide");
});
|
#!/usr/bin/env node
/*
Hack to enable source maps in with gulp-sourcemaps and autoprefixer.
Created by null on 12/08/14.
npm --save-dev install through2
npm --save-dev install autoprefixer
npm --save-dev install vinyl-sourcemaps-apply
var prefixer = require('./gulp-autoprefixer-map.js');
gulp.task('css', [], function() {
.pipe(sourcemaps.init())
.pipe(prefixer())
.pipe(sourcemaps.write('.'))
});
*/
var through = require('through2');
var prefix = require('autoprefixer');
//var applySourceMap = require('vinyl-sourcemaps-apply');
module.exports = function(browsers, options) {
options = options || {};
return through.obj(function(file, enc, cb) {
if(file.isStream()) {
throw new Error('Streams not supported');
}
if(!file.isNull()) {
if(file.sourceMap) {
options.map = {
prev: file.sourceMap.mappings ? file.sourceMap : undefined,
annotation: false,
sourcesContent: true
};
options.to = options.from = file.relative;
}
var contents = file.contents.toString();
var result = prefix.apply(this, browsers).process(contents, options);
contents = result.css;
file.contents = new Buffer(contents);
if(file.sourceMap) {
var map = JSON.parse(result.map.toString());
map.sources = file.sourceMap.sources;
map.file = file.sourceMap.file;
file.sourceMap = map;
//applySourceMap(file, map);
}
}
this.push(file);
cb();
});
};
|
import React from 'react'
import Link from 'next/link'
import { inject, observer } from 'mobx-react'
import Clock from './Clock'
@inject('store') @observer
class Page extends React.Component {
componentDidMount () {
this.props.store.start()
}
componentWillUnmount () {
this.props.store.stop()
}
render () {
return (
<div>
<h1>{this.props.title}</h1>
<Clock lastUpdate={this.props.store.lastUpdate} light={this.props.store.light} />
<nav>
<Link href={this.props.linkTo}><a>Navigate</a></Link>
</nav>
</div>
)
}
}
export default Page
|
describe("mousedown event", function () {
$.fixture("plain");
subject(function () {
return new Awesomplete("#plain", { list: ["item1", "item2", "item3"] });
});
def("li", function () { return this.subject.ul.children[1] });
beforeEach(function () {
$.type(this.subject.input, "ite");
spyOn(this.subject, "select");
});
describe("with ul target", function () {
def("target", function () { return this.subject.ul });
it("does not select item", function () {
$.fire(this.target, "mousedown", { button: 0 });
expect(this.subject.select).not.toHaveBeenCalled();
});
});
describe("with li target", function () {
def("target", function () { return this.li });
describe("on left click", function () {
it("selects item", function () {
var event = $.fire(this.target, "mousedown", { button: 0 });
expect(this.subject.select).toHaveBeenCalledWith(this.li, this.target);
expect(event.defaultPrevented).toBe(true);
});
});
describe("on right click", function () {
it("does not select item", function () {
$.fire(this.target, "mousedown", { button: 2 });
expect(this.subject.select).not.toHaveBeenCalled();
});
});
});
describe("with child of li target", function () {
def("target", function () { return $("mark", this.li) });
describe("on left click", function () {
it("selects item", function () {
var event = $.fire(this.target, "mousedown", { button: 0 });
expect(this.subject.select).toHaveBeenCalledWith(this.li, this.target);
expect(event.defaultPrevented).toBe(true);
});
});
describe("on right click", function () {
it("does not select item", function () {
$.fire(this.target, "mousedown", { button: 2 });
expect(this.subject.select).not.toHaveBeenCalled();
});
});
});
});
|
/**
* ng-csv module
* Export Javascript's arrays to csv files from the browser
*
* Author: asafdav - https://github.com/asafdav
*/
angular.module('ngCsv.directives').
directive('ngCsv', ['$parse', '$q', 'CSV', '$document', '$timeout', function ($parse, $q, CSV, $document, $timeout) {
return {
restrict: 'AC',
scope: {
data: '&ngCsv',
filename: '@filename',
header: '&csvHeader',
txtDelim: '@textDelimiter',
decimalSep: '@decimalSeparator',
quoteStrings: '@quoteStrings',
fieldSep: '@fieldSeparator',
lazyLoad: '@lazyLoad',
addByteOrderMarker: "@addBom",
ngClick: '&',
charset: '@charset'
},
controller: [
'$scope',
'$element',
'$attrs',
'$transclude',
function ($scope, $element, $attrs, $transclude) {
$scope.csv = '';
if (!angular.isDefined($scope.lazyLoad) || $scope.lazyLoad != "true") {
if (angular.isArray($scope.data)) {
$scope.$watch("data", function (newValue) {
$scope.buildCSV();
}, true);
}
}
$scope.getFilename = function () {
return $scope.filename || 'download.csv';
};
function getBuildCsvOptions() {
var options = {
txtDelim: $scope.txtDelim ? $scope.txtDelim : '"',
decimalSep: $scope.decimalSep ? $scope.decimalSep : '.',
quoteStrings: $scope.quoteStrings,
addByteOrderMarker: $scope.addByteOrderMarker
};
if (angular.isDefined($attrs.csvHeader)) options.header = $scope.$eval($scope.header);
options.fieldSep = $scope.fieldSep ? $scope.fieldSep : ",";
// Replaces any badly formatted special character string with correct special character
options.fieldSep = CSV.isSpecialChar(options.fieldSep) ? CSV.getSpecialChar(options.fieldSep) : options.fieldSep;
return options;
}
/**
* Creates the CSV and updates the scope
* @returns {*}
*/
$scope.buildCSV = function () {
var deferred = $q.defer();
$element.addClass($attrs.ngCsvLoadingClass || 'ng-csv-loading');
CSV.stringify($scope.data(), getBuildCsvOptions()).then(function (csv) {
$scope.csv = csv;
$element.removeClass($attrs.ngCsvLoadingClass || 'ng-csv-loading');
deferred.resolve(csv);
});
$scope.$apply(); // Old angular support
return deferred.promise;
};
}
],
link: function (scope, element, attrs) {
function doClick() {
var charset = scope.charset || "utf-8";
var blob = new Blob([scope.csv], {
type: "text/csv;charset="+ charset + ";"
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, scope.getFilename());
} else {
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', scope.getFilename());
downloadLink.attr('target', '_blank');
$document.find('body').append(downloadLink);
$timeout(function () {
downloadLink[0].click();
downloadLink.remove();
}, null);
}
}
element.bind('click', function (e) {
scope.buildCSV().then(function (csv) {
doClick();
});
scope.$apply();
});
}
};
}]);
|
var auto = require('autoprefixer')('last 2 versions')
var memoize = require('memoize-sync')
var rwnpm = require('rework-npm')
var rework = require('rework')
var fs = require('fs')
module.exports = process.env.NODE_ENV === 'development'
? getCSS
: memoize(getCSS, function(){})
function getCSS() {
var css = fs.readFileSync(__dirname + '/index.css', 'utf8')
css = rework(css)
.use(rwnpm({ dir: __dirname }))
.use(rework.ease())
.use(rework.inline(__dirname + '/../assets'))
.toString()
css = auto.process(css).css
return css
}
|
/**
* lodash 4.5.5 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Detect free variable `exports`. */
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
? exports
: undefined;
/** Detect free variable `module`. */
var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
? module
: undefined;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = (freeModule && freeModule.exports === freeExports)
? freeExports
: undefined;
/** Detect free variable `global` from Node.js. */
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
/** Detect `this` as the global object. */
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
*
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal ||
((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
freeSelf || thisGlobal || Function('return this')();
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `Map#set` because it doesn't return the map instance in IE 11.
map.set(pair[0], pair[1]);
return map;
}
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
set.add(value);
return set;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Checks if `value` is a global object.
*
* @private
* @param {*} value The value to check.
* @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Converts `map` to an array.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the converted array.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Converts `set` to an array.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the converted array.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
getOwnPropertySymbols = Object.getOwnPropertySymbols,
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf,
nativeKeys = Object.keys;
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @returns {Object} Returns the new hash object.
*/
function Hash() {}
/**
* Removes `key` and its value from the hash.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(hash, key) {
return hashHas(hash, key) && delete hash[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(hash, key) {
if (nativeCreate) {
var result = hash[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(hash, key) {
return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function hashSet(hash, key, value) {
hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
}
// Avoid inheriting from `Object.prototype` when possible.
Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function MapCache(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapClear() {
this.__data__ = {
'hash': new Hash,
'map': Map ? new Map : [],
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapDelete(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map['delete'](key) : assocDelete(data.map, key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapGet(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashGet(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.get(key) : assocGet(data.map, key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashHas(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.has(key) : assocHas(data.map, key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapSet(key, value) {
var data = this.__data__;
if (isKeyable(key)) {
hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
} else if (Map) {
data.map.set(key, value);
} else {
assocSet(data.map, key, value);
}
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapClear;
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function Stack(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = { 'array': [], 'map': null };
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
array = data.array;
return array ? assocDelete(array, key) : data.map['delete'](key);
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
var data = this.__data__,
array = data.array;
return array ? assocGet(array, key) : data.map.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
var data = this.__data__,
array = data.array;
return array ? assocHas(array, key) : data.map.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__,
array = data.array;
if (array) {
if (array.length < (LARGE_ARRAY_SIZE - 1)) {
assocSet(array, key, value);
} else {
data.array = null;
data.map = new MapCache(array);
}
}
var map = data.map;
if (map) {
map.set(key, value);
}
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Removes `key` and its value from the associative array.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function assocDelete(array, key) {
var index = assocIndexOf(array, key);
if (index < 0) {
return false;
}
var lastIndex = array.length - 1;
if (index == lastIndex) {
array.pop();
} else {
splice.call(array, index, 1);
}
return true;
}
/**
* Gets the associative array value for `key`.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function assocGet(array, key) {
var index = assocIndexOf(array, key);
return index < 0 ? undefined : array[index][1];
}
/**
* Checks if an associative array value for `key` exists.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function assocHas(array, key) {
return assocIndexOf(array, key) > -1;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to search.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Sets the associative array `key` to `value`.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function assocSet(array, key, value) {
var index = assocIndexOf(array, key);
if (index < 0) {
array.push([key, value]);
} else {
array[index][1] = value;
}
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
object[key] = value;
}
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @param {boolean} [isFull] Specify a clone including symbols.
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
var result;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
if (isHostObject(value)) {
return object ? value : {};
}
result = initCloneObject(isFunc ? {} : value);
if (!isDeep) {
return copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (!isArr) {
var props = isFull ? getAllKeys(value) : keys(value);
}
// Recursively populate clone (susceptible to call stack limits).
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
function baseCreate(proto) {
return isObject(proto) ? objectCreate(proto) : {};
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object)
? result
: arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
// Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
// that are composed entirely of index properties, return `false` for
// `hasOwnProperty` checks of them.
return hasOwnProperty.call(object, key) ||
(typeof object == 'object' && key in object && getPrototype(object) === null);
}
/**
* The base implementation of `_.keys` which doesn't skip the constructor
* property of prototypes or treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
return nativeKeys(Object(object));
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var result = new buffer.constructor(buffer.length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object) {
return copyObjectWith(source, props, object);
}
/**
* This function is like `copyObject` except that it accepts a function to
* customize copied values.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObjectWith(source, props, object, customizer) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: source[key];
assignValue(object, key, newValue);
}
return object;
}
/**
* Copies own symbol properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a
* [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
* Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object[key];
return isNative(value) ? value : undefined;
}
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
/**
* Creates an array of the own enumerable symbol properties of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
function getSymbols(object) {
// Coerce `object` to an object to avoid non-object errors in V8.
// See https://bugs.chromium.org/p/v8/issues/detail?id=3443 for more details.
return getOwnPropertySymbols(Object(object));
}
// Fallback for IE < 11.
if (!getOwnPropertySymbols) {
getSymbols = function() {
return [];
};
}
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function getTag(value) {
return objectToString.call(value);
}
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge, and promises in Node.js.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = objectToString.call(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : undefined;
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Creates an array of index keys for `object` values of arrays,
* `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
* @returns {Array|null} Returns index keys, else `null`.
*/
function indexKeys(object) {
var length = object ? object.length : undefined;
if (isLength(length) &&
(isArray(object) || isString(object) || isArguments(object))) {
return baseTimes(length, String);
}
return null;
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return type == 'number' || type == 'boolean' ||
(type == 'string' && value != '__proto__') || value == null;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = !Buffer ? constant(false) : function(value) {
return value instanceof Buffer;
};
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length,
* else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'user': 'fred' };
* var getter = _.constant(object);
*
* getter() === object;
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = baseClone;
|
/* -----------------------------------------------------------------------------
AnyPicker - Customizable Picker for Mobile OS
Version 2.0.4
Copyright (c)2016 Curious Solutions LLP
https://curioussolutions.in/libraries/anypicker/content/license.htm
See License Information in LICENSE file.
----------------------------------------------------------------------------- */
/*
language: Austrian German ("de-at")
file: AnyPicker-i18n-de-at
*/
(function ($) {
$.AnyPicker.i18n["de-at"] = $.extend($.AnyPicker.i18n["de-at"], {
// Common
headerTitle: "Auswählen",
setButton: "einstellen",
clearButton: "klar",
nowButton: "jetzt",
cancelButton: "Abbrechen",
dateSwitch: "Datum",
timeSwitch: "Zeit",
// DateTime
veryShortDays: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
shortDays: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
fullDays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
shortMonths: 'Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
fullMonths: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
numbers: '0_1_2_3_4_5_6_7_8_9'.split('_'),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
/*
language: German ("de")
file: AnyPicker-i18n-de
*/
(function ($) {
$.AnyPicker.i18n["de"] = $.extend($.AnyPicker.i18n["de"], {
// Common
headerTitle: "Auswählen",
setButton: "einstellen",
clearButton: "klar",
nowButton: "jetzt",
cancelButton: "Abbrechen",
dateSwitch: "Datum",
timeSwitch: "Zeit",
// DateTime
veryShortDays: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
shortDays: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
fullDays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
shortMonths: 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
fullMonths: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
numbers: '0_1_2_3_4_5_6_7_8_9'.split('_'),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
/*
language: English
file: AnyPicker-i18n-en
*/
(function ($) {
$.AnyPicker.i18n["en"] = $.extend($.AnyPicker.i18n["en"], {
// Common
headerTitle: "Select",
setButton: "Set",
clearButton: "Clear",
nowButton: "Now",
cancelButton: "Cancel",
dateSwitch: "Date",
timeSwitch: "Time",
// DateTime
veryShortDays: "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
shortDays: "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
fullDays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
shortMonths: "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
fullMonths: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
numbers: "0_1_2_3_4_5_6_7_8_9".split("_"),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
/*
language: French
file: AnyPicker-i18n-fr
*/
(function ($) {
$.AnyPicker.i18n["fr"] = $.extend($.AnyPicker.i18n["fr"], {
// Common
headerTitle: "Sélectionner",
setButton: "Set",
clearButton: "Clair",
nowButton: "Maintenant",
cancelButton: "Annuler",
dateSwitch: "Date",
timeSwitch: "Temps",
// DateTime
veryShortDays: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
shortDays: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
fullDays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
shortMonths: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
fullMonths: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
numbers: '0_1_2_3_4_5_6_7_8_9'.split('_'),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
/*
language: Norwegian Bokmål
file: AnyPicker-i18n-nb
author: Tommy Eliassen(https://github.com/pusle)
*/
(function ($) {
$.AnyPicker.i18n["nb"] = $.extend($.AnyPicker.i18n["nb"], {
// Common
headerTitle: "Velg",
setButton: "Bruk",
clearButton: "Tøm",
nowButton: "Nå",
cancelButton: "Avbryt",
dateSwitch: "Dato",
timeSwitch: "Klokkeslett",
// DateTime
veryShortDays: "Sø_Ma_Ti_On_To_Fr_Lø".split("_"),
shortDays: "Søn_Man_Tir_Ons_Tor_Fre_Lør".split("_"),
fullDays: "Søndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lørdag".split("_"),
shortMonths: "Jan_Feb_Mar_Apr_Mai_Jun_Jul_Aug_Sep_Okt_Nov_Des".split("_"),
fullMonths: "Januar_Februar_Mars_April_Mai_Juni_Juli_August_September_Oktober_November_Desember".split("_"),
numbers: "0_1_2_3_4_5_6_7_8_9".split("_"),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
/*
language: Russian
file: AnyPicker-i18n-ru
*/
(function ($) {
$.AnyPicker.i18n["ru"] = $.extend($.AnyPicker.i18n["ru"], {
// Common
headerTitle: "выбрать",
setButton: "Установите",
clearButton: "Очистить",
nowButton: "сейчас",
cancelButton: "отменить",
dateSwitch: "дата",
timeSwitch: "время",
// DateTime
veryShortDays: 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
shortDays: 'вс_пн_вт_ср_чт_пт_сб'.split('_'),
fullDays: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'),
shortMonths: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
fullMonths: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
numbers: '0_1_2_3_4_5_6_7_8_9'.split('_'),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
/*
language: Chinese
file: AnyPicker-i18n-zh-cn
*/
(function ($) {
$.AnyPicker.i18n["zh-cn"] = $.extend($.AnyPicker.i18n["zh-cn"], {
// Common
headerTitle: "选择",
setButton: "设置",
clearButton: "明确",
nowButton: "现在",
cancelButton: "取消",
dateSwitch: "日期",
timeSwitch: "时间",
// DateTime
veryShortDays: '日_一_二_三_四_五_六'.split('_'),
shortDays: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
fullDays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
shortMonths: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
fullMonths: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
numbers: '0_1_2_3_4_5_6_7_8_9'.split('_'),
meridiem:
{
a: ["a", "p"],
aa: ["am", "pm"],
A: ["A", "P"],
AA: ["AM", "PM"]
}
});
})(jQuery);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (context) {
var annotateReturn = (_lodash2.default.get(context, 'options[0]') || 'always') === 'always';
var annotateUndefined = (_lodash2.default.get(context, 'options[1].annotateUndefined') || 'never') === 'always';
var skipArrows = _lodash2.default.get(context, 'options[1].excludeArrowFunctions') || false;
var makeRegExp = function makeRegExp(str) {
return new RegExp(str);
};
var excludeMatching = _lodash2.default.get(context, 'options[1].excludeMatching', []).map(makeRegExp);
var includeOnlyMatching = _lodash2.default.get(context, 'options[1].includeOnlyMatching', []).map(makeRegExp);
var targetNodes = [];
var registerFunction = function registerFunction(functionNode) {
targetNodes.push({
functionNode
});
};
var isUndefinedReturnType = function isUndefinedReturnType(returnNode) {
return returnNode.argument === null || returnNode.argument.name === 'undefined' || returnNode.argument.operator === 'void';
};
var getIsReturnTypeAnnotationUndefined = function getIsReturnTypeAnnotationUndefined(targetNode) {
var isReturnTypeAnnotationLiteralUndefined = _lodash2.default.get(targetNode, 'functionNode.returnType.typeAnnotation.id.name') === 'undefined' && _lodash2.default.get(targetNode, 'functionNode.returnType.typeAnnotation.type') === 'GenericTypeAnnotation';
var isReturnTypeAnnotationVoid = _lodash2.default.get(targetNode, 'functionNode.returnType.typeAnnotation.type') === 'VoidTypeAnnotation';
return isReturnTypeAnnotationLiteralUndefined || isReturnTypeAnnotationVoid;
};
var shouldFilterNode = function shouldFilterNode(functionNode) {
var isArrow = functionNode.type === 'ArrowFunctionExpression';
var identiferName = _lodash2.default.get(functionNode, isArrow ? 'parent.id.name' : 'id.name');
var checkRegExp = function checkRegExp(regex) {
return regex.test(identiferName);
};
if (excludeMatching.length && _lodash2.default.some(excludeMatching, checkRegExp)) {
return true;
}
if (includeOnlyMatching.length && !_lodash2.default.some(includeOnlyMatching, checkRegExp)) {
return true;
}
return false;
};
var evaluateFunction = function evaluateFunction(functionNode) {
var targetNode = targetNodes.pop();
if (functionNode !== targetNode.functionNode) {
throw new Error('Mismatch.');
}
var isArrow = functionNode.type === 'ArrowFunctionExpression';
var isArrowFunctionExpression = functionNode.expression;
var hasImplicitReturnType = functionNode.async || functionNode.generator;
var isFunctionReturnUndefined = !isArrowFunctionExpression && !hasImplicitReturnType && (!targetNode.returnStatementNode || isUndefinedReturnType(targetNode.returnStatementNode));
var isReturnTypeAnnotationUndefined = getIsReturnTypeAnnotationUndefined(targetNode);
if (skipArrows === 'expressionsOnly' && isArrowFunctionExpression || skipArrows === true && isArrow) {
return;
}
if (isFunctionReturnUndefined && isReturnTypeAnnotationUndefined && !annotateUndefined) {
context.report(functionNode, 'Must not annotate undefined return type.');
} else if (isFunctionReturnUndefined && !isReturnTypeAnnotationUndefined && annotateUndefined) {
context.report(functionNode, 'Must annotate undefined return type.');
} else if (!isFunctionReturnUndefined && !isReturnTypeAnnotationUndefined) {
if (annotateReturn && !functionNode.returnType && !shouldFilterNode(functionNode)) {
context.report(functionNode, 'Missing return type annotation.');
}
}
};
var evaluateNoise = function evaluateNoise() {
targetNodes.pop();
};
return {
ArrowFunctionExpression: registerFunction,
'ArrowFunctionExpression:exit': evaluateFunction,
ClassDeclaration: registerFunction,
'ClassDeclaration:exit': evaluateNoise,
ClassExpression: registerFunction,
'ClassExpression:exit': evaluateNoise,
FunctionDeclaration: registerFunction,
'FunctionDeclaration:exit': evaluateFunction,
FunctionExpression: registerFunction,
'FunctionExpression:exit': evaluateFunction,
ReturnStatement: function ReturnStatement(node) {
if (targetNodes.length) {
targetNodes[targetNodes.length - 1].returnStatementNode = node;
}
}
};
};
module.exports = exports['default'];
|
var should = require('should'),
fs = require('fs'),
config = require(__dirname + '/../../../server/config'),
errors = require(config.get('paths').corePath + '/server/errors'),
schedulingUtils = require(config.get('paths').corePath + '/server/scheduling/utils');
describe('Scheduling: utils', function () {
describe('success', function () {
it('create good adapter', function (done) {
schedulingUtils.createAdapter({
active: __dirname + '/../../../server/scheduling/SchedulingDefault'
}).then(function (adapter) {
should.exist(adapter);
done();
}).catch(done);
});
it('create good adapter', function (done) {
var jsFile = '' +
'var util = require(\'util\');' +
'var SchedulingBase = require(__dirname + \'/../../../server/scheduling/SchedulingBase\');' +
'var AnotherAdapter = function (){ SchedulingBase.call(this); };' +
'util.inherits(AnotherAdapter, SchedulingBase);' +
'AnotherAdapter.prototype.run = function (){};' +
'AnotherAdapter.prototype.schedule = function (){};' +
'AnotherAdapter.prototype.reschedule = function (){};' +
'AnotherAdapter.prototype.unschedule = function (){};' +
'module.exports = AnotherAdapter';
fs.writeFileSync(__dirname + '/another-scheduler.js', jsFile);
schedulingUtils.createAdapter({
active: 'another-scheduler',
contentPath: __dirname + '/'
}).then(function (adapter) {
should.exist(adapter);
done();
}).finally(function () {
fs.unlinkSync(__dirname + '/another-scheduler.js');
}).catch(done);
});
});
describe('error', function () {
it('create without adapter path', function (done) {
schedulingUtils.createAdapter()
.catch(function (err) {
should.exist(err);
done();
});
});
it('create with unknown adapter', function (done) {
schedulingUtils.createAdapter({
active: '/follow/the/heart'
}).catch(function (err) {
should.exist(err);
done();
});
});
it('create with adapter, but missing fn\'s', function (done) {
var jsFile = '' +
'var util = require(\'util\');' +
'var SchedulingBase = require(__dirname + \'/../../../server/scheduling/SchedulingBase\');' +
'var BadAdapter = function (){ SchedulingBase.call(this); };' +
'util.inherits(BadAdapter, SchedulingBase);' +
'BadAdapter.prototype.schedule = function (){};' +
'module.exports = BadAdapter';
fs.writeFileSync(__dirname + '/bad-adapter.js', jsFile);
schedulingUtils.createAdapter({
active: __dirname + '/bad-adapter'
}).catch(function (err) {
should.exist(err);
(err instanceof errors.IncorrectUsageError).should.eql(true);
done();
}).finally(function () {
fs.unlinkSync(__dirname + '/bad-adapter.js');
});
});
});
});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Cleave"] = factory(require("react"));
else
root["Cleave"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var React = __webpack_require__(1); // eslint-disable-line no-unused-vars
var CreateReactClass = __webpack_require__(2);
var NumeralFormatter = __webpack_require__(9);
var DateFormatter = __webpack_require__(10);
var PhoneFormatter = __webpack_require__(11);
var CreditCardDetector = __webpack_require__(12);
var Util = __webpack_require__(13);
var DefaultProperties = __webpack_require__(14);
var cleaveReactClass = CreateReactClass({
componentDidMount: function componentDidMount() {
this.init();
},
componentDidUpdate: function componentDidUpdate() {
var owner = this;
if (!owner.state.updateCursorPosition) {
return;
}
owner.setCurrentSelection(owner.state.cursorPosition);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
var owner = this,
phoneRegionCode = (nextProps.options || {}).phoneRegionCode,
newValue = nextProps.value;
if (newValue !== undefined) {
newValue = newValue.toString();
if (newValue !== owner.state.value && newValue !== owner.properties.result) {
owner.properties.initValue = newValue;
owner.onInput(newValue, true);
}
}
// update phone region code
if (phoneRegionCode && phoneRegionCode !== owner.properties.phoneRegionCode) {
owner.properties.phoneRegionCode = phoneRegionCode;
owner.initPhoneFormatter();
owner.onInput(owner.properties.result);
}
},
getInitialState: function getInitialState() {
var owner = this,
_owner$props = owner.props,
value = _owner$props.value,
options = _owner$props.options,
onKeyDown = _owner$props.onKeyDown,
onChange = _owner$props.onChange,
onFocus = _owner$props.onFocus,
onBlur = _owner$props.onBlur,
onInit = _owner$props.onInit;
owner.registeredEvents = {
onInit: onInit || Util.noop,
onChange: onChange || Util.noop,
onFocus: onFocus || Util.noop,
onBlur: onBlur || Util.noop,
onKeyDown: onKeyDown || Util.noop
};
if (!options) {
options = {};
}
options.initValue = value;
owner.properties = DefaultProperties.assign({}, options);
return {
value: owner.properties.result,
cursorPosition: 0,
updateCursorPosition: false
};
},
init: function init() {
var owner = this,
pps = owner.properties;
// so no need for this lib at all
if (!pps.numeral && !pps.phone && !pps.creditCard && !pps.date && pps.blocksLength === 0 && !pps.prefix) {
owner.onInput(pps.initValue);
owner.registeredEvents.onInit(owner);
return;
}
pps.maxLength = Util.getMaxLength(pps.blocks);
owner.isAndroid = Util.isAndroid();
owner.initPhoneFormatter();
owner.initDateFormatter();
owner.initNumeralFormatter();
// avoid touch input field if value is null
// otherwise Firefox will add red box-shadow for <input required />
if (pps.initValue || pps.prefix && !pps.noImmediatePrefix) {
owner.onInput(pps.initValue);
}
owner.registeredEvents.onInit(owner);
},
initNumeralFormatter: function initNumeralFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.numeral) {
return;
}
pps.numeralFormatter = new NumeralFormatter(pps.numeralDecimalMark, pps.numeralIntegerScale, pps.numeralDecimalScale, pps.numeralThousandsGroupStyle, pps.numeralPositiveOnly, pps.stripLeadingZeroes, pps.delimiter);
},
initDateFormatter: function initDateFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.date) {
return;
}
pps.dateFormatter = new DateFormatter(pps.datePattern);
pps.blocks = pps.dateFormatter.getBlocks();
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
},
initPhoneFormatter: function initPhoneFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.phone) {
return;
}
// Cleave.AsYouTypeFormatter should be provided by
// external google closure lib
try {
pps.phoneFormatter = new PhoneFormatter(new pps.root.Cleave.AsYouTypeFormatter(pps.phoneRegionCode), pps.delimiter);
} catch (ex) {
throw new Error('Please include phone-type-formatter.{country}.js lib');
}
},
setRawValue: function setRawValue(value) {
var owner = this,
pps = owner.properties;
value = value !== undefined && value !== null ? value.toString() : '';
if (pps.numeral) {
value = value.replace('.', pps.numeralDecimalMark);
}
pps.backspace = false;
owner.onChange({
target: { value: value },
// Methods to better resemble a SyntheticEvent
stopPropagation: Util.noop,
preventDefault: Util.noop,
persist: Util.noop
});
},
getRawValue: function getRawValue() {
var owner = this,
pps = owner.properties,
rawValue = pps.result;
if (pps.rawValueTrimPrefix) {
rawValue = Util.getPrefixStrippedValue(rawValue, pps.prefix, pps.prefixLength);
}
if (pps.numeral) {
rawValue = pps.numeralFormatter ? pps.numeralFormatter.getRawValue(rawValue) : '';
} else {
rawValue = Util.stripDelimiters(rawValue, pps.delimiter, pps.delimiters);
}
return rawValue;
},
getISOFormatDate: function getISOFormatDate() {
var owner = this,
pps = owner.properties;
return pps.date ? pps.dateFormatter.getISOFormatDate() : '';
},
onInit: function onInit(owner) {
return owner;
},
onKeyDown: function onKeyDown(event) {
var owner = this,
pps = owner.properties,
charCode = event.which || event.keyCode;
// hit backspace when last character is delimiter
if (charCode === 8 && Util.isDelimiter(pps.result.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
pps.backspace = true;
} else {
pps.backspace = false;
}
owner.registeredEvents.onKeyDown(event);
},
onFocus: function onFocus(event) {
var owner = this,
pps = owner.properties;
event.target.rawValue = owner.getRawValue();
event.target.value = pps.result;
owner.registeredEvents.onFocus(event);
},
onBlur: function onBlur(event) {
var owner = this,
pps = owner.properties;
event.target.rawValue = owner.getRawValue();
event.target.value = pps.result;
owner.registeredEvents.onBlur(event);
},
onChange: function onChange(event) {
var owner = this,
pps = owner.properties;
owner.onInput(event.target.value);
event.target.rawValue = owner.getRawValue();
event.target.value = pps.result;
owner.registeredEvents.onChange(event);
},
onInput: function onInput(value, fromProps) {
var owner = this,
pps = owner.properties;
if (Util.isAndroidBackspaceKeydown(owner.lastInputValue, owner.element.value) && Util.isDelimiter(pps.result.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
pps.backspace = true;
}
// case 1: delete one more character "4"
// 1234*| -> hit backspace -> 123|
// case 2: last character is not delimiter which is:
// 12|34* -> hit backspace -> 1|34*
if (!fromProps && !pps.numeral && pps.backspace && !Util.isDelimiter(value.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
value = Util.headStr(value, value.length - pps.delimiterLength);
}
// phone formatter
if (pps.phone) {
pps.result = pps.phoneFormatter.format(value);
owner.updateValueState();
return;
}
// numeral formatter
if (pps.numeral) {
if (pps.prefix && (!pps.noImmediatePrefix || value.length)) {
pps.result = pps.prefix + pps.numeralFormatter.format(value);
} else {
pps.result = pps.numeralFormatter.format(value);
}
owner.updateValueState();
return;
}
// date
if (pps.date) {
value = pps.dateFormatter.getValidatedDate(value);
}
// strip delimiters
value = Util.stripDelimiters(value, pps.delimiter, pps.delimiters);
// strip prefix
value = Util.getPrefixStrippedValue(value, pps.prefix, pps.prefixLength);
// strip non-numeric characters
value = pps.numericOnly ? Util.strip(value, /[^\d]/g) : value;
// convert case
value = pps.uppercase ? value.toUpperCase() : value;
value = pps.lowercase ? value.toLowerCase() : value;
// prefix
if (pps.prefix && (!pps.noImmediatePrefix || value.length)) {
value = pps.prefix + value;
// no blocks specified, no need to do formatting
if (pps.blocksLength === 0) {
pps.result = value;
owner.updateValueState();
return;
}
}
// update credit card props
if (pps.creditCard) {
owner.updateCreditCardPropsByValue(value);
}
// strip over length characters
value = pps.maxLength > 0 ? Util.headStr(value, pps.maxLength) : value;
// apply blocks
pps.result = Util.getFormattedValue(value, pps.blocks, pps.blocksLength, pps.delimiter, pps.delimiters, pps.delimiterLazyShow);
owner.updateValueState();
},
updateCreditCardPropsByValue: function updateCreditCardPropsByValue(value) {
var owner = this,
pps = owner.properties,
creditCardInfo;
// At least one of the first 4 characters has changed
if (Util.headStr(pps.result, 4) === Util.headStr(value, 4)) {
return;
}
creditCardInfo = CreditCardDetector.getInfo(value, pps.creditCardStrictMode);
pps.blocks = creditCardInfo.blocks;
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
// credit card type changed
if (pps.creditCardType !== creditCardInfo.type) {
pps.creditCardType = creditCardInfo.type;
pps.onCreditCardTypeChanged.call(owner, pps.creditCardType);
}
},
getNextCursorPosition: function getNextCursorPosition(endPos, oldValue, newValue) {
// If cursor was at the end of value, just place it back.
// Because new value could contain additional chars.
if (oldValue.length === endPos) {
return newValue.length;
}
return endPos;
},
setCurrentSelection: function setCurrentSelection(cursorPosition) {
var elem = this.element;
this.setState({
updateCursorPosition: false
});
if (elem === document.activeElement) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', cursorPosition);
range.select();
} else {
elem.setSelectionRange(cursorPosition, cursorPosition);
}
}
},
updateValueState: function updateValueState() {
var owner = this;
if (!owner.element) {
owner.setState({ value: owner.properties.result });
}
var endPos = owner.element.selectionEnd;
var oldValue = owner.element.value;
var newValue = owner.properties.result;
var nextCursorPosition = owner.getNextCursorPosition(endPos, oldValue, newValue);
owner.lastInputValue = owner.properties.result;
if (owner.isAndroid) {
window.setTimeout(function () {
owner.setState({
value: owner.properties.result,
cursorPosition: nextCursorPosition,
updateCursorPosition: true
});
}, 1);
return;
}
owner.setState({
value: owner.properties.result,
cursorPosition: nextCursorPosition,
updateCursorPosition: true
});
},
render: function render() {
var owner = this;
// eslint-disable-next-line
var _owner$props2 = owner.props,
value = _owner$props2.value,
options = _owner$props2.options,
onKeyDown = _owner$props2.onKeyDown,
onFocus = _owner$props2.onFocus,
onBlur = _owner$props2.onBlur,
onChange = _owner$props2.onChange,
onInit = _owner$props2.onInit,
htmlRef = _owner$props2.htmlRef,
propsToTransfer = _objectWithoutProperties(_owner$props2, ['value', 'options', 'onKeyDown', 'onFocus', 'onBlur', 'onChange', 'onInit', 'htmlRef']);
return React.createElement('input', _extends({
type: 'text',
ref: function ref(_ref) {
owner.element = _ref;
if (!htmlRef) {
return;
}
htmlRef.apply(this, arguments);
},
value: owner.state.value,
onKeyDown: owner.onKeyDown,
onChange: owner.onChange,
onFocus: owner.onFocus,
onBlur: owner.onBlur
}, propsToTransfer));
}
});
module.exports = cleaveReactClass;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var React = __webpack_require__(1);
var factory = __webpack_require__(3);
if (typeof React === 'undefined') {
throw Error(
'create-react-class could not find the React object. If you are using script tags, ' +
'make sure that React is being loaded before create-react-class.'
);
}
// Hack to grab NoopUpdateQueue from isomorphic React
var ReactNoopUpdateQueue = new React.Component().updater;
module.exports = factory(
React.Component,
React.isValidElement,
ReactNoopUpdateQueue
);
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = __webpack_require__(4);
var emptyObject = __webpack_require__(5);
var _invariant = __webpack_require__(6);
if (process.env.NODE_ENV !== 'production') {
var warning = __webpack_require__(7);
}
var MIXINS_KEY = 'mixins';
// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
return fn;
}
var ReactPropTypeLocationNames;
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
} else {
ReactPropTypeLocationNames = {};
}
function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: 'DEFINE_MANY',
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: 'DEFINE_MANY',
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: 'DEFINE_MANY',
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: 'DEFINE_MANY',
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: 'DEFINE_MANY',
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: 'DEFINE_MANY_MERGED',
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: 'DEFINE_MANY_MERGED',
/**
* @return {object}
* @optional
*/
getChildContext: 'DEFINE_MANY_MERGED',
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @required
*/
render: 'DEFINE_ONCE',
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: 'DEFINE_MANY',
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: 'DEFINE_MANY',
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: 'DEFINE_MANY',
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: 'DEFINE_ONCE',
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: 'DEFINE_MANY',
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: 'DEFINE_MANY',
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: 'DEFINE_MANY',
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: 'OVERRIDE_BASE'
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function(Constructor, childContextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, childContextTypes, 'childContext');
}
Constructor.childContextTypes = _assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, contextTypes, 'context');
}
Constructor.contextTypes = _assign(
{},
Constructor.contextTypes,
contextTypes
);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(
Constructor.getDefaultProps,
getDefaultProps
);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function(Constructor, propTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, propTypes, 'prop');
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function() {}
};
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an _invariant so components
// don't show up in prod but only in __DEV__
if (process.env.NODE_ENV !== 'production') {
warning(
typeof typeDef[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactClass',
ReactPropTypeLocationNames[location],
propName
);
}
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name)
? ReactClassInterface[name]
: null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
_invariant(
specPolicy === 'OVERRIDE_BASE',
'ReactClassInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
);
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
_invariant(
specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
'ReactClassInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
);
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if (process.env.NODE_ENV !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
if (process.env.NODE_ENV !== 'production') {
warning(
isMixinValid,
"%s: You're attempting to include a mixin that is either null " +
'or not an object. Check the mixins included by the component, ' +
'as well as any mixins they include themselves. ' +
'Expected object but got %s.',
Constructor.displayName || 'ReactClass',
spec === null ? null : typeofSpec
);
}
}
return;
}
_invariant(
typeof spec !== 'function',
"ReactClass: You're attempting to " +
'use a component class or function as a mixin. Instead, just use a ' +
'regular object.'
);
_invariant(
!isValidElement(spec),
"ReactClass: You're attempting to " +
'use a component as a mixin. Instead, just use a regular object.'
);
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isReactClassMethod &&
!isAlreadyDefined &&
spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
_invariant(
isReactClassMethod &&
(specPolicy === 'DEFINE_MANY_MERGED' ||
specPolicy === 'DEFINE_MANY'),
'ReactClass: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
);
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
_invariant(
!isReserved,
'ReactClass: You are attempting to define a reserved ' +
'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
'as an instance property instead; it will still be accessible on the ' +
'constructor.',
name
);
var isInherited = name in Constructor;
_invariant(
!isInherited,
'ReactClass: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
);
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
_invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
);
for (var key in two) {
if (two.hasOwnProperty(key)) {
_invariant(
one[key] === undefined,
'mergeIntoWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: `%s`. This conflict ' +
'may be due to a mixin; in particular, this may be caused by two ' +
'getInitialState() or getDefaultProps() methods returning objects ' +
'with clashing keys.',
key
);
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis) {
for (
var _len = arguments.length,
args = Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
if (process.env.NODE_ENV !== 'production') {
warning(
false,
'bind(): React component methods may only be bound to the ' +
'component instance. See %s',
componentName
);
}
} else if (!args.length) {
if (process.env.NODE_ENV !== 'production') {
warning(
false,
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See %s',
componentName
);
}
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
var IsMountedPreMixin = {
componentDidMount: function() {
this.__isMounted = true;
}
};
var IsMountedPostMixin = {
componentWillUnmount: function() {
this.__isMounted = false;
}
};
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function(newState, callback) {
this.updater.enqueueReplaceState(this, newState, callback);
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
if (process.env.NODE_ENV !== 'production') {
warning(
this.__didWarnIsMounted,
'%s: isMounted is deprecated. Instead, make sure to clean up ' +
'subscriptions and pending requests in componentWillUnmount to ' +
'prevent memory leaks.',
(this.constructor && this.constructor.displayName) ||
this.name ||
'Component'
);
this.__didWarnIsMounted = true;
}
return !!this.__isMounted;
}
};
var ReactClassComponent = function() {};
_assign(
ReactClassComponent.prototype,
ReactComponent.prototype,
ReactClassMixin
);
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
function createClass(spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function(props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
);
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (
initialState === undefined &&
this.getInitialState._isMockFunction
) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
);
this.state = initialState;
});
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, IsMountedPreMixin);
mixSpecIntoComponent(Constructor, spec);
mixSpecIntoComponent(Constructor, IsMountedPostMixin);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if (process.env.NODE_ENV !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
_invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
);
if (process.env.NODE_ENV !== 'production') {
warning(
!Constructor.prototype.componentShouldUpdate,
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
spec.displayName || 'A component'
);
warning(
!Constructor.prototype.componentWillRecieveProps,
'%s has a method called ' +
'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
spec.displayName || 'A component'
);
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
}
return createClass;
}
module.exports = factory;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ }),
/* 5 */
/***/ (function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (process.env.NODE_ENV !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyFunction = __webpack_require__(8);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
/***/ }),
/* 8 */
/***/ (function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 9 */
/***/ (function(module, exports) {
'use strict';
var NumeralFormatter = function NumeralFormatter(numeralDecimalMark, numeralIntegerScale, numeralDecimalScale, numeralThousandsGroupStyle, numeralPositiveOnly, stripLeadingZeroes, delimiter) {
var owner = this;
owner.numeralDecimalMark = numeralDecimalMark || '.';
owner.numeralIntegerScale = numeralIntegerScale > 0 ? numeralIntegerScale : 0;
owner.numeralDecimalScale = numeralDecimalScale >= 0 ? numeralDecimalScale : 2;
owner.numeralThousandsGroupStyle = numeralThousandsGroupStyle || NumeralFormatter.groupStyle.thousand;
owner.numeralPositiveOnly = !!numeralPositiveOnly;
owner.stripLeadingZeroes = stripLeadingZeroes !== false;
owner.delimiter = delimiter || delimiter === '' ? delimiter : ',';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
};
NumeralFormatter.groupStyle = {
thousand: 'thousand',
lakh: 'lakh',
wan: 'wan',
none: 'none'
};
NumeralFormatter.prototype = {
getRawValue: function getRawValue(value) {
return value.replace(this.delimiterRE, '').replace(this.numeralDecimalMark, '.');
},
format: function format(value) {
var owner = this,
parts,
partInteger,
partDecimal = '';
// strip alphabet letters
value = value.replace(/[A-Za-z]/g, '')
// replace the first decimal mark with reserved placeholder
.replace(owner.numeralDecimalMark, 'M')
// strip non numeric letters except minus and "M"
// this is to ensure prefix has been stripped
.replace(/[^\dM-]/g, '')
// replace the leading minus with reserved placeholder
.replace(/^\-/, 'N')
// strip the other minus sign (if present)
.replace(/\-/g, '')
// replace the minus sign (if present)
.replace('N', owner.numeralPositiveOnly ? '' : '-')
// replace decimal mark
.replace('M', owner.numeralDecimalMark);
// strip any leading zeros
if (owner.stripLeadingZeroes) {
value = value.replace(/^(-)?0+(?=\d)/, '$1');
}
partInteger = value;
if (value.indexOf(owner.numeralDecimalMark) >= 0) {
parts = value.split(owner.numeralDecimalMark);
partInteger = parts[0];
partDecimal = owner.numeralDecimalMark + parts[1].slice(0, owner.numeralDecimalScale);
}
if (owner.numeralIntegerScale > 0) {
partInteger = partInteger.slice(0, owner.numeralIntegerScale + (value.slice(0, 1) === '-' ? 1 : 0));
}
switch (owner.numeralThousandsGroupStyle) {
case NumeralFormatter.groupStyle.lakh:
partInteger = partInteger.replace(/(\d)(?=(\d\d)+\d$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.wan:
partInteger = partInteger.replace(/(\d)(?=(\d{4})+$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.thousand:
partInteger = partInteger.replace(/(\d)(?=(\d{3})+$)/g, '$1' + owner.delimiter);
break;
}
return partInteger.toString() + (owner.numeralDecimalScale > 0 ? partDecimal.toString() : '');
}
};
module.exports = NumeralFormatter;
/***/ }),
/* 10 */
/***/ (function(module, exports) {
'use strict';
var DateFormatter = function DateFormatter(datePattern) {
var owner = this;
owner.date = [];
owner.blocks = [];
owner.datePattern = datePattern;
owner.initBlocks();
};
DateFormatter.prototype = {
initBlocks: function initBlocks() {
var owner = this;
owner.datePattern.forEach(function (value) {
if (value === 'Y') {
owner.blocks.push(4);
} else {
owner.blocks.push(2);
}
});
},
getISOFormatDate: function getISOFormatDate() {
var owner = this,
date = owner.date;
return date[2] ? date[2] + '-' + owner.addLeadingZero(date[1]) + '-' + owner.addLeadingZero(date[0]) : '';
},
getBlocks: function getBlocks() {
return this.blocks;
},
getValidatedDate: function getValidatedDate(value) {
var owner = this,
result = '';
value = value.replace(/[^\d]/g, '');
owner.blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
sub0 = sub.slice(0, 1),
rest = value.slice(length);
switch (owner.datePattern[index]) {
case 'd':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 3) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 31) {
sub = '31';
}
break;
case 'm':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 1) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 12) {
sub = '12';
}
break;
}
result += sub;
// update remaining string
value = rest;
}
});
return this.getFixedDateString(result);
},
getFixedDateString: function getFixedDateString(value) {
var owner = this,
datePattern = owner.datePattern,
date = [],
dayIndex = 0,
monthIndex = 0,
yearIndex = 0,
dayStartIndex = 0,
monthStartIndex = 0,
yearStartIndex = 0,
day,
month,
year;
// mm-dd || dd-mm
if (value.length === 4 && datePattern[0].toLowerCase() !== 'y' && datePattern[1].toLowerCase() !== 'y') {
dayStartIndex = datePattern[0] === 'd' ? 0 : 2;
monthStartIndex = 2 - dayStartIndex;
day = parseInt(value.slice(dayStartIndex, dayStartIndex + 2), 10);
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
date = this.getFixedDate(day, month, 0);
}
// yyyy-mm-dd || yyyy-dd-mm || mm-dd-yyyy || dd-mm-yyyy || dd-yyyy-mm || mm-yyyy-dd
if (value.length === 8) {
datePattern.forEach(function (type, index) {
switch (type) {
case 'd':
dayIndex = index;
break;
case 'm':
monthIndex = index;
break;
default:
yearIndex = index;
break;
}
});
yearStartIndex = yearIndex * 2;
dayStartIndex = dayIndex <= yearIndex ? dayIndex * 2 : dayIndex * 2 + 2;
monthStartIndex = monthIndex <= yearIndex ? monthIndex * 2 : monthIndex * 2 + 2;
day = parseInt(value.slice(dayStartIndex, dayStartIndex + 2), 10);
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
year = parseInt(value.slice(yearStartIndex, yearStartIndex + 4), 10);
date = this.getFixedDate(day, month, year);
}
owner.date = date;
return date.length === 0 ? value : datePattern.reduce(function (previous, current) {
switch (current) {
case 'd':
return previous + owner.addLeadingZero(date[0]);
case 'm':
return previous + owner.addLeadingZero(date[1]);
default:
return previous + '' + (date[2] || '');
}
}, '');
},
getFixedDate: function getFixedDate(day, month, year) {
day = Math.min(day, 31);
month = Math.min(month, 12);
year = parseInt(year || 0, 10);
if (month < 7 && month % 2 === 0 || month > 8 && month % 2 === 1) {
day = Math.min(day, month === 2 ? this.isLeapYear(year) ? 29 : 28 : 30);
}
return [day, month, year];
},
isLeapYear: function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
},
addLeadingZero: function addLeadingZero(number) {
return (number < 10 ? '0' : '') + number;
}
};
module.exports = DateFormatter;
/***/ }),
/* 11 */
/***/ (function(module, exports) {
'use strict';
var PhoneFormatter = function PhoneFormatter(formatter, delimiter) {
var owner = this;
owner.delimiter = delimiter || delimiter === '' ? delimiter : ' ';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
owner.formatter = formatter;
};
PhoneFormatter.prototype = {
setFormatter: function setFormatter(formatter) {
this.formatter = formatter;
},
format: function format(phoneNumber) {
var owner = this;
owner.formatter.clear();
// only keep number and +
phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
// strip delimiter
phoneNumber = phoneNumber.replace(owner.delimiterRE, '');
var result = '',
current,
validated = false;
for (var i = 0, iMax = phoneNumber.length; i < iMax; i++) {
current = owner.formatter.inputDigit(phoneNumber.charAt(i));
// has ()- or space inside
if (/[\s()-]/g.test(current)) {
result = current;
validated = true;
} else {
if (!validated) {
result = current;
}
// else: over length input
// it turns to invalid number again
}
}
// strip ()
// e.g. US: 7161234567 returns (716) 123-4567
result = result.replace(/[()]/g, '');
// replace library delimiter with user customized delimiter
result = result.replace(/[\s-]/g, owner.delimiter);
return result;
}
};
module.exports = PhoneFormatter;
/***/ }),
/* 12 */
/***/ (function(module, exports) {
'use strict';
var CreditCardDetector = {
blocks: {
uatp: [4, 5, 6],
amex: [4, 6, 5],
diners: [4, 6, 4],
discover: [4, 4, 4, 4],
mastercard: [4, 4, 4, 4],
dankort: [4, 4, 4, 4],
instapayment: [4, 4, 4, 4],
jcb: [4, 4, 4, 4],
maestro: [4, 4, 4, 4],
visa: [4, 4, 4, 4],
mir: [4, 4, 4, 4],
general: [4, 4, 4, 4],
unionPay: [4, 4, 4, 4],
generalStrict: [4, 4, 4, 7]
},
re: {
// starts with 1; 15 digits, not starts with 1800 (jcb card)
uatp: /^(?!1800)1\d{0,14}/,
// starts with 34/37; 15 digits
amex: /^3[47]\d{0,13}/,
// starts with 6011/65/644-649; 16 digits
discover: /^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/,
// starts with 300-305/309 or 36/38/39; 14 digits
diners: /^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,
// starts with 51-55/2221–2720; 16 digits
mastercard: /^(5[1-5]\d{0,2}|22[2-9]\d{0,1}|2[3-7]\d{0,2})\d{0,12}/,
// starts with 5019/4175/4571; 16 digits
dankort: /^(5019|4175|4571)\d{0,12}/,
// starts with 637-639; 16 digits
instapayment: /^63[7-9]\d{0,13}/,
// starts with 2131/1800/35; 16 digits
jcb: /^(?:2131|1800|35\d{0,2})\d{0,12}/,
// starts with 50/56-58/6304/67; 16 digits
maestro: /^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/,
// starts with 22; 16 digits
mir: /^220[0-4]\d{0,12}/,
// starts with 4; 16 digits
visa: /^4\d{0,15}/,
// starts with 62; 16 digits
unionPay: /^62\d{0,14}/
},
getInfo: function getInfo(value, strictMode) {
var blocks = CreditCardDetector.blocks,
re = CreditCardDetector.re;
// In theory, visa credit card can have up to 19 digits number.
// Set strictMode to true will remove the 16 max-length restrain,
// however, I never found any website validate card number like
// this, hence probably you don't need to enable this option.
strictMode = !!strictMode;
for (var key in re) {
if (re[key].test(value)) {
var block;
if (key === 'discover' || key === 'maestro' || key === 'visa' || key === 'mir' || key === 'unionPay') {
block = strictMode ? blocks.generalStrict : blocks[key];
} else {
block = blocks[key];
}
return {
type: key,
blocks: block
};
}
}
return {
type: 'unknown',
blocks: strictMode ? blocks.generalStrict : blocks.general
};
}
};
module.exports = CreditCardDetector;
/***/ }),
/* 13 */
/***/ (function(module, exports) {
'use strict';
var Util = {
noop: function noop() {},
strip: function strip(value, re) {
return value.replace(re, '');
},
isDelimiter: function isDelimiter(letter, delimiter, delimiters) {
// single delimiter
if (delimiters.length === 0) {
return letter === delimiter;
}
// multiple delimiters
return delimiters.some(function (current) {
if (letter === current) {
return true;
}
});
},
getDelimiterREByDelimiter: function getDelimiterREByDelimiter(delimiter) {
return new RegExp(delimiter.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), 'g');
},
stripDelimiters: function stripDelimiters(value, delimiter, delimiters) {
var owner = this;
// single delimiter
if (delimiters.length === 0) {
var delimiterRE = delimiter ? owner.getDelimiterREByDelimiter(delimiter) : '';
return value.replace(delimiterRE, '');
}
// multiple delimiters
delimiters.forEach(function (current) {
value = value.replace(owner.getDelimiterREByDelimiter(current), '');
});
return value;
},
headStr: function headStr(str, length) {
return str.slice(0, length);
},
getMaxLength: function getMaxLength(blocks) {
return blocks.reduce(function (previous, current) {
return previous + current;
}, 0);
},
// strip value by prefix length
// for prefix: PRE
// (PRE123, 3) -> 123
// (PR123, 3) -> 23 this happens when user hits backspace in front of "PRE"
getPrefixStrippedValue: function getPrefixStrippedValue(value, prefix, prefixLength) {
if (value.slice(0, prefixLength) !== prefix) {
var diffIndex = this.getFirstDiffIndex(prefix, value.slice(0, prefixLength));
value = prefix + value.slice(diffIndex, diffIndex + 1) + value.slice(prefixLength + 1);
}
return value.slice(prefixLength);
},
getFirstDiffIndex: function getFirstDiffIndex(prev, current) {
var index = 0;
while (prev.charAt(index) === current.charAt(index)) {
if (prev.charAt(index++) === '') {
return -1;
}
}
return index;
},
getFormattedValue: function getFormattedValue(value, blocks, blocksLength, delimiter, delimiters, delimiterLazyShow) {
var result = '',
multipleDelimiters = delimiters.length > 0,
currentDelimiter;
// no options, normal input
if (blocksLength === 0) {
return value;
}
blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
if (multipleDelimiters) {
currentDelimiter = delimiters[delimiterLazyShow ? index - 1 : index] || currentDelimiter;
} else {
currentDelimiter = delimiter;
}
if (delimiterLazyShow) {
if (index > 0) {
result += currentDelimiter;
}
result += sub;
} else {
result += sub;
if (sub.length === length && index < blocksLength - 1) {
result += currentDelimiter;
}
}
// update remaining string
value = rest;
}
});
return result;
},
isAndroid: function isAndroid() {
return navigator && /android/i.test(navigator.userAgent);
},
// On Android chrome, the keyup and keydown events
// always return key code 229 as a composition that
// buffers the user’s keystrokes
// see https://github.com/nosir/cleave.js/issues/147
isAndroidBackspaceKeydown: function isAndroidBackspaceKeydown(lastInputValue, currentInputValue) {
if (!this.isAndroid() || !lastInputValue || !currentInputValue) {
return false;
}
return currentInputValue === lastInputValue.slice(0, -1);
}
};
module.exports = Util;
/***/ }),
/* 14 */
/***/ (function(module, exports) {
'use strict';
/**
* Props Assignment
*
* Separate this, so react module can share the usage
*/
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var DefaultProperties = {
// Maybe change to object-assign
// for now just keep it as simple
assign: function assign(target, opts) {
target = target || {};
opts = opts || {};
// credit card
target.creditCard = !!opts.creditCard;
target.creditCardStrictMode = !!opts.creditCardStrictMode;
target.creditCardType = '';
target.onCreditCardTypeChanged = opts.onCreditCardTypeChanged || function () {};
// phone
target.phone = !!opts.phone;
target.phoneRegionCode = opts.phoneRegionCode || 'AU';
target.phoneFormatter = {};
// date
target.date = !!opts.date;
target.datePattern = opts.datePattern || ['d', 'm', 'Y'];
target.dateFormatter = {};
// numeral
target.numeral = !!opts.numeral;
target.numeralIntegerScale = opts.numeralIntegerScale > 0 ? opts.numeralIntegerScale : 0;
target.numeralDecimalScale = opts.numeralDecimalScale >= 0 ? opts.numeralDecimalScale : 2;
target.numeralDecimalMark = opts.numeralDecimalMark || '.';
target.numeralThousandsGroupStyle = opts.numeralThousandsGroupStyle || 'thousand';
target.numeralPositiveOnly = !!opts.numeralPositiveOnly;
target.stripLeadingZeroes = opts.stripLeadingZeroes !== false;
// others
target.numericOnly = target.creditCard || target.date || !!opts.numericOnly;
target.uppercase = !!opts.uppercase;
target.lowercase = !!opts.lowercase;
target.prefix = target.creditCard || target.date ? '' : opts.prefix || '';
target.noImmediatePrefix = !!opts.noImmediatePrefix;
target.prefixLength = target.prefix.length;
target.rawValueTrimPrefix = !!opts.rawValueTrimPrefix;
target.copyDelimiter = !!opts.copyDelimiter;
target.initValue = opts.initValue !== undefined && opts.initValue !== null ? opts.initValue.toString() : '';
target.delimiter = opts.delimiter || opts.delimiter === '' ? opts.delimiter : opts.date ? '/' : opts.numeral ? ',' : opts.phone ? ' ' : ' ';
target.delimiterLength = target.delimiter.length;
target.delimiterLazyShow = !!opts.delimiterLazyShow;
target.delimiters = opts.delimiters || [];
target.blocks = opts.blocks || [];
target.blocksLength = target.blocks.length;
target.root = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object' && global ? global : window;
target.maxLength = 0;
target.backspace = false;
target.result = '';
return target;
}
};
module.exports = DefaultProperties;
/***/ })
/******/ ])
});
;
|
/* */
'use strict';
var EventConstants = require("./EventConstants");
var emptyFunction = require("./emptyFunction");
var topLevelTypes = EventConstants.topLevelTypes;
var MobileSafariClickEventPlugin = {
eventTypes: null,
extractEvents: function(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) {
if (topLevelType === topLevelTypes.topTouchStart) {
var target = nativeEvent.target;
if (target && !target.onclick) {
target.onclick = emptyFunction;
}
}
}
};
module.exports = MobileSafariClickEventPlugin;
|
/*!
* ui-grid - v4.4.1 - 2018-03-16
* Copyright (c) 2018 ; License: MIT
*/
(function () {
'use strict';
/**
* @ngdoc overview
* @name ui.grid.treeView
* @description
*
* # ui.grid.treeView
*
* <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
*
* This module provides a tree view of the data that it is provided, with nodes in that
* tree and leaves. Unlike grouping, the tree is an inherent property of the data and must
* be provided with your data array.
*
* Design information:
* -------------------
*
* TreeView uses treeBase for the underlying functionality, and is a very thin wrapper around
* that logic. Most of the design information has now moved to treebase.
* <br/>
* <br/>
*
* <div doc-module-components="ui.grid.treeView"></div>
*/
var module = angular.module('ui.grid.treeView', ['ui.grid', 'ui.grid.treeBase']);
/**
* @ngdoc object
* @name ui.grid.treeView.constant:uiGridTreeViewConstants
*
* @description constants available in treeView module, this includes
* all the constants declared in the treeBase module (these are manually copied
* as there isn't an easy way to include constants in another constants file, and
* we don't want to make users include treeBase)
*
*/
module.constant('uiGridTreeViewConstants', {
featureName: "treeView",
rowHeaderColName: 'treeBaseRowHeaderCol',
EXPANDED: 'expanded',
COLLAPSED: 'collapsed',
aggregation: {
COUNT: 'count',
SUM: 'sum',
MAX: 'max',
MIN: 'min',
AVG: 'avg'
}
});
/**
* @ngdoc service
* @name ui.grid.treeView.service:uiGridTreeViewService
*
* @description Services for treeView features
*/
module.service('uiGridTreeViewService', ['$q', 'uiGridTreeViewConstants', 'uiGridTreeBaseConstants', 'uiGridTreeBaseService', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants',
function ($q, uiGridTreeViewConstants, uiGridTreeBaseConstants, uiGridTreeBaseService, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants) {
var service = {
initializeGrid: function (grid, $scope) {
uiGridTreeBaseService.initializeGrid( grid, $scope );
/**
* @ngdoc object
* @name ui.grid.treeView.grid:treeView
*
* @description Grid properties and functions added for treeView
*/
grid.treeView = {};
grid.registerRowsProcessor(service.adjustSorting, 60);
/**
* @ngdoc object
* @name ui.grid.treeView.api:PublicApi
*
* @description Public Api for treeView feature
*/
var publicApi = {
events: {
treeView: {
}
},
methods: {
treeView: {
}
}
};
grid.api.registerEventsFromObject(publicApi.events);
grid.api.registerMethodsFromObject(publicApi.methods);
},
defaultGridOptions: function (gridOptions) {
//default option to true unless it was explicitly set to false
/**
* @ngdoc object
* @name ui.grid.treeView.api:GridOptions
*
* @description GridOptions for treeView feature, these are available to be
* set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
*
* Many tree options are set on treeBase, make sure to look at that feature in
* conjunction with these options.
*/
/**
* @ngdoc object
* @name enableTreeView
* @propertyOf ui.grid.treeView.api:GridOptions
* @description Enable row tree view for entire grid.
* <br/>Defaults to true
*/
gridOptions.enableTreeView = gridOptions.enableTreeView !== false;
},
/**
* @ngdoc function
* @name adjustSorting
* @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
* @description Trees cannot be sorted the same as flat lists of rows -
* trees are sorted recursively within each level - so the children of each
* node are sorted, but not the full set of rows.
*
* To achieve this, we suppress the normal sorting by setting ignoreSort on
* each of the sort columns. When the treeBase rowsProcessor runs it will then
* unignore these, and will perform a recursive sort against the tree that it builds.
*
* @param {array} renderableRows the rows that we need to pass on through
* @returns {array} renderableRows that we passed on through
*/
adjustSorting: function( renderableRows ) {
var grid = this;
grid.columns.forEach( function( column ){
if ( column.sort ){
column.sort.ignoreSort = true;
}
});
return renderableRows;
}
};
return service;
}]);
/**
* @ngdoc directive
* @name ui.grid.treeView.directive:uiGridTreeView
* @element div
* @restrict A
*
* @description Adds treeView features to grid
*
* @example
<example module="app">
<file name="app.js">
var app = angular.module('app', ['ui.grid', 'ui.grid.treeView']);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.data = [
{ name: 'Bob', title: 'CEO' },
{ name: 'Frank', title: 'Lowly Developer' }
];
$scope.columnDefs = [
{name: 'name', enableCellEdit: true},
{name: 'title', enableCellEdit: true}
];
$scope.gridOptions = { columnDefs: $scope.columnDefs, data: $scope.data };
}]);
</file>
<file name="index.html">
<div ng-controller="MainCtrl">
<div ui-grid="gridOptions" ui-grid-tree-view></div>
</div>
</file>
</example>
*/
module.directive('uiGridTreeView', ['uiGridTreeViewConstants', 'uiGridTreeViewService', '$templateCache',
function (uiGridTreeViewConstants, uiGridTreeViewService, $templateCache) {
return {
replace: true,
priority: 0,
require: '^uiGrid',
scope: false,
compile: function () {
return {
pre: function ($scope, $elm, $attrs, uiGridCtrl) {
if (uiGridCtrl.grid.options.enableTreeView !== false){
uiGridTreeViewService.initializeGrid(uiGridCtrl.grid, $scope);
}
},
post: function ($scope, $elm, $attrs, uiGridCtrl) {
}
};
}
};
}]);
})();
|
/**
@module ember
@submodule ember-views
*/
import Ember from 'ember-metal/core';
import { Mixin } from 'ember-metal/mixin';
import { get } from 'ember-metal/property_get';
import { set } from 'ember-metal/property_set';
import setProperties from 'ember-metal/set_properties';
var EMPTY_ARRAY = [];
export default Mixin.create({
/**
Array of child views. You should never edit this array directly.
Instead, use `appendChild` and `removeFromParent`.
@property childViews
@type Array
@default []
@private
*/
childViews: EMPTY_ARRAY,
init() {
this._super(...arguments);
// setup child views. be sure to clone the child views array first
// 2.0TODO: Remove Ember.A() here
this.childViews = Ember.A(this.childViews.slice());
this.ownerView = this.ownerView || this;
},
appendChild(view) {
this.linkChild(view);
this.childViews.push(view);
},
destroyChild(view) {
view.destroy();
},
/**
Removes the child view from the parent view.
@method removeChild
@param {Ember.View} view
@return {Ember.View} receiver
@private
*/
removeChild(view) {
// If we're destroying, the entire subtree will be
// freed, and the DOM will be handled separately,
// so no need to mess with childViews.
if (this.isDestroying) { return; }
// update parent node
this.unlinkChild(view);
// remove view from childViews array.
var childViews = get(this, 'childViews');
var index = childViews.indexOf(view);
if (index !== -1) { childViews.splice(index, 1); }
return this;
},
/**
Instantiates a view to be added to the childViews array during view
initialization. You generally will not call this method directly unless
you are overriding `createChildViews()`. Note that this method will
automatically configure the correct settings on the new view instance to
act as a child of the parent.
@method createChildView
@param {Class|String} viewClass
@param {Object} [attrs] Attributes to add
@return {Ember.View} new instance
@private
*/
createChildView(maybeViewClass, _attrs) {
if (!maybeViewClass) {
throw new TypeError('createChildViews first argument must exist');
}
if (maybeViewClass.isView && maybeViewClass.parentView === this && maybeViewClass.container === this.container) {
return maybeViewClass;
}
var attrs = _attrs || {};
var view;
attrs.parentView = this;
attrs.renderer = this.renderer;
attrs._viewRegistry = this._viewRegistry;
if (maybeViewClass.isViewFactory) {
attrs.container = this.container;
view = maybeViewClass.create(attrs);
if (view.viewName) {
set(this, view.viewName, view);
}
} else if ('string' === typeof maybeViewClass) {
var fullName = 'view:' + maybeViewClass;
var ViewKlass = this.container.lookupFactory(fullName);
Ember.assert('Could not find view: \'' + fullName + '\'', !!ViewKlass);
view = ViewKlass.create(attrs);
} else {
view = maybeViewClass;
Ember.assert('You must pass instance or subclass of View', view.isView);
attrs.container = this.container;
setProperties(view, attrs);
}
this.linkChild(view);
return view;
},
linkChild(instance) {
instance.container = this.container;
instance.parentView = this;
instance.ownerView = this.ownerView;
},
unlinkChild(instance) {
instance.parentView = null;
}
});
|
import Ember from 'ember';
import {
moduleForComponent,
test
} from 'ember-qunit';
moduleForComponent('paper-radio', 'PaperRadioComponent', {
// specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar']
unit: true
});
test('it renders', function(assert) {
assert.expect(2);
// creates the component instance
var component = this.subject();
assert.equal(component._state, 'preRender');
// appends the component to the page
this.render();
assert.equal(component._state, 'inDOM');
});
test('should set checked css class', function(assert) {
var component = this.subject();
this.render();
Ember.run(function() {
component.set('checked', true);
});
assert.ok(this.$().hasClass('md-checked'));
});
test('it updates when clicked, and triggers the `changed` action', function(assert) {
var changedActionCallCount = 0;
var Controller = Ember.Controller.extend({
actions: {
changed: function() {
changedActionCallCount++;
}
}
});
var component = this.subject({
value: 'component-value',
selected: 'initial-selected-value',
changed: 'changed',
targetObject: Controller.create()
});
this.render();
assert.equal(changedActionCallCount, 0);
assert.equal(component.$().hasClass('md-checked'), false);
Ember.run(function() {
component.$().trigger('click');
});
assert.equal(component.$().hasClass('md-checked'), true, 'updates element property');
assert.equal(component.get('checked'), true, 'updates component property');
assert.equal(component.get('selected'), 'component-value', 'updates selected ');
assert.equal(changedActionCallCount, 1);
});
test('it is possible to check and set selected property to value', function(assert) {
var component = this.subject();
assert.ok(!component.get('selected'));
var value = 'some value';
Ember.run(function() {
component.set('value', value);
});
this.$().trigger('click');
assert.equal(component.get('selected'), value);
});
test('it isn\'t possible to uncheck and set selected property to null', function(assert) {
var component = this.subject();
var value = 'some value';
Ember.run(function() {
component.set('value', value);
component.set('selected', value);
});
this.$().trigger('click');
//still has value
assert.equal(component.get('selected'), value);
});
test('it is possible to uncheck and set selected property to null if toggle is true', function(assert) {
var component = this.subject();
var value = 'some value';
Ember.run(function() {
component.set('value', value);
component.set('selected', value);
component.set('toggle', true);
});
this.$().trigger('click');
assert.equal(component.get('selected'), null);
});
test('it isn\'t possible to check a disabled radio button', function(assert) {
var component = this.subject();
Ember.run(function() {
component.set('disabled', true);
component.set('selected', false);
});
this.$().trigger('click');
assert.equal(component.get('selected'), false);
});
|
var sass = require('../sass')
, fs = require('fs')
, url = require('url')
, basename = require('path').basename
, dirname = require('path').dirname
, mkdirp = require('mkdirp')
, join = require('path').join;
var imports = {};
/**
* Return Connect middleware with the given `options`.
*
* Options:
*
* `force` Always re-compile
* `debug` Output debugging information
* `src` Source directory used to find .scss files
* `dest` Destination directory used to output .css files
* when undefined defaults to `src`.
* `outputStyle` Sass output style (nested,expanded, compact or compressed)
*
* Examples:
*
* Pass the middleware to Connect, grabbing .scss files from this directory
* and saving .css files to _./public_.
*
* Following that we have a `staticProvider` layer setup to serve the .css
* files generated by Sass.
*
* var server = connect.createServer(
* sass.middleware({
* src: __dirname
* , dest: __dirname + '/public'
* })
* , connect.static(__dirname + '/public')
* );
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function(options){
options = options || {};
// Accept src/dest dir
if ('string' == typeof options) {
options = { src: options };
}
// Force compilation
var force = options.force;
// Debug option
var debug = options.debug;
// Source dir required
var src = options.src;
if (!src) throw new Error('sass.middleware() requires "src" directory');
// Default dest dir to source
var dest = options.dest
? options.dest
: src;
var root = options.root || null;
// Default compile callback
options.compile = options.compile || function(){
return sass
};
// Middleware
return function sass(req, res, next){
if ('GET' != req.method && 'HEAD' != req.method) return next();
var path = url.parse(req.url).pathname;
if (/\.css$/.test(path)) {
var cssPath = join(dest, path)
, sassPath = join(src, path.replace('.css', '.scss'))
, sassDir = dirname(sassPath);
if (root) {
cssPath = join(root, dest, path.replace(dest, ''));
sassPath = join(root, src, path
.replace(dest, '')
.replace('.css', '.scss'));
sassDir = dirname(sassPath);
}
if (debug) {
log('source', sassPath);
log('dest', cssPath);
}
// Ignore ENOENT to fall through as 404
function error(err) {
next('ENOENT' == err.code
? null
: err);
}
// Force
if (force) return compile();
// Compile to cssPath
function compile() {
if (debug) log('read', cssPath);
fs.readFile(sassPath, 'utf8', function(err, str){
if (err) return error(err);
var style = options.compile();
var paths = [];
delete imports[sassPath];
style.render(str, function(err, css){
if (err) return next(err);
if (debug) log('render', sassPath);
imports[sassPath] = paths;
mkdirp(dirname(cssPath), 0700, function(err){
if (err) return error(err);
fs.writeFile(cssPath, css, 'utf8', next);
});
}, {
include_paths: [ sassDir ].concat(options.include_paths || options.includePaths || []),
output_style: options.output_style || options.outputStyle
});
});
}
// Re-compile on server restart, disregarding
// mtimes since we need to map imports
if (!imports[sassPath]) return compile();
// Compare mtimes
fs.stat(sassPath, function(err, sassStats){
if (err) return error(err);
fs.stat(cssPath, function(err, cssStats){
// CSS has not been compiled, compile it!
if (err) {
if ('ENOENT' == err.code) {
if (debug) log('not found', cssPath);
compile();
} else {
next(err);
}
} else {
// Source has changed, compile it
if (sassStats.mtime > cssStats.mtime) {
if (debug) log('modified', cssPath);
compile();
// Already compiled, check imports
} else {
checkImports(sassPath, function(changed){
if (debug && changed && changed.length) {
changed.forEach(function(path) {
log('modified import %s', path);
});
}
changed && changed.length ? compile() : next();
});
}
}
});
});
} else {
next();
}
}
};
/**
* Check `path`'s imports to see if they have been altered.
*
* @param {String} path
* @param {Function} fn
* @api private
*/
function checkImports(path, fn) {
var nodes = imports[path];
if (!nodes) return fn();
if (!nodes.length) return fn();
var pending = nodes.length
, changed = [];
nodes.forEach(function(imported){
fs.stat(imported.path, function(err, stat){
// error or newer mtime
if (err || !imported.mtime || stat.mtime > imported.mtime) {
changed.push(imported.path);
}
--pending || fn(changed);
});
});
}
/**
* Log a message.
*
* @api private
*/
function log(key, val) {
console.error(' \033[90m%s :\033[0m \033[36m%s\033[0m', key, val);
}
|
describe("ResultsNode", function() {
it("wraps a result", function() {
var fakeResult = {
id: 123,
message: "foo"
},
node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null);
expect(node.result).toBe(fakeResult);
expect(node.type).toEqual("suite");
});
it("can add children with a type", function() {
var fakeResult = {
id: 123,
message: "foo"
},
fakeChildResult = {
id: 456,
message: "bar"
},
node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null);
node.addChild(fakeChildResult, "spec");
expect(node.children.length).toEqual(1);
expect(node.children[0].result).toEqual(fakeChildResult);
expect(node.children[0].type).toEqual("spec");
});
it("has a pointer back to its parent ResultNode", function() {
var fakeResult = {
id: 123,
message: "foo"
},
fakeChildResult = {
id: 456,
message: "bar"
},
node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null);
node.addChild(fakeChildResult, "spec");
expect(node.children[0].parent).toBe(node);
});
it("can provide the most recent child", function() {
var fakeResult = {
id: 123,
message: "foo"
},
fakeChildResult = {
id: 456,
message: "bar"
},
node = new jasmineUnderTest.ResultsNode(fakeResult, "suite", null);
node.addChild(fakeChildResult, "spec");
expect(node.last()).toBe(node.children[node.children.length - 1]);
});
});
|
/**
* Created by wangjian on 16/1/20.
*/
define(['dojo/_base/declare',
'dijit/_WidgetBase',
'dojo/_base/lang',
'dojo/_base/html',
'dojo/on',
'dojo/mouse',
'dojo/_base/fx',
'dojo/Evented'
], function(declare, _WidgetBase, lang, html, on, Mouse, baseFx, Evented) {
var ANIMATION_DURATION = 1000,
AUTO_CLOSE_INTERVAL = 10000,
STATE_HIDE = 0,
STATE_SHOW = 1;
return declare([_WidgetBase, Evented], {
'baseClass': 'jimu-appstate-popup',
declaredClass: 'jimu.dijit.AppStatePopup',
currentState: STATE_HIDE,
timeoutHandler: undefined,
constructor: function(params) {
this.inherited(arguments);
if('animationDuration' in params) {
ANIMATION_DURATION = params.animationDuration;
}
if('autoCloseInterval' in params) {
AUTO_CLOSE_INTERVAL = params.autoCloseInterval;
}
},
postCreate: function() {
if(window.appInfo.isRunInMobile){
html.addClass(this.domNode, 'mobile');
}
var header = html.create('div', {
'class': 'appstate-header'
});
html.create('div', {
'class': 'appstate-title',
innerHTML: this.nls.title
}, header);
var closeNode = html.create('div', {
'class': 'appstate-close'
}, header);
html.place(header, this.domNode);
var labelNode = html.create('div', {
'class': 'appstate-tips',
innerHTML: this.nls.restoreMap
});
html.place(labelNode, this.domNode);
this.own(on(labelNode, 'click', lang.hitch(this, function() {
this.emit('applyAppState');
this.hide();
})));
this.own(on(closeNode, 'click', lang.hitch(this, function() {
this.hide();
})));
this.own(on(this.domNode, Mouse.enter, lang.hitch(this, function() {
if(this.timeoutHandler) {
clearTimeout(this.timeoutHandler);
this.timeoutHandler = undefined;
}
})));
this.own(on(this.domNode, Mouse.leave, lang.hitch(this, function() {
if(this.currentState === STATE_SHOW && !this.timeoutHandler) {
this.timeoutHandler = setTimeout(lang.hitch(this, this.hide), AUTO_CLOSE_INTERVAL);
}
})));
},
show: function() {
var animProperties;
if(window.appInfo.isRunInMobile){
animProperties = {
top: {
start: -120,
end: 0
}
};
}else {
animProperties = {
bottom: {
start: -100,
end: 10
}
};
}
baseFx.animateProperty({
node: this.domNode,
duration: ANIMATION_DURATION,
properties: animProperties,
onEnd: lang.hitch(this, function() {
this.currentState = STATE_SHOW;
})
}).play();
this.timeoutHandler = setTimeout(lang.hitch(this, this.hide), AUTO_CLOSE_INTERVAL);
},
hide: function() {
if(this.currentState === STATE_HIDE) {
return;
}
var animProperties;
if(window.appInfo.isRunInMobile){
animProperties = {
top: {
start: 0,
end: -120
}
};
}else {
animProperties = {
bottom: {
start: 10,
end: -100
}
};
}
baseFx.animateProperty({
node: this.domNode,
duration: ANIMATION_DURATION,
properties: animProperties,
onEnd: lang.hitch(this, function() {
this.currentState = STATE_HIDE;
html.setStyle(this.domNode, 'display', 'none');
})
}).play();
}
});
});
|
FamousFramework.scene('famous-tests:physics:basic:spring', {
behaviors: {
'.particle': {
'size': [100, 100],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5]
},
'.one': {
'position': function(position1) {
return position1
},
'style': {
'background': '#666',
'border-radius': '50%',
'box-shadow': '0 0 100px #fff'
}
},
'.two': {
'position': function(position2) {
return position2;
},
'style': {
'background': 'whitesmoke',
'border-radius': '50%'
}
}
},
events: {
'$lifecycle': {
'post-load': function($state) {
$state.applyPhysicsForce('spring', [ 'position1', 'position2' ], {
period: 2,
dampingRatio: 0.3
});
$state.setPhysicsMass('position1', 500);
$state.setPhysicsMass('position2', 5);
}
},
'.one': {
'click': function($state) {
var xPos = Math.floor(Math.random() * window.innerWidth / 2);
var yPos = Math.floor(Math.random() * window.innerHeight / 2);
xPos = Math.random() > 0.5 ? -xPos : xPos;
yPos = Math.random() > 0.5 ? -yPos : yPos;
$state.setPhysicsPosition('position1', [ xPos, yPos, 0 ]);
}
},
'.two': {
'click': function($state) {
var xPos = Math.floor(Math.random() * window.innerWidth / 2);
var yPos = Math.floor(Math.random() * window.innerHeight / 2);
xPos = Math.random() > 0.5 ? -xPos : xPos;
yPos = Math.random() > 0.5 ? -yPos : yPos;
$state.setPhysicsPosition('position1', [ xPos, yPos, 0 ]);
}
}
},
states: {
'position1': [ 200, 0, 0],
'position2': [-200, 0, 0]
},
tree: `
<node class="particle one"></node>
<node class="particle two"></node>
`
});
|
const foo = {
a: 'a' /* comment for this line */,
/* Section B */
b: 'b',
};
|
module.exports=/[\u2800-\u28FF]/
|
'use strict';
var path = require('path');
var fs = require('graceful-fs');
var stripBom = require('strip-bom');
var File = require('vinyl');
exports.read = function (pth, opts, cb) {
opts = opts || {};
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
fs.stat(pth, function (err, stat) {
if (err) {
cb(err);
return;
}
var cwd = opts.cwd || process.cwd();
var base = opts.base || cwd;
var file = new File({
cwd: cwd,
base: base,
path: path.resolve(pth),
stat: stat,
});
if (opts.read === false) {
cb(null, file);
return;
}
if (opts.buffer === false) {
file.contents = fs.createReadStream(pth).pipe(stripBom.stream());
cb(null, file);
return;
}
fs.readFile(pth, function (err, buf) {
if (err) {
cb(err);
return;
}
file.contents = stripBom(buf);
cb(null, file);
});
});
};
exports.readSync = function (pth, opts) {
opts = opts || {};
var contents;
if (opts.read !== false) {
contents = opts.buffer === false ?
fs.createReadStream(pth).pipe(stripBom.stream()) :
stripBom(fs.readFileSync(pth));
}
return new File({
cwd: opts.cwd || process.cwd(),
base: opts.base || process.cwd(),
path: path.resolve(pth),
stat: fs.statSync(pth),
contents: contents
});
};
|
module.exports={A:{A:{"2":"I C G E SB","1028":"B","1316":"A"},B:{"1":"D g q K"},C:{"1":"0 1 2 X Y Z a b c d e f J h i j k l m n o p u v w t y r W","164":"3 QB F H I C G E A B D g q K L M N O P Q OB NB","516":"R S T U V s"},D:{"1":"0 1 2 6 9 Y Z a b c d e f J h i j k l m n o p u v w t y r W CB RB AB","33":"Q R S T U V s X","164":"F H I C G E A B D g q K L M N O P"},E:{"1":"E A GB HB IB","33":"C G EB FB","164":"7 F H I BB DB"},F:{"1":"M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p z","2":"4 5 E B D JB KB LB MB PB","33":"K L"},G:{"1":"XB YB ZB aB","33":"G VB WB","164":"7 8 x TB UB"},H:{"1":"bB"},I:{"1":"W gB hB","164":"3 F cB dB eB fB x"},J:{"1":"A","164":"C"},K:{"1":"J z","2":"4 5 A B D"},L:{"1":"6"},M:{"1":"r"},N:{"1":"B","292":"A"},O:{"164":"iB"},P:{"1":"F H"},Q:{"1":"jB"},R:{"1":"kB"}},B:4,C:"Flexible Box Layout Module"};
|
/**
* Module dependencies.
*/
var _ = require('lodash');
var async = require('async');
var __hooks = require('../../hooks');
module.exports = function(sails) {
var Hook = __hooks(sails);
/**
* Resolve the hook definitions and then finish loading them
*
* @api private
*/
return function initializeHooks(hooks, cb) {
// Instantiate Hook instances using definitions
_.each(hooks, function(hookPrototype, id) {
// Allow disabling of hooks by setting them to "false"
// Useful for testing, but may cause instability in production!
// I sure hope you know what you're doing :)
if (hookPrototype === false || hooks[id.split('.')[0]] === false) {
delete hooks[id];
return;
}
// Check for invalid hook config
if (hooks.userconfig && !hooks.moduleloader) {
return cb('Invalid configuration:: Cannot use the `userconfig` hook w/o the `moduleloader` hook enabled!');
}
// Handle folder-defined modules (default to index.js)
// Since a hook definition must be a function
if (_.isObject(hookPrototype) && !_.isArray(hookPrototype) && !_.isFunction(hookPrototype)) {
hookPrototype = hookPrototype.index;
}
if (!_.isFunction(hookPrototype)) {
sails.log.error('Malformed hook! (' + id + ')');
sails.log.error('Hooks should be a function with one argument (`sails`)');
process.exit(1);
}
// Instantiate the hook
var def = hookPrototype(sails);
// Mix in an `identity` property to hook definition
def.identity = id.toLowerCase();
// New up an actual Hook instance
hooks[id] = new Hook(def);
});
// Call `load` on each hook
async.auto({
initialize: function(cb) {
async.each(_.keys(hooks), function initializeHook(id, cb) {
sails.log.silly('Loading hook: ' + id);
hooks[id].load(function(err) {
if (err) {
sails.log.error('A hook (`' + id + '`) failed to load!');
sails.emit('hook:' + id + ':error');
return cb(err);
}
sails.log.verbose(id, 'hook loaded successfully.');
sails.emit('hook:' + id + ':loaded');
// Defer to next tick to allow other stuff to happen
process.nextTick(cb);
});
}, cb);
}
},
function hooksReady(err) {
return cb(err);
});
};
};
|
module.exports={"title":"Discover","hex":"FF6000","source":"https://www.discovernetwork.com/en-us/business-resources/free-signage-logos","svg":"<svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>Discover icon</title><circle cx=\"12\" cy=\"12\" r=\"12\"/></svg>"};
|
require('babel-register')
const config = require('../config')
const server = require('../server/app')
const debug = require('debug')('app:bin:server')
const host = config.server_host
const port = config.server_port
server.listen(port, host, function () {
debug('Server is now running at ' + host + ':' + port + '.')
})
|
var vows = require('vows');
var assert = require('assert');
var suite = vows.describe('jStat.diff');
require('../env.js');
suite.addBatch({
'diff': {
'topic': function() {
return jStat;
},
'return basic diff': function(jStat) {
assert.deepEqual(jStat.diff([1, 2, 3]), [1, 1]);
},
'diff from instance': function(jStat) {
assert.deepEqual(jStat([1, 2, 3]).diff(), [1, 1]);
},
'diff matrix cols': function(jStat) {
assert.deepEqual(jStat([[1, 2], [3, 4]]).diff(), [[2], [2]]);
}
},
'#diff vector': {
'topic': function() {
jStat([1, 2, 3]).diff(this.callback);
},
'diff callback': function(val, stat) {
assert.deepEqual(val, [1, 1]);
}
},
'#diff matrix cols': {
'topic': function() {
jStat([[1, 2], [3, 4]]).diff(this.callback);
},
'diff matrix cols callback': function(val, stat) {
assert.deepEqual(val, [[2], [2]]);
}
}
});
suite.export(module);
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
/* globals jscolor */
frappe.provide("frappe.website_theme");
$.extend(frappe.website_theme, {
color_variables: ["background_color", "top_bar_color", "top_bar_text_color",
"footer_color", "footer_text_color", "text_color", "link_color"]
});
frappe.ui.form.on("Website Theme", "onload_post_render", function(frm) {
frappe.require('assets/frappe/js/lib/jscolor/jscolor.js', function() {
$.each(frappe.website_theme.color_variables, function(i, v) {
$(frm.fields_dict[v].input).addClass('color {required:false,hash:true}');
});
jscolor.bind();
});
});
frappe.ui.form.on("Website Theme", "refresh", function(frm) {
frm.set_intro(__('Default theme is set in {0}', ['<a href="#Form/Website Settings">'
+ __('Website Settings') + '</a>']));
frm.toggle_display(["module", "custom"], !frappe.boot.developer_mode);
if (!frm.doc.custom && !frappe.boot.developer_mode) {
frm.set_read_only();
frm.disable_save();
} else {
frm.enable_save();
}
});
|
function render(_ref) {
let text = _ref.text;
var _ref2 = <Component text={text} />;
return () => _ref2;
}
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var test = require('tape');
var Readable = require('stream').Readable;
var EE = require('events').EventEmitter;
test('stream2 - readable wrap empty', function (t) {
var oldStream = new EE();
oldStream.pause = function(){};
oldStream.resume = function(){};
var newStream = new Readable().wrap(oldStream);
var ended = false;
newStream
.on('readable', function(){})
.on('end', function(){ ended = true; });
oldStream.emit('end');
function done(){
t.ok(ended);
t.end();
}
newStream.on('end', done);
});
|
/* @flow */
//not including this
//it currently requires the whole of moment, which we dont want to take as a dependency
var ImageFormatter = require('./ImageFormatter');
var Formatters = {
ImageFormatter : ImageFormatter
}
module.exports = Formatters;
|
// Duplicate exports are an early/parse error
export {foo as bar};
export {bar};
|
/**
* Super simple wysiwyg editor on Bootstrap v@VERSION
* http://hackerwins.github.io/summernote/
*
* summernote.js
* Copyright 2013 Alan Hong. and outher contributors
* summernote may be freely distributed under the MIT license./
*
* Date: @DATE
*/
(function (factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'codemirror'], factory);
} else {
// Browser globals: jQuery, CodeMirror
factory(window.jQuery, window.CodeMirror);
}
}(function ($, CodeMirror) {
'use strict';
|
/**
* jqGrid Brazilian-Portuguese Translation
* Sergio Righi sergio.righi@gmail.com
* http://curve.com.br
*
* Updated by Jonnas Fonini
* http://fonini.net
*
*
* Updated by Fabio Ferreira da Silva fabio_ferreiradasilva@yahoo.com.br
*
* Updated by Anderson Pimentel anderson.pimentel[at]gmail.com
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
**/
/*global jQuery, define */
(function( factory ) {
"use strict";
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"../grid.base"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
$.jgrid = $.jgrid || {};
if(!$.jgrid.hasOwnProperty("regional")) {
$.jgrid.regional = [];
}
$.jgrid.regional["pt-br"] = {
defaults : {
recordtext: "Ver {0} - {1} de {2}",
emptyrecords: "Nenhum registro para visualizar",
loadtext: "Carregando...",
pgtext : "Página {0} de {1}",
savetext: "Salvando...",
pgfirst : "Primeira Página",
pglast : "Última Página",
pgnext : "Próxima Página",
pgprev : "Página Anterior",
pgrecs : "Registros por Página",
showhide: "Mostrar/Ocultar Grid"
},
search : {
caption: "Procurar...",
Find: "Procurar",
Reset: "Limpar",
odata: [{ oper:'eq', text:"igual"},{ oper:'ne', text:"diferente"},{ oper:'lt', text:"menor"},{ oper:'le', text:"menor ou igual"},{ oper:'gt', text:"maior"},{ oper:'ge', text:"maior ou igual"},{ oper:'bw', text:"inicia com"},{ oper:'bn', text:"não inicia com"},{ oper:'in', text:"está em"},{ oper:'ni', text:"não está em"},{ oper:'ew', text:"termina com"},{ oper:'en', text:"não termina com"},{ oper:'cn', text:"contém"},{ oper:'nc', text:"não contém"},{ oper:'nu', text:"nulo"},{ oper:'nn', text:"não nulo"}],
groupOps: [ { op: "AND", text: "todos" },{ op: "OR", text: "qualquer um" } ],
operandTitle : "Clique para escolher a operação de pesquisa.",
resetTitle : "Limpar valor de pesquisa"
},
edit : {
addCaption: "Incluir",
editCaption: "Alterar",
bSubmit: "Enviar",
bCancel: "Cancelar",
bClose: "Fechar",
saveData: "Os dados foram alterados! Salvar alterações?",
bYes : "Sim",
bNo : "Não",
bExit : "Cancelar",
msg: {
required:"Campo obrigatório",
number:"Por favor, informe um número válido",
minValue:"valor deve ser igual ou maior que ",
maxValue:"valor deve ser menor ou igual a",
email: "este e-mail não é válido",
integer: "Por favor, informe um valor inteiro",
date: "Por favor, informe uma data válida",
url: "não é uma URL válida. Prefixo obrigatório ('http://' or 'https://')",
nodefined : " não está definido!",
novalue : " um valor de retorno é obrigatório!",
customarray : "Função customizada deve retornar um array!",
customfcheck : "Função customizada deve estar presente em caso de validação customizada!"
}
},
view : {
caption: "Ver Registro",
bClose: "Fechar"
},
del : {
caption: "Apagar",
msg: "Apagar registro(s) selecionado(s)?",
bSubmit: "Apagar",
bCancel: "Cancelar"
},
nav : {
edittext: " ",
edittitle: "Alterar registro selecionado",
addtext:" ",
addtitle: "Incluir novo registro",
deltext: " ",
deltitle: "Apagar registro selecionado",
searchtext: " ",
searchtitle: "Procurar registros",
refreshtext: "",
refreshtitle: "Recarregar tabela",
alertcap: "Aviso",
alerttext: "Por favor, selecione um registro",
viewtext: "",
viewtitle: "Ver linha selecionada",
savetext: "",
savetitle: "Salvar linha",
canceltext: "",
canceltitle : "Cancelar edição da linha"
},
col : {
caption: "Mostrar/Esconder Colunas",
bSubmit: "Enviar",
bCancel: "Cancelar"
},
errors : {
errcap : "Erro",
nourl : "Nenhuma URL definida",
norecords: "Sem registros para exibir",
model : "Comprimento de colNames <> colModel!"
},
formatter : {
integer : {thousandsSeparator: " ", defaultValue: '0'},
number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'},
currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "R$ ", suffix:"", defaultValue: '0,00'},
date : {
dayNames: [
"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb",
"Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"
],
monthNames: [
"Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez",
"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
],
AmPm : ["am","pm","AM","PM"],
S: function (j) {return j < 11 || j > 13 ? ['º', 'º', 'º', 'º'][Math.min((j - 1) % 10, 3)] : 'º'},
srcformat: 'Y-m-d',
newformat: 'd/m/Y',
parseRe : /[#%\\\/:_;.,\t\s-]/,
masks : {
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
},
reformatAfterEdit : false,
userLocalTime : false
},
baseLinkUrl: '',
showAction: '',
target: '',
checkbox : {disabled:true},
idName : 'id'
}
};
}));
|
/* @flow */
import invariant from 'fbjs/lib/invariant';
import type { NavigationRoute, NavigationState } from './TypeDefinition';
/**
* Utilities to perform atomic operation with navigate state and routes.
*
* ```javascript
* const state1 = {key: 'screen 1'};
* const state2 = NavigationStateUtils.push(state1, {key: 'screen 2'});
* ```
*/
const StateUtils = {
/**
* Gets a route by key. If the route isn't found, returns `null`.
*/
get(state: NavigationState, key: string): ?NavigationRoute {
return state.routes.find((route: *) => route.key === key) || null;
},
/**
* Returns the first index at which a given route's key can be found in the
* routes of the navigation state, or -1 if it is not present.
*/
indexOf(state: NavigationState, key: string): number {
return state.routes.map((route: *) => route.key).indexOf(key);
},
/**
* Returns `true` at which a given route's key can be found in the
* routes of the navigation state.
*/
has(state: NavigationState, key: string): boolean {
return !!state.routes.some((route: *) => route.key === key);
},
/**
* Pushes a new route into the navigation state.
* Note that this moves the index to the positon to where the last route in the
* stack is at.
*/
push(state: NavigationState, route: NavigationRoute): NavigationState {
invariant(
StateUtils.indexOf(state, route.key) === -1,
'should not push route with duplicated key %s',
route.key
);
const routes = state.routes.slice();
routes.push(route);
return {
...state,
index: routes.length - 1,
routes,
};
},
/**
* Pops out a route from the navigation state.
* Note that this moves the index to the positon to where the last route in the
* stack is at.
*/
pop(state: NavigationState): NavigationState {
if (state.index <= 0) {
// [Note]: Over-popping does not throw error. Instead, it will be no-op.
return state;
}
const routes = state.routes.slice(0, -1);
return {
...state,
index: routes.length - 1,
routes,
};
},
/**
* Sets the focused route of the navigation state by index.
*/
jumpToIndex(state: NavigationState, index: number): NavigationState {
if (index === state.index) {
return state;
}
invariant(!!state.routes[index], 'invalid index %s to jump to', index);
return {
...state,
index,
};
},
/**
* Sets the focused route of the navigation state by key.
*/
jumpTo(state: NavigationState, key: string): NavigationState {
const index = StateUtils.indexOf(state, key);
return StateUtils.jumpToIndex(state, index);
},
/**
* Sets the focused route to the previous route.
*/
back(state: NavigationState): NavigationState {
const index = state.index - 1;
const route = state.routes[index];
return route ? StateUtils.jumpToIndex(state, index) : state;
},
/**
* Sets the focused route to the next route.
*/
forward(state: NavigationState): NavigationState {
const index = state.index + 1;
const route = state.routes[index];
return route ? StateUtils.jumpToIndex(state, index) : state;
},
/**
* Replace a route by a key.
* Note that this moves the index to the positon to where the new route in the
* stack is at.
*/
replaceAt(
state: NavigationState,
key: string,
route: NavigationRoute
): NavigationState {
const index = StateUtils.indexOf(state, key);
return StateUtils.replaceAtIndex(state, index, route);
},
/**
* Replace a route by a index.
* Note that this moves the index to the positon to where the new route in the
* stack is at.
*/
replaceAtIndex(
state: NavigationState,
index: number,
route: NavigationRoute
): NavigationState {
invariant(
!!state.routes[index],
'invalid index %s for replacing route %s',
index,
route.key
);
if (state.routes[index] === route) {
return state;
}
const routes = state.routes.slice();
routes[index] = route;
return {
...state,
index,
routes,
};
},
/**
* Resets all routes.
* Note that this moves the index to the positon to where the last route in the
* stack is at if the param `index` isn't provided.
*/
reset(
state: NavigationState,
routes: Array<NavigationRoute>,
index?: number
): NavigationState {
invariant(
routes.length && Array.isArray(routes),
'invalid routes to replace'
);
const nextIndex: number = index === undefined ? routes.length - 1 : index;
if (state.routes.length === routes.length && state.index === nextIndex) {
const compare = (route: *, ii: *) => routes[ii] === route;
if (state.routes.every(compare)) {
return state;
}
}
invariant(!!routes[nextIndex], 'invalid index %s to reset', nextIndex);
return {
...state,
index: nextIndex,
routes,
};
},
};
export default StateUtils;
|
(function(){var c=function(a){""!==a&&(1==a?($("#gis_location_wkt__row").hide(),$("#gis_location_wkt__row1").hide(),$("#gis_location_lat__row").show(),$("#gis_location_lon__row").show(),$("#gis_location_lat__row1").show(),$("#gis_location_lon__row1").show()):($("#gis_location_lat__row").hide(),$("#gis_location_lon__row").hide(),$("#gis_location_lat__row1").hide(),$("#gis_location_lon__row1").hide(),$("#gis_location_wkt__row").show(),$("#gis_location_wkt__row1").show(),2==a?""===$("#gis_location_wkt").val()&&
$("#gis_location_wkt").val("LINESTRING( , , )"):3==a?""===$("#gis_location_wkt").val()&&$("#gis_location_wkt").val("POLYGON(( , , ))"):6==a&&""===$("#gis_location_wkt").val()&&$("#gis_location_wkt").val("MULTIPOLYGON(( , , ))")))},f=function(a){var b=new jQuery.Deferred,d=S3.gis;setTimeout(function e(){void 0!=d.maps&&void 0!=d.maps[a]?b.resolve("loaded"):"pending"===b.state()&&(b.notify("waiting for JS to load..."),setTimeout(e,500))},1);return b.promise()};$(document).ready(function(){var a=$("#gis_location_gis_feature_type").val();
c(a);$("#gis_location_gis_feature_type").change(function(){a=$(this).val();c(a)});var b=$("#gis_location_level").val();b&&($("#gis_location_addr_street__row").hide(),$("#gis_location_addr_street__row1").hide(),$("#gis_location_addr_postcode__row").hide(),$("#gis_location_addr_postcode__row1").hide(),"L0"==b&&$("#gis_location_parent__row").hide());$("#gis_location_level").change(function(){var a=$(this).val();a?($("#gis_location_addr_street__row").hide(),$("#gis_location_addr_street__row1").hide(),
$("#gis_location_addr_postcode__row").hide(),$("#gis_location_addr_postcode__row1").hide(),"L0"==a?($("#gis_location_parent__row").hide(),$("#gis_location_parent__row1").hide(),$("#gis_location_parent").val("")):($("#gis_location_parent__row").show(),$("#gis_location_parent__row1").show())):($("#gis_location_addr_street__row").show(),$("#gis_location_addr_street__row1").show(),$("#gis_location_addr_postcode__row").show(),$("#gis_location_addr_postcode__row1").show(),$("#gis_location_parent__row").show(),
$("#gis_location_parent__row1").show())});$.when(f("default_map")).then(function(a){var b=S3.gis.maps.default_map;b.s3.pointPlaced=function(a){a=a.geometry.getBounds().getCenterLonLat();a.transform(b.getProjectionObject(),S3.gis.proj4326);$("#gis_location_lon").val(a.lon);$("#gis_location_lat").val(a.lat);$("#gis_location_wkt").val("")}})})})();
|
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this);
var len = t.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
export { some as default };
|
describe("", function() {
var rootEl;
beforeEach(function() {
rootEl = browser.rootEl;
browser.get("build/docs/examples/example-example98/index-jquery.html");
});
it('should format date', function() {
expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
});
});
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v13.3.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../../context/context");
var rowNode_1 = require("../../entities/rowNode");
var utils_1 = require("../../utils");
var gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var selectionController_1 = require("../../selectionController");
var eventService_1 = require("../../eventService");
var columnController_1 = require("../../columnController/columnController");
var FlattenStage = (function () {
function FlattenStage() {
}
FlattenStage.prototype.execute = function (params) {
var rootNode = params.rowNode;
// even if not doing grouping, we do the mapping, as the client might
// of passed in data that already has a grouping in it somewhere
var result = [];
// putting value into a wrapper so it's passed by reference
var nextRowTop = { value: 0 };
var skipLeafNodes = this.columnController.isPivotMode();
// if we are reducing, and not grouping, then we want to show the root node, as that
// is where the pivot values are
var showRootNode = skipLeafNodes && rootNode.leafGroup;
var topList = showRootNode ? [rootNode] : rootNode.childrenAfterSort;
// set all row tops to null, then set row tops on all visible rows. if we don't
// do this, then the algorithm below only sets row tops, old row tops from old rows
// will still lie around
this.resetRowTops(rootNode);
this.recursivelyAddToRowsToDisplay(topList, result, nextRowTop, skipLeafNodes, 0);
return result;
};
FlattenStage.prototype.resetRowTops = function (rowNode) {
rowNode.clearRowTop();
if (rowNode.group) {
if (rowNode.childrenAfterGroup) {
for (var i = 0; i < rowNode.childrenAfterGroup.length; i++) {
this.resetRowTops(rowNode.childrenAfterGroup[i]);
}
}
if (rowNode.sibling) {
rowNode.sibling.clearRowTop();
}
}
};
FlattenStage.prototype.recursivelyAddToRowsToDisplay = function (rowsToFlatten, result, nextRowTop, skipLeafNodes, uiLevel) {
if (utils_1.Utils.missingOrEmpty(rowsToFlatten)) {
return;
}
var groupSuppressRow = this.gridOptionsWrapper.isGroupSuppressRow();
var hideOpenParents = this.gridOptionsWrapper.isGroupHideOpenParents();
var removeSingleChildrenGroups = this.gridOptionsWrapper.isGroupRemoveSingleChildren();
for (var i = 0; i < rowsToFlatten.length; i++) {
var rowNode = rowsToFlatten[i];
// check all these cases, for working out if this row should be included in the final mapped list
var isGroupSuppressedNode = groupSuppressRow && rowNode.group;
var isSkippedLeafNode = skipLeafNodes && !rowNode.group;
var isRemovedSingleChildrenGroup = removeSingleChildrenGroups && rowNode.group && rowNode.childrenAfterGroup.length === 1;
// hide open parents means when group is open, we don't show it. we also need to make sure the
// group is expandable in the first place (as leaf groups are not expandable if pivot mode is on).
// the UI will never allow expanding leaf groups, however the user might via the API (or menu option 'expand all')
var neverAllowToExpand = skipLeafNodes && rowNode.leafGroup;
var isHiddenOpenParent = hideOpenParents && rowNode.expanded && (!neverAllowToExpand);
var thisRowShouldBeRendered = !isSkippedLeafNode && !isGroupSuppressedNode && !isHiddenOpenParent && !isRemovedSingleChildrenGroup;
if (thisRowShouldBeRendered) {
this.addRowNodeToRowsToDisplay(rowNode, result, nextRowTop, uiLevel);
}
// if we are pivoting, we never map below the leaf group
if (skipLeafNodes && rowNode.leafGroup) {
continue;
}
if (rowNode.group) {
// we traverse the group if it is expended, however we always traverse if the parent node
// was removed (as the group will never be opened if it is not displayed, we show the children instead)
if (rowNode.expanded || isRemovedSingleChildrenGroup) {
// if the parent was excluded, then ui level is that of the parent
var uiLevelForChildren = isRemovedSingleChildrenGroup ? uiLevel : uiLevel + 1;
this.recursivelyAddToRowsToDisplay(rowNode.childrenAfterSort, result, nextRowTop, skipLeafNodes, uiLevelForChildren);
// put a footer in if user is looking for it
if (this.gridOptionsWrapper.isGroupIncludeFooter()) {
this.ensureFooterNodeExists(rowNode);
this.addRowNodeToRowsToDisplay(rowNode.sibling, result, nextRowTop, uiLevel);
}
}
else {
}
}
else if (rowNode.canFlower && rowNode.expanded) {
var flowerNode = this.createFlowerNode(rowNode);
this.addRowNodeToRowsToDisplay(flowerNode, result, nextRowTop, uiLevel);
}
}
};
// duplicated method, it's also in floatingRowModel
FlattenStage.prototype.addRowNodeToRowsToDisplay = function (rowNode, result, nextRowTop, uiLevel) {
result.push(rowNode);
if (utils_1.Utils.missing(rowNode.rowHeight)) {
var rowHeight = this.gridOptionsWrapper.getRowHeightForNode(rowNode);
rowNode.setRowHeight(rowHeight);
}
rowNode.setUiLevel(uiLevel);
rowNode.setRowTop(nextRowTop.value);
rowNode.setRowIndex(result.length - 1);
nextRowTop.value += rowNode.rowHeight;
};
FlattenStage.prototype.ensureFooterNodeExists = function (groupNode) {
// only create footer node once, otherwise we have daemons and
// the animate screws up with the daemons hanging around
if (utils_1.Utils.exists(groupNode.sibling)) {
return;
}
var footerNode = new rowNode_1.RowNode();
this.context.wireBean(footerNode);
Object.keys(groupNode).forEach(function (key) {
footerNode[key] = groupNode[key];
});
footerNode.footer = true;
footerNode.rowTop = null;
footerNode.oldRowTop = null;
if (utils_1.Utils.exists(footerNode.id)) {
footerNode.id = 'rowGroupFooter_' + footerNode.id;
}
// get both header and footer to reference each other as siblings. this is never undone,
// only overwritten. so if a group is expanded, then contracted, it will have a ghost
// sibling - but that's fine, as we can ignore this if the header is contracted.
footerNode.sibling = groupNode;
groupNode.sibling = footerNode;
};
FlattenStage.prototype.createFlowerNode = function (parentNode) {
if (utils_1.Utils.exists(parentNode.childFlower)) {
return parentNode.childFlower;
}
else {
var flowerNode = new rowNode_1.RowNode();
this.context.wireBean(flowerNode);
flowerNode.flower = true;
flowerNode.parent = parentNode;
if (utils_1.Utils.exists(parentNode.id)) {
flowerNode.id = 'flowerNode_' + parentNode.id;
}
flowerNode.data = parentNode.data;
flowerNode.level = parentNode.level + 1;
parentNode.childFlower = flowerNode;
return flowerNode;
}
};
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], FlattenStage.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('selectionController'),
__metadata("design:type", selectionController_1.SelectionController)
], FlattenStage.prototype, "selectionController", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], FlattenStage.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('context'),
__metadata("design:type", context_1.Context)
], FlattenStage.prototype, "context", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], FlattenStage.prototype, "columnController", void 0);
FlattenStage = __decorate([
context_1.Bean('flattenStage')
], FlattenStage);
return FlattenStage;
}());
exports.FlattenStage = FlattenStage;
|
/**
* On-demand JavaScript handler
*
* Based on http://plugins.jquery.com/files/issues/jquery.ondemand.js_.txt
* and heavily modified to integrate with SilverStripe and prototype.js.
* Adds capabilities for custom X-Include-CSS and X-Include-JS HTTP headers
* to request loading of externals alongside an ajax response.
*
* Requires jQuery 1.5 ($.Deferred support)
*
* CAUTION: Relies on customization of the 'beforeSend' callback in jQuery.ajaxSetup()
*
* @author Ingo Schommer (ingo at silverstripe dot com)
* @author Sam Minnee (sam at silverstripe dot com)
*/
(function($){
var decodePath = function(str) {
return str.replace(/%2C/g,',').replace(/\&/g, '&').replace(/^\s+|\s+$/g, '');
};
$.extend({
// loaded files list - to protect against loading existed file again (by PGA)
_ondemand_loaded_list : null,
/**
* Returns true if the given CSS or JS script has already been loaded
*/
isItemLoaded : function(scriptUrl) {
var self = this, src;
if(this._ondemand_loaded_list === null) {
this._ondemand_loaded_list = {};
$('script').each(function() {
src = $(this).attr('src');
if(src) self._ondemand_loaded_list[src] = 1;
});
$('link[rel="stylesheet"]').each(function() {
src = $(this).attr('href');
if(src) self._ondemand_loaded_list[src] = 1;
});
}
return (this._ondemand_loaded_list[decodePath(scriptUrl)] !== undefined);
},
requireCss : function(styleUrl, media){
if(!media) media = 'all';
// Don't double up on loading scripts
if($.isItemLoaded(styleUrl)) return;
if(document.createStyleSheet){
var ss = document.createStyleSheet(styleUrl);
ss.media = media;
} else {
var styleTag = document.createElement('link');
$(styleTag).attr({
href : styleUrl,
type : 'text/css',
media : media,
rel : 'stylesheet'
}).appendTo($('head').get(0));
}
this._ondemand_loaded_list[styleUrl] = 1;
},
/**
* Process the X-Include-CSS and X-Include-JS headers provided by the Requirements class
*/
processOnDemandHeaders: function(xml, status, xhr) {
var self = this, processDfd = new $.Deferred();
// CSS
if(xhr.getResponseHeader && xhr.getResponseHeader('X-Include-CSS')) {
var cssIncludes = xhr.getResponseHeader('X-Include-CSS').split(',');
for(var i=0;i<cssIncludes.length;i++) {
// Syntax: "URL:##:media"
if(cssIncludes[i].match(/^(.*):##:(.*)$/)) {
$.requireCss(decodePath(RegExp.$1), RegExp.$2);
// Syntax: "URL"
} else {
$.requireCss(decodePath(cssIncludes[i]));
}
}
}
// JavaScript
var newJsIncludes = [];
if(xhr.getResponseHeader && xhr.getResponseHeader('X-Include-JS')) {
var jsIncludes = xhr.getResponseHeader('X-Include-JS').split(',');
for(var i=0;i<jsIncludes.length;i++) {
var jsIncludePath = decodePath(jsIncludes[i]);
if(!$.isItemLoaded(jsIncludePath)) {
newJsIncludes.push(jsIncludePath);
}
}
}
// We make an array of the includes that are actually new, and attach the callback to the last one
// They are placed in a queue and will be included in order. This means that the callback will
// be able to execute script in the new includes (such as a livequery update)
var getScriptQueue = function() {
if(newJsIncludes.length) {
var newJsInclude = newJsIncludes.shift();
// emulates getScript() with addtl. setting
$.ajax({
dataType: 'script',
url: newJsInclude,
success: function() {
self._ondemand_loaded_list[newJsInclude] = 1;
getScriptQueue();
},
cache: false,
// jQuery seems to override the XHR objects if used in async mode
async: false
});
} else {
processDfd.resolve(xml, status, xhr);
}
}
if(newJsIncludes.length) {
getScriptQueue();
} else {
// If there aren't any new includes, then we can just call the callbacks ourselves
processDfd.resolve(xml, status, xhr);
}
return processDfd.promise();
}
});
$.ajaxSetup({
// beforeSend is the only place to access the XHR object before success handlers are added
beforeSend: function(jqXHR, s) {
// Avoid recursion in ajax callbacks caused by getScript(), by not parsing
// ondemand headers for 'script' datatypes
if(s.dataType == 'script') return;
var dfd = new $.Deferred();
// Register our own success handler (assumes no handlers are already registered)
// 'success' is an alias for 'done', which is executed by the built-in deferred instance in $.ajax()
jqXHR.success(function(success, statusText, jXHR) {
$.processOnDemandHeaders(success, statusText, jXHR).done(function() {
dfd.resolveWith(s.context || this, [success, statusText, jXHR]);
});
});
// Reroute all external success hanlders through our own deferred.
// Not overloading fail() as no event can cause the original request to fail.
jqXHR.success = function(callback) {
dfd.done(callback);
}
}
});
})(jQuery);
|
var os = require('os');
var path = require('path');
var fs = require('fs');
var builder = require('xmlbuilder');
var helper = require('../helper');
var log = require('../logger').create('reporter');
var JUnitReporter = function(formatError, outputFile, pkgName, emitter) {
var xml;
var suites;
var pendingFileWritings = 0;
var fileWritingFinished = function() {};
this.adapters = [];
this.onRunStart = function(browsers) {
suites = {};
xml = builder.create('testsuites');
var suite;
var timestamp = (new Date()).toISOString().substr(0, 19);
browsers.forEach(function(browser) {
suite = suites[browser.id] = xml.ele('testsuite', {
name: browser.name, 'package': pkgName, timestamp: timestamp, id: 0, hostname: os.hostname()
});
suite.ele('properties').ele('property', {name: 'browser.fullName', value: browser.fullName});
});
};
this.onBrowserComplete = function(browser) {
var suite = suites[browser.id];
var result = browser.lastResult;
suite.att('tests', result.total);
suite.att('errors', result.disconnected || result.error ? 1 : 0);
suite.att('failures', result.failed);
suite.att('time', result.netTime / 1000);
suite.ele('system-out');
suite.ele('system-err');
};
this.onRunComplete = function() {
var xmlToOutput = xml;
pendingFileWritings++;
helper.mkdirIfNotExists(path.dirname(outputFile), function() {
fs.writeFile(outputFile, xmlToOutput.end({pretty: true}), function(err) {
if (err) {
log.warn('Cannot write JUnit xml\n\t' + err.message);
} else {
log.debug('JUnit results written to "%s".', outputFile);
}
if (!--pendingFileWritings) {
fileWritingFinished();
}
});
});
suites = xml = null;
};
this.onSpecComplete = function(browser, result) {
var spec = suites[browser.id].ele('testcase', {
name: result.description, time: result.time / 1000,
classname: (pkgName ? pkgName + ' ' : '') + browser.name + '.' + result.suite.join(' ').replace(/\./g, '_')
});
if (!result.success) {
result.log.forEach(function(err) {
spec.ele('failure', {type: ''}, formatError(err));
});
}
};
// wait for writing all the xml files, before exiting
emitter.on('exit', function(done) {
if (pendingFileWritings) {
fileWritingFinished = done;
} else {
done();
}
});
};
// PUBLISH
module.exports = JUnitReporter;
|
'use strict';
angular.module('gridster', [])
.constant('gridsterConfig', {
columns: 6, // number of columns in the grid
pushing: true, // whether to push other items out of the way
floating: true, // whether to automatically float items up so they stack
width: 'auto', // the width of the grid. "auto" will expand the grid to its parent container
colWidth: 'auto', // the width of the columns. "auto" will divide the width of the grid evenly among the columns
rowHeight: 'match', // the height of the rows. "match" will set the row height to be the same as the column width
margins: [10, 10], // the margins in between grid items
outerMargin: true,
isMobile: false, // toggle mobile view
mobileBreakPoint: 600, // the width threshold to toggle mobile mode
mobileModeEnabled: true, // whether or not to toggle mobile mode when screen width is less than mobileBreakPoint
minColumns: 1, // the minimum amount of columns the grid can scale down to
minRows: 1, // the minimum amount of rows to show if the grid is empty
maxRows: 100, // the maximum amount of rows in the grid
defaultSizeX: 2, // the default width of a item
defaultSizeY: 1, // the default height of a item
resizable: { // options to pass to resizable handler
enabled: true,
handles: ['s', 'e', 'n', 'w', 'se', 'ne', 'sw', 'nw']
},
draggable: { // options to pass to draggable handler
enabled: true
}
})
.controller('GridsterCtrl', ['gridsterConfig',
function(gridsterConfig) {
/**
* Create options from gridsterConfig constant
*/
angular.extend(this, gridsterConfig);
this.resizable = angular.extend({}, gridsterConfig.resizable || {});
this.draggable = angular.extend({}, gridsterConfig.draggable || {});
/**
* A positional array of the items in the grid
*/
this.grid = [];
/**
* Clean up after yourself
*/
this.destroy = function() {
if (this.grid) {
this.grid.length = 0;
this.grid = null;
}
};
/**
* Overrides default options
*
* @param {object} options The options to override
*/
this.setOptions = function(options) {
if (!options) {
return;
}
options = angular.extend({}, options);
// all this to avoid using jQuery...
if (options.draggable) {
angular.extend(this.draggable, options.draggable);
delete(options.draggable);
}
if (options.resizable) {
angular.extend(this.resizable, options.resizable);
delete(options.resizable);
}
angular.extend(this, options);
if (!this.margins || this.margins.length !== 2) {
this.margins = [0, 0];
} else {
for (var x = 0, l = this.margins.length; x < l; ++x) {
this.margins[x] = parseInt(this.margins[x], 10);
if (isNaN(this.margins[x])) {
this.margins[x] = 0;
}
}
}
};
/**
* Check if item can occupy a specified position in the grid
*
* @param {object} item The item in question
* @param {number} row The row index
* @param {number} column The column index
* @returns {boolean} True if if item fits
*/
this.canItemOccupy = function(item, row, column) {
return row > -1 && column > -1 && item.sizeX + column <= this.columns && item.sizeY + row <= this.maxRows;
};
/**
* Set the item in the first suitable position
*
* @param {object} item The item to insert
*/
this.autoSetItemPosition = function(item) {
// walk through each row and column looking for a place it will fit
for (var rowIndex = 0; rowIndex < this.maxRows; ++rowIndex) {
for (var colIndex = 0; colIndex < this.columns; ++colIndex) {
// only insert if position is not already taken and it can fit
var items = this.getItems(rowIndex, colIndex, item.sizeX, item.sizeY, item);
if (items.length === 0 && this.canItemOccupy(item, rowIndex, colIndex)) {
this.putItem(item, rowIndex, colIndex);
return;
}
}
}
throw new Error('Unable to place item!');
};
/**
* Gets items at a specific coordinate
*
* @param {number} row
* @param {number} column
* @param {number} sizeX
* @param {number} sizeY
* @param {array} excludeItems An array of items to exclude from selection
* @returns {array} Items that match the criteria
*/
this.getItems = function(row, column, sizeX, sizeY, excludeItems) {
var items = [];
if (!sizeX || !sizeY) {
sizeX = sizeY = 1;
}
if (excludeItems && !(excludeItems instanceof Array)) {
excludeItems = [excludeItems];
}
for (var h = 0; h < sizeY; ++h) {
for (var w = 0; w < sizeX; ++w) {
var item = this.getItem(row + h, column + w, excludeItems);
if (item && (!excludeItems || excludeItems.indexOf(item) === -1) && items.indexOf(item) === -1) {
items.push(item);
}
}
}
return items;
};
/**
* Removes an item from the grid
*
* @param {object} item
*/
this.removeItem = function(item) {
for (var rowIndex = 0, l = this.grid.length; rowIndex < l; ++rowIndex) {
var columns = this.grid[rowIndex];
if (!columns) {
continue;
}
var index = columns.indexOf(item);
if (index !== -1) {
columns[index] = null;
break;
}
}
this.floatItemsUp();
this.updateHeight();
};
/**
* Returns the item at a specified coordinate
*
* @param {number} row
* @param {number} column
* @param {array} excludeitems Items to exclude from selection
* @returns {object} The matched item or null
*/
this.getItem = function(row, column, excludeItems) {
if (excludeItems && !(excludeItems instanceof Array)) {
excludeItems = [excludeItems];
}
var sizeY = 1;
while (row > -1) {
var sizeX = 1,
col = column;
while (col > -1) {
var items = this.grid[row];
if (items) {
var item = items[col];
if (item && (!excludeItems || excludeItems.indexOf(item) === -1) && item.sizeX >= sizeX && item.sizeY >= sizeY) {
return item;
}
}
++sizeX;
--col;
}
--row;
++sizeY;
}
return null;
};
/**
* Insert an array of items into the grid
*
* @param {array} items An array of items to insert
*/
this.putItems = function(items) {
for (var i = 0, l = items.length; i < l; ++i) {
this.putItem(items[i]);
}
};
/**
* Insert a single item into the grid
*
* @param {object} item The item to insert
* @param {number} row (Optional) Specifies the items row index
* @param {number} column (Optional) Specifies the items column index
* @param {array} ignoreItems
*/
this.putItem = function(item, row, column, ignoreItems) {
if (typeof row === 'undefined' || row === null) {
row = item.row;
column = item.col;
if (typeof row === 'undefined' || row === null) {
this.autoSetItemPosition(item);
return;
}
}
if (!this.canItemOccupy(item, row, column)) {
column = Math.min(this.columns - item.sizeX, Math.max(0, column));
row = Math.min(this.maxRows - item.sizeY, Math.max(0, row));
}
if (item && item.oldRow !== null && typeof item.oldRow !== 'undefined') {
if (item.oldRow === row && item.oldColumn === column) {
item.row = row;
item.col = column;
return;
} else {
// remove from old position
var oldRow = this.grid[item.oldRow];
if (oldRow && oldRow[item.oldColumn] === item) {
delete oldRow[item.oldColumn];
}
}
}
item.oldRow = item.row = row;
item.oldColumn = item.col = column;
this.moveOverlappingItems(item, ignoreItems);
if (!this.grid[row]) {
this.grid[row] = [];
}
this.grid[row][column] = item;
};
/**
* Prevents items from being overlapped
*
* @param {object} item The item that should remain
* @param {array} ignoreItems
*/
this.moveOverlappingItems = function(item, ignoreItems) {
if (ignoreItems) {
if (ignoreItems.indexOf(item) === -1) {
ignoreItems = ignoreItems.slice(0);
ignoreItems.push(item);
}
} else {
ignoreItems = [item];
}
var overlappingItems = this.getItems(
item.row,
item.col,
item.sizeX,
item.sizeY,
ignoreItems
);
this.moveItemsDown(overlappingItems, item.row + item.sizeY, ignoreItems);
};
/**
* Moves an array of items to a specified row
*
* @param {array} items The items to move
* @param {number} newRow The target row
* @param {array} ignoreItems
*/
this.moveItemsDown = function(items, newRow, ignoreItems) {
if (!items || items.length === 0) {
return;
}
items.sort(function(a, b) {
return a.row - b.row;
});
ignoreItems = ignoreItems ? ignoreItems.slice(0) : [];
var topRows = {},
item, i, l;
// calculate the top rows in each column
for (i = 0, l = items.length; i < l; ++i) {
item = items[i];
var topRow = topRows[item.col];
if (typeof topRow === 'undefined' || item.row < topRow) {
topRows[item.col] = item.row;
}
}
// move each item down from the top row in its column to the row
for (i = 0, l = items.length; i < l; ++i) {
item = items[i];
var rowsToMove = newRow - topRows[item.col];
this.moveItemDown(item, item.row + rowsToMove, ignoreItems);
ignoreItems.push(item);
}
};
this.moveItemDown = function(item, newRow, ignoreItems) {
if (item.row >= newRow) {
return;
}
while (item.row < newRow) {
++item.row;
this.moveOverlappingItems(item, ignoreItems);
}
this.putItem(item, item.row, item.col, ignoreItems);
};
/**
* Moves all items up as much as possible
*/
this.floatItemsUp = function() {
if (this.floating === false) {
return;
}
for (var rowIndex = 0, l = this.grid.length; rowIndex < l; ++rowIndex) {
var columns = this.grid[rowIndex];
if (!columns) {
continue;
}
for (var colIndex = 0, len = columns.length; colIndex < len; ++colIndex) {
if (columns[colIndex]) {
this.floatItemUp(columns[colIndex]);
}
}
}
};
/**
* Float an item up to the most suitable row
*
* @param {object} item The item to move
*/
this.floatItemUp = function(item) {
var colIndex = item.col,
sizeY = item.sizeY,
sizeX = item.sizeX,
bestRow = null,
bestColumn = null,
rowIndex = item.row - 1;
while (rowIndex > -1) {
var items = this.getItems(rowIndex, colIndex, sizeX, sizeY, item);
if (items.length !== 0) {
break;
}
bestRow = rowIndex;
bestColumn = colIndex;
--rowIndex;
}
if (bestRow !== null) {
this.putItem(item, bestRow, bestColumn);
}
};
/**
* Update gridsters height
*
* @param {number} plus (Optional) Additional height to add
*/
this.updateHeight = function(plus) {
var maxHeight = this.minRows;
if (!plus) {
plus = 0;
}
for (var rowIndex = this.grid.length; rowIndex >= 0; --rowIndex) {
var columns = this.grid[rowIndex];
if (!columns) {
continue;
}
for (var colIndex = 0, len = columns.length; colIndex < len; ++colIndex) {
if (columns[colIndex]) {
maxHeight = Math.max(maxHeight, rowIndex + plus + columns[colIndex].sizeY);
}
}
}
this.gridHeight = this.maxRows - maxHeight > 0 ? Math.min(this.maxRows, maxHeight) : Math.max(this.maxRows, maxHeight);
};
/**
* Returns the number of rows that will fit in given amount of pixels
*
* @param {number} pixels
* @param {boolean} ceilOrFloor (Optional) Determines rounding method
*/
this.pixelsToRows = function(pixels, ceilOrFloor) {
if (ceilOrFloor === true) {
return Math.ceil(pixels / this.curRowHeight);
} else if (ceilOrFloor === false) {
return Math.floor(pixels / this.curRowHeight);
}
return Math.round(pixels / this.curRowHeight);
};
/**
* Returns the number of columns that will fit in a given amount of pixels
*
* @param {number} pixels
* @param {boolean} ceilOrFloor (Optional) Determines rounding method
* @returns {number} The number of columns
*/
this.pixelsToColumns = function(pixels, ceilOrFloor) {
if (ceilOrFloor === true) {
return Math.ceil(pixels / this.curColWidth);
} else if (ceilOrFloor === false) {
return Math.floor(pixels / this.curColWidth);
}
return Math.round(pixels / this.curColWidth);
};
}
])
/**
* The gridster directive
*
* @param {object} $parse
* @param {object} $timeout
*/
.directive('gridster', ['$timeout', '$rootScope', '$window',
function($timeout, $rootScope, $window) {
return {
restrict: 'EAC',
// without transclude, some child items may lose their parent scope
transclude: true,
replace: true,
template: '<div ng-class="gridsterClass()"><div ng-style="previewStyle()" class="gridster-item gridster-preview-holder"></div><div class="gridster-content" ng-transclude></div></div>',
controller: 'GridsterCtrl',
controllerAs: 'gridster',
scope: {
config: '=?gridster'
},
compile: function() {
return function(scope, $elem, attrs, gridster) {
gridster.loaded = false;
scope.gridsterClass = function() {
return {
gridster: true,
'gridster-desktop': !gridster.isMobile,
'gridster-mobile': gridster.isMobile,
'gridster-loaded': gridster.loaded
};
};
/**
* @returns {Object} style object for preview element
*/
scope.previewStyle = function() {
if (!gridster.movingItem) {
return {
display: 'none'
};
}
return {
display: 'block',
height: (gridster.movingItem.sizeY * gridster.curRowHeight - gridster.margins[0]) + 'px',
width: (gridster.movingItem.sizeX * gridster.curColWidth - gridster.margins[1]) + 'px',
top: (gridster.movingItem.row * gridster.curRowHeight + (gridster.outerMargin ? gridster.margins[0] : 0)) + 'px',
left: (gridster.movingItem.col * gridster.curColWidth + (gridster.outerMargin ? gridster.margins[1] : 0)) + 'px'
};
};
var refresh = function() {
gridster.setOptions(scope.config);
// resolve "auto" & "match" values
if (gridster.width === 'auto') {
gridster.curWidth = parseInt($elem.css('width')) || $elem.prop('offsetWidth');
} else {
gridster.curWidth = gridster.width;
}
if (gridster.colWidth === 'auto') {
gridster.curColWidth = parseInt((gridster.curWidth + (gridster.outerMargin ? -gridster.margins[1] : gridster.margins[1])) / gridster.columns);
} else {
gridster.curColWidth = gridster.colWidth;
}
if (gridster.rowHeight === 'match') {
gridster.curRowHeight = gridster.curColWidth;
} else {
gridster.curRowHeight = gridster.rowHeight;
}
gridster.isMobile = gridster.mobileModeEnabled && gridster.curWidth <= gridster.mobileBreakPoint;
// loop through all items and reset their CSS
for (var rowIndex = 0, l = gridster.grid.length; rowIndex < l; ++rowIndex) {
var columns = gridster.grid[rowIndex];
if (!columns) {
continue;
}
for (var colIndex = 0, len = columns.length; colIndex < len; ++colIndex) {
if (columns[colIndex]) {
var item = columns[colIndex];
item.setElementPosition();
item.setElementSizeY();
item.setElementSizeX();
}
}
}
updateHeight();
};
// update grid items on config changes
scope.$watch('config', refresh, true);
scope.$watch('config.draggable', function() {
$rootScope.$broadcast('gridster-draggable-changed');
}, true);
scope.$watch('config.resizable', function() {
$rootScope.$broadcast('gridster-resizable-changed');
}, true);
var updateHeight = function() {
$elem.css('height', (gridster.gridHeight * gridster.curRowHeight) + (gridster.outerMargin ? gridster.margins[0] : -gridster.margins[0]) + 'px');
};
scope.$watch('gridster.gridHeight', updateHeight);
var prevWidth = parseInt($elem.css('width')) || $elem.prop('offsetWidth');
function resize() {
var width = parseInt($elem.css('width')) || $elem.prop('offsetWidth');
if (width === prevWidth || gridster.movingItem) {
return;
}
prevWidth = width;
if (gridster.loaded) {
$elem.removeClass('gridster-loaded');
}
refresh();
if (gridster.loaded) {
$elem.addClass('gridster-loaded');
}
}
// track element width changes any way we can
function onResize() {
resize();
$timeout(function() {
scope.$apply();
});
}
if (typeof $elem.resize === 'function') {
$elem.resize(onResize);
}
var $win = angular.element($window);
$win.on('resize', onResize);
scope.$watch(function() {
var _width = parseInt($elem.css('width')) || $elem.prop('offsetWidth');
return _width;
}, resize);
// be sure to cleanup
scope.$on('$destroy', function() {
gridster.destroy();
$win.off('resize', onResize);
});
// allow a little time to place items before floating up
$timeout(function() {
scope.$watch('gridster.floating', function() {
gridster.floatItemsUp();
});
gridster.loaded = true;
}, 100);
};
}
};
}
])
.controller('GridsterItemCtrl', function() {
this.$element = null;
this.gridster = null;
this.row = null;
this.col = null;
this.sizeX = null;
this.sizeY = null;
this.init = function($element, gridster) {
this.$element = $element;
this.gridster = gridster;
this.sizeX = gridster.defaultSizeX;
this.sizeY = gridster.defaultSizeY;
};
this.destroy = function() {
this.gridster = null;
this.$element = null;
};
/**
* Returns the items most important attributes
*/
this.toJSON = function() {
return {
row: this.row,
col: this.col,
sizeY: this.sizeY,
sizeX: this.sizeX
};
};
this.isMoving = function() {
return this.gridster.movingItem === this;
};
/**
* Set the items position
*
* @param {number} row
* @param {number} column
*/
this.setPosition = function(row, column) {
this.gridster.putItem(this, row, column);
if (this.gridster.loaded) {
this.gridster.floatItemsUp();
}
this.gridster.updateHeight(this.isMoving() ? this.sizeY : 0);
if (!this.isMoving()) {
this.setElementPosition();
}
};
/**
* Sets a specified size property
*
* @param {string} key Can be either "x" or "y"
* @param {number} value The size amount
*/
this.setSize = function(key, value) {
key = key.toUpperCase();
var camelCase = 'size' + key,
titleCase = 'Size' + key;
if (value === '') {
return;
}
value = parseInt(value, 10);
if (isNaN(value) || value === 0) {
value = this.gridster['default' + titleCase];
}
var changed = !(this[camelCase] === value && this['old' + titleCase] && this['old' + titleCase] === value);
this['old' + titleCase] = this[camelCase] = value;
if (!this.isMoving()) {
this['setElement' + titleCase]();
}
if (changed) {
this.gridster.moveOverlappingItems(this);
if (this.gridster.loaded) {
this.gridster.floatItemsUp();
}
this.gridster.updateHeight(this.isMoving() ? this.sizeY : 0);
}
};
/**
* Sets the items sizeY property
*
* @param {number} rows
*/
this.setSizeY = function(rows) {
this.setSize('y', rows);
};
/**
* Sets the items sizeX property
*
* @param {number} rows
*/
this.setSizeX = function(columns) {
this.setSize('x', columns);
};
/**
* Sets an elements position on the page
*
* @param {number} row
* @param {number} column
*/
this.setElementPosition = function() {
if (this.gridster.isMobile) {
this.$element.css({
marginLeft: this.gridster.margins[0] + 'px',
marginRight: this.gridster.margins[0] + 'px',
marginTop: this.gridster.margins[1] + 'px',
marginBottom: this.gridster.margins[1] + 'px',
top: '',
left: ''
});
} else {
this.$element.css({
margin: 0,
top: (this.row * this.gridster.curRowHeight + (this.gridster.outerMargin ? this.gridster.margins[0] : 0)) + 'px',
left: (this.col * this.gridster.curColWidth + (this.gridster.outerMargin ? this.gridster.margins[1] : 0)) + 'px'
});
}
};
/**
* Sets an elements height
*/
this.setElementSizeY = function() {
if (this.gridster.isMobile) {
this.$element.css('height', '');
} else {
this.$element.css('height', (this.sizeY * this.gridster.curRowHeight - this.gridster.margins[0]) + 'px');
}
};
/**
* Sets an elements width
*/
this.setElementSizeX = function() {
if (this.gridster.isMobile) {
this.$element.css('width', '');
} else {
this.$element.css('width', (this.sizeX * this.gridster.curColWidth - this.gridster.margins[1]) + 'px');
}
};
})
.factory('GridsterDraggable', ['$document', '$timeout', function($document, $timeout) {
function GridsterDraggable($el, scope, gridster, item, itemOptions) {
var elmX, elmY, elmW, elmH,
mouseX = 0,
mouseY = 0,
lastMouseX = 0,
lastMouseY = 0,
mOffX = 0,
mOffY = 0,
minTop = 0,
maxTop = 9999,
minLeft = 0;
var originalCol, originalRow;
function mouseDown(e) {
lastMouseX = e.pageX;
lastMouseY = e.pageY;
elmX = parseInt($el.css('left'));
elmY = parseInt($el.css('top'));
elmW = parseInt($el.css('width'));
elmH = parseInt($el.css('height'));
originalCol = item.col;
originalRow = item.row;
dragStart(e);
$document.on('mousemove', mouseMove);
$document.on('mouseup', mouseUp);
e.preventDefault();
e.stopPropagation();
}
function mouseMove(e) {
var maxLeft = gridster.curWidth - 1;
// Get the current mouse position.
mouseX = e.pageX;
mouseY = e.pageY;
// Get the deltas
var diffX = mouseX - lastMouseX + mOffX;
var diffY = mouseY - lastMouseY + mOffY;
mOffX = mOffY = 0;
// Update last processed mouse positions.
lastMouseX = mouseX;
lastMouseY = mouseY;
var dX = diffX,
dY = diffY;
if (elmX + dX < minLeft) {
diffX = minLeft - elmX;
mOffX = dX - diffX;
} else if (elmX + elmW + dX > maxLeft) {
diffX = maxLeft - elmX - elmW;
mOffX = dX - diffX;
}
if (elmY + dY < minTop) {
diffY = minTop - elmY;
mOffY = dY - diffY;
} else if (elmY + elmH + dY > maxTop) {
diffY = maxTop - elmY - elmH;
mOffY = dY - diffY;
}
elmX += diffX;
elmY += diffY;
// set new position
$el.css({
'top': elmY + 'px',
'left': elmX + 'px'
});
drag(e);
e.stopPropagation();
e.preventDefault();
}
function mouseUp(e) {
$document.off('mouseup', mouseUp);
$document.off('mousemove', mouseMove);
mOffX = mOffY = 0;
dragStop(e);
}
function dragStart(event) {
$el.addClass('gridster-item-moving');
gridster.movingItem = item;
gridster.updateHeight(item.sizeY);
scope.$apply(function() {
if (gridster.draggable && gridster.draggable.start) {
gridster.draggable.start(event, $el, itemOptions);
}
});
}
function drag(event) {
item.row = gridster.pixelsToRows(elmY);
item.col = gridster.pixelsToColumns(elmX);
scope.$apply(function() {
if (gridster.draggable && gridster.draggable.drag) {
gridster.draggable.drag(event, $el, itemOptions);
}
});
}
function dragStop(event) {
$el.removeClass('gridster-item-moving');
var row = gridster.pixelsToRows(elmY);
var col = gridster.pixelsToColumns(elmX);
if (gridster.pushing !== false || gridster.getItems(row, col, item.sizeX, item.sizeY, item).length === 0) {
item.row = row;
item.col = col;
}
gridster.movingItem = null;
var itemMoved = (originalCol !== item.col || originalRow !== item.row);
scope.$apply(function() {
// callback only if item really changed position
if (itemMoved && gridster.draggable && gridster.draggable.stop) {
gridster.draggable.stop(event, $el, itemOptions);
}
});
item.setPosition(item.row, item.col);
gridster.updateHeight();
}
var enabled = false;
var $dragHandle = null;
this.enable = function() {
var self = this;
// disable and timeout required for some template rendering
$timeout(function() {
self.disable();
if (gridster.draggable && gridster.draggable.handle) {
$dragHandle = angular.element($el[0].querySelector(gridster.draggable.handle));
if ($dragHandle.length === 0) {
// fall back to element if handle not found...
$dragHandle = $el;
}
} else {
$dragHandle = $el;
}
$dragHandle.on('mousedown', mouseDown);
enabled = true;
});
};
this.disable = function() {
if (!enabled) {
return;
}
$document.off('mouseup', mouseUp);
$document.off('mousemove', mouseMove);
if ($dragHandle) {
$dragHandle.off('mousedown', mouseDown);
}
enabled = false;
};
this.toggle = function(enabled) {
if (enabled) {
this.enable();
} else {
this.disable();
}
};
this.destroy = function() {
this.disable();
};
}
return GridsterDraggable;
}])
.factory('GridsterResizable', ['$document', function($document) {
function GridsterResizable($el, scope, gridster, item, itemOptions) {
function ResizeHandle(handleClass) {
var hClass = handleClass;
var elmX, elmY, elmW, elmH,
mouseX = 0,
mouseY = 0,
lastMouseX = 0,
lastMouseY = 0,
mOffX = 0,
mOffY = 0,
minTop = 0,
maxTop = 9999,
minLeft = 0;
var minHeight = gridster.curRowHeight - gridster.margins[0],
minWidth = gridster.curColWidth - gridster.margins[1];
var originalWidth, originalHeight;
function mouseDown(e) {
// Get the current mouse position.
lastMouseX = e.pageX;
lastMouseY = e.pageY;
// Record current widget dimensions
elmX = parseInt($el.css('left'));
elmY = parseInt($el.css('top'));
elmW = parseInt($el.css('width'));
elmH = parseInt($el.css('height'));
originalWidth = item.sizeX;
originalHeight = item.sizeY;
resizeStart(e);
$document.on('mousemove', mouseMove);
$document.on('mouseup', mouseUp);
e.preventDefault();
e.stopPropagation();
}
function resizeStart(e) {
$el.addClass('gridster-item-moving');
gridster.movingItem = item;
item.setElementSizeX();
item.setElementSizeY();
item.setElementPosition();
scope.$apply(function() {
// callback
if (gridster.resizable && gridster.resizable.start) {
gridster.resizable.start(e, $el, itemOptions); // options is the item model
}
});
}
function mouseMove(e) {
var maxLeft = gridster.curWidth - 1;
// Get the current mouse position.
mouseX = e.pageX;
mouseY = e.pageY;
// Get the deltas
var diffX = mouseX - lastMouseX + mOffX;
var diffY = mouseY - lastMouseY + mOffY;
mOffX = mOffY = 0;
// Update last processed mouse positions.
lastMouseX = mouseX;
lastMouseY = mouseY;
var dY = diffY,
dX = diffX;
if (hClass.indexOf('n') >= 0) {
if (elmH - dY < minHeight) {
diffY = elmH - minHeight;
mOffY = dY - diffY;
} else if (elmY + dY < minTop) {
diffY = minTop - elmY;
mOffY = dY - diffY;
}
elmY += diffY;
elmH -= diffY;
}
if (hClass.indexOf('s') >= 0) {
if (elmH + dY < minHeight) {
diffY = minHeight - elmH;
mOffY = dY - diffY;
} else if (elmY + elmH + dY > maxTop) {
diffY = maxTop - elmY - elmH;
mOffY = dY - diffY;
}
elmH += diffY;
}
if (hClass.indexOf('w') >= 0) {
if (elmW - dX < minWidth) {
diffX = elmW - minWidth;
mOffX = dX - diffX;
} else if (elmX + dX < minLeft) {
diffX = minLeft - elmX;
mOffX = dX - diffX;
}
elmX += diffX;
elmW -= diffX;
}
if (hClass.indexOf('e') >= 0) {
if (elmW + dX < minWidth) {
diffX = minWidth - elmW;
mOffX = dX - diffX;
} else if (elmX + elmW + dX > maxLeft) {
diffX = maxLeft - elmX - elmW;
mOffX = dX - diffX;
}
elmW += diffX;
}
// set new position
$el.css({
'top': elmY + 'px',
'left': elmX + 'px',
'width': elmW + 'px',
'height': elmH + 'px'
});
resize(e);
e.preventDefault();
e.stopPropagation();
}
function mouseUp(e) {
$document.off('mouseup', mouseUp);
$document.off('mousemove', mouseMove);
mOffX = mOffY = 0;
resizeStop(e);
}
function resize(e) {
item.row = gridster.pixelsToRows(elmY, false);
item.col = gridster.pixelsToColumns(elmX, false);
item.sizeX = gridster.pixelsToColumns(elmW, true);
item.sizeY = gridster.pixelsToRows(elmH, true);
scope.$apply(function() {
// callback
if (gridster.resizable && gridster.resizable.resize) {
gridster.resizable.resize(e, $el, itemOptions); // options is the item model
}
});
}
function resizeStop(e) {
$el.removeClass('gridster-item-moving');
gridster.movingItem = null;
item.setPosition(item.row, item.col);
item.setSizeY(item.sizeY);
item.setSizeX(item.sizeX);
var itemResized = (originalWidth !== item.sizeX || originalHeight !== item.sizeY);
scope.$apply(function() {
// callback only if item really changed size
if (itemResized && gridster.resizable && gridster.resizable.stop) {
gridster.resizable.stop(e, $el, itemOptions); // options is the item model
}
});
}
var $dragHandle = null;
this.enable = function() {
if (!$dragHandle) {
$dragHandle = angular.element('<div class="gridster-item-resizable-handler handle-' + hClass + '"></div>');
$el.append($dragHandle);
}
$dragHandle.on('mousedown', mouseDown);
};
this.disable = function() {
if ($dragHandle) {
$dragHandle.off('mousedown', mouseDown);
$dragHandle.remove();
$dragHandle = null;
}
$document.off('mouseup', mouseUp);
$document.off('mousemove', mouseMove);
};
this.destroy = function() {
this.disable();
};
}
var handles = [];
var enabled = false;
for (var c = 0, l = gridster.resizable.handles.length; c < l; c++) {
handles.push(new ResizeHandle(gridster.resizable.handles[c]));
}
this.enable = function() {
if (enabled) {
return;
}
for (var c = 0, l = handles.length; c < l; c++) {
handles[c].enable();
}
enabled = true;
};
this.disable = function() {
if (!enabled) {
return;
}
for (var c = 0, l = handles.length; c < l; c++) {
handles[c].disable();
}
enabled = false;
};
this.toggle = function(enabled) {
if (enabled) {
this.enable();
} else {
this.disable();
}
};
this.destroy = function() {
for (var c = 0, l = handles.length; c < l; c++) {
handles[c].destroy();
}
};
}
return GridsterResizable;
}])
/**
* GridsterItem directive
*
* @param {object} $parse
* @param {object} $controller
* @param {object} $timeout
*/
.directive('gridsterItem', ['$parse', '$timeout', 'GridsterDraggable', 'GridsterResizable',
function($parse, $timeout, GridsterDraggable, GridsterResizable) {
return {
restrict: 'EA',
controller: 'GridsterItemCtrl',
require: ['^gridster', 'gridsterItem'],
link: function(scope, $el, attrs, controllers) {
var optionsKey = attrs.gridsterItem,
options;
var gridster = controllers[0],
item = controllers[1];
//bind the items position properties
if (optionsKey) {
var $optionsGetter = $parse(optionsKey);
options = $optionsGetter(scope) || {};
if (!options && $optionsGetter.assign) {
options = {
row: item.row,
col: item.col,
sizeX: item.sizeX,
sizeY: item.sizeY
};
$optionsGetter.assign(scope, options);
}
} else {
options = attrs;
}
item.init($el, gridster);
$el.addClass('gridster-item');
var aspects = ['sizeX', 'sizeY', 'row', 'col'],
$getters = {};
var aspectFn = function(aspect) {
var key;
if (typeof options[aspect] === 'string') {
key = options[aspect];
} else if (typeof options[aspect.toLowerCase()] === 'string') {
key = options[aspect.toLowerCase()];
} else if (optionsKey) {
key = $parse(optionsKey + '.' + aspect);
} else {
return;
}
$getters[aspect] = $parse(key);
// when the value changes externally, update the internal item object
scope.$watch(key, function(newVal) {
newVal = parseInt(newVal, 10);
if (!isNaN(newVal)) {
item[aspect] = newVal;
}
});
// initial set
var val = $getters[aspect](scope);
if (typeof val === 'number') {
item[aspect] = val;
}
};
for (var i = 0, l = aspects.length; i < l; ++i) {
aspectFn(aspects[i]);
}
function positionChanged() {
// call setPosition so the element and gridster controller are updated
item.setPosition(item.row, item.col);
// when internal item position changes, update externally bound values
if ($getters.row && $getters.row.assign) {
$getters.row.assign(scope, item.row);
}
if ($getters.col && $getters.col.assign) {
$getters.col.assign(scope, item.col);
}
}
scope.$watch(function() {
return item.row;
}, positionChanged);
scope.$watch(function() {
return item.col;
}, positionChanged);
scope.$watch(function() {
return item.sizeY;
}, function(sizeY) {
item.setSizeY(sizeY);
if ($getters.sizeY && $getters.sizeY.assign) {
$getters.sizeY.assign(scope, item.sizeY);
}
});
scope.$watch(function() {
return item.sizeX;
}, function(sizeX) {
item.setSizeX(sizeX);
if ($getters.sizeX && $getters.sizeX.assign) {
$getters.sizeX.assign(scope, item.sizeX);
}
});
var draggable = new GridsterDraggable($el, scope, gridster, item, options);
var resizable = new GridsterResizable($el, scope, gridster, item, options);
scope.$on('gridster-draggable-changed', function() {
draggable.toggle(gridster.draggable && gridster.draggable.enabled);
});
scope.$on('gridster-resizable-changed', function() {
resizable.toggle(gridster.resizable && gridster.resizable.enabled);
});
if (gridster.draggable && gridster.draggable.enabled) {
draggable.enable();
}
if (gridster.resizable && gridster.resizable.enabled) {
resizable.enable();
}
return scope.$on('$destroy', function() {
try {
resizable.destroy();
draggable.destroy();
} catch (e) {}
try {
gridster.removeItem(item);
} catch (e) {}
try {
item.destroy();
} catch (e) {}
});
}
};
}
])
;
|
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2012, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Polish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['pl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, wyłączone</span>',
confirmCancel : 'Pewne opcje zostały zmienione. Czy na pewno zamknąć okno dialogowe?',
ok : 'OK',
cancel : 'Anuluj',
confirmationTitle : 'Potwierdzenie',
messageTitle : 'Informacja',
inputTitle : 'Pytanie',
undo : 'Cofnij',
redo : 'Ponów',
skip : 'Pomiń',
skipAll : 'Pomiń wszystkie',
makeDecision : 'Wybierz jedną z opcji:',
rememberDecision: 'Zapamiętaj mój wybór'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'pl',
LangCode : 'pl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Foldery',
FolderLoading : 'Ładowanie...',
FolderNew : 'Podaj nazwę nowego folderu: ',
FolderRename : 'Podaj nową nazwę folderu: ',
FolderDelete : 'Czy na pewno chcesz usunąć folder "%1"?',
FolderRenaming : ' (Zmieniam nazwę...)',
FolderDeleting : ' (Kasowanie...)',
// Files
FileRename : 'Podaj nową nazwę pliku: ',
FileRenameExt : 'Czy na pewno chcesz zmienić rozszerzenie pliku? Może to spowodować problemy z otwieraniem pliku przez innych użytkowników.',
FileRenaming : 'Zmieniam nazwę...',
FileDelete : 'Czy na pewno chcesz usunąć plik "%1"?',
FilesLoading : 'Ładowanie...',
FilesEmpty : 'Folder jest pusty',
FilesMoved : 'Plik %1 został przeniesiony do %2:%3.',
FilesCopied : 'Plik %1 został skopiowany do %2:%3.',
// Basket
BasketFolder : 'Koszyk',
BasketClear : 'Wyczyść koszyk',
BasketRemove : 'Usuń z koszyka',
BasketOpenFolder : 'Otwórz folder z plikiem',
BasketTruncateConfirm : 'Czy naprawdę chcesz usunąć wszystkie pliki z koszyka?',
BasketRemoveConfirm : 'Czy naprawdę chcesz usunąć plik "%1" z koszyka?',
BasketEmpty : 'Brak plików w koszyku. Aby dodać plik, przeciągnij i upuść (drag\'n\'drop) dowolny plik do koszyka.',
BasketCopyFilesHere : 'Skopiuj pliki z koszyka',
BasketMoveFilesHere : 'Przenieś pliki z koszyka',
BasketPasteErrorOther : 'Plik: %s błąd: %e',
BasketPasteMoveSuccess : 'Następujące pliki zostały przeniesione: %s',
BasketPasteCopySuccess : 'Następujące pliki zostały skopiowane: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Wyślij',
UploadTip : 'Wyślij plik',
Refresh : 'Odśwież',
Settings : 'Ustawienia',
Help : 'Pomoc',
HelpTip : 'Wskazówka',
// Context Menus
Select : 'Wybierz',
SelectThumbnail : 'Wybierz miniaturkę',
View : 'Zobacz',
Download : 'Pobierz',
NewSubFolder : 'Nowy podfolder',
Rename : 'Zmień nazwę',
Delete : 'Usuń',
CopyDragDrop : 'Skopiuj plik tutaj',
MoveDragDrop : 'Przenieś plik tutaj',
// Dialogs
RenameDlgTitle : 'Zmiana nazwy',
NewNameDlgTitle : 'Nowa nazwa',
FileExistsDlgTitle : 'Plik już istnieje',
SysErrorDlgTitle : 'Błąd systemu',
FileOverwrite : 'Nadpisz',
FileAutorename : 'Zmień automatycznie nazwę',
// Generic
OkBtn : 'OK',
CancelBtn : 'Anuluj',
CloseBtn : 'Zamknij',
// Upload Panel
UploadTitle : 'Wyślij plik',
UploadSelectLbl : 'Wybierz plik',
UploadProgressLbl : '(Trwa wysyłanie pliku, proszę czekać...)',
UploadBtn : 'Wyślij wybrany plik',
UploadBtnCancel : 'Anuluj',
UploadNoFileMsg : 'Wybierz plik ze swojego komputera.',
UploadNoFolder : 'Wybierz folder przed wysłaniem pliku.',
UploadNoPerms : 'Wysyłanie plików nie jest dozwolone.',
UploadUnknError : 'Błąd podczas wysyłania pliku.',
UploadExtIncorrect : 'Rozszerzenie pliku nie jest dozwolone w tym folderze.',
// Flash Uploads
UploadLabel : 'Pliki do wysłania',
UploadTotalFiles : 'Ilość razem:',
UploadTotalSize : 'Rozmiar razem:',
UploadSend : 'Wyślij',
UploadAddFiles : 'Dodaj pliki',
UploadClearFiles : 'Wyczyść wszystko',
UploadCancel : 'Anuluj wysyłanie',
UploadRemove : 'Usuń',
UploadRemoveTip : 'Usuń !f',
UploadUploaded : 'Wysłano: !n',
UploadProcessing : 'Przetwarzanie...',
// Settings Panel
SetTitle : 'Ustawienia',
SetView : 'Widok:',
SetViewThumb : 'Miniaturki',
SetViewList : 'Lista',
SetDisplay : 'Wyświetlanie:',
SetDisplayName : 'Nazwa pliku',
SetDisplayDate : 'Data',
SetDisplaySize : 'Rozmiar pliku',
SetSort : 'Sortowanie:',
SetSortName : 'wg nazwy pliku',
SetSortDate : 'wg daty',
SetSortSize : 'wg rozmiaru',
SetSortExtension : 'wg rozszerzenia',
// Status Bar
FilesCountEmpty : '<Pusty folder>',
FilesCountOne : '1 plik',
FilesCountMany : 'Ilość plików: %1',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Wykonanie operacji zakończyło się niepowodzeniem. (Błąd %1)',
Errors :
{
10 : 'Nieprawidłowe polecenie (command).',
11 : 'Brak wymaganego parametru: typ danych (resource type).',
12 : 'Nieprawidłowy typ danych (resource type).',
102 : 'Nieprawidłowa nazwa pliku lub folderu.',
103 : 'Wykonanie operacji nie jest możliwe: brak uprawnień.',
104 : 'Wykonanie operacji nie powiodło się z powodu niewystarczających uprawnień do systemu plików.',
105 : 'Nieprawidłowe rozszerzenie.',
109 : 'Nieprawiłowe żądanie.',
110 : 'Niezidentyfikowany błąd.',
115 : 'Plik lub folder o podanej nazwie już istnieje.',
116 : 'Nie znaleziono folderu. Odśwież panel i spróbuj ponownie.',
117 : 'Nie znaleziono pliku. Odśwież listę plików i spróbuj ponownie.',
118 : 'Ścieżki źródłowa i docelowa są jednakowe.',
201 : 'Plik o podanej nazwie już istnieje. Nazwa przesłanego pliku została zmieniona na "%1".',
202 : 'Nieprawidłowy plik.',
203 : 'Nieprawidłowy plik. Plik przekracza dozwolony rozmiar.',
204 : 'Przesłany plik jest uszkodzony.',
205 : 'Brak folderu tymczasowego na serwerze do przesyłania plików.',
206 : 'Przesyłanie pliku zakończyło się niepowodzeniem z powodów bezpieczeństwa. Plik zawiera dane przypominające HTML.',
207 : 'Nazwa przesłanego pliku została zmieniona na "%1".',
300 : 'Przenoszenie nie powiodło się.',
301 : 'Kopiowanie nie powiodo się.',
500 : 'Menedżer plików jest wyłączony z powodów bezpieczeństwa. Skontaktuj się z administratorem oraz sprawdź plik konfiguracyjny CKFindera.',
501 : 'Tworzenie miniaturek jest wyłączone.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Nazwa pliku nie może być pusta.',
FileExists : 'Plik %s już istnieje.',
FolderEmpty : 'Nazwa folderu nie może być pusta.',
FileInvChar : 'Nazwa pliku nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
FolderInvChar : 'Nazwa folderu nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
PopupBlockView : 'Otwarcie pliku w nowym oknie nie powiodło się. Należy zmienić konfigurację przeglądarki i wyłączyć wszelkie blokady okienek popup dla tej strony.',
XmlError : 'Nie można poprawnie załadować odpowiedzi XML z serwera WWW.',
XmlEmpty : 'Nie można załadować odpowiedzi XML z serwera WWW. Serwer zwrócił pustą odpowiedź.',
XmlRawResponse : 'Odpowiedź serwera: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Zmiana rozmiaru %s',
sizeTooBig : 'Nie możesz zmienić wysokości lub szerokości na wartość większą od oryginalnego rozmiaru (%size).',
resizeSuccess : 'Obrazek został pomyślnie przeskalowany.',
thumbnailNew : 'Utwórz nową miniaturkę',
thumbnailSmall : 'Mała (%s)',
thumbnailMedium : 'Średnia (%s)',
thumbnailLarge : 'Duża (%s)',
newSize : 'Podaj nowe wymiary',
width : 'Szerokość',
height : 'Wysokość',
invalidHeight : 'Nieprawidłowa wysokość.',
invalidWidth : 'Nieprawidłowa szerokość.',
invalidName : 'Nieprawidłowa nazwa pliku.',
newImage : 'Utwórz nowy obrazek',
noExtensionChange : 'Rozszerzenie pliku nie może zostac zmienione.',
imageSmall : 'Plik źródłowy jest zbyt mały.',
contextMenuName : 'Zmień rozmiar',
lockRatio : 'Zablokuj proporcje',
resetSize : 'Przywróć rozmiar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Zapisz',
fileOpenError : 'Nie udało się otworzyć pliku.',
fileSaveSuccess : 'Plik został zapisany pomyślnie.',
contextMenuName : 'Edytuj',
loadingFile : 'Trwa ładowanie pliku, proszę czekać...'
},
Maximize :
{
maximize : 'Maksymalizuj',
minimize : 'Minimalizuj'
}
};
|
module.exports={title:"Winmate",slug:"winmate",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Winmate icon</title><path d="M5.785 4.058l-4.473.004L1.311.01 19.469 0c3.514.42 3.199 4.047 3.199 4.047l-2.156-.002-2.769 15.888L14.79 4.049l-4.731.005.856 7.376-2.137 8.507L5.785 4.058zM4.491 21.373L1.317 8.52l.009 12.338C1.756 23.983 4.629 24 4.629 24l1.687-.001c-1.393-.69-1.825-2.626-1.825-2.626zm9.237.659l-1.724-6.724-1.673 6.678c-.517 1.652-1.702 2.009-1.702 2.009l6.602-.002c-1.206-.499-1.503-1.961-1.503-1.961zm8.949-17.643l-2.844 15.865c-.711 3.767-2.285 3.738-2.285 3.738l5.141-.008-.012-19.595z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.winmate.com/NewsAndEvents/Publications",hex:"C11920",guidelines:void 0,license:void 0};
|
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var Auth2Client = require('./oauth2client.js');
var util = require('util');
/**
* Google Compute Engine metadata server token endpoint.
* @private
*/
Compute.GOOGLE_OAUTH2_TOKEN_URL_ =
'http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token';
/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
* @constructor@constructor
*/
function Compute() {
Compute.super_.call(this);
// Start with an expired refresh token, which will automatically be refreshed
// before the first API call is made.
this.credentials = {
refresh_token: 'compute-placeholder',
expiry_date: 1
};
// Hook the post request method so we can provide better error messages.
this._postRequest = this._injectErrorMessage;
}
/**
* Inherit from Auth2Client.
*/
util.inherits(Compute, Auth2Client);
/**
* Indicates whether the credential requires scopes to be created by calling createdScoped before
* use.
* @return {object} The cloned instance.
*/
Compute.prototype.createScopedRequired = function() {
// On compute engine, scopes are specified at the compute instance's creation time,
// and cannot be changed. For this reason, always return false.
return false;
};
/**
* Refreshes the access token.
* @param {object=} ignored_
* @param {function=} opt_callback Optional callback.
* @private
*/
Compute.prototype.refreshToken_ = function(ignored_, opt_callback) {
var uri = this.opts.tokenUrl || Compute.GOOGLE_OAUTH2_TOKEN_URL_;
// request for new token
this.transporter.request({
method: 'GET',
uri: uri,
json: true
}, function(err, tokens, response) {
if (!err && tokens && tokens.expires_in) {
tokens.expiry_date = ((new Date()).getTime() + (tokens.expires_in * 1000));
delete tokens.expires_in;
}
if (opt_callback) {
opt_callback(err, tokens, response);
}
});
};
/**
* Inserts a helpful error message guiding the user toward fixing common auth issues.
* @param {object} err Error result.
* @param {object} result The result.
* @param {object} response The HTTP response.
* @param {Function} callback The callback.
* @private
*/
Compute.prototype._injectErrorMessage = function(err, result, response, callback) {
if (response && response.statusCode) {
var helpfulMessage = null;
if (response.statusCode === 403) {
helpfulMessage = 'A Forbidden error was returned while attempting to retrieve an access ' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have the correct permission scopes specified.';
} else if (response.statusCode === 404) {
helpfulMessage = 'A Not Found error was returned while attempting to retrieve an access' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have any permission scopes specified.';
}
if (helpfulMessage) {
if (err && err.message) {
helpfulMessage += ' ' + err.message;
}
if (err) {
err.message = helpfulMessage;
} else {
err = new Error(helpfulMessage);
err.code = response.statusCode;
}
}
}
callback(err, result, response);
};
/**
* Export Compute.
*/
module.exports = Compute;
|
/*
* English/UK (UTF-8) initialisation for the jQuery UI date picker plugin.
* Adapted to match the Zend Data localization for SilverStripe CMS
* See: README
*/
jQuery(function($){
$.datepicker.regional['en-GB'] = {
closeText: 'Done',
prevText: 'Prev',
nextText: 'Next',
currentText: 'Today',
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
weekHeader: 'Wk',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['en-GB']);
});
|
var ObjectRenderer = require('../../renderers/webgl/utils/ObjectRenderer'),
WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'),
ParticleShader = require('./ParticleShader'),
ParticleBuffer = require('./ParticleBuffer'),
math = require('../../math');
/**
* @author Mat Groves
*
* Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
* for creating the original pixi version!
* Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer
*
* Heavily inspired by LibGDX's ParticleRenderer:
* https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java
*/
/**
*
* @class
* @private
* @memberof PIXI
* @param renderer {PIXI.WebGLRenderer} The renderer this sprite batch works for.
*/
function ParticleRenderer(renderer)
{
ObjectRenderer.call(this, renderer);
// 65535 is max vertex index in the index buffer (see ParticleRenderer)
// so max number of particles is 65536 / 4 = 16384
// and max number of element in the index buffer is 16384 * 6 = 98304
// Creating a full index buffer, overhead is 98304 * 2 = 196Ko
var numIndices = 98304;
/**
* Holds the indices
*
* @member {Uint16Array}
*/
this.indices = new Uint16Array(numIndices);
for (var i=0, j=0; i < numIndices; i += 6, j += 4)
{
this.indices[i + 0] = j + 0;
this.indices[i + 1] = j + 1;
this.indices[i + 2] = j + 2;
this.indices[i + 3] = j + 0;
this.indices[i + 4] = j + 2;
this.indices[i + 5] = j + 3;
}
/**
* The default shader that is used if a sprite doesn't have a more specific one.
*
* @member {PIXI.Shader}
*/
this.shader = null;
this.indexBuffer = null;
this.properties = null;
this.tempMatrix = new math.Matrix();
}
ParticleRenderer.prototype = Object.create(ObjectRenderer.prototype);
ParticleRenderer.prototype.constructor = ParticleRenderer;
module.exports = ParticleRenderer;
WebGLRenderer.registerPlugin('particle', ParticleRenderer);
/**
* When there is a WebGL context change
*
* @private
*/
ParticleRenderer.prototype.onContextChange = function ()
{
var gl = this.renderer.gl;
// setup default shader
this.shader = new ParticleShader(this.renderer.shaderManager);
this.indexBuffer = gl.createBuffer();
// 65535 is max index, so 65535 / 6 = 10922.
//upload the index data
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
this.properties = [
// verticesData
{
attribute:this.shader.attributes.aVertexPosition,
size:2,
uploadFunction:this.uploadVertices,
offset:0
},
// positionData
{
attribute:this.shader.attributes.aPositionCoord,
size:2,
uploadFunction:this.uploadPosition,
offset:0
},
// rotationData
{
attribute:this.shader.attributes.aRotation,
size:1,
uploadFunction:this.uploadRotation,
offset:0
},
// uvsData
{
attribute:this.shader.attributes.aTextureCoord,
size:2,
uploadFunction:this.uploadUvs,
offset:0
},
// alphaData
{
attribute:this.shader.attributes.aColor,
size:1,
uploadFunction:this.uploadAlpha,
offset:0
}
];
};
/**
* Starts a new particle batch.
*
*/
ParticleRenderer.prototype.start = function ()
{
var gl = this.renderer.gl;
// bind the main texture
gl.activeTexture(gl.TEXTURE0);
// bind the buffers
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
var shader = this.shader;
this.renderer.shaderManager.setShader(shader);
};
/**
* Renders the particle container object.
*
* @param container {PIXI.ParticleContainer} The container to render using this ParticleRenderer
*/
ParticleRenderer.prototype.render = function (container)
{
var children = container.children,
totalChildren = children.length,
maxSize = container._maxSize,
batchSize = container._batchSize;
if(totalChildren === 0)
{
return;
}
else if(totalChildren > maxSize)
{
totalChildren = maxSize;
}
if(!container._buffers)
{
container._buffers = this.generateBuffers( container );
}
// if the uvs have not updated then no point rendering just yet!
this.renderer.blendModeManager.setBlendMode(container.blendMode);
var gl = this.renderer.gl;
var m = container.worldTransform.copy( this.tempMatrix );
m.prepend( this.renderer.currentRenderTarget.projectionMatrix );
gl.uniformMatrix3fv(this.shader.uniforms.projectionMatrix._location, false, m.toArray(true));
gl.uniform1f(this.shader.uniforms.uAlpha._location, container.worldAlpha);
// make sure the texture is bound..
var baseTexture = children[0]._texture.baseTexture;
if (!baseTexture._glTextures[gl.id])
{
// if the texture has not updated then lets not upload any static properties
if(!this.renderer.updateTexture(baseTexture))
{
return;
}
if(!container._properties[0] || !container._properties[3])
{
container._bufferToUpdate = 0;
}
}
else
{
gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]);
}
// now lets upload and render the buffers..
for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1)
{
var amount = ( totalChildren - i);
if(amount > batchSize)
{
amount = batchSize;
}
var buffer = container._buffers[j];
// we always upload the dynamic
buffer.uploadDynamic(children, i, amount);
// we only upload the static content when we have to!
if(container._bufferToUpdate === j)
{
buffer.uploadStatic(children, i, amount);
container._bufferToUpdate = j + 1;
}
// bind the buffer
buffer.bind( this.shader );
// now draw those suckas!
gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0);
this.renderer.drawCount++;
}
};
/**
* Creates one particle buffer for each child in the container we want to render and updates internal properties
*
* @param container {PIXI.ParticleContainer} The container to render using this ParticleRenderer
*/
ParticleRenderer.prototype.generateBuffers = function (container)
{
var gl = this.renderer.gl,
buffers = [],
size = container._maxSize,
batchSize = container._batchSize,
dynamicPropertyFlags = container._properties,
i;
for (i = 0; i < size; i += batchSize)
{
buffers.push(new ParticleBuffer(gl, this.properties, dynamicPropertyFlags, batchSize));
}
return buffers;
};
/**
* Uploads the verticies.
*
* @param children {PIXI.DisplayObject[]} the array of display objects to render
* @param startIndex {number} the index to start from in the children array
* @param amount {number} the amount of children that will have their vertices uploaded
* @param array {number[]}
* @param stride {number}
* @param offset {number}
*/
ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset)
{
var sprite,
texture,
trim,
sx,
sy,
w0, w1, h0, h1;
for (var i = 0; i < amount; i++) {
sprite = children[startIndex + i];
texture = sprite._texture;
sx = sprite.scale.x;
sy = sprite.scale.y;
if (texture.trim)
{
// if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
trim = texture.trim;
w1 = trim.x - sprite.anchor.x * trim.width;
w0 = w1 + texture.crop.width;
h1 = trim.y - sprite.anchor.y * trim.height;
h0 = h1 + texture.crop.height;
}
else
{
w0 = (texture._frame.width ) * (1-sprite.anchor.x);
w1 = (texture._frame.width ) * -sprite.anchor.x;
h0 = texture._frame.height * (1-sprite.anchor.y);
h1 = texture._frame.height * -sprite.anchor.y;
}
array[offset] = w1 * sx;
array[offset + 1] = h1 * sy;
array[offset + stride] = w0 * sx;
array[offset + stride + 1] = h1 * sy;
array[offset + stride * 2] = w0 * sx;
array[offset + stride * 2 + 1] = h0 * sy;
array[offset + stride * 3] = w1 * sx;
array[offset + stride * 3 + 1] = h0 * sy;
offset += stride * 4;
}
};
/**
*
* @param children {PIXI.DisplayObject[]} the array of display objects to render
* @param startIndex {number} the index to start from in the children array
* @param amount {number} the amount of children that will have their positions uploaded
* @param array {number[]}
* @param stride {number}
* @param offset {number}
*/
ParticleRenderer.prototype.uploadPosition = function (children,startIndex, amount, array, stride, offset)
{
for (var i = 0; i < amount; i++)
{
var spritePosition = children[startIndex + i].position;
array[offset] = spritePosition.x;
array[offset + 1] = spritePosition.y;
array[offset + stride] = spritePosition.x;
array[offset + stride + 1] = spritePosition.y;
array[offset + stride * 2] = spritePosition.x;
array[offset + stride * 2 + 1] = spritePosition.y;
array[offset + stride * 3] = spritePosition.x;
array[offset + stride * 3 + 1] = spritePosition.y;
offset += stride * 4;
}
};
/**
*
* @param children {PIXI.DisplayObject[]} the array of display objects to render
* @param startIndex {number} the index to start from in the children array
* @param amount {number} the amount of children that will have their rotation uploaded
* @param array {number[]}
* @param stride {number}
* @param offset {number}
*/
ParticleRenderer.prototype.uploadRotation = function (children,startIndex, amount, array, stride, offset)
{
for (var i = 0; i < amount; i++)
{
var spriteRotation = children[startIndex + i].rotation;
array[offset] = spriteRotation;
array[offset + stride] = spriteRotation;
array[offset + stride * 2] = spriteRotation;
array[offset + stride * 3] = spriteRotation;
offset += stride * 4;
}
};
/**
*
* @param children {PIXI.DisplayObject[]} the array of display objects to render
* @param startIndex {number} the index to start from in the children array
* @param amount {number} the amount of children that will have their Uvs uploaded
* @param array {number[]}
* @param stride {number}
* @param offset {number}
*/
ParticleRenderer.prototype.uploadUvs = function (children,startIndex, amount, array, stride, offset)
{
for (var i = 0; i < amount; i++)
{
var textureUvs = children[startIndex + i]._texture._uvs;
if (textureUvs)
{
array[offset] = textureUvs.x0;
array[offset + 1] = textureUvs.y0;
array[offset + stride] = textureUvs.x1;
array[offset + stride + 1] = textureUvs.y1;
array[offset + stride * 2] = textureUvs.x2;
array[offset + stride * 2 + 1] = textureUvs.y2;
array[offset + stride * 3] = textureUvs.x3;
array[offset + stride * 3 + 1] = textureUvs.y3;
offset += stride * 4;
}
else
{
//TODO you know this can be easier!
array[offset] = 0;
array[offset + 1] = 0;
array[offset + stride] = 0;
array[offset + stride + 1] = 0;
array[offset + stride * 2] = 0;
array[offset + stride * 2 + 1] = 0;
array[offset + stride * 3] = 0;
array[offset + stride * 3 + 1] = 0;
offset += stride * 4;
}
}
};
/**
*
* @param children {PIXI.DisplayObject[]} the array of display objects to render
* @param startIndex {number} the index to start from in the children array
* @param amount {number} the amount of children that will have their alpha uploaded
* @param array {number[]}
* @param stride {number}
* @param offset {number}
*/
ParticleRenderer.prototype.uploadAlpha = function (children,startIndex, amount, array, stride, offset)
{
for (var i = 0; i < amount; i++)
{
var spriteAlpha = children[startIndex + i].alpha;
array[offset] = spriteAlpha;
array[offset + stride] = spriteAlpha;
array[offset + stride * 2] = spriteAlpha;
array[offset + stride * 3] = spriteAlpha;
offset += stride * 4;
}
};
/**
* Destroys the ParticleRenderer.
*
*/
ParticleRenderer.prototype.destroy = function ()
{
if (this.renderer.gl) {
this.renderer.gl.deleteBuffer(this.indexBuffer);
}
ObjectRenderer.prototype.destroy.apply(this, arguments);
this.shader.destroy();
this.indices = null;
this.tempMatrix = null;
};
|
var Pos = CodeMirror.Pos;
CodeMirror.defaults.rtlMoveVisually = true;
function forEach(arr, f) {
for (var i = 0, e = arr.length; i < e; ++i) f(arr[i], i);
}
function addDoc(cm, width, height) {
var content = [], line = "";
for (var i = 0; i < width; ++i) line += "x";
for (var i = 0; i < height; ++i) content.push(line);
cm.setValue(content.join("\n"));
}
function byClassName(elt, cls) {
if (elt.getElementsByClassName) return elt.getElementsByClassName(cls);
var found = [], re = new RegExp("\\b" + cls + "\\b");
function search(elt) {
if (elt.nodeType == 3) return;
if (re.test(elt.className)) found.push(elt);
for (var i = 0, e = elt.childNodes.length; i < e; ++i)
search(elt.childNodes[i]);
}
search(elt);
return found;
}
var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
var mac = /Mac/.test(navigator.platform);
var phantom = /PhantomJS/.test(navigator.userAgent);
var opera = /Opera\/\./.test(navigator.userAgent);
var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/);
if (opera_version) opera_version = Number(opera_version);
var opera_lt10 = opera && (!opera_version || opera_version < 10);
namespace = "core_";
test("core_fromTextArea", function() {
var te = document.getElementById("code");
te.value = "CONTENT";
var cm = CodeMirror.fromTextArea(te);
is(!te.offsetHeight);
eq(cm.getValue(), "CONTENT");
cm.setValue("foo\nbar");
eq(cm.getValue(), "foo\nbar");
cm.save();
is(/^foo\r?\nbar$/.test(te.value));
cm.setValue("xxx");
cm.toTextArea();
is(te.offsetHeight);
eq(te.value, "xxx");
});
testCM("getRange", function(cm) {
eq(cm.getLine(0), "1234");
eq(cm.getLine(1), "5678");
eq(cm.getLine(2), null);
eq(cm.getLine(-1), null);
eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123");
eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234");
eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56");
eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78");
}, {value: "1234\n5678"});
testCM("replaceRange", function(cm) {
eq(cm.getValue(), "");
cm.replaceRange("foo\n", Pos(0, 0));
eq(cm.getValue(), "foo\n");
cm.replaceRange("a\nb", Pos(0, 1));
eq(cm.getValue(), "fa\nboo\n");
eq(cm.lineCount(), 3);
cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1));
eq(cm.getValue(), "xyzzyoo\n");
cm.replaceRange("abc", Pos(0, 0), Pos(10, 0));
eq(cm.getValue(), "abc");
eq(cm.lineCount(), 1);
});
testCM("selection", function(cm) {
cm.setSelection(Pos(0, 4), Pos(2, 2));
is(cm.somethingSelected());
eq(cm.getSelection(), "11\n222222\n33");
eqPos(cm.getCursor(false), Pos(2, 2));
eqPos(cm.getCursor(true), Pos(0, 4));
cm.setSelection(Pos(1, 0));
is(!cm.somethingSelected());
eq(cm.getSelection(), "");
eqPos(cm.getCursor(true), Pos(1, 0));
cm.replaceSelection("abc", "around");
eq(cm.getSelection(), "abc");
eq(cm.getValue(), "111111\nabc222222\n333333");
cm.replaceSelection("def", "end");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(true), Pos(1, 3));
cm.setCursor(Pos(2, 1));
eqPos(cm.getCursor(true), Pos(2, 1));
cm.setCursor(1, 2);
eqPos(cm.getCursor(true), Pos(1, 2));
}, {value: "111111\n222222\n333333"});
testCM("extendSelection", function(cm) {
cm.setExtending(true);
addDoc(cm, 10, 10);
cm.setSelection(Pos(3, 5));
eqPos(cm.getCursor("head"), Pos(3, 5));
eqPos(cm.getCursor("anchor"), Pos(3, 5));
cm.setSelection(Pos(2, 5), Pos(5, 5));
eqPos(cm.getCursor("head"), Pos(5, 5));
eqPos(cm.getCursor("anchor"), Pos(2, 5));
eqPos(cm.getCursor("start"), Pos(2, 5));
eqPos(cm.getCursor("end"), Pos(5, 5));
cm.setSelection(Pos(5, 5), Pos(2, 5));
eqPos(cm.getCursor("head"), Pos(2, 5));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
eqPos(cm.getCursor("start"), Pos(2, 5));
eqPos(cm.getCursor("end"), Pos(5, 5));
cm.extendSelection(Pos(3, 2));
eqPos(cm.getCursor("head"), Pos(3, 2));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(6, 2));
eqPos(cm.getCursor("head"), Pos(6, 2));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(6, 3), Pos(6, 4));
eqPos(cm.getCursor("head"), Pos(6, 4));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(0, 3), Pos(0, 4));
eqPos(cm.getCursor("head"), Pos(0, 3));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(4, 5), Pos(6, 5));
eqPos(cm.getCursor("head"), Pos(6, 5));
eqPos(cm.getCursor("anchor"), Pos(4, 5));
cm.setExtending(false);
cm.extendSelection(Pos(0, 3), Pos(0, 4));
eqPos(cm.getCursor("head"), Pos(0, 3));
eqPos(cm.getCursor("anchor"), Pos(0, 4));
});
testCM("lines", function(cm) {
eq(cm.getLine(0), "111111");
eq(cm.getLine(1), "222222");
eq(cm.getLine(-1), null);
cm.replaceRange("", Pos(1, 0), Pos(2, 0))
cm.replaceRange("abc", Pos(1, 0), Pos(1));
eq(cm.getValue(), "111111\nabc");
}, {value: "111111\n222222\n333333"});
testCM("indent", function(cm) {
cm.indentLine(1);
eq(cm.getLine(1), " blah();");
cm.setOption("indentUnit", 8);
cm.indentLine(1);
eq(cm.getLine(1), "\tblah();");
cm.setOption("indentUnit", 10);
cm.setOption("tabSize", 4);
cm.indentLine(1);
eq(cm.getLine(1), "\t\t blah();");
}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8});
testCM("indentByNumber", function(cm) {
cm.indentLine(0, 2);
eq(cm.getLine(0), " foo");
cm.indentLine(0, -200);
eq(cm.getLine(0), "foo");
cm.setSelection(Pos(0, 0), Pos(1, 2));
cm.indentSelection(3);
eq(cm.getValue(), " foo\n bar\nbaz");
}, {value: "foo\nbar\nbaz"});
test("core_defaults", function() {
var defsCopy = {}, defs = CodeMirror.defaults;
for (var opt in defs) defsCopy[opt] = defs[opt];
defs.indentUnit = 5;
defs.value = "uu";
defs.indentWithTabs = true;
defs.tabindex = 55;
var place = document.getElementById("testground"), cm = CodeMirror(place);
try {
eq(cm.getOption("indentUnit"), 5);
cm.setOption("indentUnit", 10);
eq(defs.indentUnit, 5);
eq(cm.getValue(), "uu");
eq(cm.getOption("indentWithTabs"), true);
eq(cm.getInputField().tabIndex, 55);
}
finally {
for (var opt in defsCopy) defs[opt] = defsCopy[opt];
place.removeChild(cm.getWrapperElement());
}
});
testCM("lineInfo", function(cm) {
eq(cm.lineInfo(-1), null);
var mark = document.createElement("span");
var lh = cm.setGutterMarker(1, "FOO", mark);
var info = cm.lineInfo(1);
eq(info.text, "222222");
eq(info.gutterMarkers.FOO, mark);
eq(info.line, 1);
eq(cm.lineInfo(2).gutterMarkers, null);
cm.setGutterMarker(lh, "FOO", null);
eq(cm.lineInfo(1).gutterMarkers, null);
cm.setGutterMarker(1, "FOO", mark);
cm.setGutterMarker(0, "FOO", mark);
cm.clearGutter("FOO");
eq(cm.lineInfo(0).gutterMarkers, null);
eq(cm.lineInfo(1).gutterMarkers, null);
}, {value: "111111\n222222\n333333"});
testCM("coords", function(cm) {
cm.setSize(null, 100);
addDoc(cm, 32, 200);
var top = cm.charCoords(Pos(0, 0));
var bot = cm.charCoords(Pos(200, 30));
is(top.left < bot.left);
is(top.top < bot.top);
is(top.top < top.bottom);
cm.scrollTo(null, 100);
var top2 = cm.charCoords(Pos(0, 0));
is(top.top > top2.top);
eq(top.left, top2.left);
});
testCM("coordsChar", function(cm) {
addDoc(cm, 35, 70);
for (var i = 0; i < 2; ++i) {
var sys = i ? "local" : "page";
for (var ch = 0; ch <= 35; ch += 5) {
for (var line = 0; line < 70; line += 5) {
cm.setCursor(line, ch);
var coords = cm.charCoords(Pos(line, ch), sys);
var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
eqPos(pos, Pos(line, ch));
}
}
}
}, {lineNumbers: true});
testCM("posFromIndex", function(cm) {
cm.setValue(
"This function should\n" +
"convert a zero based index\n" +
"to line and ch."
);
var examples = [
{ index: -1, line: 0, ch: 0 }, // <- Tests clipping
{ index: 0, line: 0, ch: 0 },
{ index: 10, line: 0, ch: 10 },
{ index: 39, line: 1, ch: 18 },
{ index: 55, line: 2, ch: 7 },
{ index: 63, line: 2, ch: 15 },
{ index: 64, line: 2, ch: 15 } // <- Tests clipping
];
for (var i = 0; i < examples.length; i++) {
var example = examples[i];
var pos = cm.posFromIndex(example.index);
eq(pos.line, example.line);
eq(pos.ch, example.ch);
if (example.index >= 0 && example.index < 64)
eq(cm.indexFromPos(pos), example.index);
}
});
testCM("undo", function(cm) {
cm.replaceRange("def", Pos(0, 0), Pos(0));
eq(cm.historySize().undo, 1);
cm.undo();
eq(cm.getValue(), "abc");
eq(cm.historySize().undo, 0);
eq(cm.historySize().redo, 1);
cm.redo();
eq(cm.getValue(), "def");
eq(cm.historySize().undo, 1);
eq(cm.historySize().redo, 0);
cm.setValue("1\n\n\n2");
cm.clearHistory();
eq(cm.historySize().undo, 0);
for (var i = 0; i < 20; ++i) {
cm.replaceRange("a", Pos(0, 0));
cm.replaceRange("b", Pos(3, 0));
}
eq(cm.historySize().undo, 40);
for (var i = 0; i < 40; ++i)
cm.undo();
eq(cm.historySize().redo, 40);
eq(cm.getValue(), "1\n\n\n2");
}, {value: "abc"});
testCM("undoDepth", function(cm) {
cm.replaceRange("d", Pos(0));
cm.replaceRange("e", Pos(0));
cm.replaceRange("f", Pos(0));
cm.undo(); cm.undo(); cm.undo();
eq(cm.getValue(), "abcd");
}, {value: "abc", undoDepth: 4});
testCM("undoDoesntClearValue", function(cm) {
cm.undo();
eq(cm.getValue(), "x");
}, {value: "x"});
testCM("undoMultiLine", function(cm) {
cm.operation(function() {
cm.replaceRange("x", Pos(0, 0));
cm.replaceRange("y", Pos(1, 0));
});
cm.undo();
eq(cm.getValue(), "abc\ndef\nghi");
cm.operation(function() {
cm.replaceRange("y", Pos(1, 0));
cm.replaceRange("x", Pos(0, 0));
});
cm.undo();
eq(cm.getValue(), "abc\ndef\nghi");
cm.operation(function() {
cm.replaceRange("y", Pos(2, 0));
cm.replaceRange("x", Pos(1, 0));
cm.replaceRange("z", Pos(2, 0));
});
cm.undo();
eq(cm.getValue(), "abc\ndef\nghi", 3);
}, {value: "abc\ndef\nghi"});
testCM("undoComposite", function(cm) {
cm.replaceRange("y", Pos(1));
cm.operation(function() {
cm.replaceRange("x", Pos(0));
cm.replaceRange("z", Pos(2));
});
eq(cm.getValue(), "ax\nby\ncz\n");
cm.undo();
eq(cm.getValue(), "a\nby\nc\n");
cm.undo();
eq(cm.getValue(), "a\nb\nc\n");
cm.redo(); cm.redo();
eq(cm.getValue(), "ax\nby\ncz\n");
}, {value: "a\nb\nc\n"});
testCM("undoSelection", function(cm) {
cm.setSelection(Pos(0, 2), Pos(0, 4));
cm.replaceSelection("");
cm.setCursor(Pos(1, 0));
cm.undo();
eqPos(cm.getCursor(true), Pos(0, 2));
eqPos(cm.getCursor(false), Pos(0, 4));
cm.setCursor(Pos(1, 0));
cm.redo();
eqPos(cm.getCursor(true), Pos(0, 2));
eqPos(cm.getCursor(false), Pos(0, 2));
}, {value: "abcdefgh\n"});
testCM("undoSelectionAsBefore", function(cm) {
cm.replaceSelection("abc", "around");
cm.undo();
cm.redo();
eq(cm.getSelection(), "abc");
});
testCM("selectionChangeConfusesHistory", function(cm) {
cm.replaceSelection("abc", null, "dontmerge");
cm.operation(function() {
cm.setCursor(Pos(0, 0));
cm.replaceSelection("abc", null, "dontmerge");
});
eq(cm.historySize().undo, 2);
});
testCM("markTextSingleLine", function(cm) {
forEach([{a: 0, b: 1, c: "", f: 2, t: 5},
{a: 0, b: 4, c: "", f: 0, t: 2},
{a: 1, b: 2, c: "x", f: 3, t: 6},
{a: 4, b: 5, c: "", f: 3, t: 5},
{a: 4, b: 5, c: "xx", f: 3, t: 7},
{a: 2, b: 5, c: "", f: 2, t: 3},
{a: 2, b: 5, c: "abcd", f: 6, t: 7},
{a: 2, b: 6, c: "x", f: null, t: null},
{a: 3, b: 6, c: "", f: null, t: null},
{a: 0, b: 9, c: "hallo", f: null, t: null},
{a: 4, b: 6, c: "x", f: 3, t: 4},
{a: 4, b: 8, c: "", f: 3, t: 4},
{a: 6, b: 6, c: "a", f: 3, t: 6},
{a: 8, b: 9, c: "", f: 3, t: 6}], function(test) {
cm.setValue("1234567890");
var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"});
cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b));
var f = r.find();
eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t);
});
});
testCM("markTextMultiLine", function(cm) {
function p(v) { return v && Pos(v[0], v[1]); }
forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]},
{a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]},
{a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]},
{a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]},
{a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]},
{a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]},
{a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]},
{a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]},
{a: [0, 5], b: [2, 5], c: "xx", f: null, t: null},
{a: [0, 0], b: [2, 10], c: "x", f: null, t: null},
{a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]},
{a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]},
{a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]},
{a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]},
{a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) {
cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n");
var r = cm.markText(Pos(0, 5), Pos(2, 5),
{className: "CodeMirror-matchingbracket"});
cm.replaceRange(test.c, p(test.a), p(test.b));
var f = r.find();
eqPos(f && f.from, p(test.f)); eqPos(f && f.to, p(test.t));
});
});
testCM("markTextUndo", function(cm) {
var marker1, marker2, bookmark;
marker1 = cm.markText(Pos(0, 1), Pos(0, 3),
{className: "CodeMirror-matchingbracket"});
marker2 = cm.markText(Pos(0, 0), Pos(2, 1),
{className: "CodeMirror-matchingbracket"});
bookmark = cm.setBookmark(Pos(1, 5));
cm.operation(function(){
cm.replaceRange("foo", Pos(0, 2));
cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0));
});
var v1 = cm.getValue();
cm.setValue("");
eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null);
cm.undo();
eqPos(bookmark.find(), Pos(1, 5), "still there");
cm.undo();
var m1Pos = marker1.find(), m2Pos = marker2.find();
eqPos(m1Pos.from, Pos(0, 1)); eqPos(m1Pos.to, Pos(0, 3));
eqPos(m2Pos.from, Pos(0, 0)); eqPos(m2Pos.to, Pos(2, 1));
eqPos(bookmark.find(), Pos(1, 5));
cm.redo(); cm.redo();
eq(bookmark.find(), null);
cm.undo();
eqPos(bookmark.find(), Pos(1, 5));
eq(cm.getValue(), v1);
}, {value: "1234\n56789\n00\n"});
testCM("markTextStayGone", function(cm) {
var m1 = cm.markText(Pos(0, 0), Pos(0, 1));
cm.replaceRange("hi", Pos(0, 2));
m1.clear();
cm.undo();
eq(m1.find(), null);
}, {value: "hello"});
testCM("markTextAllowEmpty", function(cm) {
var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false});
is(m1.find());
cm.replaceRange("x", Pos(0, 0));
is(m1.find());
cm.replaceRange("y", Pos(0, 2));
is(m1.find());
cm.replaceRange("z", Pos(0, 3), Pos(0, 4));
is(!m1.find());
var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false,
inclusiveLeft: true,
inclusiveRight: true});
cm.replaceRange("q", Pos(0, 1), Pos(0, 2));
is(m2.find());
cm.replaceRange("", Pos(0, 0), Pos(0, 3));
is(!m2.find());
var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false});
cm.replaceRange("a", Pos(0, 3));
is(m3.find());
cm.replaceRange("b", Pos(0, 1));
is(!m3.find());
}, {value: "abcde"});
testCM("markTextStacked", function(cm) {
var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});
var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});
cm.replaceRange("B", Pos(0, 1));
is(m1.find() && m2.find());
}, {value: "A"});
testCM("undoPreservesNewMarks", function(cm) {
cm.markText(Pos(0, 3), Pos(0, 4));
cm.markText(Pos(1, 1), Pos(1, 3));
cm.replaceRange("", Pos(0, 3), Pos(3, 1));
var mBefore = cm.markText(Pos(0, 0), Pos(0, 1));
var mAfter = cm.markText(Pos(0, 5), Pos(0, 6));
var mAround = cm.markText(Pos(0, 2), Pos(0, 4));
cm.undo();
eqPos(mBefore.find().from, Pos(0, 0));
eqPos(mBefore.find().to, Pos(0, 1));
eqPos(mAfter.find().from, Pos(3, 3));
eqPos(mAfter.find().to, Pos(3, 4));
eqPos(mAround.find().from, Pos(0, 2));
eqPos(mAround.find().to, Pos(3, 2));
var found = cm.findMarksAt(Pos(2, 2));
eq(found.length, 1);
eq(found[0], mAround);
}, {value: "aaaa\nbbbb\ncccc\ndddd"});
testCM("markClearBetween", function(cm) {
cm.setValue("aaa\nbbb\nccc\nddd\n");
cm.markText(Pos(0, 0), Pos(2));
cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2));
eq(cm.findMarksAt(Pos(1, 1)).length, 0);
});
testCM("deleteSpanCollapsedInclusiveLeft", function(cm) {
var from = Pos(1, 0), to = Pos(1, 1);
var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true});
// Delete collapsed span.
cm.replaceRange("", from, to);
}, {value: "abc\nX\ndef"});
testCM("markTextCSS", function(cm) {
function present() {
var spans = cm.display.lineDiv.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++)
if (spans[i].style.color == "cyan" && span[i].textContent == "cdefg") return true;
}
var m = cm.markText(Pos(0, 2), Pos(0, 6), {css: "color: cyan"});
m.clear();
is(!present());
}, {value: "abcdefgh"});
testCM("bookmark", function(cm) {
function p(v) { return v && Pos(v[0], v[1]); }
forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]},
{a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]},
{a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]},
{a: [1, 4], b: [1, 6], c: "", d: null},
{a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]},
{a: [1, 6], b: [1, 8], c: "", d: [1, 5]},
{a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]},
{bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) {
cm.setValue("1234567890\n1234567890\n1234567890");
var b = cm.setBookmark(p(test.bm) || Pos(1, 5));
cm.replaceRange(test.c, p(test.a), p(test.b));
eqPos(b.find(), p(test.d));
});
});
testCM("bookmarkInsertLeft", function(cm) {
var br = cm.setBookmark(Pos(0, 2), {insertLeft: false});
var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true});
cm.setCursor(Pos(0, 2));
cm.replaceSelection("hi");
eqPos(br.find(), Pos(0, 2));
eqPos(bl.find(), Pos(0, 4));
cm.replaceRange("", Pos(0, 4), Pos(0, 5));
cm.replaceRange("", Pos(0, 2), Pos(0, 4));
cm.replaceRange("", Pos(0, 1), Pos(0, 2));
// Verify that deleting next to bookmarks doesn't kill them
eqPos(br.find(), Pos(0, 1));
eqPos(bl.find(), Pos(0, 1));
}, {value: "abcdef"});
testCM("bookmarkCursor", function(cm) {
var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)),
pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)),
pos41 = cm.cursorCoords(Pos(4, 1));
cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true});
cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true});
cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")});
cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")});
var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)),
new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0));
near(new01.left, pos01.left, 1);
near(new01.top, pos01.top, 1);
is(new11.left > pos11.left, "at right, middle of line");
near(new11.top == pos11.top, 1);
near(new20.left, pos20.left, 1);
near(new20.top, pos20.top, 1);
is(new30.left > pos30.left, "at right, empty line");
near(new30.top, pos30, 1);
cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")});
is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug");
}, {value: "foo\nbar\n\n\nx\ny"});
testCM("multiBookmarkCursor", function(cm) {
if (phantom) return;
var ms = [], m;
function add(insertLeft) {
for (var i = 0; i < 3; ++i) {
var node = document.createElement("span");
node.innerHTML = "X";
ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft}));
}
}
var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left;
add(true);
near(base1, cm.cursorCoords(Pos(0, 1)).left, 1);
while (m = ms.pop()) m.clear();
add(false);
near(base4, cm.cursorCoords(Pos(0, 1)).left, 1);
}, {value: "abcdefg"});
testCM("getAllMarks", function(cm) {
addDoc(cm, 10, 10);
var m1 = cm.setBookmark(Pos(0, 2));
var m2 = cm.markText(Pos(0, 2), Pos(3, 2));
var m3 = cm.markText(Pos(1, 2), Pos(1, 8));
var m4 = cm.markText(Pos(8, 0), Pos(9, 0));
eq(cm.getAllMarks().length, 4);
m1.clear();
m3.clear();
eq(cm.getAllMarks().length, 2);
});
testCM("setValueClears", function(cm) {
cm.addLineClass(0, "wrap", "foo");
var mark = cm.markText(Pos(0, 0), Pos(1, 1), {inclusiveLeft: true, inclusiveRight: true});
cm.setValue("foo");
is(!cm.lineInfo(0).wrapClass);
is(!mark.find());
}, {value: "a\nb"});
testCM("bug577", function(cm) {
cm.setValue("a\nb");
cm.clearHistory();
cm.setValue("fooooo");
cm.undo();
});
testCM("scrollSnap", function(cm) {
cm.setSize(100, 100);
addDoc(cm, 200, 200);
cm.setCursor(Pos(100, 180));
var info = cm.getScrollInfo();
is(info.left > 0 && info.top > 0);
cm.setCursor(Pos(0, 0));
info = cm.getScrollInfo();
is(info.left == 0 && info.top == 0, "scrolled clean to top");
cm.setCursor(Pos(100, 180));
cm.setCursor(Pos(199, 0));
info = cm.getScrollInfo();
is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom");
});
testCM("scrollIntoView", function(cm) {
if (phantom) return;
var outer = cm.getWrapperElement().getBoundingClientRect();
function test(line, ch, msg) {
var pos = Pos(line, ch);
cm.scrollIntoView(pos);
var box = cm.charCoords(pos, "window");
is(box.left >= outer.left, msg + " (left)");
is(box.right <= outer.right, msg + " (right)");
is(box.top >= outer.top, msg + " (top)");
is(box.bottom <= outer.bottom, msg + " (bottom)");
}
addDoc(cm, 200, 200);
test(199, 199, "bottom right");
test(0, 0, "top left");
test(100, 100, "center");
test(199, 0, "bottom left");
test(0, 199, "top right");
test(100, 100, "center again");
});
testCM("scrollBackAndForth", function(cm) {
addDoc(cm, 1, 200);
cm.operation(function() {
cm.scrollIntoView(Pos(199, 0));
cm.scrollIntoView(Pos(4, 0));
});
is(cm.getScrollInfo().top > 0);
});
testCM("selectAllNoScroll", function(cm) {
addDoc(cm, 1, 200);
cm.execCommand("selectAll");
eq(cm.getScrollInfo().top, 0);
cm.setCursor(199);
cm.execCommand("selectAll");
is(cm.getScrollInfo().top > 0);
});
testCM("selectionPos", function(cm) {
if (phantom || cm.getOption("inputStyle") != "textarea") return;
cm.setSize(100, 100);
addDoc(cm, 200, 100);
cm.setSelection(Pos(1, 100), Pos(98, 100));
var lineWidth = cm.charCoords(Pos(0, 200), "local").left;
var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100;
cm.scrollTo(0, 0);
var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
var outer = cm.getWrapperElement().getBoundingClientRect();
var sawMiddle, sawTop, sawBottom;
for (var i = 0, e = selElt.length; i < e; ++i) {
var box = selElt[i].getBoundingClientRect();
var atLeft = box.left - outer.left < 30;
var width = box.right - box.left;
var atRight = box.right - outer.left > .8 * lineWidth;
if (atLeft && atRight) {
sawMiddle = true;
is(box.bottom - box.top > 90 * lineHeight, "middle high");
is(width > .9 * lineWidth, "middle wide");
} else {
is(width > .4 * lineWidth, "top/bot wide enough");
is(width < .6 * lineWidth, "top/bot slim enough");
if (atLeft) {
sawBottom = true;
is(box.top - outer.top > 96 * lineHeight, "bot below");
} else if (atRight) {
sawTop = true;
is(box.top - outer.top < 2.1 * lineHeight, "top above");
}
}
}
is(sawTop && sawBottom && sawMiddle, "all parts");
}, null);
testCM("restoreHistory", function(cm) {
cm.setValue("abc\ndef");
cm.replaceRange("hello", Pos(1, 0), Pos(1));
cm.replaceRange("goop", Pos(0, 0), Pos(0));
cm.undo();
var storedVal = cm.getValue(), storedHist = cm.getHistory();
if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist));
eq(storedVal, "abc\nhello");
cm.setValue("");
cm.clearHistory();
eq(cm.historySize().undo, 0);
cm.setValue(storedVal);
cm.setHistory(storedHist);
cm.redo();
eq(cm.getValue(), "goop\nhello");
cm.undo(); cm.undo();
eq(cm.getValue(), "abc\ndef");
});
testCM("doubleScrollbar", function(cm) {
var dummy = document.body.appendChild(document.createElement("p"));
dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px";
var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth;
document.body.removeChild(dummy);
if (scrollbarWidth < 2) return;
cm.setSize(null, 100);
addDoc(cm, 1, 300);
var wrap = cm.getWrapperElement();
is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5);
});
testCM("weirdLinebreaks", function(cm) {
cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop");
is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop");
is(cm.lineCount(), 6);
cm.setValue("\n\n");
is(cm.lineCount(), 3);
});
testCM("setSize", function(cm) {
cm.setSize(100, 100);
var wrap = cm.getWrapperElement();
is(wrap.offsetWidth, 100);
is(wrap.offsetHeight, 100);
cm.setSize("100%", "3em");
is(wrap.style.width, "100%");
is(wrap.style.height, "3em");
cm.setSize(null, 40);
is(wrap.style.width, "100%");
is(wrap.style.height, "40px");
});
function foldLines(cm, start, end, autoClear) {
return cm.markText(Pos(start, 0), Pos(end - 1), {
inclusiveLeft: true,
inclusiveRight: true,
collapsed: true,
clearOnEnter: autoClear
});
}
testCM("collapsedLines", function(cm) {
addDoc(cm, 4, 10);
var range = foldLines(cm, 4, 5), cleared = 0;
CodeMirror.on(range, "clear", function() {cleared++;});
cm.setCursor(Pos(3, 0));
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(5, 0));
cm.replaceRange("abcdefg", Pos(3, 0), Pos(3));
cm.setCursor(Pos(3, 6));
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(5, 4));
cm.replaceRange("ab", Pos(3, 0), Pos(3));
cm.setCursor(Pos(3, 2));
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(5, 2));
cm.operation(function() {range.clear(); range.clear();});
eq(cleared, 1);
});
testCM("collapsedRangeCoordsChar", function(cm) {
var pos_1_3 = cm.charCoords(Pos(1, 3));
pos_1_3.left += 2; pos_1_3.top += 2;
var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true};
var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts);
eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
m1.clear();
var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true});
var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true});
eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
m1.clear(); m2.clear();
var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts);
eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"});
testCM("collapsedRangeBetweenLinesSelected", function(cm) {
if (cm.getOption("inputStyle") != "textarea") return;
var widget = document.createElement("span");
widget.textContent = "\u2194";
cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget});
cm.setSelection(Pos(0, 3), Pos(1, 0));
var selElts = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
for (var i = 0, w = 0; i < selElts.length; i++)
w += selElts[i].offsetWidth;
is(w > 0);
}, {value: "one\ntwo"});
testCM("randomCollapsedRanges", function(cm) {
addDoc(cm, 20, 500);
cm.operation(function() {
for (var i = 0; i < 200; i++) {
var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20));
if (i % 4)
try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); }
catch(e) { if (!/overlapping/.test(String(e))) throw e; }
else
cm.markText(start, Pos(start.line, start.ch + 4), {"className": "foo"});
}
});
});
testCM("hiddenLinesAutoUnfold", function(cm) {
var range = foldLines(cm, 1, 3, true), cleared = 0;
CodeMirror.on(range, "clear", function() {cleared++;});
cm.setCursor(Pos(3, 0));
eq(cleared, 0);
cm.execCommand("goCharLeft");
eq(cleared, 1);
range = foldLines(cm, 1, 3, true);
CodeMirror.on(range, "clear", function() {cleared++;});
eqPos(cm.getCursor(), Pos(3, 0));
cm.setCursor(Pos(0, 3));
cm.execCommand("goCharRight");
eq(cleared, 2);
}, {value: "abc\ndef\nghi\njkl"});
testCM("hiddenLinesSelectAll", function(cm) { // Issue #484
addDoc(cm, 4, 20);
foldLines(cm, 0, 10);
foldLines(cm, 11, 20);
CodeMirror.commands.selectAll(cm);
eqPos(cm.getCursor(true), Pos(10, 0));
eqPos(cm.getCursor(false), Pos(10, 4));
});
testCM("everythingFolded", function(cm) {
addDoc(cm, 2, 2);
function enterPress() {
cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}});
}
var fold = foldLines(cm, 0, 2);
enterPress();
eq(cm.getValue(), "xx\nxx");
fold.clear();
fold = foldLines(cm, 0, 2, true);
eq(fold.find(), null);
enterPress();
eq(cm.getValue(), "\nxx\nxx");
});
testCM("structuredFold", function(cm) {
if (phantom) return;
addDoc(cm, 4, 8);
var range = cm.markText(Pos(1, 2), Pos(6, 2), {
replacedWith: document.createTextNode("Q")
});
cm.setCursor(0, 3);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(6, 2));
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(1, 2));
CodeMirror.commands.delCharAfter(cm);
eq(cm.getValue(), "xxxx\nxxxx\nxxxx");
addDoc(cm, 4, 8);
range = cm.markText(Pos(1, 2), Pos(6, 2), {
replacedWith: document.createTextNode("M"),
clearOnEnter: true
});
var cleared = 0;
CodeMirror.on(range, "clear", function(){++cleared;});
cm.setCursor(0, 3);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(6, 2));
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(6, 1));
eq(cleared, 1);
range.clear();
eq(cleared, 1);
range = cm.markText(Pos(1, 2), Pos(6, 2), {
replacedWith: document.createTextNode("Q"),
clearOnEnter: true
});
range.clear();
cm.setCursor(1, 2);
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(1, 3));
range = cm.markText(Pos(2, 0), Pos(4, 4), {
replacedWith: document.createTextNode("M")
});
cm.setCursor(1, 0);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(2, 0));
}, null);
testCM("nestedFold", function(cm) {
addDoc(cm, 10, 3);
function fold(ll, cl, lr, cr) {
return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true});
}
var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6);
cm.setCursor(0, 1);
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(2, 3));
inner0.clear();
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(0, 1));
outer.clear();
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(0, 2));
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(1, 8));
inner2.clear();
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(1, 7));
cm.setCursor(0, 5);
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(0, 6));
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(1, 3));
});
testCM("badNestedFold", function(cm) {
addDoc(cm, 4, 4);
cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true});
var caught;
try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});}
catch(e) {caught = e;}
is(caught instanceof Error, "no error");
is(/overlap/i.test(caught.message), "wrong error");
});
testCM("nestedFoldOnSide", function(cm) {
var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true});
var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true});
cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear();
try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); }
catch(e) { var caught = e; }
is(caught && /overlap/i.test(caught.message));
var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true});
var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true});
m1.clear(); m4.clear();
m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true});
cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear();
try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); }
catch(e) { var caught = e; }
is(caught && /overlap/i.test(caught.message));
}, {value: "ab\ncd\ef"});
testCM("editInFold", function(cm) {
addDoc(cm, 4, 6);
var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true});
cm.replaceRange("", Pos(0, 0), Pos(1, 3));
cm.replaceRange("", Pos(2, 1), Pos(3, 3));
cm.replaceRange("a\nb\nc\nd", Pos(0, 1), Pos(1, 0));
cm.cursorCoords(Pos(0, 0));
});
testCM("wrappingInlineWidget", function(cm) {
cm.setSize("11em");
var w = document.createElement("span");
w.style.color = "red";
w.innerHTML = "one two three four";
cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w});
var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10));
is(cur0.top < cur1.top);
is(cur0.bottom < cur1.bottom);
var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9));
eq(curL.top, cur0.top);
eq(curL.bottom, cur0.bottom);
eq(curR.top, cur1.top);
eq(curR.bottom, cur1.bottom);
cm.replaceRange("", Pos(0, 9), Pos(0));
curR = cm.cursorCoords(Pos(0, 9));
if (phantom) return;
eq(curR.top, cur1.top);
eq(curR.bottom, cur1.bottom);
}, {value: "1 2 3 xxx 4", lineWrapping: true});
testCM("changedInlineWidget", function(cm) {
cm.setSize("10em");
var w = document.createElement("span");
w.innerHTML = "x";
var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w});
w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
m.changed();
var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
is(hScroll.scrollWidth > hScroll.clientWidth);
}, {value: "hello there"});
testCM("changedBookmark", function(cm) {
cm.setSize("10em");
var w = document.createElement("span");
w.innerHTML = "x";
var m = cm.setBookmark(Pos(0, 4), {widget: w});
w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
m.changed();
var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
is(hScroll.scrollWidth > hScroll.clientWidth);
}, {value: "abcdefg"});
testCM("inlineWidget", function(cm) {
var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")});
cm.setCursor(0, 2);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(1, 4));
cm.setCursor(0, 2);
cm.replaceSelection("hi");
eqPos(w.find(), Pos(0, 2));
cm.setCursor(0, 1);
cm.replaceSelection("ay");
eqPos(w.find(), Pos(0, 4));
eq(cm.getLine(0), "uayuhiuu");
}, {value: "uuuu\nuuuuuu"});
testCM("wrappingAndResizing", function(cm) {
cm.setSize(null, "auto");
cm.setOption("lineWrapping", true);
var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight;
var doc = "xxx xxx xxx xxx xxx";
cm.setValue(doc);
for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) {
cm.setSize(w);
if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) {
if (step == 10) { w -= 10; step = 1; }
else break;
}
}
// Ensure that putting the cursor at the end of the maximally long
// line doesn't cause wrapping to happen.
cm.setCursor(Pos(0, doc.length));
eq(wrap.offsetHeight, h0);
cm.replaceSelection("x");
is(wrap.offsetHeight > h0, "wrapping happens");
// Now add a max-height and, in a document consisting of
// almost-wrapped lines, go over it so that a scrollbar appears.
cm.setValue(doc + "\n" + doc + "\n");
cm.getScrollerElement().style.maxHeight = "100px";
cm.replaceRange("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n!\n", Pos(2, 0));
forEach([Pos(0, doc.length), Pos(0, doc.length - 1),
Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)],
function(pos) {
var coords = cm.charCoords(pos);
eqPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5}));
});
}, null, ie_lt8);
testCM("measureEndOfLine", function(cm) {
cm.setSize(null, "auto");
var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild;
var lh = inner.offsetHeight;
for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) {
cm.setSize(w);
if (inner.offsetHeight < 2.5 * lh) {
if (step == 10) { w -= 10; step = 1; }
else break;
}
}
cm.setValue(cm.getValue() + "\n\n");
var endPos = cm.charCoords(Pos(0, 18), "local");
is(endPos.top > lh * .8, "not at top");
is(endPos.left > w - 20, "not at right");
endPos = cm.charCoords(Pos(0, 18));
eqPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18));
}, {mode: "text/html", value: "<!-- foo barrr -->", lineWrapping: true}, ie_lt8 || opera_lt10);
testCM("scrollVerticallyAndHorizontally", function(cm) {
if (cm.getOption("inputStyle") != "textarea") return;
cm.setSize(100, 100);
addDoc(cm, 40, 40);
cm.setCursor(39);
var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0];
is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one");
var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect();
var editorBox = wrap.getBoundingClientRect();
is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight,
"bottom line visible");
}, {lineNumbers: true});
testCM("moveVstuck", function(cm) {
var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight;
var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n";
cm.setValue(val);
for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) {
cm.setSize(w);
if (lines.offsetHeight <= 3.5 * h0) break;
}
cm.setCursor(Pos(0, val.length - 1));
cm.moveV(-1, "line");
eqPos(cm.getCursor(), Pos(0, 26));
}, {lineWrapping: true}, ie_lt8 || opera_lt10);
testCM("collapseOnMove", function(cm) {
cm.setSelection(Pos(0, 1), Pos(2, 4));
cm.execCommand("goLineUp");
is(!cm.somethingSelected());
eqPos(cm.getCursor(), Pos(0, 1));
cm.setSelection(Pos(0, 1), Pos(2, 4));
cm.execCommand("goPageDown");
is(!cm.somethingSelected());
eqPos(cm.getCursor(), Pos(2, 4));
cm.execCommand("goLineUp");
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(0, 4));
cm.setSelection(Pos(0, 1), Pos(2, 4));
cm.execCommand("goCharLeft");
is(!cm.somethingSelected());
eqPos(cm.getCursor(), Pos(0, 1));
}, {value: "aaaaa\nb\nccccc"});
testCM("clickTab", function(cm) {
var p0 = cm.charCoords(Pos(0, 0));
eqPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0));
eqPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1));
}, {value: "\t\n\n", lineWrapping: true, tabSize: 8});
testCM("verticalScroll", function(cm) {
cm.setSize(100, 200);
cm.setValue("foo\nbar\nbaz\n");
var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth;
cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0));
is(sc.scrollWidth > baseWidth, "scrollbar present");
cm.replaceRange("foo", Pos(0, 0), Pos(0));
if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone");
cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0));
cm.replaceRange("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh", Pos(1, 0), Pos(1));
is(sc.scrollWidth > baseWidth, "present again");
var curWidth = sc.scrollWidth;
cm.replaceRange("foo", Pos(0, 0), Pos(0));
is(sc.scrollWidth < curWidth, "scrollbar smaller");
is(sc.scrollWidth > baseWidth, "but still present");
});
testCM("extraKeys", function(cm) {
var outcome;
function fakeKey(expected, code, props) {
if (typeof code == "string") code = code.charCodeAt(0);
var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}};
if (props) for (var n in props) e[n] = props[n];
outcome = null;
cm.triggerOnKeyDown(e);
eq(outcome, expected);
}
CodeMirror.commands.testCommand = function() {outcome = "tc";};
CodeMirror.commands.goTestCommand = function() {outcome = "gtc";};
cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";},
"X": function() {outcome = "x";},
"Ctrl-Alt-U": function() {outcome = "cau";},
"End": "testCommand",
"Home": "goTestCommand",
"Tab": false});
fakeKey(null, "U");
fakeKey("cau", "U", {ctrlKey: true, altKey: true});
fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true});
fakeKey("x", "X");
fakeKey("sx", "X", {shiftKey: true});
fakeKey("tc", 35);
fakeKey(null, 35, {shiftKey: true});
fakeKey("gtc", 36);
fakeKey("gtc", 36, {shiftKey: true});
fakeKey(null, 9);
}, null, window.opera && mac);
testCM("wordMovementCommands", function(cm) {
cm.execCommand("goWordLeft");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(0, 7));
cm.execCommand("goWordLeft");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(0, 12));
cm.execCommand("goWordLeft");
eqPos(cm.getCursor(), Pos(0, 9));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(0, 24));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(1, 9));
cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(1, 13));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(2, 0));
}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"});
testCM("groupMovementCommands", function(cm) {
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 4));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 7));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 10));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 7));
cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 15));
cm.setCursor(Pos(0, 17));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 16));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 14));
cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 20));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(1, 2));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(1, 5));
cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 20));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 16));
}, {value: "booo ba---quux. ffff\n abc d"});
testCM("groupsAndWhitespace", function(cm) {
var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11),
Pos(1, 0), Pos(1, 2), Pos(1, 5)];
for (var i = 1; i < positions.length; i++) {
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), positions[i]);
}
for (var i = positions.length - 2; i >= 0; i--) {
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), i == 2 ? Pos(0, 6) : positions[i]);
}
}, {value: " foo +++ \n bar"});
testCM("charMovementCommands", function(cm) {
cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goCharRight"); cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 2));
cm.setCursor(Pos(1, 0));
cm.execCommand("goColumnLeft");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goColumnRight");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goLineEnd");
eqPos(cm.getCursor(), Pos(1, 5));
cm.execCommand("goLineStartSmart");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineStartSmart");
eqPos(cm.getCursor(), Pos(1, 0));
cm.setCursor(Pos(2, 0));
cm.execCommand("goCharRight"); cm.execCommand("goColumnRight");
eqPos(cm.getCursor(), Pos(2, 0));
}, {value: "line1\n ine2\n"});
testCM("verticalMovementCommands", function(cm) {
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goLineDown");
if (!phantom) // This fails in PhantomJS, though not in a real Webkit
eqPos(cm.getCursor(), Pos(1, 0));
cm.setCursor(Pos(1, 12));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(2, 5));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(3, 0));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(2, 5));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 12));
cm.execCommand("goPageDown");
eqPos(cm.getCursor(), Pos(5, 0));
cm.execCommand("goPageDown"); cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(5, 0));
cm.execCommand("goPageUp");
eqPos(cm.getCursor(), Pos(0, 0));
}, {value: "line1\nlong long line2\nline3\n\nline5\n"});
testCM("verticalMovementCommandsWrapping", function(cm) {
cm.setSize(120);
cm.setCursor(Pos(0, 5));
cm.execCommand("goLineDown");
eq(cm.getCursor().line, 0);
is(cm.getCursor().ch > 5, "moved beyond wrap");
for (var i = 0; ; ++i) {
is(i < 20, "no endless loop");
cm.execCommand("goLineDown");
var cur = cm.getCursor();
if (cur.line == 1) eq(cur.ch, 5);
if (cur.line == 2) { eq(cur.ch, 1); break; }
}
}, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk",
lineWrapping: true});
testCM("rtlMovement", function(cm) {
if (cm.getOption("inputStyle") != "textarea") return;
forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج",
"خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر", "خ ة ق",
"<img src=\"/בדיקה3.jpg\">"], function(line) {
var inv = line.charAt(0) == "خ";
cm.setValue(line + "\n"); cm.execCommand(inv ? "goLineEnd" : "goLineStart");
var cursors = byClassName(cm.getWrapperElement(), "CodeMirror-cursors")[0];
var cursor = cursors.firstChild;
var prevX = cursor.offsetLeft, prevY = cursor.offsetTop;
for (var i = 0; i <= line.length; ++i) {
cm.execCommand("goCharRight");
cursor = cursors.firstChild;
if (i == line.length) is(cursor.offsetTop > prevY, "next line");
else is(cursor.offsetLeft > prevX, "moved right");
prevX = cursor.offsetLeft; prevY = cursor.offsetTop;
}
cm.setCursor(0, 0); cm.execCommand(inv ? "goLineStart" : "goLineEnd");
prevX = cursors.firstChild.offsetLeft;
for (var i = 0; i < line.length; ++i) {
cm.execCommand("goCharLeft");
cursor = cursors.firstChild;
is(cursor.offsetLeft < prevX, "moved left");
prevX = cursor.offsetLeft;
}
});
}, null, ie_lt9);
// Verify that updating a line clears its bidi ordering
testCM("bidiUpdate", function(cm) {
cm.setCursor(Pos(0, 2));
cm.replaceSelection("خحج", "start");
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 4));
}, {value: "abcd\n"});
testCM("movebyTextUnit", function(cm) {
cm.setValue("בְּרֵאשִ\nééé́\n");
cm.execCommand("goLineEnd");
for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goCharRight");
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 4));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 7));
});
testCM("lineChangeEvents", function(cm) {
addDoc(cm, 3, 5);
var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"];
for (var i = 0; i < 5; ++i) {
CodeMirror.on(cm.getLineHandle(i), "delete", function(i) {
return function() {log.push("del " + i);};
}(i));
CodeMirror.on(cm.getLineHandle(i), "change", function(i) {
return function() {log.push("ch " + i);};
}(i));
}
cm.replaceRange("x", Pos(0, 1));
cm.replaceRange("xy", Pos(1, 1), Pos(2));
cm.replaceRange("foo\nbar", Pos(0, 1));
cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount()));
eq(log.length, want.length, "same length");
for (var i = 0; i < log.length; ++i)
eq(log[i], want[i]);
});
testCM("scrollEntirelyToRight", function(cm) {
if (phantom || cm.getOption("inputStyle") != "textarea") return;
addDoc(cm, 500, 2);
cm.setCursor(Pos(0, 500));
var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0];
is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left);
});
testCM("lineWidgets", function(cm) {
addDoc(cm, 500, 3);
var last = cm.charCoords(Pos(2, 0));
var node = document.createElement("div");
node.innerHTML = "hi";
var widget = cm.addLineWidget(1, node);
is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space");
cm.setCursor(Pos(1, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(2, 1));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 1));
});
testCM("lineWidgetFocus", function(cm) {
var place = document.getElementById("testground");
place.className = "offscreen";
try {
addDoc(cm, 500, 10);
var node = document.createElement("input");
var widget = cm.addLineWidget(1, node);
node.focus();
eq(document.activeElement, node);
cm.replaceRange("new stuff", Pos(1, 0));
eq(document.activeElement, node);
} finally {
place.className = "";
}
});
testCM("lineWidgetCautiousRedraw", function(cm) {
var node = document.createElement("div");
node.innerHTML = "hahah";
var w = cm.addLineWidget(0, node);
var redrawn = false;
w.on("redraw", function() { redrawn = true; });
cm.replaceSelection("0");
is(!redrawn);
}, {value: "123\n456"});
var knownScrollbarWidth;
function scrollbarWidth(measure) {
if (knownScrollbarWidth != null) return knownScrollbarWidth;
var div = document.createElement('div');
div.style.cssText = "width: 50px; height: 50px; overflow-x: scroll";
document.body.appendChild(div);
knownScrollbarWidth = div.offsetHeight - div.clientHeight;
document.body.removeChild(div);
return knownScrollbarWidth || 0;
}
testCM("lineWidgetChanged", function(cm) {
addDoc(cm, 2, 300);
var halfScrollbarWidth = scrollbarWidth(cm.display.measure)/2;
cm.setOption('lineNumbers', true);
cm.setSize(600, cm.defaultTextHeight() * 50);
cm.scrollTo(null, cm.heightAtLine(125, "local"));
var expectedWidgetHeight = 60;
var expectedLinesInWidget = 3;
function w() {
var node = document.createElement("div");
// we use these children with just under half width of the line to check measurements are made with correct width
// when placed in the measure div.
// If the widget is measured at a width much narrower than it is displayed at, the underHalf children will span two lines and break the test.
// If the widget is measured at a width much wider than it is displayed at, the overHalf children will combine and break the test.
// Note that this test only checks widgets where coverGutter is true, because these require extra styling to get the width right.
// It may also be worthwhile to check this for non-coverGutter widgets.
// Visually:
// Good:
// | ------------- display width ------------- |
// | ------- widget-width when measured ------ |
// | | -- under-half -- | | -- under-half -- | |
// | | --- over-half --- | |
// | | --- over-half --- | |
// Height: measured as 3 lines, same as it will be when actually displayed
// Bad (too narrow):
// | ------------- display width ------------- |
// | ------ widget-width when measured ----- | < -- uh oh
// | | -- under-half -- | |
// | | -- under-half -- | | < -- when measured, shoved to next line
// | | --- over-half --- | |
// | | --- over-half --- | |
// Height: measured as 4 lines, more than expected . Will be displayed as 3 lines!
// Bad (too wide):
// | ------------- display width ------------- |
// | -------- widget-width when measured ------- | < -- uh oh
// | | -- under-half -- | | -- under-half -- | |
// | | --- over-half --- | | --- over-half --- | | < -- when measured, combined on one line
// Height: measured as 2 lines, less than expected. Will be displayed as 3 lines!
var barelyUnderHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(285 - halfScrollbarWidth)+'px;"></div>';
var barelyOverHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(305 - halfScrollbarWidth)+'px;"></div>';
node.innerHTML = new Array(3).join(barelyUnderHalfWidthHtml) + new Array(3).join(barelyOverHalfWidthHtml);
node.style.cssText = "background: yellow;font-size:0;line-height: " + (expectedWidgetHeight/expectedLinesInWidget) + "px;";
return node;
}
var info0 = cm.getScrollInfo();
var w0 = cm.addLineWidget(0, w(), { coverGutter: true });
var w150 = cm.addLineWidget(150, w(), { coverGutter: true });
var w300 = cm.addLineWidget(300, w(), { coverGutter: true });
var info1 = cm.getScrollInfo();
eq(info0.height + (3 * expectedWidgetHeight), info1.height);
eq(info0.top + expectedWidgetHeight, info1.top);
expectedWidgetHeight = 12;
w0.node.style.lineHeight = w150.node.style.lineHeight = w300.node.style.lineHeight = (expectedWidgetHeight/expectedLinesInWidget) + "px";
w0.changed(); w150.changed(); w300.changed();
var info2 = cm.getScrollInfo();
eq(info0.height + (3 * expectedWidgetHeight), info2.height);
eq(info0.top + expectedWidgetHeight, info2.top);
});
testCM("getLineNumber", function(cm) {
addDoc(cm, 2, 20);
var h1 = cm.getLineHandle(1);
eq(cm.getLineNumber(h1), 1);
cm.replaceRange("hi\nbye\n", Pos(0, 0));
eq(cm.getLineNumber(h1), 3);
cm.setValue("");
eq(cm.getLineNumber(h1), null);
});
testCM("jumpTheGap", function(cm) {
if (phantom) return;
var longLine = "abcdef ghiklmnop qrstuvw xyz ";
longLine += longLine; longLine += longLine; longLine += longLine;
cm.replaceRange(longLine, Pos(2, 0), Pos(2));
cm.setSize("200px", null);
cm.getWrapperElement().style.lineHeight = 2;
cm.refresh();
cm.setCursor(Pos(0, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(2, 1));
cm.execCommand("goLineDown");
eq(cm.getCursor().line, 2);
is(cm.getCursor().ch > 1);
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(2, 1));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 1));
var node = document.createElement("div");
node.innerHTML = "hi"; node.style.height = "30px";
cm.addLineWidget(0, node);
cm.addLineWidget(1, node.cloneNode(true), {above: true});
cm.setCursor(Pos(0, 2));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(1, 2));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(0, 2));
}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"});
testCM("addLineClass", function(cm) {
function cls(line, text, bg, wrap, gutter) {
var i = cm.lineInfo(line);
eq(i.textClass, text);
eq(i.bgClass, bg);
eq(i.wrapClass, wrap);
if (typeof i.handle.gutterClass !== 'undefined') {
eq(i.handle.gutterClass, gutter);
}
}
cm.addLineClass(0, "text", "foo");
cm.addLineClass(0, "text", "bar");
cm.addLineClass(1, "background", "baz");
cm.addLineClass(1, "wrap", "foo");
cm.addLineClass(1, "gutter", "gutter-class");
cls(0, "foo bar", null, null, null);
cls(1, null, "baz", "foo", "gutter-class");
var lines = cm.display.lineDiv;
eq(byClassName(lines, "foo").length, 2);
eq(byClassName(lines, "bar").length, 1);
eq(byClassName(lines, "baz").length, 1);
eq(byClassName(lines, "gutter-class").length, 1);
cm.removeLineClass(0, "text", "foo");
cls(0, "bar", null, null, null);
cm.removeLineClass(0, "text", "foo");
cls(0, "bar", null, null, null);
cm.removeLineClass(0, "text", "bar");
cls(0, null, null, null);
cm.addLineClass(1, "wrap", "quux");
cls(1, null, "baz", "foo quux", "gutter-class");
cm.removeLineClass(1, "wrap");
cls(1, null, "baz", null, "gutter-class");
cm.removeLineClass(1, "gutter", "gutter-class");
eq(byClassName(lines, "gutter-class").length, 0);
cls(1, null, "baz", null, null);
cm.addLineClass(1, "gutter", "gutter-class");
cls(1, null, "baz", null, "gutter-class");
cm.removeLineClass(1, "gutter", "gutter-class");
cls(1, null, "baz", null, null);
}, {value: "hohoho\n", lineNumbers: true});
testCM("atomicMarker", function(cm) {
addDoc(cm, 10, 10);
function atom(ll, cl, lr, cr, li, ri) {
return cm.markText(Pos(ll, cl), Pos(lr, cr),
{atomic: true, inclusiveLeft: li, inclusiveRight: ri});
}
var m = atom(0, 1, 0, 5);
cm.setCursor(Pos(0, 1));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 1));
m.clear();
m = atom(0, 0, 0, 5, true);
eqPos(cm.getCursor(), Pos(0, 5), "pushed out");
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 5));
m.clear();
m = atom(8, 4, 9, 10, false, true);
cm.setCursor(Pos(9, 8));
eqPos(cm.getCursor(), Pos(8, 4), "set");
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(8, 4), "char right");
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(8, 4), "line down");
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(8, 3));
m.clear();
m = atom(1, 1, 3, 8);
cm.setCursor(Pos(0, 0));
cm.setCursor(Pos(2, 0));
eqPos(cm.getCursor(), Pos(3, 8));
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(3, 8));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(3, 8));
cm.execCommand("delCharBefore");
eq(cm.getValue().length, 80, "del chunk");
m = atom(3, 0, 5, 5);
cm.setCursor(Pos(3, 0));
cm.execCommand("delWordAfter");
eq(cm.getValue().length, 53, "del chunk");
});
testCM("selectionBias", function(cm) {
cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true});
cm.setCursor(Pos(0, 2));
eqPos(cm.getCursor(), Pos(0, 3));
cm.setCursor(Pos(0, 2));
eqPos(cm.getCursor(), Pos(0, 1));
cm.setCursor(Pos(0, 2), null, {bias: -1});
eqPos(cm.getCursor(), Pos(0, 1));
cm.setCursor(Pos(0, 4));
cm.setCursor(Pos(0, 2), null, {bias: 1});
eqPos(cm.getCursor(), Pos(0, 3));
}, {value: "12345"});
testCM("selectionHomeEnd", function(cm) {
cm.markText(Pos(1, 0), Pos(1, 1), {atomic: true, inclusiveLeft: true});
cm.markText(Pos(1, 3), Pos(1, 4), {atomic: true, inclusiveRight: true});
cm.setCursor(Pos(1, 2));
cm.execCommand("goLineStart");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineEnd");
eqPos(cm.getCursor(), Pos(1, 3));
}, {value: "ab\ncdef\ngh"});
testCM("readOnlyMarker", function(cm) {
function mark(ll, cl, lr, cr, at) {
return cm.markText(Pos(ll, cl), Pos(lr, cr),
{readOnly: true, atomic: at});
}
var m = mark(0, 1, 0, 4);
cm.setCursor(Pos(0, 2));
cm.replaceSelection("hi", "end");
eqPos(cm.getCursor(), Pos(0, 2));
eq(cm.getLine(0), "abcde");
cm.execCommand("selectAll");
cm.replaceSelection("oops", "around");
eq(cm.getValue(), "oopsbcd");
cm.undo();
eqPos(m.find().from, Pos(0, 1));
eqPos(m.find().to, Pos(0, 4));
m.clear();
cm.setCursor(Pos(0, 2));
cm.replaceSelection("hi", "around");
eq(cm.getLine(0), "abhicde");
eqPos(cm.getCursor(), Pos(0, 4));
m = mark(0, 2, 2, 2, true);
cm.setSelection(Pos(1, 1), Pos(2, 4));
cm.replaceSelection("t", "end");
eqPos(cm.getCursor(), Pos(2, 3));
eq(cm.getLine(2), "klto");
cm.execCommand("goCharLeft");
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 2));
cm.setSelection(Pos(0, 1), Pos(0, 3));
cm.replaceSelection("xx", "around");
eqPos(cm.getCursor(), Pos(0, 3));
eq(cm.getLine(0), "axxhicde");
}, {value: "abcde\nfghij\nklmno\n"});
testCM("dirtyBit", function(cm) {
eq(cm.isClean(), true);
cm.replaceSelection("boo", null, "test");
eq(cm.isClean(), false);
cm.undo();
eq(cm.isClean(), true);
cm.replaceSelection("boo", null, "test");
cm.replaceSelection("baz", null, "test");
cm.undo();
eq(cm.isClean(), false);
cm.markClean();
eq(cm.isClean(), true);
cm.undo();
eq(cm.isClean(), false);
cm.redo();
eq(cm.isClean(), true);
});
testCM("changeGeneration", function(cm) {
cm.replaceSelection("x");
var softGen = cm.changeGeneration();
cm.replaceSelection("x");
cm.undo();
eq(cm.getValue(), "");
is(!cm.isClean(softGen));
cm.replaceSelection("x");
var hardGen = cm.changeGeneration(true);
cm.replaceSelection("x");
cm.undo();
eq(cm.getValue(), "x");
is(cm.isClean(hardGen));
});
testCM("addKeyMap", function(cm) {
function sendKey(code) {
cm.triggerOnKeyDown({type: "keydown", keyCode: code,
preventDefault: function(){}, stopPropagation: function(){}});
}
sendKey(39);
eqPos(cm.getCursor(), Pos(0, 1));
var test = 0;
var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }}
cm.addKeyMap(map1);
sendKey(39);
eqPos(cm.getCursor(), Pos(0, 1));
eq(test, 1);
cm.addKeyMap(map2, true);
sendKey(39);
eq(test, 2);
cm.removeKeyMap(map1);
sendKey(39);
eq(test, 12);
cm.removeKeyMap(map2);
sendKey(39);
eq(test, 12);
eqPos(cm.getCursor(), Pos(0, 2));
cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"});
sendKey(39);
eq(test, 55);
cm.removeKeyMap("mymap");
sendKey(39);
eqPos(cm.getCursor(), Pos(0, 3));
}, {value: "abc"});
testCM("findPosH", function(cm) {
forEach([{from: Pos(0, 0), to: Pos(0, 1), by: 1},
{from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true},
{from: Pos(0, 0), to: Pos(0, 4), by: 1, unit: "word"},
{from: Pos(0, 0), to: Pos(0, 8), by: 2, unit: "word"},
{from: Pos(0, 0), to: Pos(2, 0), by: 20, unit: "word", hitSide: true},
{from: Pos(0, 7), to: Pos(0, 5), by: -1, unit: "word"},
{from: Pos(0, 4), to: Pos(0, 8), by: 1, unit: "word"},
{from: Pos(1, 0), to: Pos(1, 18), by: 3, unit: "word"},
{from: Pos(1, 22), to: Pos(1, 5), by: -3, unit: "word"},
{from: Pos(1, 15), to: Pos(1, 10), by: -5},
{from: Pos(1, 15), to: Pos(1, 10), by: -5, unit: "column"},
{from: Pos(1, 15), to: Pos(1, 0), by: -50, unit: "column", hitSide: true},
{from: Pos(1, 15), to: Pos(1, 24), by: 50, unit: "column", hitSide: true},
{from: Pos(1, 15), to: Pos(2, 0), by: 50, hitSide: true}], function(t) {
var r = cm.findPosH(t.from, t.by, t.unit || "char");
eqPos(r, t.to);
eq(!!r.hitSide, !!t.hitSide);
});
}, {value: "line one\nline two.something.other\n"});
testCM("beforeChange", function(cm) {
cm.on("beforeChange", function(cm, change) {
var text = [];
for (var i = 0; i < change.text.length; ++i)
text.push(change.text[i].replace(/\s/g, "_"));
change.update(null, null, text);
});
cm.setValue("hello, i am a\nnew document\n");
eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) {
if (change.from.line == 0) change.cancel();
});
cm.setValue("oops"); // Canceled
eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0));
eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey");
}, {value: "abcdefghijk"});
testCM("beforeChangeUndo", function(cm) {
cm.replaceRange("hi", Pos(0, 0), Pos(0));
cm.replaceRange("bye", Pos(0, 0), Pos(0));
eq(cm.historySize().undo, 2);
cm.on("beforeChange", function(cm, change) {
is(!change.update);
change.cancel();
});
cm.undo();
eq(cm.historySize().undo, 0);
eq(cm.getValue(), "bye\ntwo");
}, {value: "one\ntwo"});
testCM("beforeSelectionChange", function(cm) {
function notAtEnd(cm, pos) {
var len = cm.getLine(pos.line).length;
if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1);
return pos;
}
cm.on("beforeSelectionChange", function(cm, obj) {
obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor),
head: notAtEnd(cm, obj.ranges[0].head)}]);
});
addDoc(cm, 10, 10);
cm.execCommand("goLineEnd");
eqPos(cm.getCursor(), Pos(0, 9));
cm.execCommand("selectAll");
eqPos(cm.getCursor("start"), Pos(0, 0));
eqPos(cm.getCursor("end"), Pos(9, 9));
});
testCM("change_removedText", function(cm) {
cm.setValue("abc\ndef");
var removedText = [];
cm.on("change", function(cm, change) {
removedText.push(change.removed);
});
cm.operation(function() {
cm.replaceRange("xyz", Pos(0, 0), Pos(1,1));
cm.replaceRange("123", Pos(0,0));
});
eq(removedText.length, 2);
eq(removedText[0].join("\n"), "abc\nd");
eq(removedText[1].join("\n"), "");
var removedText = [];
cm.undo();
eq(removedText.length, 2);
eq(removedText[0].join("\n"), "123");
eq(removedText[1].join("\n"), "xyz");
var removedText = [];
cm.redo();
eq(removedText.length, 2);
eq(removedText[0].join("\n"), "abc\nd");
eq(removedText[1].join("\n"), "");
});
testCM("lineStyleFromMode", function(cm) {
CodeMirror.defineMode("test_mode", function() {
return {token: function(stream) {
if (stream.match(/^\[[^\]]*\]/)) return " line-brackets ";
if (stream.match(/^\([^\)]*\)/)) return " line-background-parens ";
if (stream.match(/^<[^>]*>/)) return " span line-line line-background-bg ";
stream.match(/^\s+|^\S+/);
}};
});
cm.setOption("mode", "test_mode");
var bracketElts = byClassName(cm.getWrapperElement(), "brackets");
eq(bracketElts.length, 1, "brackets count");
eq(bracketElts[0].nodeName, "PRE");
is(!/brackets.*brackets/.test(bracketElts[0].className));
var parenElts = byClassName(cm.getWrapperElement(), "parens");
eq(parenElts.length, 1, "parens count");
eq(parenElts[0].nodeName, "DIV");
is(!/parens.*parens/.test(parenElts[0].className));
eq(parenElts[0].parentElement.nodeName, "DIV");
eq(byClassName(cm.getWrapperElement(), "bg").length, 1);
eq(byClassName(cm.getWrapperElement(), "line").length, 1);
var spanElts = byClassName(cm.getWrapperElement(), "cm-span");
eq(spanElts.length, 2);
is(/^\s*cm-span\s*$/.test(spanElts[0].className));
}, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: <tag> <tag>"});
testCM("lineStyleFromBlankLine", function(cm) {
CodeMirror.defineMode("lineStyleFromBlankLine_mode", function() {
return {token: function(stream) { stream.skipToEnd(); return "comment"; },
blankLine: function() { return "line-blank"; }};
});
cm.setOption("mode", "lineStyleFromBlankLine_mode");
var blankElts = byClassName(cm.getWrapperElement(), "blank");
eq(blankElts.length, 1);
eq(blankElts[0].nodeName, "PRE");
cm.replaceRange("x", Pos(1, 0));
blankElts = byClassName(cm.getWrapperElement(), "blank");
eq(blankElts.length, 0);
}, {value: "foo\n\nbar"});
CodeMirror.registerHelper("xxx", "a", "A");
CodeMirror.registerHelper("xxx", "b", "B");
CodeMirror.defineMode("yyy", function() {
return {
token: function(stream) { stream.skipToEnd(); },
xxx: ["a", "b", "q"]
};
});
CodeMirror.registerGlobalHelper("xxx", "c", function(m) { return m.enableC; }, "C");
testCM("helpers", function(cm) {
cm.setOption("mode", "yyy");
eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "A/B");
cm.setOption("mode", {name: "yyy", modeProps: {xxx: "b", enableC: true}});
eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "B/C");
cm.setOption("mode", "javascript");
eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "");
});
testCM("selectionHistory", function(cm) {
for (var i = 0; i < 3; i++) {
cm.setExtending(true);
cm.execCommand("goCharRight");
cm.setExtending(false);
cm.execCommand("goCharRight");
cm.execCommand("goCharRight");
}
cm.execCommand("undoSelection");
eq(cm.getSelection(), "c");
cm.execCommand("undoSelection");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(), Pos(0, 4));
cm.execCommand("undoSelection");
eq(cm.getSelection(), "b");
cm.execCommand("redoSelection");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(), Pos(0, 4));
cm.execCommand("redoSelection");
eq(cm.getSelection(), "c");
cm.execCommand("redoSelection");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(), Pos(0, 6));
}, {value: "a b c d"});
testCM("selectionChangeReducesRedo", function(cm) {
cm.replaceSelection("X");
cm.execCommand("goCharRight");
cm.undoSelection();
cm.execCommand("selectAll");
cm.undoSelection();
eq(cm.getValue(), "Xabc");
eqPos(cm.getCursor(), Pos(0, 1));
cm.undoSelection();
eq(cm.getValue(), "abc");
}, {value: "abc"});
testCM("selectionHistoryNonOverlapping", function(cm) {
cm.setSelection(Pos(0, 0), Pos(0, 1));
cm.setSelection(Pos(0, 2), Pos(0, 3));
cm.execCommand("undoSelection");
eqPos(cm.getCursor("anchor"), Pos(0, 0));
eqPos(cm.getCursor("head"), Pos(0, 1));
}, {value: "1234"});
testCM("cursorMotionSplitsHistory", function(cm) {
cm.replaceSelection("a");
cm.execCommand("goCharRight");
cm.replaceSelection("b");
cm.replaceSelection("c");
cm.undo();
eq(cm.getValue(), "a1234");
eqPos(cm.getCursor(), Pos(0, 2));
cm.undo();
eq(cm.getValue(), "1234");
eqPos(cm.getCursor(), Pos(0, 0));
}, {value: "1234"});
testCM("selChangeInOperationDoesNotSplit", function(cm) {
for (var i = 0; i < 4; i++) {
cm.operation(function() {
cm.replaceSelection("x");
cm.setCursor(Pos(0, cm.getCursor().ch - 1));
});
}
eqPos(cm.getCursor(), Pos(0, 0));
eq(cm.getValue(), "xxxxa");
cm.undo();
eq(cm.getValue(), "a");
}, {value: "a"});
testCM("alwaysMergeSelEventWithChangeOrigin", function(cm) {
cm.replaceSelection("U", null, "foo");
cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "foo"});
cm.undoSelection();
eq(cm.getValue(), "a");
cm.replaceSelection("V", null, "foo");
cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "bar"});
cm.undoSelection();
eq(cm.getValue(), "Va");
}, {value: "a"});
testCM("getTokenAt", function(cm) {
var tokPlus = cm.getTokenAt(Pos(0, 2));
eq(tokPlus.type, "operator");
eq(tokPlus.string, "+");
var toks = cm.getLineTokens(0);
eq(toks.length, 3);
forEach([["number", "1"], ["operator", "+"], ["number", "2"]], function(expect, i) {
eq(toks[i].type, expect[0]);
eq(toks[i].string, expect[1]);
});
}, {value: "1+2", mode: "javascript"});
testCM("getTokenTypeAt", function(cm) {
eq(cm.getTokenTypeAt(Pos(0, 0)), "number");
eq(cm.getTokenTypeAt(Pos(0, 6)), "string");
cm.addOverlay({
token: function(stream) {
if (stream.match("foo")) return "foo";
else stream.next();
}
});
eq(byClassName(cm.getWrapperElement(), "cm-foo").length, 1);
eq(cm.getTokenTypeAt(Pos(0, 6)), "string");
}, {value: "1 + 'foo'", mode: "javascript"});
testCM("resizeLineWidget", function(cm) {
addDoc(cm, 200, 3);
var widget = document.createElement("pre");
widget.innerHTML = "imwidget";
widget.style.background = "yellow";
cm.addLineWidget(1, widget, {noHScroll: true});
cm.setSize(40);
is(widget.parentNode.offsetWidth < 42);
});
testCM("combinedOperations", function(cm) {
var place = document.getElementById("testground");
var other = CodeMirror(place, {value: "123"});
try {
cm.operation(function() {
cm.addLineClass(0, "wrap", "foo");
other.addLineClass(0, "wrap", "foo");
});
eq(byClassName(cm.getWrapperElement(), "foo").length, 1);
eq(byClassName(other.getWrapperElement(), "foo").length, 1);
cm.operation(function() {
cm.removeLineClass(0, "wrap", "foo");
other.removeLineClass(0, "wrap", "foo");
});
eq(byClassName(cm.getWrapperElement(), "foo").length, 0);
eq(byClassName(other.getWrapperElement(), "foo").length, 0);
} finally {
place.removeChild(other.getWrapperElement());
}
}, {value: "abc"});
testCM("eventOrder", function(cm) {
var seen = [];
cm.on("change", function() {
if (!seen.length) cm.replaceSelection(".");
seen.push("change");
});
cm.on("cursorActivity", function() {
cm.replaceSelection("!");
seen.push("activity");
});
cm.replaceSelection("/");
eq(seen.join(","), "change,change,activity,change");
});
testCM("splitSpaces_nonspecial", function(cm) {
eq(byClassName(cm.getWrapperElement(), "cm-invalidchar").length, 0);
}, {
specialChars: /[\u00a0]/,
value: "spaces -> <- between"
});
test("core_rmClass", function() {
var node = document.createElement("div");
node.className = "foo-bar baz-quux yadda";
CodeMirror.rmClass(node, "quux");
eq(node.className, "foo-bar baz-quux yadda");
CodeMirror.rmClass(node, "baz-quux");
eq(node.className, "foo-bar yadda");
CodeMirror.rmClass(node, "yadda");
eq(node.className, "foo-bar");
CodeMirror.rmClass(node, "foo-bar");
eq(node.className, "");
node.className = " foo ";
CodeMirror.rmClass(node, "foo");
eq(node.className, "");
});
test("core_addClass", function() {
var node = document.createElement("div");
CodeMirror.addClass(node, "a");
eq(node.className, "a");
CodeMirror.addClass(node, "a");
eq(node.className, "a");
CodeMirror.addClass(node, "b");
eq(node.className, "a b");
CodeMirror.addClass(node, "a");
CodeMirror.addClass(node, "b");
eq(node.className, "a b");
});
|
Prism.languages.moonscript = {
'comment': /--.*/,
'string': [
{
pattern: /'[^']*'|\[(=*)\[[\s\S]*?\]\1\]/,
greedy: true
},
{
pattern: /"[^"]*"/,
greedy: true,
inside: {
'interpolation': {
pattern: /#\{[^{}]*\}/,
inside: {
'moonscript': {
pattern: /(^#\{)[\s\S]+(?=\})/,
lookbehind: true,
inside: null // see beow
},
'interpolation-punctuation': {
pattern: /#\{|\}/,
alias: 'punctuation'
}
}
}
}
}
],
'class-name': [
{
pattern: /(\b(?:class|extends)[ \t]+)\w+/,
lookbehind: true
},
// class-like names start with a capital letter
/\b[A-Z]\w*/
],
'keyword': /\b(?:class|continue|do|else|elseif|export|extends|for|from|if|import|in|local|nil|return|self|super|switch|then|unless|using|when|while|with)\b/,
'variable': /@@?\w*/,
'property': {
pattern: /\b(?!\d)\w+(?=:)|(:)(?!\d)\w+/,
lookbehind: true
},
'function': {
pattern: /\b(?:_G|_VERSION|assert|collectgarbage|coroutine\.(?:running|create|resume|status|wrap|yield)|debug\.(?:debug|gethook|getinfo|getlocal|getupvalue|setlocal|setupvalue|sethook|traceback|getfenv|getmetatable|getregistry|setfenv|setmetatable)|dofile|error|getfenv|getmetatable|io\.(?:stdin|stdout|stderr|close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|ipairs|load|loadfile|loadstring|math\.(?:abs|acos|asin|atan|atan2|ceil|sin|cos|tan|deg|exp|floor|log|log10|max|min|fmod|modf|cosh|sinh|tanh|pow|rad|sqrt|frexp|ldexp|random|randomseed|pi)|module|next|os\.(?:clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\.(?:cpath|loaded|loadlib|path|preload|seeall)|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|string\.(?:byte|char|dump|find|len|lower|rep|sub|upper|format|gsub|gmatch|match|reverse)|table\.(?:maxn|concat|sort|insert|remove)|tonumber|tostring|type|unpack|xpcall)\b/,
inside: {
'punctuation': /\./
}
},
'boolean': /\b(?:false|true)\b/,
'number': /(?:\B\.\d+|\b\d+\.\d+|\b\d+(?=[eE]))(?:[eE][-+]?\d+)?\b|\b(?:0x[a-fA-F\d]+|\d+)(?:U?LL)?\b/,
'operator': /\.{3}|[-=]>|~=|(?:[-+*/%<>!=]|\.\.)=?|[:#^]|\b(?:and|or)\b=?|\b(?:not)\b/,
'punctuation': /[.,()[\]{}\\]/
};
Prism.languages.moonscript.string[1].inside.interpolation.inside.moonscript.inside = Prism.languages.moonscript;
Prism.languages.moon = Prism.languages.moonscript;
|
var registerGeometry = require('../core/geometry').registerGeometry;
var THREE = require('../lib/three');
var degToRad = THREE.Math.degToRad;
registerGeometry('cylinder', {
schema: {
height: {default: 1, min: 0},
openEnded: {default: false},
radius: {default: 1, min: 0},
segmentsHeight: {default: 18, min: 1, type: 'int'},
segmentsRadial: {default: 36, min: 3, type: 'int'},
thetaLength: {default: 360, min: 0},
thetaStart: {default: 0}
},
init: function (data) {
this.geometry = new THREE.CylinderGeometry(
data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
}
});
|
/*
YUI 3.17.0 (build ce55cc9)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('color-hsv', function (Y, NAME) {
/**
Color provides static methods for color conversion hsv values.
Y.Color.toHSV('f00'); // hsv(0, 100%, 100%)
Y.Color.toHSVA('rgb(255, 255, 0'); // hsva(60, 100%, 100%, 1)
@module color
@submodule color-hsv
@class HSV
@namespace Color
@since 3.8.0
**/
Color = {
/**
@static
@property REGEX_HSV
@type RegExp
@default /hsva?\(([.\d]*), ?([.\d]*)%, ?([.\d]*)%,? ?([.\d]*)?\)/
@since 3.8.0
**/
REGEX_HSV: /hsva?\(([.\d]*), ?([.\d]*)%, ?([.\d]*)%,? ?([.\d]*)?\)/,
/**
@static
@property STR_HSV
@type String
@default hsv({*}, {*}%, {*}%)
@since 3.8.0
**/
STR_HSV: 'hsv({*}, {*}%, {*}%)',
/**
@static
@property STR_HSVA
@type String
@default hsva({*}, {*}%, {*}%, {*})
@since 3.8.0
**/
STR_HSVA: 'hsva({*}, {*}%, {*}%, {*})',
/**
Converts provided color value to an HSV string.
@public
@method toHSV
@param {String} str
@return {String}
@since 3.8.0
**/
toHSV: function (str) {
var clr = Y.Color._convertTo(str, 'hsv');
return clr.toLowerCase();
},
/**
Converts provided color value to an HSVA string.
@public
@method toHSVA
@param {String} str
@return {String}
@since 3.8.0
**/
toHSVA: function (str) {
var clr = Y.Color._convertTo(str, 'hsva');
return clr.toLowerCase();
},
/**
Parses the RGB string into h, s, v values. Will return an Array
of values or an HSV string.
@protected
@method _rgbToHsv
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_rgbToHsv: function (str, toArray) {
var h, s, v,
rgb = Y.Color.REGEX_RGB.exec(str),
r = rgb[1] / 255,
g = rgb[2] / 255,
b = rgb[3] / 255,
max = Math.max(r, g, b),
min = Math.min(r, g, b),
delta = max - min;
if (max === min) {
h = 0;
} else if (max === r) {
h = 60 * (g - b) / delta;
} else if (max === g) {
h = (60 * (b - r) / delta) + 120;
} else { // max === b
h = (60 * (r - g) / delta) + 240;
}
s = (max === 0) ? 0 : 1 - (min / max);
// ensure h is between 0 and 360
while (h < 0) {
h += 360;
}
h %= 360;
h = Math.round(h);
// saturation is percentage
s = Math.round(s * 100);
// value is percentage
v = Math.round(max * 100);
if (toArray) {
return [h, s, v];
}
return Y.Color.fromArray([h, s, v], Y.Color.TYPES.HSV);
},
/**
Parses the HSV string into r, b, g values. Will return an Array
of values or an RGB string.
@protected
@method _hsvToRgb
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_hsvToRgb: function (str, toArray) {
var hsv = Y.Color.REGEX_HSV.exec(str),
h = parseInt(hsv[1], 10),
s = parseInt(hsv[2], 10) / 100, // 0 - 1
v = parseInt(hsv[3], 10) / 100, // 0 - 1
r,
g,
b,
i = Math.floor(h / 60) % 6,
f = (h / 60) - i,
p = v * (1 - s),
q = v * (1 - (s * f)),
t = v * (1 - (s * (1 - f)));
if (s === 0) {
r = v;
g = v;
b = v;
} else {
switch (i) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
}
r = Math.min(255, Math.round(r * 256));
g = Math.min(255, Math.round(g * 256));
b = Math.min(255, Math.round(b * 256));
if (toArray) {
return [r, g, b];
}
return Y.Color.fromArray([r, g, b], Y.Color.TYPES.RGB);
}
};
Y.Color = Y.mix(Color, Y.Color);
Y.Color.TYPES = Y.mix(Y.Color.TYPES, {'HSV':'hsv', 'HSVA':'hsva'});
Y.Color.CONVERTS = Y.mix(Y.Color.CONVERTS, {'hsv': 'toHSV', 'hsva': 'toHSVA'});
}, '3.17.0', {"requires": ["color-base"]});
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v8.2.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FUNCTION_STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var FUNCTION_ARGUMENT_NAMES = /([^\s,]+)/g;
// util class, only used when debugging, for printing time to console
var Timer = (function () {
function Timer() {
this.timestamp = new Date().getTime();
}
Timer.prototype.print = function (msg) {
var duration = (new Date().getTime()) - this.timestamp;
console.log(msg + " = " + duration);
this.timestamp = new Date().getTime();
};
return Timer;
}());
exports.Timer = Timer;
/** HTML Escapes. */
var HTML_ESCAPES = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
var reUnescapedHtml = /[&<>"']/g;
var Utils = (function () {
function Utils() {
}
// returns true if the event is close to the original event by X pixels either vertically or horizontally.
// we only start dragging after X pixels so this allows us to know if we should start dragging yet.
Utils.areEventsNear = function (e1, e2, pixelCount) {
// by default, we wait 4 pixels before starting the drag
if (pixelCount === 0) {
return false;
}
var diffX = Math.abs(e1.clientX - e2.clientX);
var diffY = Math.abs(e1.clientY - e2.clientY);
return Math.max(diffX, diffY) <= pixelCount;
};
Utils.shallowCompare = function (arr1, arr2) {
// if both are missing, then they are the same
if (this.missing(arr1) && this.missing(arr2)) {
return true;
}
// if one is present, but other is missing, then then are different
if (this.missing(arr1) || this.missing(arr2)) {
return false;
}
if (arr1.length !== arr2.length) {
return false;
}
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
Utils.getNameOfClass = function (TheClass) {
var funcNameRegex = /function (.{1,})\(/;
var funcAsString = TheClass.toString();
var results = (funcNameRegex).exec(funcAsString);
return (results && results.length > 1) ? results[1] : "";
};
Utils.values = function (object) {
var result = [];
this.iterateObject(object, function (key, value) {
result.push(value);
});
return result;
};
Utils.getValueUsingField = function (data, field, fieldContainsDots) {
if (!field || !data) {
return;
}
// if no '.', then it's not a deep value
if (!fieldContainsDots) {
return data[field];
}
else {
// otherwise it is a deep value, so need to dig for it
var fields = field.split('.');
var currentObject = data;
for (var i = 0; i < fields.length; i++) {
currentObject = currentObject[fields[i]];
if (this.missing(currentObject)) {
return null;
}
}
return currentObject;
}
};
Utils.getScrollLeft = function (element, rtl) {
var scrollLeft = element.scrollLeft;
if (rtl) {
// Absolute value - for FF that reports RTL scrolls in negative numbers
scrollLeft = Math.abs(scrollLeft);
// Get Chrome and Safari to return the same value as well
if (this.isBrowserSafari() || this.isBrowserChrome()) {
scrollLeft = element.scrollWidth - element.clientWidth - scrollLeft;
}
}
return scrollLeft;
};
Utils.cleanNumber = function (value) {
if (typeof value === 'string') {
value = parseInt(value);
}
if (typeof value === 'number') {
value = Math.floor(value);
}
else {
value = null;
}
return value;
};
Utils.setScrollLeft = function (element, value, rtl) {
if (rtl) {
// Chrome and Safari when doing RTL have the END position of the scroll as zero, not the start
if (this.isBrowserSafari() || this.isBrowserChrome()) {
value = element.scrollWidth - element.clientWidth - value;
}
// Firefox uses negative numbers when doing RTL scrolling
if (this.isBrowserFirefox()) {
value *= -1;
}
}
element.scrollLeft = value;
};
Utils.iterateObject = function (object, callback) {
if (this.missing(object)) {
return;
}
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = object[key];
callback(key, value);
}
};
Utils.cloneObject = function (object) {
var copy = {};
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = object[key];
copy[key] = value;
}
return copy;
};
Utils.map = function (array, callback) {
var result = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
var mappedItem = callback(item);
result.push(mappedItem);
}
return result;
};
Utils.mapObject = function (object, callback) {
var result = [];
Utils.iterateObject(object, function (key, value) {
result.push(callback(value));
});
return result;
};
Utils.forEach = function (array, callback) {
if (!array) {
return;
}
for (var i = 0; i < array.length; i++) {
var value = array[i];
callback(value, i);
}
};
Utils.filter = function (array, callback) {
var result = [];
array.forEach(function (item) {
if (callback(item)) {
result.push(item);
}
});
return result;
};
Utils.mergeDeep = function (object, source) {
if (this.exists(source)) {
this.iterateObject(source, function (key, value) {
var currentValue = object[key];
var target = source[key];
if (currentValue == null) {
object[key] = value;
}
if (typeof currentValue === 'object') {
if (target) {
Utils.mergeDeep(object[key], target);
}
}
if (target) {
object[key] = target;
}
});
}
};
Utils.assign = function (object, source) {
if (this.exists(source)) {
this.iterateObject(source, function (key, value) {
object[key] = value;
});
}
};
Utils.parseYyyyMmDdToDate = function (yyyyMmDd, separator) {
try {
if (!yyyyMmDd)
return null;
if (yyyyMmDd.indexOf(separator) === -1)
return null;
var fields = yyyyMmDd.split(separator);
if (fields.length != 3)
return null;
return new Date(Number(fields[0]), Number(fields[1]) - 1, Number(fields[2]));
}
catch (e) {
return null;
}
};
Utils.serializeDateToYyyyMmDd = function (date, separator) {
if (!date)
return null;
return date.getFullYear() + separator + Utils.pad(date.getMonth() + 1, 2) + separator + Utils.pad(date.getDate(), 2);
};
Utils.pad = function (num, totalStringSize) {
var asString = num + "";
while (asString.length < totalStringSize)
asString = "0" + asString;
return asString;
};
Utils.pushAll = function (target, source) {
if (this.missing(source) || this.missing(target)) {
return;
}
source.forEach(function (func) { return target.push(func); });
};
Utils.getFunctionParameters = function (func) {
var fnStr = func.toString().replace(FUNCTION_STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(FUNCTION_ARGUMENT_NAMES);
if (result === null) {
return [];
}
else {
return result;
}
};
Utils.find = function (collection, predicate, value) {
if (collection === null || collection === undefined) {
return null;
}
if (!Array.isArray(collection)) {
var objToArray = this.values(collection);
return this.find(objToArray, predicate, value);
}
var collectionAsArray = collection;
var firstMatchingItem;
for (var i = 0; i < collectionAsArray.length; i++) {
var item = collectionAsArray[i];
if (typeof predicate === 'string') {
if (item[predicate] === value) {
firstMatchingItem = item;
break;
}
}
else {
var callback = predicate;
if (callback(item)) {
firstMatchingItem = item;
break;
}
}
}
return firstMatchingItem;
};
Utils.toStrings = function (array) {
return this.map(array, function (item) {
if (item === undefined || item === null || !item.toString) {
return null;
}
else {
return item.toString();
}
});
};
Utils.iterateArray = function (array, callback) {
for (var index = 0; index < array.length; index++) {
var value = array[index];
callback(value, index);
}
};
//Returns true if it is a DOM node
//taken from: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
Utils.isNode = function (o) {
return (typeof Node === "function" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
};
//Returns true if it is a DOM element
//taken from: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
Utils.isElement = function (o) {
return (typeof HTMLElement === "function" ? o instanceof HTMLElement :
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string");
};
Utils.isNodeOrElement = function (o) {
return this.isNode(o) || this.isElement(o);
};
//adds all type of change listeners to an element, intended to be a text field
Utils.addChangeListener = function (element, listener) {
element.addEventListener("changed", listener);
element.addEventListener("paste", listener);
element.addEventListener("input", listener);
// IE doesn't fire changed for special keys (eg delete, backspace), so need to
// listen for this further ones
element.addEventListener("keydown", listener);
element.addEventListener("keyup", listener);
};
//if value is undefined, null or blank, returns null, otherwise returns the value
Utils.makeNull = function (value) {
if (value === null || value === undefined || value === "") {
return null;
}
else {
return value;
}
};
Utils.missing = function (value) {
return !this.exists(value);
};
Utils.missingOrEmpty = function (value) {
return this.missing(value) || value.length === 0;
};
Utils.missingOrEmptyObject = function (value) {
return this.missing(value) || Object.keys(value).length === 0;
};
Utils.exists = function (value) {
if (value === null || value === undefined || value === '') {
return false;
}
else {
return true;
}
};
Utils.anyExists = function (values) {
if (values) {
for (var i = 0; i < values.length; i++) {
if (this.exists(values[i])) {
return true;
}
}
}
return false;
};
Utils.existsAndNotEmpty = function (value) {
return this.exists(value) && value.length > 0;
};
Utils.removeAllChildren = function (node) {
if (node) {
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}
};
Utils.removeElement = function (parent, cssSelector) {
this.removeFromParent(parent.querySelector(cssSelector));
};
Utils.removeFromParent = function (node) {
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
};
Utils.isVisible = function (element) {
return (element.offsetParent !== null);
};
/**
* loads the template and returns it as an element. makes up for no simple way in
* the dom api to load html directly, eg we cannot do this: document.createElement(template)
*/
Utils.loadTemplate = function (template) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = template;
return tempDiv.firstChild;
};
Utils.addOrRemoveCssClass = function (element, className, addOrRemove) {
if (addOrRemove) {
this.addCssClass(element, className);
}
else {
this.removeCssClass(element, className);
}
};
Utils.callIfPresent = function (func) {
if (func) {
func();
}
};
Utils.addCssClass = function (element, className) {
var _this = this;
if (!className || className.length === 0) {
return;
}
if (className.indexOf(' ') >= 0) {
className.split(' ').forEach(function (value) { return _this.addCssClass(element, value); });
return;
}
if (element.classList) {
element.classList.add(className);
}
else {
if (element.className && element.className.length > 0) {
var cssClasses = element.className.split(' ');
if (cssClasses.indexOf(className) < 0) {
cssClasses.push(className);
element.className = cssClasses.join(' ');
}
}
else {
element.className = className;
}
}
};
Utils.containsClass = function (element, className) {
if (element.classList) {
// for modern browsers
return element.classList.contains(className);
}
else if (element.className) {
// for older browsers, check against the string of class names
// if only one class, can check for exact match
var onlyClass = element.className === className;
// if many classes, check for class name, we have to pad with ' ' to stop other
// class names that are a substring of this class
var contains = element.className.indexOf(' ' + className + ' ') >= 0;
// the padding above then breaks when it's the first or last class names
var startsWithClass = element.className.indexOf(className + ' ') === 0;
var endsWithClass = element.className.lastIndexOf(' ' + className) === (element.className.length - className.length - 1);
return onlyClass || contains || startsWithClass || endsWithClass;
}
else {
// if item is not a node
return false;
}
};
Utils.getElementAttribute = function (element, attributeName) {
if (element.attributes) {
if (element.attributes[attributeName]) {
var attribute = element.attributes[attributeName];
return attribute.value;
}
else {
return null;
}
}
else {
return null;
}
};
Utils.offsetHeight = function (element) {
return element && element.clientHeight ? element.clientHeight : 0;
};
Utils.offsetWidth = function (element) {
return element && element.clientWidth ? element.clientWidth : 0;
};
Utils.removeCssClass = function (element, className) {
if (element.className && element.className.length > 0) {
var cssClasses = element.className.split(' ');
var index = cssClasses.indexOf(className);
if (index >= 0) {
cssClasses.splice(index, 1);
element.className = cssClasses.join(' ');
}
}
};
Utils.removeRepeatsFromArray = function (array, object) {
if (!array) {
return;
}
for (var index = array.length - 2; index >= 0; index--) {
var thisOneMatches = array[index] === object;
var nextOneMatches = array[index + 1] === object;
if (thisOneMatches && nextOneMatches) {
array.splice(index + 1, 1);
}
}
};
Utils.removeFromArray = function (array, object) {
if (array.indexOf(object) >= 0) {
array.splice(array.indexOf(object), 1);
}
};
Utils.removeAllFromArray = function (array, toRemove) {
toRemove.forEach(function (item) {
if (array.indexOf(item) >= 0) {
array.splice(array.indexOf(item), 1);
}
});
};
Utils.insertIntoArray = function (array, object, toIndex) {
array.splice(toIndex, 0, object);
};
Utils.insertArrayIntoArray = function (dest, src, toIndex) {
if (this.missing(dest) || this.missing(src)) {
return;
}
// put items in backwards, otherwise inserted items end up in reverse order
for (var i = src.length - 1; i >= 0; i--) {
var item = src[i];
this.insertIntoArray(dest, item, toIndex);
}
};
Utils.moveInArray = function (array, objectsToMove, toIndex) {
var _this = this;
// first take out it items from the array
objectsToMove.forEach(function (obj) {
_this.removeFromArray(array, obj);
});
// now add the objects, in same order as provided to us, that means we start at the end
// as the objects will be pushed to the right as they are inserted
objectsToMove.slice().reverse().forEach(function (obj) {
_this.insertIntoArray(array, obj, toIndex);
});
};
Utils.defaultComparator = function (valueA, valueB) {
var valueAMissing = valueA === null || valueA === undefined;
var valueBMissing = valueB === null || valueB === undefined;
if (valueAMissing && valueBMissing) {
return 0;
}
if (valueAMissing) {
return -1;
}
if (valueBMissing) {
return 1;
}
if (typeof valueA === "string") {
try {
// using local compare also allows chinese comparisons
return valueA.localeCompare(valueB);
}
catch (e) {
// if something wrong with localeCompare, eg not supported
// by browser, then just continue without using it
}
}
if (valueA < valueB) {
return -1;
}
else if (valueA > valueB) {
return 1;
}
else {
return 0;
}
};
Utils.compareArrays = function (array1, array2) {
if (this.missing(array1) && this.missing(array2)) {
return true;
}
if (this.missing(array1) || this.missing(array2)) {
return false;
}
if (array1.length !== array2.length) {
return false;
}
for (var i = 0; i < array1.length; i++) {
if (array1[i] !== array2[i]) {
return false;
}
}
return true;
};
Utils.toStringOrNull = function (value) {
if (this.exists(value) && value.toString) {
return value.toString();
}
else {
return null;
}
};
Utils.formatWidth = function (width) {
if (typeof width === "number") {
return width + "px";
}
else {
return width;
}
};
Utils.formatNumberTwoDecimalPlacesAndCommas = function (value) {
// took this from: http://blog.tompawlak.org/number-currency-formatting-javascript
if (typeof value === 'number') {
return (Math.round(value * 100) / 100).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
else {
return '';
}
};
Utils.prependDC = function (parent, documentFragment) {
if (this.exists(parent.firstChild)) {
parent.insertBefore(documentFragment, parent.firstChild);
}
else {
parent.appendChild(documentFragment);
}
};
// static prepend(parent: HTMLElement, child: HTMLElement): void {
// if (this.exists(parent.firstChild)) {
// parent.insertBefore(child, parent.firstChild);
// } else {
// parent.appendChild(child);
// }
// }
/**
* If icon provided, use this (either a string, or a function callback).
* if not, then use the second parameter, which is the svgFactory function
*/
Utils.createIcon = function (iconName, gridOptionsWrapper, column, svgFactoryFunc) {
var eResult = document.createElement('span');
eResult.appendChild(this.createIconNoSpan(iconName, gridOptionsWrapper, column, svgFactoryFunc));
return eResult;
};
Utils.createIconNoSpan = function (iconName, gridOptionsWrapper, column, svgFactoryFunc) {
var userProvidedIcon;
// check col for icon first
if (column && column.getColDef().icons) {
userProvidedIcon = column.getColDef().icons[iconName];
}
// it not in col, try grid options
if (!userProvidedIcon && gridOptionsWrapper.getIcons()) {
userProvidedIcon = gridOptionsWrapper.getIcons()[iconName];
}
// now if user provided, use it
if (userProvidedIcon) {
var rendererResult;
if (typeof userProvidedIcon === 'function') {
rendererResult = userProvidedIcon();
}
else if (typeof userProvidedIcon === 'string') {
rendererResult = userProvidedIcon;
}
else {
throw 'icon from grid options needs to be a string or a function';
}
if (typeof rendererResult === 'string') {
return this.loadTemplate(rendererResult);
}
else if (this.isNodeOrElement(rendererResult)) {
return rendererResult;
}
else {
throw 'iconRenderer should return back a string or a dom object';
}
}
else {
// otherwise we use the built in icon
if (svgFactoryFunc) {
return svgFactoryFunc();
}
else {
return null;
}
}
};
Utils.addStylesToElement = function (eElement, styles) {
if (!styles) {
return;
}
Object.keys(styles).forEach(function (key) {
eElement.style[key] = styles[key];
});
};
Utils.isHorizontalScrollShowing = function (element) {
return element.clientWidth < element.scrollWidth;
};
Utils.isVerticalScrollShowing = function (element) {
return element.clientHeight < element.scrollHeight;
};
Utils.getScrollbarWidth = function () {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
};
Utils.isKeyPressed = function (event, keyToCheck) {
var pressedKey = event.which || event.keyCode;
return pressedKey === keyToCheck;
};
Utils.setVisible = function (element, visible) {
this.addOrRemoveCssClass(element, 'ag-hidden', !visible);
};
Utils.setHidden = function (element, hidden) {
this.addOrRemoveCssClass(element, 'ag-visibility-hidden', hidden);
};
Utils.isBrowserIE = function () {
if (this.isIE === undefined) {
this.isIE = false || !!document.documentMode; // At least IE6
}
return this.isIE;
};
Utils.isBrowserEdge = function () {
if (this.isEdge === undefined) {
this.isEdge = !this.isBrowserIE() && !!window.StyleMedia;
}
return this.isEdge;
};
Utils.isBrowserSafari = function () {
if (this.isSafari === undefined) {
var anyWindow = window;
// taken from https://github.com/ceolter/ag-grid/issues/550
this.isSafari = Object.prototype.toString.call(anyWindow.HTMLElement).indexOf('Constructor') > 0
|| (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!anyWindow.safari || anyWindow.safari.pushNotification);
}
return this.isSafari;
};
Utils.isBrowserChrome = function () {
if (this.isChrome === undefined) {
var anyWindow = window;
this.isChrome = !!anyWindow.chrome && !!anyWindow.chrome.webstore;
}
return this.isChrome;
};
Utils.isBrowserFirefox = function () {
if (this.isFirefox === undefined) {
var anyWindow = window;
this.isFirefox = typeof anyWindow.InstallTrigger !== 'undefined';
;
}
return this.isFirefox;
};
// srcElement is only available in IE. In all other browsers it is target
// http://stackoverflow.com/questions/5301643/how-can-i-make-event-srcelement-work-in-firefox-and-what-does-it-mean
Utils.getTarget = function (event) {
var eventNoType = event;
return eventNoType.target || eventNoType.srcElement;
};
// taken from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
Utils.getBodyWidth = function () {
if (document.body) {
return document.body.clientWidth;
}
if (window.innerHeight) {
return window.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
return -1;
};
// taken from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
Utils.getBodyHeight = function () {
if (document.body) {
return document.body.clientHeight;
}
if (window.innerHeight) {
return window.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
return -1;
};
Utils.setCheckboxState = function (eCheckbox, state) {
if (typeof state === 'boolean') {
eCheckbox.checked = state;
eCheckbox.indeterminate = false;
}
else {
// isNodeSelected returns back undefined if it's a group and the children
// are a mix of selected and unselected
eCheckbox.indeterminate = true;
}
};
Utils.traverseNodesWithKey = function (nodes, callback) {
var keyParts = [];
recursiveSearchNodes(nodes);
function recursiveSearchNodes(nodes) {
nodes.forEach(function (node) {
if (node.group) {
keyParts.push(node.key);
var key = keyParts.join('|');
callback(node, key);
recursiveSearchNodes(node.childrenAfterGroup);
keyParts.pop();
}
});
}
};
Utils.isNumeric = function (value) {
return !isNaN(parseFloat(value)) && isFinite(value);
};
Utils.escape = function (toEscape) {
if (toEscape === null)
return null;
if (!toEscape.replace)
return toEscape;
return toEscape.replace(reUnescapedHtml, function (chr) { return HTML_ESCAPES[chr]; });
};
// Taken from here: https://github.com/facebook/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
/**
* Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
* complicated, thus this doc is long and (hopefully) detailed enough to answer
* your questions.
*
* If you need to react to the mouse wheel in a predictable way, this code is
* like your bestest friend. * hugs *
*
* As of today, there are 4 DOM event types you can listen to:
*
* 'wheel' -- Chrome(31+), FF(17+), IE(9+)
* 'mousewheel' -- Chrome, IE(6+), Opera, Safari
* 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
* 'DOMMouseScroll' -- FF(0.9.7+) since 2003
*
* So what to do? The is the best:
*
* normalizeWheel.getEventType();
*
* In your event callback, use this code to get sane interpretation of the
* deltas. This code will return an object with properties:
*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*
* Wheel values are provided by the browser assuming you are using the wheel to
* scroll a web page by a number of lines or pixels (or pages). Values can vary
* significantly on different platforms and browsers, forgetting that you can
* scroll at different speeds. Some devices (like trackpads) emit more events
* at smaller increments with fine granularity, and some emit massive jumps with
* linear speed or acceleration.
*
* This code does its best to normalize the deltas for you:
*
* - spin is trying to normalize how far the wheel was spun (or trackpad
* dragged). This is super useful for zoom support where you want to
* throw away the chunky scroll steps on the PC and make those equal to
* the slow and smooth tiny steps on the Mac. Key data: This code tries to
* resolve a single slow step on a wheel to 1.
*
* - pixel is normalizing the desired scroll delta in pixel units. You'll
* get the crazy differences between browsers, but at least it'll be in
* pixels!
*
* - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
* should translate to positive value zooming IN, negative zooming OUT.
* This matches the newer 'wheel' event.
*
* Why are there spinX, spinY (or pixels)?
*
* - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
* with a mouse. It results in side-scrolling in the browser by default.
*
* - spinY is what you expect -- it's the classic axis of a mouse wheel.
*
* - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
* probably is by browsers in conjunction with fancy 3D controllers .. but
* you know.
*
* Implementation info:
*
* Examples of 'wheel' event if you scroll slowly (down) by one step with an
* average mouse:
*
* OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
* OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
* OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
* Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
* Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
*
* On the trackpad:
*
* OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
* OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
*
* On other/older browsers.. it's more complicated as there can be multiple and
* also missing delta values.
*
* The 'wheel' event is more standard:
*
* http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
*
* The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
* deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
* backward compatibility with older events. Those other values help us
* better normalize spin speed. Example of what the browsers provide:
*
* | event.wheelDelta | event.detail
* ------------------+------------------+--------------
* Safari v5/OS X | -120 | 0
* Safari v5/Win7 | -120 | 0
* Chrome v17/OS X | -120 | 0
* Chrome v17/Win7 | -120 | 0
* IE9/Win7 | -120 | undefined
* Firefox v4/OS X | undefined | 1
* Firefox v4/Win7 | undefined | 3
*
*/
Utils.normalizeWheel = function (event) {
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
// spinX, spinY
var sX = 0;
var sY = 0;
// pixelX, pixelY
var pX = 0;
var pY = 0;
// Legacy
if ('detail' in event) {
sY = event.detail;
}
if ('wheelDelta' in event) {
sY = -event.wheelDelta / 120;
}
if ('wheelDeltaY' in event) {
sY = -event.wheelDeltaY / 120;
}
if ('wheelDeltaX' in event) {
sX = -event.wheelDeltaX / 120;
}
// side scrolling on FF with DOMMouseScroll
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) {
pY = event.deltaY;
}
if ('deltaX' in event) {
pX = event.deltaX;
}
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode == 1) {
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
}
else {
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) {
sX = (pX < 1) ? -1 : 1;
}
if (pY && !sY) {
sY = (pY < 1) ? -1 : 1;
}
return { spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY };
};
return Utils;
}());
exports.Utils = Utils;
var NumberSequence = (function () {
function NumberSequence(initValue, step) {
if (initValue === void 0) { initValue = 0; }
if (step === void 0) { step = 1; }
this.nextValue = initValue;
this.step = step;
}
NumberSequence.prototype.next = function () {
var valToReturn = this.nextValue;
this.nextValue += this.step;
return valToReturn;
};
return NumberSequence;
}());
exports.NumberSequence = NumberSequence;
exports._ = Utils;
|
var constants = require('../tokenizer/const');
var TYPE = constants.TYPE;
var NAME = constants.NAME;
var utils = require('../tokenizer/utils');
var cmpStr = utils.cmpStr;
var EOF = TYPE.EOF;
var WHITESPACE = TYPE.WhiteSpace;
var COMMENT = TYPE.Comment;
var OFFSET_MASK = 0x00FFFFFF;
var TYPE_SHIFT = 24;
var TokenStream = function() {
this.offsetAndType = null;
this.balance = null;
this.reset();
};
TokenStream.prototype = {
reset: function() {
this.eof = false;
this.tokenIndex = -1;
this.tokenType = 0;
this.tokenStart = this.firstCharOffset;
this.tokenEnd = this.firstCharOffset;
},
lookupType: function(offset) {
offset += this.tokenIndex;
if (offset < this.tokenCount) {
return this.offsetAndType[offset] >> TYPE_SHIFT;
}
return EOF;
},
lookupOffset: function(offset) {
offset += this.tokenIndex;
if (offset < this.tokenCount) {
return this.offsetAndType[offset - 1] & OFFSET_MASK;
}
return this.source.length;
},
lookupValue: function(offset, referenceStr) {
offset += this.tokenIndex;
if (offset < this.tokenCount) {
return cmpStr(
this.source,
this.offsetAndType[offset - 1] & OFFSET_MASK,
this.offsetAndType[offset] & OFFSET_MASK,
referenceStr
);
}
return false;
},
getTokenStart: function(tokenIndex) {
if (tokenIndex === this.tokenIndex) {
return this.tokenStart;
}
if (tokenIndex > 0) {
return tokenIndex < this.tokenCount
? this.offsetAndType[tokenIndex - 1] & OFFSET_MASK
: this.offsetAndType[this.tokenCount] & OFFSET_MASK;
}
return this.firstCharOffset;
},
// TODO: -> skipUntilBalanced
getRawLength: function(startToken, mode) {
var cursor = startToken;
var balanceEnd;
var offset = this.offsetAndType[Math.max(cursor - 1, 0)] & OFFSET_MASK;
var type;
loop:
for (; cursor < this.tokenCount; cursor++) {
balanceEnd = this.balance[cursor];
// stop scanning on balance edge that points to offset before start token
if (balanceEnd < startToken) {
break loop;
}
type = this.offsetAndType[cursor] >> TYPE_SHIFT;
// check token is stop type
switch (mode(type, this.source, offset)) {
case 1:
break loop;
case 2:
cursor++;
break loop;
default:
offset = this.offsetAndType[cursor] & OFFSET_MASK;
// fast forward to the end of balanced block
if (this.balance[balanceEnd] === cursor) {
cursor = balanceEnd;
}
}
}
return cursor - this.tokenIndex;
},
isBalanceEdge: function(pos) {
return this.balance[this.tokenIndex] < pos;
},
isDelim: function(code, offset) {
if (offset) {
return (
this.lookupType(offset) === TYPE.Delim &&
this.source.charCodeAt(this.lookupOffset(offset)) === code
);
}
return (
this.tokenType === TYPE.Delim &&
this.source.charCodeAt(this.tokenStart) === code
);
},
getTokenValue: function() {
return this.source.substring(this.tokenStart, this.tokenEnd);
},
getTokenLength: function() {
return this.tokenEnd - this.tokenStart;
},
substrToCursor: function(start) {
return this.source.substring(start, this.tokenStart);
},
skipWS: function() {
for (var i = this.tokenIndex, skipTokenCount = 0; i < this.tokenCount; i++, skipTokenCount++) {
if ((this.offsetAndType[i] >> TYPE_SHIFT) !== WHITESPACE) {
break;
}
}
if (skipTokenCount > 0) {
this.skip(skipTokenCount);
}
},
skipSC: function() {
while (this.tokenType === WHITESPACE || this.tokenType === COMMENT) {
this.next();
}
},
skip: function(tokenCount) {
var next = this.tokenIndex + tokenCount;
if (next < this.tokenCount) {
this.tokenIndex = next;
this.tokenStart = this.offsetAndType[next - 1] & OFFSET_MASK;
next = this.offsetAndType[next];
this.tokenType = next >> TYPE_SHIFT;
this.tokenEnd = next & OFFSET_MASK;
} else {
this.tokenIndex = this.tokenCount;
this.next();
}
},
next: function() {
var next = this.tokenIndex + 1;
if (next < this.tokenCount) {
this.tokenIndex = next;
this.tokenStart = this.tokenEnd;
next = this.offsetAndType[next];
this.tokenType = next >> TYPE_SHIFT;
this.tokenEnd = next & OFFSET_MASK;
} else {
this.tokenIndex = this.tokenCount;
this.eof = true;
this.tokenType = EOF;
this.tokenStart = this.tokenEnd = this.source.length;
}
},
dump: function() {
var offset = this.firstCharOffset;
return Array.prototype.slice.call(this.offsetAndType, 0, this.tokenCount).map(function(item, idx) {
var start = offset;
var end = item & OFFSET_MASK;
offset = end;
return {
idx: idx,
type: NAME[item >> TYPE_SHIFT],
chunk: this.source.substring(start, end),
balance: this.balance[idx]
};
}, this);
}
};
module.exports = TokenStream;
|
/*!
* Vue.js v2.1.6
* (c) 2014-2016 Evan You
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Vue = factory());
}(this, (function () { 'use strict';
/* */
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val, 10);
return (n || n === 0) ? n : val
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Remove an item from an array
*/
function remove$1 (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
}
}
/**
* Camelize a hyphen-delmited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind$1 (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
var toString = Object.prototype.toString;
var OBJECT_STRING = '[object Object]';
function isPlainObject (obj) {
return toString.call(obj) === OBJECT_STRING
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
/* eslint-disable eqeqeq */
return a == b || (
isObject(a) && isObject(b)
? JSON.stringify(a) === JSON.stringify(b)
: false
)
/* eslint-enable eqeqeq */
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/* */
var config = {
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Whether to enable devtools
*/
devtools: "development" !== 'production',
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: null,
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* List of asset types that a component can own.
*/
_assetTypes: [
'component',
'directive',
'filter'
],
/**
* List of lifecycle hooks.
*/
_lifecycleHooks: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
],
/**
* Max circular updates allowed in a scheduler flush cycle.
*/
_maxUpdateCount: 100
};
/* */
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = /[^\w.$]/;
function parsePath (path) {
if (bailRE.test(path)) {
return
} else {
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return /native code/.test(Ctor.toString())
}
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) { cb.call(ctx); }
if (_resolve) { _resolve(ctx); }
});
if (!pending) {
pending = true;
timerFunc();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] === true
};
Set.prototype.add = function add (key) {
this.set[key] = true;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
var warn = noop;
var formatComponentName;
{
var hasConsole = typeof console !== 'undefined';
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + " " + (
vm ? formatLocation(formatComponentName(vm)) : ''
));
}
};
formatComponentName = function (vm) {
if (vm.$root === vm) {
return 'root instance'
}
var name = vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
return (
(name ? ("component <" + name + ">") : "anonymous component") +
(vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '')
)
};
var formatLocation = function (str) {
if (str === 'anonymous component') {
str += " - use the \"name\" option for better debugging messages.";
}
return ("\n(found in " + str + ")")
};
}
/* */
var uid$1 = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid$1++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove$1(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stablize the subscriber list first
var subs = this.subs.slice();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
var childOb = observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
if (Array.isArray(value)) {
dependArray(value);
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if ("development" !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set$1 (obj, key, val) {
if (Array.isArray(obj)) {
obj.length = Math.max(obj.length, key);
obj.splice(key, 1, val);
return val
}
if (hasOwn(obj, key)) {
obj[key] = val;
return
}
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
"development" !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return
}
if (!ob) {
obj[key] = val;
return
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (obj, key) {
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
"development" !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(obj, key)) {
return
}
delete obj[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
{
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set$1(to, key, fromVal);
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
"development" !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and param attributes are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
config._lifecycleHooks.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: res
}
config._assetTypes.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
{
checkComponents(child);
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = typeof extendsFrom === 'function'
? mergeOptions(parent, extendsFrom.options, vm)
: mergeOptions(parent, extendsFrom, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
var mixin = child.mixins[i];
if (mixin.prototype instanceof Vue$3) {
mixin = mixin.options;
}
parent = mergeOptions(parent, mixin, vm);
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) { return assets[id] }
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if ("development" !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// handle boolean props
if (isBooleanType(prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (value === '' || value === hyphenate(key)) {
value = true;
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
{
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
"development" !== 'production' && warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm[key] !== undefined) {
return vm[key]
}
// call factory function for non-Function types
return typeof def === 'function' && prop.type !== Function
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType);
valid = assertedType.valid;
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
/**
* Assert the type of a value
*/
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (expectedType === 'String') {
valid = typeof value === (expectedType = 'string');
} else if (expectedType === 'Number') {
valid = typeof value === (expectedType = 'number');
} else if (expectedType === 'Boolean') {
valid = typeof value === (expectedType = 'boolean');
} else if (expectedType === 'Function') {
valid = typeof value === (expectedType = 'function');
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match && match[1]
}
function isBooleanType (fn) {
if (!Array.isArray(fn)) {
return getType(fn) === 'Boolean'
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === 'Boolean') {
return true
}
}
/* istanbul ignore next */
return false
}
var util = Object.freeze({
defineReactive: defineReactive$$1,
_toString: _toString,
toNumber: toNumber,
makeMap: makeMap,
isBuiltInTag: isBuiltInTag,
remove: remove$1,
hasOwn: hasOwn,
isPrimitive: isPrimitive,
cached: cached,
camelize: camelize,
capitalize: capitalize,
hyphenate: hyphenate,
bind: bind$1,
toArray: toArray,
extend: extend,
isObject: isObject,
isPlainObject: isPlainObject,
toObject: toObject,
noop: noop,
no: no,
identity: identity,
genStaticKeys: genStaticKeys,
looseEqual: looseEqual,
looseIndexOf: looseIndexOf,
isReserved: isReserved,
def: def,
parsePath: parsePath,
hasProto: hasProto,
inBrowser: inBrowser,
UA: UA,
isIE: isIE,
isIE9: isIE9,
isEdge: isEdge,
isAndroid: isAndroid,
isIOS: isIOS,
isServerRendering: isServerRendering,
devtools: devtools,
nextTick: nextTick,
get _Set () { return _Set; },
mergeOptions: mergeOptions,
resolveAsset: resolveAsset,
get warn () { return warn; },
get formatComponentName () { return formatComponentName; },
validateProp: validateProp
});
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
{
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
return false
} else {
target[key] = value;
return true
}
}
});
}
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key);
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var queue = [];
var has$1 = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = 0;
has$1 = {};
{
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
var watcher = queue[index];
var id = watcher.id;
has$1[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if ("development" !== 'production' && has$1[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > config._maxUpdateCount) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
resetSchedulerState();
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has$1[id] == null) {
has$1[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i >= 0 && queue[i].id > watcher.id) {
i--;
}
queue.splice(Math.max(i, index) + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$2 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$2; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = expOrFn.toString();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
"development" !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value = this.getter.call(this.vm, this.vm);
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, this.vm);
} else {
"development" !== 'production' && warn(
("Error in watcher \"" + (this.expression) + "\""),
this.vm
);
throw e
}
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed or is performing a v-for
// re-render (the watcher list is then filtered by v-for).
if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) {
remove$1(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/* */
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch) { initWatch(vm, opts.watch); }
}
var isReservedProp = { key: 1, ref: 1, slot: 1 };
function initProps (vm, props) {
var propsData = vm.$options.propsData || {};
var keys = vm.$options._propKeys = Object.keys(props);
var isRoot = !vm.$parent;
// root instance props should be converted
observerState.shouldConvert = isRoot;
var loop = function ( i ) {
var key = keys[i];
/* istanbul ignore else */
{
if (isReservedProp[key]) {
warn(
("\"" + key + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
}
};
for (var i = 0; i < keys.length; i++) loop( i );
observerState.shouldConvert = true;
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? data.call(vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
"development" !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
"development" !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else {
proxy(vm, keys[i]);
}
}
// observe data
observe(data, true /* asRootData */);
}
var computedSharedDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function initComputed (vm, computed) {
for (var key in computed) {
var userDef = computed[key];
if (typeof userDef === 'function') {
computedSharedDefinition.get = makeComputedGetter(userDef, vm);
computedSharedDefinition.set = noop;
} else {
computedSharedDefinition.get = userDef.get
? userDef.cache !== false
? makeComputedGetter(userDef.get, vm)
: bind$1(userDef.get, vm)
: noop;
computedSharedDefinition.set = userDef.set
? bind$1(userDef.set, vm)
: noop;
}
Object.defineProperty(vm, key, computedSharedDefinition);
}
}
function makeComputedGetter (getter, owner) {
var watcher = new Watcher(owner, getter, noop, {
lazy: true
});
return function computedGetter () {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
function initMethods (vm, methods) {
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind$1(methods[key], vm);
if ("development" !== 'production' && methods[key] == null) {
warn(
"method \"" + key + "\" has an undefined value in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
}
}
function initWatch (vm, watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (vm, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, handler, options);
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () {
return this._data
};
{
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Vue.prototype.$set = set$1;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
function proxy (vm, key) {
if (!isReserved(key)) {
Object.defineProperty(vm, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return vm._data[key]
},
set: function proxySetter (val) {
vm._data[key] = val;
}
});
}
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.functionalContext = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.child = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
};
var createEmptyVNode = function () {
var node = new VNode();
node.text = '';
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
function mergeVNodeHook (def, hookKey, hook, key) {
key = key + hookKey;
var injectedHash = def.__injected || (def.__injected = {});
if (!injectedHash[key]) {
injectedHash[key] = true;
var oldHook = def[hookKey];
if (oldHook) {
def[hookKey] = function () {
oldHook.apply(this, arguments);
hook.apply(this, arguments);
};
} else {
def[hookKey] = hook;
}
}
}
/* */
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, fn, event, capture, once;
for (name in on) {
cur = on[name];
old = oldOn[name];
if (!cur) {
"development" !== 'production' && warn(
"Invalid handler for event \"" + name + "\": got " + String(cur),
vm
);
} else if (!old) {
once = name.charAt(0) === '~'; // Prefixed last, checked first
event = once ? name.slice(1) : name;
capture = event.charAt(0) === '!';
event = capture ? event.slice(1) : event;
if (Array.isArray(cur)) {
add(event, (cur.invoker = arrInvoker(cur)), once, capture);
} else {
if (!cur.invoker) {
fn = cur;
cur = on[name] = {};
cur.fn = fn;
cur.invoker = fnInvoker(cur);
}
add(event, cur.invoker, once, capture);
}
} else if (cur !== old) {
if (Array.isArray(old)) {
old.length = cur.length;
for (var i = 0; i < old.length; i++) { old[i] = cur[i]; }
on[name] = old;
} else {
old.fn = cur;
on[name] = old;
}
}
}
for (name in oldOn) {
if (!on[name]) {
once = name.charAt(0) === '~'; // Prefixed last, checked first
event = once ? name.slice(1) : name;
capture = event.charAt(0) === '!';
event = capture ? event.slice(1) : event;
remove$$1(event, oldOn[name].invoker, capture);
}
}
}
function arrInvoker (arr) {
return function (ev) {
var arguments$1 = arguments;
var single = arguments.length === 1;
for (var i = 0; i < arr.length; i++) {
single ? arr[i](ev) : arr[i].apply(null, arguments$1);
}
}
}
function fnInvoker (o) {
return function (ev) {
var single = arguments.length === 1;
single ? o.fn(ev) : o.fn.apply(null, arguments);
}
}
/* */
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (c == null || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (last && last.text) {
last.text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (c.text && last && last.text) {
res[res.length - 1] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (c.tag && c.key == null && nestedIndex != null) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function getFirstComponentChild (children) {
return children && children.filter(function (c) { return c && c.componentOptions; })[0]
}
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
var listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
var target;
function add$1 (event, fn, once) {
if (once) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$2 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add$1, remove$2, vm);
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
var activeInstance = null;
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._mount = function (
el,
hydrating
) {
var vm = this;
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
{
/* istanbul ignore if */
if (vm.$options.template && vm.$options.template.charAt(0) !== '#') {
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
vm._watcher = new Watcher(vm, function () {
vm._update(vm._render(), hydrating);
}, noop);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
};
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var prevActiveInstance = activeInstance;
activeInstance = vm;
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(
vm.$el, vnode, hydrating, false /* removeOnly */,
vm.$options._parentElm,
vm.$options._refElm
);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
if (vm._isMounted) {
callHook(vm, 'updated');
}
};
Vue.prototype._updateFromParent = function (
propsData,
listeners,
parentVnode,
renderChildren
) {
var vm = this;
var hasChildren = !!(vm.$options._renderChildren || renderChildren);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
{
observerState.isSettingProps = true;
}
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
vm[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
{
observerState.isSettingProps = false;
}
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove$1(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
};
}
function callHook (vm, hook) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
handlers[i].call(vm);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 };
var hooksToMerge = Object.keys(hooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (!Ctor) {
return
}
var baseCtor = context.$options._base;
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
if (typeof Ctor !== 'function') {
{
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
if (!Ctor.cid) {
if (Ctor.resolved) {
Ctor = Ctor.resolved;
} else {
Ctor = resolveAsyncComponent(Ctor, baseCtor, function () {
// it's ok to queue this on every render because
// $forceUpdate is buffered by the scheduler.
context.$forceUpdate();
});
if (!Ctor) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
data = data || {};
// extract props
var propsData = extractProps(data, Ctor);
// functional component
if (Ctor.options.functional) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
data.on = data.nativeOn;
if (Ctor.options.abstract) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
);
return vnode
}
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (propOptions) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData);
}
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
props: props,
data: data,
parent: context,
children: children,
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (inlineTemplate) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.child || vnode.child._isDestroyed) {
var child = vnode.child = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
prepatch(mountedNode, mountedNode);
}
}
function prepatch (
oldVnode,
vnode
) {
var options = vnode.componentOptions;
var child = vnode.child = oldVnode.child;
child._updateFromParent(
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
}
function insert (vnode) {
if (!vnode.child._isMounted) {
vnode.child._isMounted = true;
callHook(vnode.child, 'mounted');
}
if (vnode.data.keepAlive) {
vnode.child._inactive = false;
callHook(vnode.child, 'activated');
}
}
function destroy$1 (vnode) {
if (!vnode.child._isDestroyed) {
if (!vnode.data.keepAlive) {
vnode.child.$destroy();
} else {
vnode.child._inactive = true;
callHook(vnode.child, 'deactivated');
}
}
}
function resolveAsyncComponent (
factory,
baseCtor,
cb
) {
if (factory.requested) {
// pool callbacks
factory.pendingCallbacks.push(cb);
} else {
factory.requested = true;
var cbs = factory.pendingCallbacks = [cb];
var sync = true;
var resolve = function (res) {
if (isObject(res)) {
res = baseCtor.extend(res);
}
// cache resolved
factory.resolved = res;
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i](res);
}
}
};
var reject = function (reason) {
"development" !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
};
var res = factory(resolve, reject);
// handle promise
if (res && typeof res.then === 'function' && !factory.resolved) {
res.then(resolve, reject);
}
sync = false;
// return in case resolved synchronously
return factory.resolved
}
}
function extractProps (data, Ctor) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (!propOptions) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
var domProps = data.domProps;
if (attrs || props || domProps) {
for (var key in propOptions) {
var altKey = hyphenate(key);
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey) ||
checkProp(res, domProps, key, altKey);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (hash) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = hooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
/* */
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
needNormalization,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
needNormalization = children;
children = data;
data = undefined;
}
if (alwaysNormalize) { needNormalization = true; }
return _createElement(context, tag, data, children, needNormalization)
}
function _createElement (
context,
tag,
data,
children,
needNormalization
) {
if (data && data.__ob__) {
"development" !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function') {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (needNormalization) {
children = normalizeChildren(children);
}
var vnode, ns;
if (typeof tag === 'string') {
var Ctor;
ns = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
ns = tag === 'foreignObject' ? 'xhtml' : ns;
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (vnode) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.children) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (child.tag && !child.ns) {
applyNS(child, ns);
}
}
}
}
/* */
function initRender (vm) {
vm.$vnode = null; // the placeholder node in parent tree
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
var parentVnode = vm.$options._parentVnode;
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext);
vm.$scopedSlots = {};
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, needNormalization, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
if (_parentVnode && _parentVnode.data.scopedSlots) {
vm.$scopedSlots = _parentVnode.data.scopedSlots;
}
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, vm);
} else {
{
warn(("Error when rendering " + (formatComponentName(vm)) + ":"));
}
throw e
}
// return previous vnode to prevent render error causing blank component
vnode = vm._vnode;
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if ("development" !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
// toString for mustaches
Vue.prototype._s = _toString;
// convert text to vnode
Vue.prototype._v = createTextVNode;
// number conversion
Vue.prototype._n = toNumber;
// empty vnode
Vue.prototype._e = createEmptyVNode;
// loose equal
Vue.prototype._q = looseEqual;
// loose indexOf
Vue.prototype._i = looseIndexOf;
// render static tree by index
Vue.prototype._m = function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy);
markStatic(tree, ("__static__" + index), false);
return tree
};
// mark node as static (v-once)
Vue.prototype._o = function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
};
function markStatic (tree, key, isOnce) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
// filter resolution helper
Vue.prototype._f = function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
};
// render v-for
Vue.prototype._l = function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val)) {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
return ret
};
// renderSlot
Vue.prototype._t = function (
name,
fallback,
props
) {
var scopedSlotFn = this.$scopedSlots[name];
if (scopedSlotFn) { // scoped slot
return scopedSlotFn(props || {}) || fallback
} else {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && "development" !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
}
};
// apply v-bind object
Vue.prototype._b = function bindProps (
data,
tag,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
"development" !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
for (var key in value) {
if (key === 'class' || key === 'style') {
data[key] = value[key];
} else {
var hash = asProp || config.mustUseProp(tag, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
hash[key] = value[key];
}
}
}
}
return data
};
// check v-on keyCodes
Vue.prototype._k = function checkKeyCodes (
eventKeyCode,
key,
builtInAlias
) {
var keyCodes = config.keyCodes[key] || builtInAlias;
if (Array.isArray(keyCodes)) {
return keyCodes.indexOf(eventKeyCode) === -1
} else {
return keyCodes !== eventKeyCode
}
};
}
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
var name, child;
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && (name = child.data.slot)) {
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore single whitespace
if (defaultSlot.length && !(
defaultSlot.length === 1 &&
(defaultSlot[0].text === ' ' || defaultSlot[0].isComment)
)) {
slots.default = defaultSlot;
}
return slots
}
/* */
var uid = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid++;
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
{
initProxy(vm);
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
callHook(vm, 'beforeCreate');
initState(vm);
callHook(vm, 'created');
initRender(vm);
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
opts._parentElm = options._parentElm;
opts._refElm = options._refElm;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = Ctor.super.options;
var cachedSuperOptions = Ctor.superOptions;
var extendOptions = Ctor.extendOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed
Ctor.superOptions = superOptions;
extendOptions.render = options.render;
extendOptions.staticRenderFns = options.staticRenderFns;
extendOptions._scopeId = options._scopeId;
options = Ctor.options = mergeOptions(superOptions, extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function Vue$3 (options) {
if ("development" !== 'production' &&
!(this instanceof Vue$3)) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue$3);
stateMixin(Vue$3);
eventsMixin(Vue$3);
lifecycleMixin(Vue$3);
renderMixin(Vue$3);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else {
plugin.apply(null, args);
}
plugin.installed = true;
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
{
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characters and the hyphen, ' +
'and must start with a letter.'
);
}
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
config._assetTypes.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
config._assetTypes.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
{
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + id
);
}
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
var patternTypes = [String, RegExp];
function matches (pattern, name) {
if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else {
return pattern.test(name)
}
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes
},
created: function created () {
this.cache = Object.create(null);
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default);
if (vnode && vnode.componentOptions) {
var opts = vnode.componentOptions;
// check pattern
var name = opts.Ctor.options.name || opts.tag;
if (name && (
(this.include && !matches(this.include, name)) ||
(this.exclude && matches(this.exclude, name))
)) {
return vnode
}
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? opts.Ctor.cid + (opts.tag ? ("::" + (opts.tag)) : '')
: vnode.key;
if (this.cache[key]) {
vnode.child = this.cache[key].child;
} else {
this.cache[key] = vnode;
}
vnode.data.keepAlive = true;
}
return vnode
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this.cache) {
var vnode = this$1.cache[key];
callHook(vnode.child, 'deactivated');
vnode.child.$destroy();
}
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
{
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
Vue.util = util;
Vue.set = set$1;
Vue.delete = del;
Vue.nextTick = nextTick;
Vue.options = Object.create(null);
config._assetTypes.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue$3);
Object.defineProperty(Vue$3.prototype, '$isServer', {
get: isServerRendering
});
Vue$3.version = '2.1.6';
/* */
// attributes that should be using props for binding
var acceptValue = makeMap('input,textarea,option,select');
var mustUseProp = function (tag, attr) {
return (
(attr === 'value' && acceptValue(tag)) ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
};
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
var xlinkNS = 'http://www.w3.org/1999/xlink';
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
};
var isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (childNode.child) {
childNode = childNode.child._vnode;
if (childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while ((parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return genClassFromData(data)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: child.class
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class;
var staticClass = data.staticClass;
if (staticClass || dynamicClass) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
var res = '';
if (!value) {
return res
}
if (typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (value[i]) {
if ((stringified = stringifyClass(value[i]))) {
res += stringified + ' ';
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' '; }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML',
xhtml: 'http://www.w3.org/1999/xhtml'
};
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,' +
'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isPreTag = function (tag) { return tag === 'pre'; };
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selector = el;
el = document.querySelector(el);
if (!el) {
"development" !== 'production' && warn(
'Cannot find element: ' + selector
);
return document.createElement('div')
}
}
return el
}
/* */
function createElement$1 (tagName, vnode) {
var elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function setAttribute (node, key, val) {
node.setAttribute(key, val);
}
var nodeOps = Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setAttribute: setAttribute
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode);
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref;
if (!key) { return }
var vm = vnode.context;
var ref = vnode.child || vnode.elm;
var refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove$1(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) {
refs[key].push(ref);
} else {
refs[key] = [ref];
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
/*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyNode = new VNode('', {}, []);
var hooks$1 = ['create', 'activate', 'update', 'remove', 'destroy'];
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
vnode1.isComment === vnode2.isComment &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key;
var map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) { map[key] = i; }
}
return map
}
function createPatchFunction (backend) {
var i, j;
var cbs = {};
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks$1.length; ++i) {
cbs[hooks$1[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]); }
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeElement(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeElement (el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html
if (parent) {
nodeOps.removeChild(parent, el);
}
}
var inPre = 0;
function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) {
vnode.isRootInsert = !nested; // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
var data = vnode.data;
var children = vnode.children;
var tag = vnode.tag;
if (isDef(tag)) {
{
if (data && data.pre) {
inPre++;
}
if (
!inPre &&
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
/* istanbul ignore if */
{
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
if ("development" !== 'production' && data && data.pre) {
inPre--;
}
} else if (vnode.isComment) {
vnode.elm = nodeOps.createComment(vnode.text);
insert(parentElm, vnode.elm, refElm);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
insert(parentElm, vnode.elm, refElm);
}
}
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i = vnode.data;
if (isDef(i)) {
var isReactivated = isDef(vnode.child) && i.keepAlive;
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */, parentElm, refElm);
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.child)) {
initComponent(vnode, insertedVnodeQueue);
if (isReactivated) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
}
return true
}
}
}
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i;
// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
var innerNode = vnode;
while (innerNode.child) {
innerNode = innerNode.child._vnode;
if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
for (i = 0; i < cbs.activate.length; ++i) {
cbs.activate[i](emptyNode, innerNode);
}
insertedVnodeQueue.push(innerNode);
break
}
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}
function insert (parent, elm, ref) {
if (parent) {
if (ref) {
nodeOps.insertBefore(parent, elm, ref);
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text));
}
}
function isPatchable (vnode) {
while (vnode.child) {
vnode = vnode.child._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (i.create) { i.create(emptyNode, vnode); }
if (i.insert) { insertedVnodeQueue.push(vnode); }
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
}
vnode.elm = vnode.child.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i;
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
if (isDef(i = activeInstance) &&
i !== vnode.context &&
isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm);
}
}
function invokeDestroyHook (vnode) {
var i, j;
var data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
var listeners = cbs.remove.length + 1;
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners);
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeElement(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0;
var newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, refElm;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null;
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
/* istanbul ignore if */
if ("development" !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
);
}
if (sameVnode(elmToMove, newStartVnode)) {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (vnode.isStatic &&
oldVnode.isStatic &&
vnode.key === oldVnode.key &&
(vnode.isCloned || vnode.isOnce)) {
vnode.elm = oldVnode.elm;
vnode.child = oldVnode.child;
return
}
var i;
var data = vnode.data;
var hasData = isDef(data);
if (hasData && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
var elm = vnode.elm = oldVnode.elm;
var oldCh = oldVnode.children;
var ch = vnode.children;
if (hasData && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (hasData) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue;
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
var bailed = false;
// list of modules that can skip create hook during hydration because they
// are already rendered on the client or has no need for initialization
var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue) {
{
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (!elm.hasChildNodes()) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
var childrenMatch = true;
var childNode = elm.firstChild;
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) {
childrenMatch = false;
break
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) {
if ("development" !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
if (isDef(data)) {
for (var key in data) {
if (!isRenderedModule(key)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
}
}
return true
}
function assertNodeMatch (node, vnode) {
if (vnode.tag) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return _toString(vnode.text) === node.data
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {
if (!vnode) {
if (oldVnode) { invokeDestroyHook(oldVnode); }
return
}
var elm, parent;
var isInitialPatch = false;
var insertedVnodeQueue = [];
if (!oldVnode) {
// empty mount (likely as component), create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue, parentElm, refElm);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered');
hydrating = true;
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
// replacing existing element
elm = oldVnode.elm;
parent = nodeOps.parentNode(elm);
createElm(vnode, insertedVnodeQueue, parent, nodeOps.nextSibling(elm));
if (vnode.parent) {
// component root element replaced.
// update parent placeholder node element, recursively
var ancestor = vnode.parent;
while (ancestor) {
ancestor.elm = vnode.elm;
ancestor = ancestor.parent;
}
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent);
}
}
}
if (parent !== null) {
removeVnodes(parent, [oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode);
}
}
function _update (oldVnode, vnode) {
var isCreate = oldVnode === emptyNode;
var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
var dirsWithInsert = [];
var dirsWithPostpatch = [];
var key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
var callInsert = function () {
for (var i = 0; i < dirsWithInsert.length; i++) {
callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
}
};
if (isCreate) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert, 'dir-insert');
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () {
for (var i = 0; i < dirsWithPostpatch.length; i++) {
callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}
}, 'dir-postpatch');
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode);
}
}
}
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
var res = Object.create(null);
if (!dirs) {
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
return res
}
function getRawDirName (dir) {
return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
}
function callHook$1 (dir, hook, vnode, oldVnode) {
var fn = dir.def && dir.def[hook];
if (fn) {
fn(vnode.elm, dir, vnode, oldVnode);
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
if (!oldVnode.data.attrs && !vnode.data.attrs) {
return
}
var key, cur, old;
var elm = vnode.elm;
var oldAttrs = oldVnode.data.attrs || {};
var attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (attrs.__ob__) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur);
}
}
// #4391: in IE9, setting type can reset value for input[type=radio]
/* istanbul ignore if */
if (isIE9 && attrs.value !== oldAttrs.value) {
setAttr(elm, 'value', attrs.value);
}
for (key in oldAttrs) {
if (attrs[key] == null) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value) {
if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, key);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true');
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, value);
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var data = vnode.data;
var oldData = oldVnode.data;
if (!data.staticClass && !data.class &&
(!oldData || (!oldData.staticClass && !oldData.class))) {
return
}
var cls = genClassForVnode(vnode);
// handle transition classes
var transitionClass = el._transitionClasses;
if (transitionClass) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
/* */
var target$1;
function add$2 (event, handler, once, capture) {
if (once) {
var oldHandler = handler;
handler = function (ev) {
remove$3(event, handler, capture);
arguments.length === 1
? oldHandler(ev)
: oldHandler.apply(null, arguments);
};
}
target$1.addEventListener(event, handler, capture);
}
function remove$3 (event, handler, capture) {
target$1.removeEventListener(event, handler, capture);
}
function updateDOMListeners (oldVnode, vnode) {
if (!oldVnode.data.on && !vnode.data.on) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
target$1 = vnode.elm;
updateListeners(on, oldOn, add$2, remove$3, vnode.context);
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
function updateDOMProps (oldVnode, vnode) {
if (!oldVnode.data.domProps && !vnode.data.domProps) {
return
}
var key, cur;
var elm = vnode.elm;
var oldProps = oldVnode.data.domProps || {};
var props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (props.__ob__) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (props[key] == null) {
elm[key] = '';
}
}
for (key in props) {
cur = props[key];
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (key === 'textContent' || key === 'innerHTML') {
if (vnode.children) { vnode.children.length = 0; }
if (cur === oldProps[key]) { continue }
}
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = cur == null ? '' : String(cur);
if (!elm.composing && (
(document.activeElement !== elm && elm.value !== strCur) ||
isValueChanged(vnode, strCur)
)) {
elm.value = strCur;
}
} else {
elm[key] = cur;
}
}
}
function isValueChanged (vnode, newVal) {
var value = vnode.elm.value;
var modifiers = vnode.elm._vModifiers; // injected by v-model runtime
if ((modifiers && modifiers.number) || vnode.elm.type === 'number') {
return toNumber(value) !== toNumber(newVal)
}
if (modifiers && modifiers.trim) {
return value.trim() !== newVal.trim()
}
return value !== newVal
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
var parseStyleText = cached(function (cssText) {
var res = {};
var listDelimiter = /;(?![^(]*\))/g;
var propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data) {
var style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
function getStyle (vnode, checkChild) {
var res = {};
var styleData;
if (checkChild) {
var childNode = vnode;
while (childNode.child) {
childNode = childNode.child._vnode;
if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
var parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
/* */
var cssVarRE = /^--/;
var importantRE = /\s*!important$/;
var setProp = function (el, name, val) {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else if (importantRE.test(val)) {
el.style.setProperty(name, val.replace(importantRE, ''), 'important');
} else {
el.style[normalize(name)] = val;
}
};
var prefixes = ['Webkit', 'Moz', 'ms'];
var testEl;
var normalize = cached(function (prop) {
testEl = testEl || document.createElement('div');
prop = camelize(prop);
if (prop !== 'filter' && (prop in testEl.style)) {
return prop
}
var upper = prop.charAt(0).toUpperCase() + prop.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefixed = prefixes[i] + upper;
if (prefixed in testEl.style) {
return prefixed
}
}
});
function updateStyle (oldVnode, vnode) {
var data = vnode.data;
var oldData = oldVnode.data;
if (!data.staticStyle && !data.style &&
!oldData.staticStyle && !oldData.style) {
return
}
var cur, name;
var el = vnode.elm;
var oldStaticStyle = oldVnode.data.staticStyle;
var oldStyleBinding = oldVnode.data.style || {};
// if static style exists, stylebinding already merged into it when doing normalizeStyleData
var oldStyle = oldStaticStyle || oldStyleBinding;
var style = normalizeStyleBinding(vnode.data.style) || {};
vnode.data.style = style.__ob__ ? extend({}, style) : style;
var newStyle = getStyle(vnode, true);
for (name in oldStyle) {
if (newStyle[name] == null) {
setProp(el, name, '');
}
}
for (name in newStyle) {
cur = newStyle[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !cls.trim()) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); });
} else {
el.classList.add(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !cls.trim()) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
el.setAttribute('class', cur.trim());
}
}
/* */
var hasTransition = inBrowser && !isIE9;
var TRANSITION = 'transition';
var ANIMATION = 'animation';
// Transition property/event sniffing
var transitionProp = 'transition';
var transitionEndEvent = 'transitionend';
var animationProp = 'animation';
var animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
var raf = (inBrowser && window.requestAnimationFrame) || setTimeout;
function nextFrame (fn) {
raf(function () {
raf(fn);
});
}
function addTransitionClass (el, cls) {
(el._transitionClasses || (el._transitionClasses = [])).push(cls);
addClass(el, cls);
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove$1(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
var ended = 0;
var end = function () {
el.removeEventListener(event, onEnd);
cb();
};
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(function () {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el);
var transitioneDelays = styles[transitionProp + 'Delay'].split(', ');
var transitionDurations = styles[transitionProp + 'Duration'].split(', ');
var transitionTimeout = getTimeout(transitioneDelays, transitionDurations);
var animationDelays = styles[animationProp + 'Delay'].split(', ');
var animationDurations = styles[animationProp + 'Duration'].split(', ');
var animationTimeout = getTimeout(animationDelays, animationDurations);
var type;
var timeout = 0;
var propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
function toMs (s) {
return Number(s.slice(0, -1)) * 1000
}
/* */
function enter (vnode, toggleDisplay) {
var el = vnode.elm;
// call leave callback now
if (el._leaveCb) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
var data = resolveTransition(vnode.data.transition);
if (!data) {
return
}
/* istanbul ignore if */
if (el._enterCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var enterClass = data.enterClass;
var enterActiveClass = data.enterActiveClass;
var appearClass = data.appearClass;
var appearActiveClass = data.appearActiveClass;
var beforeEnter = data.beforeEnter;
var enter = data.enter;
var afterEnter = data.afterEnter;
var enterCancelled = data.enterCancelled;
var beforeAppear = data.beforeAppear;
var appear = data.appear;
var afterAppear = data.afterAppear;
var appearCancelled = data.appearCancelled;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var context = activeInstance;
var transitionNode = activeInstance.$vnode;
while (transitionNode && transitionNode.parent) {
transitionNode = transitionNode.parent;
context = transitionNode.context;
}
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear ? appearClass : enterClass;
var activeClass = isAppear ? appearActiveClass : enterActiveClass;
var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter;
var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter;
var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter;
var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled;
var expectsCSS = css !== false && !isIE9;
var userWantsControl =
enterHook &&
// enterHook may be a bound method which exposes
// the length of original fn as _length
(enterHook._length || enterHook.length) > 1;
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
var parent = el.parentNode;
var pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode &&
pendingNode.context === vnode.context &&
pendingNode.tag === vnode.tag &&
pendingNode.elm._leaveCb) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
}, 'transition-insert');
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(function () {
removeTransitionClass(el, startClass);
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb);
}
});
}
if (vnode.data.show) {
toggleDisplay && toggleDisplay();
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
var el = vnode.elm;
// call enter callback now
if (el._enterCb) {
el._enterCb.cancelled = true;
el._enterCb();
}
var data = resolveTransition(vnode.data.transition);
if (!data) {
return rm()
}
/* istanbul ignore if */
if (el._leaveCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var leaveClass = data.leaveClass;
var leaveActiveClass = data.leaveActiveClass;
var beforeLeave = data.beforeLeave;
var leave = data.leave;
var afterLeave = data.afterLeave;
var leaveCancelled = data.leaveCancelled;
var delayLeave = data.delayLeave;
var expectsCSS = css !== false && !isIE9;
var userWantsControl =
leave &&
// leave hook may be a bound method which exposes
// the length of original fn as _length
(leave._length || leave.length) > 1;
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show) {
(el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(function () {
removeTransitionClass(el, leaveClass);
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb);
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
leaveClass: (name + "-leave"),
appearClass: (name + "-enter"),
enterActiveClass: (name + "-enter-active"),
leaveActiveClass: (name + "-leave-active"),
appearActiveClass: (name + "-enter-active")
}
});
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn();
}
}
}
function _enter (_, vnode) {
if (!vnode.data.show) {
enter(vnode);
}
}
var transition = inBrowser ? {
create: _enter,
activate: _enter,
remove: function remove (vnode, rm) {
/* istanbul ignore else */
if (!vnode.data.show) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules);
var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/;
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
var model = {
inserted: function inserted (el, binding, vnode) {
{
if (!modelableTagRE.test(vnode.tag)) {
warn(
"v-model is not supported on element type: <" + (vnode.tag) + ">. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
vnode.context
);
}
}
if (vnode.tag === 'select') {
var cb = function () {
setSelected(el, binding, vnode.context);
};
cb();
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(cb, 0);
}
} else if (vnode.tag === 'textarea' || el.type === 'text') {
el._vModifiers = binding.modifiers;
if (!binding.modifiers.lazy) {
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options);
if (needReset) {
trigger(el, 'change');
}
}
}
};
function setSelected (el, binding, vm) {
var value = binding.value;
var isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
"development" !== 'production' && warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
);
return
}
var selected, option;
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
for (var i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.child && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.child._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
var originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? '' : el.style.display;
if (value && transition && !isIE9) {
vnode.data.show = true;
enter(vnode, function () {
el.style.display = originalDisplay;
});
} else {
el.style.display = value ? originalDisplay : 'none';
}
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (value === oldValue) { return }
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
if (transition && !isIE9) {
vnode.data.show = true;
if (value) {
enter(vnode, function () {
el.style.display = el.__vOriginalDisplay;
});
} else {
leave(vnode, function () {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
}
};
var platformDirectives = {
model: model,
show: show
};
/* */
// Provides transition support for a single element/component.
// supports transition mode (out-in / in-out)
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {};
var options = comp.$options;
// props
for (var key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1].fn;
}
return data
}
function placeholder (h, rawChild) {
return /\d-keep-alive$/.test(rawChild.tag)
? h('keep-alive')
: null
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(function (c) { return c.tag; });
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if ("development" !== 'production' && children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
var mode = this.mode;
// warn invalid mode
if ("development" !== 'production' &&
mode && mode !== 'in-out' && mode !== 'out-in') {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
var key = child.key = child.key == null || child.isStatic
? ("__v" + (child.tag + this._uid) + "__")
: child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this);
var oldRawChild = this._vnode;
var oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {
child.data.show = true;
}
if (oldChild && oldChild.data && oldChild.key !== key) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild.data.transition = extend({}, data);
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false;
this$1.$forceUpdate();
}, key);
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
var delayedLeave;
var performLeave = function () { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave, key);
mergeVNodeHook(data, 'enterCancelled', performLeave, key);
mergeVNodeHook(oldData, 'delayLeave', function (leave) {
delayedLeave = leave;
}, key);
}
}
return rawChild
}
};
/* */
// Provides transition support for list items.
// supports move transitions using the FLIP technique.
// Because the vdom's children update algorithm is "unstable" - i.e.
// it doesn't guarantee the relative positioning of removed elements,
// we force transition-group to update its children into two passes:
// in the first pass, we remove all nodes that need to be removed,
// triggering their leaving transition; in the second pass, we insert/move
// into the final disired state. This way in the second pass removed
// nodes will remain where they should be.
var props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props: props,
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span';
var map = Object.create(null);
var prevChildren = this.prevChildren = this.children;
var rawChildren = this.$slots.default || [];
var children = this.children = [];
var transitionData = extractTransitionData(this);
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else {
var opts = c.componentOptions;
var name = opts
? (opts.Ctor.options.name || opts.tag)
: c.tag;
warn(("<transition-group> children must be keyed: <" + name + ">"));
}
}
}
if (prevChildren) {
var kept = [];
var removed = [];
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData;
c$1.data.pos = c$1.elm.getBoundingClientRect();
if (map[c$1.key]) {
kept.push(c$1);
} else {
removed.push(c$1);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
beforeUpdate: function beforeUpdate () {
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this._vnode = this.kept;
},
updated: function updated () {
var children = this.prevChildren;
var moveClass = this.moveClass || ((this.name || 'v') + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
var f = document.body.offsetHeight; // eslint-disable-line
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm;
var s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
if (this._hasMove != null) {
return this._hasMove
}
addTransitionClass(el, moveClass);
var info = getTransitionInfo(el);
removeTransitionClass(el, moveClass);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
var oldPos = c.data.pos;
var newPos = c.data.newPos;
var dx = oldPos.left - newPos.left;
var dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)";
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
/* */
// install platform specific utils
Vue$3.config.isUnknownElement = isUnknownElement;
Vue$3.config.isReservedTag = isReservedTag;
Vue$3.config.getTagNamespace = getTagNamespace;
Vue$3.config.mustUseProp = mustUseProp;
// install platform runtime directives & components
extend(Vue$3.options.directives, platformDirectives);
extend(Vue$3.options.components, platformComponents);
// install platform patch function
Vue$3.prototype.__patch__ = inBrowser ? patch$1 : noop;
// wrap mount
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && inBrowser ? query(el) : undefined;
return this._mount(el, hydrating)
};
// devtools global hook
/* istanbul ignore next */
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue$3);
} else if (
"development" !== 'production' &&
inBrowser && !isEdge && /Chrome\/\d+/.test(window.navigator.userAgent)
) {
console.log(
'Download the Vue Devtools for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
}, 0);
/* */
// check whether current browser encodes a char inside attribute values
function shouldDecode (content, encoded) {
var div = document.createElement('div');
div.innerHTML = "<div a=\"" + content + "\">";
return div.innerHTML.indexOf(encoded) > 0
}
// #3663
// IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', ' ') : false;
/* */
var decoder;
function decode (html) {
decoder = decoder || document.createElement('div');
decoder.innerHTML = html;
return decoder.textContent
}
/* */
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr',
true
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source',
true
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track',
true
);
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^<!DOCTYPE [^>]+>/i;
var comment = /^<!--/;
var conditionalComment = /^<!\[/;
var IS_REGEX_CAPTURING_BROKEN = false;
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === '';
});
// Special Elements (can contain anything)
var isScriptOrStyle = makeMap('script,style', true);
var hasLang = function (attr) { return attr.name === 'lang' && attr.value !== 'html'; };
var isSpecialTag = function (tag, isSFC, stack) {
if (isScriptOrStyle(tag)) {
return true
}
if (isSFC && stack.length === 1) {
// top-level template that has no pre-processor
if (tag === 'template' && !stack[0].attrs.some(hasLang)) {
return false
} else {
return true
}
}
return false
};
var reCache = {};
var ltRE = /</g;
var gtRE = />/g;
var nlRE = / /g;
var ampRE = /&/g;
var quoteRE = /"/g;
function decodeAttr (value, shouldDecodeNewlines) {
if (shouldDecodeNewlines) {
value = value.replace(nlRE, '\n');
}
return value
.replace(ltRE, '<')
.replace(gtRE, '>')
.replace(ampRE, '&')
.replace(quoteRE, '"')
}
function parseHTML (html, options) {
var stack = [];
var expectHTML = options.expectHTML;
var isUnaryTag$$1 = options.isUnaryTag || no;
var index = 0;
var last, lastTag;
while (html) {
last = html;
// Make sure we're not in a script or style element
if (!lastTag || !isSpecialTag(lastTag, options.sfc, stack)) {
var textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[0], endTagMatch[1], curIndex, index);
continue
}
// Start tag:
var startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
continue
}
}
var text = (void 0), rest$1 = (void 0), next = (void 0);
if (textEnd > 0) {
rest$1 = html.slice(textEnd);
while (
!endTag.test(rest$1) &&
!startTagOpen.test(rest$1) &&
!comment.test(rest$1) &&
!conditionalComment.test(rest$1)
) {
// < in plain text, be forgiving and treat it as text
next = rest$1.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest$1 = html.slice(textEnd);
}
text = html.substring(0, textEnd);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
var endTagLength = 0;
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag('</' + stackedTag + '>', stackedTag, index - endTagLength, index);
}
if (html === last && options.chars) {
options.chars(html);
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
var start = html.match(startTagOpen);
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
var end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length);
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
var tagName = match.tagName;
var unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag('', lastTag);
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag('', tagName);
}
}
var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, attrs: attrs });
lastTag = tagName;
unarySlash = '';
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tag, tagName, start, end) {
var pos;
if (start == null) { start = index; }
if (end == null) { end = index; }
// Find the closest opened tag of the same type
if (tagName) {
var needle = tagName.toLowerCase();
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].tag.toLowerCase() === needle) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (tagName.toLowerCase() === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (tagName.toLowerCase() === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
function parseFilters (exp) {
var inSingle = false;
var inDouble = false;
var inTemplateString = false;
var inRegex = false;
var curly = 0;
var square = 0;
var paren = 0;
var lastFilterIndex = 0;
var c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) { inSingle = false; }
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) { inDouble = false; }
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) { inRegex = false; }
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
if (c === 0x2f) { // /
var j = i - 1;
var p = (void 0);
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j);
if (p !== ' ') { break }
}
if (!p || !/[\w$]/.test(p)) {
inRegex = true;
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
var name = filter.slice(0, i);
var args = filter.slice(i + 1);
return ("_f(\"" + name + "\")(" + exp + "," + args)
}
}
/* */
var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g;
var regexEscapeRE = /[-.*+?^${}()|[\]/\\]/g;
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&');
var close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
var tokens = [];
var lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
function baseWarn (msg) {
console.error(("[Vue parser]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important
) {
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, modifiers: modifiers };
var handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
}
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
var staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
function getAndRemoveAttr (el, name) {
var val;
if ((val = el.attrsMap[name]) != null) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
return val
}
var len;
var str;
var chr;
var index$1;
var expressionPos;
var expressionEndPos;
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
function parseModel (val) {
str = val;
len = str.length;
index$1 = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var bindRE = /^:|^v-bind:/;
var onRE = /^@|^v-on:/;
var argRE = /:(.*)$/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(decode);
// configurable state
var warn$1;
var platformGetTagNamespace;
var platformMustUseProp;
var platformIsPreTag;
var preTransforms;
var transforms;
var postTransforms;
var delimiters;
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$1 = options.warn || baseWarn;
platformGetTagNamespace = options.getTagNamespace || no;
platformMustUseProp = options.mustUseProp || no;
platformIsPreTag = options.isPreTag || no;
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
transforms = pluckModuleFunction(options.modules, 'transformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
parseHTML(template, {
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start: function start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
var element = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
"development" !== 'production' && warn$1(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
"<" + tag + ">."
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if ("development" !== 'production' && !warned) {
if (el.tag === 'slot' || el.tag === 'template') {
warned = true;
warn$1(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes:\n' + template
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warned = true;
warn$1(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements:\n' + template
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element);
addIfCondition(root, {
exp: element.elseif,
block: element
});
} else if ("development" !== 'production' && !warned) {
warned = true;
warn$1(
"Component template should contain exactly one root element:" +
"\n\n" + template + "\n\n" +
"If you are using v-if on multiple elements, " +
"use v-else-if to chain them instead."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || 'default';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ') {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
},
chars: function chars (text) {
if (!currentParent) {
if ("development" !== 'production' && !warned && text === template) {
warned = true;
warn$1(
'Component template requires a root element, rather than just text:\n\n' + template
);
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && currentParent.children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
currentParent.children.push({
type: 2,
expression: expression,
text: text
});
} else {
currentParent.children.push({
type: 3,
text: text
});
}
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if ("development" !== 'production' && el.tag === 'template') {
warn$1("<template> cannot be keyed. Place the key on real elements instead.");
}
el.key = exp;
}
}
function processRef (el) {
var ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
var exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var inMatch = exp.match(forAliasRE);
if (!inMatch) {
"development" !== 'production' && warn$1(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
function processIf (el) {
var exp = getAndRemoveAttr(el, 'v-if');
if (exp) {
el.if = exp;
addIfCondition(el, {
exp: exp,
block: el
});
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true;
}
var elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
var prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else {
warn$1(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = [];
}
el.ifConditions.push(condition);
}
function processOnce (el) {
var once = getAndRemoveAttr(el, 'v-once');
if (once != null) {
el.once = true;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if ("development" !== 'production' && el.key) {
warn$1(
"`key` does not work on <slot> because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
function processComponent (el) {
var binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
var list = el.attrsList;
var i, l, name, rawName, value, arg, modifiers, isProp;
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name;
value = list[i].value;
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true;
// modifiers
modifiers = parseModifiers(name);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
}
if (isProp || platformMustUseProp(el.tag, name)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
if (argMatch && (arg = argMatch[1])) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if ("development" !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
{
var expression = parseText(value, delimiters);
if (expression) {
warn$1(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
function checkInFor (el) {
var parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
match.forEach(function (m) { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
var map = {};
for (var i = 0, l = attrs.length; i < l; i++) {
if ("development" !== 'production' && map[attrs[i].name] && !isIE) {
warn$1('duplicate attribute: ' + attrs[i].name);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].tag) { return children[i] }
}
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
var ieNSBug = /^xmlns:NS\d+/;
var ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
var _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"You are binding v-model directly to a v-for iteration alias. " +
"This will not be able to modify the v-for source array because " +
"writing to the alias is like modifying a function local variable. " +
"Consider using an array of objects and use v-model on an object property instead."
);
}
_el = _el.parent;
}
}
/* */
var isStaticKey;
var isPlatformReservedTag;
var genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) { return }
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
markStatic(child);
if (!child.static) {
node.static = false;
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
walkThroughConditionsBlocks(node.ifConditions, isInFor);
}
}
}
function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
for (var i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].block, isInFor);
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: 'if($event.target !== $event.currentTarget)return;',
ctrl: 'if(!$event.ctrlKey)return;',
shift: 'if(!$event.shiftKey)return;',
alt: 'if(!$event.altKey)return;',
meta: 'if(!$event.metaKey)return;'
};
function genHandlers (events, native) {
var res = native ? 'nativeOn:{' : 'on:{';
for (var name in events) {
res += "\"" + name + "\":" + (genHandler(name, events[name])) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
} else if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
} else if (!handler.modifiers) {
return fnExpRE.test(handler.value) || simplePathRE.test(handler.value)
? handler.value
: ("function($event){" + (handler.value) + "}")
} else {
var code = '';
var keys = [];
for (var key in handler.modifiers) {
if (modifierCode[key]) {
code += modifierCode[key];
} else {
keys.push(key);
}
}
if (keys.length) {
code = genKeyFilter(keys) + code;
}
var handlerCode = simplePathRE.test(handler.value)
? handler.value + '($event)'
: handler.value;
return 'function($event){' + code + handlerCode + '}'
}
}
function genKeyFilter (keys) {
return ("if(" + (keys.map(genFilterCode).join('&&')) + ")return;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function bind$2 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
};
}
var baseDirectives = {
bind: bind$2,
cloak: noop
};
/* */
// configurable state
var warn$2;
var transforms$1;
var dataGenFns;
var platformDirectives$1;
var staticRenderFns;
var onceCount;
var currentOptions;
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
var prevStaticRenderFns = staticRenderFns;
var currentStaticRenderFns = staticRenderFns = [];
var prevOnceCount = onceCount;
onceCount = 0;
currentOptions = options;
warn$2 = options.warn || baseWarn;
transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
dataGenFns = pluckModuleFunction(options.modules, 'genData');
platformDirectives$1 = options.directives || {};
var code = ast ? genElement(ast) : '_c("div")';
staticRenderFns = prevStaticRenderFns;
onceCount = prevOnceCount;
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
}
}
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el);
} else {
var data = el.plain ? undefined : genData(el);
var children = el.inlineTemplate ? null : genChildren(el, true);
code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
code = transforms$1[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el) {
el.staticProcessed = true;
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
"development" !== 'production' && warn$2(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el)
}
return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
} else {
return genStatic(el)
}
}
function genIf (el) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice())
}
function genIfConditions (conditions) {
if (!conditions.length) {
return '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
}
function genFor (el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
function genData (el) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el);
if (dirs) { data += dirs + ','; }
// key
if (el.key) {
data += "key:" + (el.key) + ",";
}
// ref
if (el.ref) {
data += "ref:" + (el.ref) + ",";
}
if (el.refInFor) {
data += "refInFor:true,";
}
// pre
if (el.pre) {
data += "pre:true,";
}
// record original tag name for components using "is" attribute
if (el.component) {
data += "tag:\"" + (el.tag) + "\",";
}
// module data generation functions
for (var i = 0; i < dataGenFns.length; i++) {
data += dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += "attrs:{" + (genProps(el.attrs)) + "},";
}
// DOM props
if (el.props) {
data += "domProps:{" + (genProps(el.props)) + "},";
}
// event handlers
if (el.events) {
data += (genHandlers(el.events)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el.scopedSlots)) + ",";
}
// inline-template
if (el.inlineTemplate) {
var inlineTemplate = genInlineTemplate(el);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
return data
}
function genDirectives (el) {
var dirs = el.directives;
if (!dirs) { return }
var res = 'directives:[';
var hasRuntime = false;
var i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn$2);
}
if (needRuntime) {
hasRuntime = true;
res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el) {
var ast = el.children[0];
if ("development" !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$2('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate(ast, currentOptions);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (slots) {
return ("scopedSlots:{" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "}")
}
function genScopedSlot (key, el) {
return key + ":function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)) + "}"
}
function genChildren (el, checkSkip) {
var children = el.children;
if (children.length) {
var el$1 = children[0];
// optimize single v-for
if (children.length === 1 &&
el$1.for &&
el$1.tag !== 'template' &&
el$1.tag !== 'slot') {
return genElement(el$1)
}
return ("[" + (children.map(genNode).join(',')) + "]" + (checkSkip
? canSkipNormalization(children) ? '' : ',true'
: ''))
}
}
function canSkipNormalization (children) {
for (var i = 0; i < children.length; i++) {
var el = children[i];
if (needsNormalization(el) ||
(el.if && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {
return false
}
}
return true
}
function needsNormalization (el) {
return el.for || el.tag === 'template' || el.tag === 'slot'
}
function genNode (node) {
if (node.type === 1) {
return genElement(node)
} else {
return genText(node)
}
}
function genText (text) {
return ("_v(" + (text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))) + ")")
}
function genSlot (el) {
var slotName = el.slotName || '"default"';
var children = genChildren(el);
return ("_t(" + slotName + (children ? ("," + children) : '') + (el.attrs ? ((children ? '' : ',null') + ",{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}") : '') + ")")
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (componentName, el) {
var children = el.inlineTemplate ? null : genChildren(el, true);
return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
/**
* Compile a template.
*/
function compile$1 (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
}
/* */
// operators like typeof, instanceof and in are allowed
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("- invalid " + type + " \"" + ident + "\" in expression: " + text));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"- avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + text
);
} else {
errors.push(("- invalid expression: " + text));
}
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if ("development" !== 'production' && staticClass) {
var expression = parseText(staticClass, options.delimiters);
if (expression) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div class="{{ val }}">, use <div :class="val">.'
);
}
}
if (staticClass) {
el.staticClass = JSON.stringify(staticClass);
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
}
}
function genData$1 (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
var klass$1 = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
};
/* */
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
{
var expression = parseText(staticStyle, options.delimiters);
if (expression) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div style="{{ val }}">, use <div :style="val">.'
);
}
}
el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
}
}
function genData$2 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:(" + (el.styleBinding) + "),";
}
return data
}
var style$1 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$2
};
var modules$1 = [
klass$1,
style$1
];
/* */
var warn$3;
function model$1 (
el,
dir,
_warn
) {
warn$3 = _warn;
var value = dir.value;
var modifiers = dir.modifiers;
var tag = el.tag;
var type = el.attrsMap.type;
{
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$3(
"<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
}
if (tag === 'select') {
genSelect(el, value, modifiers);
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers);
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers);
} else {
genDefaultModel(el, value, modifiers);
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el,
value,
modifiers
) {
if ("development" !== 'production' &&
el.attrsMap.checked != null) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" +
"inline checked attributes will be ignored when using v-model. " +
'Declare initial values in the component\'s data option instead.'
);
}
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';
var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';
addProp(el, 'checked',
"Array.isArray(" + value + ")" +
"?_i(" + value + "," + valueBinding + ")>-1" +
":_q(" + value + "," + trueValueBinding + ")"
);
addHandler(el, 'change',
"var $$a=" + value + "," +
'$$el=$event.target,' +
"$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" +
'if(Array.isArray($$a)){' +
"var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," +
'$$i=_i($$a,$$v);' +
"if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" +
"}else{" + value + "=$$c}",
null, true
);
}
function genRadioModel (
el,
value,
modifiers
) {
if ("development" !== 'production' &&
el.attrsMap.checked != null) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" +
"inline checked attributes will be ignored when using v-model. " +
'Declare initial values in the component\'s data option instead.'
);
}
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding;
addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")"));
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true);
}
function genDefaultModel (
el,
value,
modifiers
) {
{
if (el.tag === 'input' && el.attrsMap.value) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" value=\"" + (el.attrsMap.value) + "\">:\n" +
'inline value attributes will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
);
}
if (el.tag === 'textarea' && el.children.length) {
warn$3(
"<textarea v-model=\"" + value + "\">:\n" +
'inline content inside <textarea> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
);
}
}
var type = el.attrsMap.type;
var ref = modifiers || {};
var lazy = ref.lazy;
var number = ref.number;
var trim = ref.trim;
var event = lazy || (isIE && type === 'range') ? 'change' : 'input';
var needCompositionGuard = !lazy && type !== 'range';
var isNative = el.tag === 'input' || el.tag === 'textarea';
var valueExpression = isNative
? ("$event.target.value" + (trim ? '.trim()' : ''))
: trim ? "(typeof $event === 'string' ? $event.trim() : $event)" : "$event";
valueExpression = number || type === 'number'
? ("_n(" + valueExpression + ")")
: valueExpression;
var code = genAssignmentCode(value, valueExpression);
if (isNative && needCompositionGuard) {
code = "if($event.target.composing)return;" + code;
}
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if ("development" !== 'production' &&
type === 'file') {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" +
"File inputs are read only. Use a v-on:change listener instead."
);
}
addProp(el, 'value', isNative ? ("_s(" + value + ")") : ("(" + value + ")"));
addHandler(el, event, code, null, true);
if (trim || number || type === 'number') {
addHandler(el, 'blur', '$forceUpdate()');
}
}
function genSelect (
el,
value,
modifiers
) {
{
el.children.some(checkOptionWarning);
}
var number = modifiers && modifiers.number;
var assignment = "Array.prototype.filter" +
".call($event.target.options,function(o){return o.selected})" +
".map(function(o){var val = \"_value\" in o ? o._value : o.value;" +
"return " + (number ? '_n(val)' : 'val') + "})" +
(el.attrsMap.multiple == null ? '[0]' : '');
var code = genAssignmentCode(value, assignment);
addHandler(el, 'change', code, null, true);
}
function checkOptionWarning (option) {
if (option.type === 1 &&
option.tag === 'option' &&
option.attrsMap.selected != null) {
warn$3(
"<select v-model=\"" + (option.parent.attrsMap['v-model']) + "\">:\n" +
'inline selected attributes on <option> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
);
return true
}
return false
}
function genAssignmentCode (value, assignment) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" +
"if (!Array.isArray($$exp)){" +
value + "=" + assignment + "}" +
"else{$$exp.splice($$idx, 1, " + assignment + ")}"
}
}
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
var directives$1 = {
model: model$1,
text: text,
html: html
};
/* */
var cache = Object.create(null);
var baseOptions = {
expectHTML: true,
modules: modules$1,
staticKeys: genStaticKeys(modules$1),
directives: directives$1,
isReservedTag: isReservedTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
getTagNamespace: getTagNamespace,
isPreTag: isPreTag
};
function compile$$1 (
template,
options
) {
options = options
? extend(extend({}, baseOptions), options)
: baseOptions;
return compile$1(template, options)
}
function compileToFunctions (
template,
options,
vm
) {
var _warn = (options && options.warn) || warn;
// detect possible CSP restriction
/* istanbul ignore if */
{
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
_warn(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
);
}
}
}
var key = options && options.delimiters
? String(options.delimiters) + template
: template;
if (cache[key]) {
return cache[key]
}
var res = {};
var compiled = compile$$1(template, options);
res.render = makeFunction(compiled.render);
var l = compiled.staticRenderFns.length;
res.staticRenderFns = new Array(l);
for (var i = 0; i < l; i++) {
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i]);
}
{
if (res.render === noop || res.staticRenderFns.some(function (fn) { return fn === noop; })) {
_warn(
"failed to compile template:\n\n" + template + "\n\n" +
detectErrors(compiled.ast).join('\n') +
'\n\n',
vm
);
}
}
return (cache[key] = res)
}
function makeFunction (code) {
try {
return new Function(code)
} catch (e) {
return noop
}
}
/* */
var idToTemplate = cached(function (id) {
var el = query(id);
return el && el.innerHTML
});
var mount = Vue$3.prototype.$mount;
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el);
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
"development" !== 'production' && warn(
"Do not mount Vue to <html> or <body> - mount to normal elements instead."
);
return this
}
var options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
var template = options.template;
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if ("development" !== 'production' && !template) {
warn(
("Template element not found or is empty: " + (options.template)),
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
{
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
template = getOuterHTML(el);
}
if (template) {
var ref = compileToFunctions(template, {
warn: warn,
shouldDecodeNewlines: shouldDecodeNewlines,
delimiters: options.delimiters
}, this);
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
options.render = render;
options.staticRenderFns = staticRenderFns;
}
}
return mount.call(this, el, hydrating)
};
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
var container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
Vue$3.compile = compileToFunctions;
return Vue$3;
})));
|
if(!window.calendar_languages) {
window.calendar_languages = {};
}
window.calendar_languages['ru-RU'] = {
error_noview: 'Календарь: Шаблон вида {0} не найден.',
error_dateformat: 'Календарь: неверный формат даты {0}. Должно быть или "now" или "yyyy-mm-dd"',
error_loadurl: 'Календарь: не назначен URL для загрузки событий.',
error_where: 'Календарь: неправильная навигация {0}. Можно только "next", "prev" или "today"',
title_year: '{0}',
title_month: '{0} {1}',
title_week: '{0} неделя года {1}',
title_day: '{0}, {1} {2} {3}',
week:'Неделя',
m0: 'Январь',
m1: 'Февраль',
m2: 'Март',
m3: 'Апрель',
m4: 'Май',
m5: 'Июнь',
m6: 'Июль',
m7: 'Август',
m8: 'Сентябрь',
m9: 'Октябрь',
m10: 'Ноябрь',
m11: 'Декабрь',
ms0: 'Янв',
ms1: 'Фев',
ms2: 'Мар',
ms3: 'Апр',
ms4: 'Май',
ms5: 'Июн',
ms6: 'Июл',
ms7: 'Авг',
ms8: 'Сен',
ms9: 'Окт',
ms10: 'Ноя',
ms11: 'Дек',
d0: 'Воскресенье',
d1: 'Понедельник',
d2: 'Вторник',
d3: 'Среда',
d4: 'Четверг',
d5: 'Пятница',
d6: 'Суббота',
easter: 'Пасха',
easterMonday: 'Пасхальный понедельник',
enable_easter_holidays: false,
first_day: 1
};
|
/// <autosync enabled="true" />
/// <reference path="../gulpfile.js" />
/// <reference path="js/app.js" />
/// <reference path="js/site.js" />
/// <reference path="lib/bootstrap/dist/js/bootstrap.js" />
/// <reference path="lib/jquery/dist/jquery.js" />
/// <reference path="lib/jquery-validation/dist/jquery.validate.js" />
/// <reference path="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" />
|
/// <reference path="Game.ts" />
/**
* Phaser - Basic
*
* A useful "generic" object on which all GameObjects and Groups are based.
* It has no size, position or graphical data.
*/
var Phaser;
(function (Phaser) {
var Basic = (function () {
/**
* Instantiate the basic object.
*/
function Basic(game) {
/**
* Allows you to give this object a name. Useful for debugging, but not actually used internally.
*/
this.name = '';
this._game = game;
this.ID = -1;
this.exists = true;
this.active = true;
this.visible = true;
this.alive = true;
this.isGroup = false;
this.ignoreDrawDebug = false;
}
Basic.prototype.destroy = /**
* Override this to null out iables or manually call
* <code>destroy()</code> on class members if necessary.
* Don't forget to call <code>super.destroy()</code>!
*/
function () {
};
Basic.prototype.preUpdate = /**
* Pre-update is called right before <code>update()</code> on each object in the game loop.
*/
function () {
};
Basic.prototype.update = /**
* Override this to update your class's position and appearance.
* This is where most of your game rules and behavioral code will go.
*/
function () {
};
Basic.prototype.postUpdate = /**
* Post-update is called right after <code>update()</code> on each object in the game loop.
*/
function () {
};
Basic.prototype.render = function (camera, cameraOffsetX, cameraOffsetY) {
};
Basic.prototype.kill = /**
* Handy for "killing" game objects.
* Default behavior is to flag them as nonexistent AND dead.
* However, if you want the "corpse" to remain in the game,
* like to animate an effect or whatever, you should override this,
* setting only alive to false, and leaving exists true.
*/
function () {
this.alive = false;
this.exists = false;
};
Basic.prototype.revive = /**
* Handy for bringing game objects "back to life". Just sets alive and exists back to true.
* In practice, this is most often called by <code>Object.reset()</code>.
*/
function () {
this.alive = true;
this.exists = true;
};
Basic.prototype.toString = /**
* Convert object to readable string name. Useful for debugging, save games, etc.
*/
function () {
return "";
};
return Basic;
})();
Phaser.Basic = Basic;
})(Phaser || (Phaser = {}));
/// <reference path="Signal.ts" />
/**
* Phaser - SignalBinding
*
* An object that represents a binding between a Signal and a listener function.
* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey.
* Released under the MIT license
* http://millermedeiros.github.com/js-signals/
*/
var Phaser;
(function (Phaser) {
var SignalBinding = (function () {
/**
* Object that represents a binding between a Signal and a listener function.
* <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
* <br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
* @author Miller Medeiros
* @constructor
* @internal
* @name SignalBinding
* @param {Signal} signal Reference to Signal object that listener is currently bound to.
* @param {Function} listener Handler function bound to the signal.
* @param {boolean} isOnce If binding should be executed just once.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. (default = 0).
*/
function SignalBinding(signal, listener, isOnce, listenerContext, priority) {
if (typeof priority === "undefined") { priority = 0; }
/**
* If binding is active and should be executed.
* @type boolean
*/
this.active = true;
/**
* Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
* @type Array|null
*/
this.params = null;
this._listener = listener;
this._isOnce = isOnce;
this.context = listenerContext;
this._signal = signal;
this.priority = priority || 0;
}
SignalBinding.prototype.execute = /**
* Call listener passing arbitrary parameters.
* <p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
* @param {Array} [paramsArr] Array of parameters that should be passed to the listener
* @return {*} Value returned by the listener.
*/
function (paramsArr) {
var handlerReturn;
var params;
if(this.active && !!this._listener) {
params = this.params ? this.params.concat(paramsArr) : paramsArr;
handlerReturn = this._listener.apply(this.context, params);
if(this._isOnce) {
this.detach();
}
}
return handlerReturn;
};
SignalBinding.prototype.detach = /**
* Detach binding from signal.
* - alias to: mySignal.remove(myBinding.getListener());
* @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
*/
function () {
return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
};
SignalBinding.prototype.isBound = /**
* @return {Boolean} `true` if binding is still bound to the signal and have a listener.
*/
function () {
return (!!this._signal && !!this._listener);
};
SignalBinding.prototype.isOnce = /**
* @return {boolean} If SignalBinding will only be executed once.
*/
function () {
return this._isOnce;
};
SignalBinding.prototype.getListener = /**
* @return {Function} Handler function bound to the signal.
*/
function () {
return this._listener;
};
SignalBinding.prototype.getSignal = /**
* @return {Signal} Signal that listener is currently bound to.
*/
function () {
return this._signal;
};
SignalBinding.prototype._destroy = /**
* Delete instance properties
* @private
*/
function () {
delete this._signal;
delete this._listener;
delete this.context;
};
SignalBinding.prototype.toString = /**
* @return {string} String representation of the object.
*/
function () {
return '[SignalBinding isOnce:' + this._isOnce + ', isBound:' + this.isBound() + ', active:' + this.active + ']';
};
return SignalBinding;
})();
Phaser.SignalBinding = SignalBinding;
})(Phaser || (Phaser = {}));
/// <reference path="SignalBinding.ts" />
/**
* Phaser - Signal
*
* A Signal is used for object communication via a custom broadcaster instead of Events.
* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey.
* Released under the MIT license
* http://millermedeiros.github.com/js-signals/
*/
var Phaser;
(function (Phaser) {
var Signal = (function () {
function Signal() {
/**
*
* @property _bindings
* @type Array
* @private
*/
this._bindings = [];
/**
*
* @property _prevParams
* @type Any
* @private
*/
this._prevParams = null;
/**
* If Signal should keep record of previously dispatched parameters and
* automatically execute listener during `add()`/`addOnce()` if Signal was
* already dispatched before.
* @type boolean
*/
this.memorize = false;
/**
* @type boolean
* @private
*/
this._shouldPropagate = true;
/**
* If Signal is active and should broadcast events.
* <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
* @type boolean
*/
this.active = true;
}
Signal.VERSION = '1.0.0';
Signal.prototype.validateListener = /**
*
* @method validateListener
* @param {Any} listener
* @param {Any} fnName
*/
function (listener, fnName) {
if(typeof listener !== 'function') {
throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
}
};
Signal.prototype._registerListener = /**
* @param {Function} listener
* @param {boolean} isOnce
* @param {Object} [listenerContext]
* @param {Number} [priority]
* @return {SignalBinding}
* @private
*/
function (listener, isOnce, listenerContext, priority) {
var prevIndex = this._indexOfListener(listener, listenerContext);
var binding;
if(prevIndex !== -1) {
binding = this._bindings[prevIndex];
if(binding.isOnce() !== isOnce) {
throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
}
} else {
binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
this._addBinding(binding);
}
if(this.memorize && this._prevParams) {
binding.execute(this._prevParams);
}
return binding;
};
Signal.prototype._addBinding = /**
*
* @method _addBinding
* @param {SignalBinding} binding
* @private
*/
function (binding) {
//simplified insertion sort
var n = this._bindings.length;
do {
--n;
}while(this._bindings[n] && binding.priority <= this._bindings[n].priority);
this._bindings.splice(n + 1, 0, binding);
};
Signal.prototype._indexOfListener = /**
*
* @method _indexOfListener
* @param {Function} listener
* @return {number}
* @private
*/
function (listener, context) {
var n = this._bindings.length;
var cur;
while(n--) {
cur = this._bindings[n];
if(cur.getListener() === listener && cur.context === context) {
return n;
}
}
return -1;
};
Signal.prototype.has = /**
* Check if listener was attached to Signal.
* @param {Function} listener
* @param {Object} [context]
* @return {boolean} if Signal has the specified listener.
*/
function (listener, context) {
if (typeof context === "undefined") { context = null; }
return this._indexOfListener(listener, context) !== -1;
};
Signal.prototype.add = /**
* Add a listener to the signal.
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {SignalBinding} An Object representing the binding between the Signal and listener.
*/
function (listener, listenerContext, priority) {
if (typeof listenerContext === "undefined") { listenerContext = null; }
if (typeof priority === "undefined") { priority = 0; }
this.validateListener(listener, 'add');
return this._registerListener(listener, false, listenerContext, priority);
};
Signal.prototype.addOnce = /**
* Add listener to the signal that should be removed after first execution (will be executed only once).
* @param {Function} listener Signal handler function.
* @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
* @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
* @return {SignalBinding} An Object representing the binding between the Signal and listener.
*/
function (listener, listenerContext, priority) {
if (typeof listenerContext === "undefined") { listenerContext = null; }
if (typeof priority === "undefined") { priority = 0; }
this.validateListener(listener, 'addOnce');
return this._registerListener(listener, true, listenerContext, priority);
};
Signal.prototype.remove = /**
* Remove a single listener from the dispatch queue.
* @param {Function} listener Handler function that should be removed.
* @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
* @return {Function} Listener handler function.
*/
function (listener, context) {
if (typeof context === "undefined") { context = null; }
this.validateListener(listener, 'remove');
var i = this._indexOfListener(listener, context);
if(i !== -1) {
this._bindings[i]._destroy()//no reason to a SignalBinding exist if it isn't attached to a signal
;
this._bindings.splice(i, 1);
}
return listener;
};
Signal.prototype.removeAll = /**
* Remove all listeners from the Signal.
*/
function () {
var n = this._bindings.length;
while(n--) {
this._bindings[n]._destroy();
}
this._bindings.length = 0;
};
Signal.prototype.getNumListeners = /**
* @return {number} Number of listeners attached to the Signal.
*/
function () {
return this._bindings.length;
};
Signal.prototype.halt = /**
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
* <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
* @see Signal.prototype.disable
*/
function () {
this._shouldPropagate = false;
};
Signal.prototype.dispatch = /**
* Dispatch/Broadcast Signal to all listeners added to the queue.
* @param {...*} [params] Parameters that should be passed to each handler.
*/
function () {
var paramsArr = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
paramsArr[_i] = arguments[_i + 0];
}
if(!this.active) {
return;
}
var n = this._bindings.length;
var bindings;
if(this.memorize) {
this._prevParams = paramsArr;
}
if(!n) {
//should come after memorize
return;
}
bindings = this._bindings.slice(0)//clone array in case add/remove items during dispatch
;
this._shouldPropagate = true//in case `halt` was called before dispatch or during the previous dispatch.
;
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
//reverse loop since listeners with higher priority will be added at the end of the list
do {
n--;
}while(bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
};
Signal.prototype.forget = /**
* Forget memorized arguments.
* @see Signal.memorize
*/
function () {
this._prevParams = null;
};
Signal.prototype.dispose = /**
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
* <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
*/
function () {
this.removeAll();
delete this._bindings;
delete this._prevParams;
};
Signal.prototype.toString = /**
* @return {string} String representation of the object.
*/
function () {
return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']';
};
return Signal;
})();
Phaser.Signal = Signal;
})(Phaser || (Phaser = {}));
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
/// <reference path="../Game.ts" />
/// <reference path="../Basic.ts" />
/// <reference path="../Signal.ts" />
/**
* Phaser - GameObject
*
* This is the base GameObject on which all other game objects are derived. It contains all the logic required for position,
* motion, size, collision and input.
*/
var Phaser;
(function (Phaser) {
var GameObject = (function (_super) {
__extends(GameObject, _super);
function GameObject(game, x, y, width, height) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof width === "undefined") { width = 16; }
if (typeof height === "undefined") { height = 16; }
_super.call(this, game);
this._angle = 0;
this.z = 0;
this.moves = true;
// Input
this.inputEnabled = false;
this._inputOver = false;
this.bounds = new Phaser.Rectangle(x, y, width, height);
this.exists = true;
this.active = true;
this.visible = true;
this.alive = true;
this.isGroup = false;
this.alpha = 1;
this.scale = new Phaser.MicroPoint(1, 1);
this.last = new Phaser.MicroPoint(x, y);
this.origin = new Phaser.MicroPoint(this.bounds.halfWidth, this.bounds.halfHeight);
this.align = GameObject.ALIGN_TOP_LEFT;
this.mass = 1.0;
this.elasticity = 0.0;
this.health = 1;
this.immovable = false;
this.moves = true;
this.touching = Phaser.Collision.NONE;
this.wasTouching = Phaser.Collision.NONE;
this.allowCollisions = Phaser.Collision.ANY;
this.velocity = new Phaser.MicroPoint();
this.acceleration = new Phaser.MicroPoint();
this.drag = new Phaser.MicroPoint();
this.maxVelocity = new Phaser.MicroPoint(10000, 10000);
this.angle = 0;
this.angularVelocity = 0;
this.angularAcceleration = 0;
this.angularDrag = 0;
this.maxAngular = 10000;
this.scrollFactor = new Phaser.MicroPoint(1.0, 1.0);
}
GameObject.ALIGN_TOP_LEFT = 0;
GameObject.ALIGN_TOP_CENTER = 1;
GameObject.ALIGN_TOP_RIGHT = 2;
GameObject.ALIGN_CENTER_LEFT = 3;
GameObject.ALIGN_CENTER = 4;
GameObject.ALIGN_CENTER_RIGHT = 5;
GameObject.ALIGN_BOTTOM_LEFT = 6;
GameObject.ALIGN_BOTTOM_CENTER = 7;
GameObject.ALIGN_BOTTOM_RIGHT = 8;
GameObject.prototype.preUpdate = function () {
// flicker time
this.last.x = this.bounds.x;
this.last.y = this.bounds.y;
};
GameObject.prototype.update = function () {
};
GameObject.prototype.postUpdate = function () {
if(this.moves) {
this.updateMotion();
}
if(this.inputEnabled) {
this.updateInput();
}
this.wasTouching = this.touching;
this.touching = Phaser.Collision.NONE;
};
GameObject.prototype.updateInput = function () {
};
GameObject.prototype.updateMotion = function () {
var delta;
var velocityDelta;
velocityDelta = (this._game.motion.computeVelocity(this.angularVelocity, this.angularAcceleration, this.angularDrag, this.maxAngular) - this.angularVelocity) / 2;
this.angularVelocity += velocityDelta;
this._angle += this.angularVelocity * this._game.time.elapsed;
this.angularVelocity += velocityDelta;
velocityDelta = (this._game.motion.computeVelocity(this.velocity.x, this.acceleration.x, this.drag.x, this.maxVelocity.x) - this.velocity.x) / 2;
this.velocity.x += velocityDelta;
delta = this.velocity.x * this._game.time.elapsed;
this.velocity.x += velocityDelta;
this.bounds.x += delta;
velocityDelta = (this._game.motion.computeVelocity(this.velocity.y, this.acceleration.y, this.drag.y, this.maxVelocity.y) - this.velocity.y) / 2;
this.velocity.y += velocityDelta;
delta = this.velocity.y * this._game.time.elapsed;
this.velocity.y += velocityDelta;
this.bounds.y += delta;
};
GameObject.prototype.overlaps = /**
* Checks to see if some <code>GameObject</code> overlaps this <code>GameObject</code> or <code>Group</code>.
* If the group has a LOT of things in it, it might be faster to use <code>G.overlaps()</code>.
* WARNING: Currently tilemaps do NOT support screen space overlap checks!
*
* @param ObjectOrGroup The object or group being tested.
* @param InScreenSpace Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space."
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether or not the two objects overlap.
*/
function (ObjectOrGroup, InScreenSpace, Camera) {
if (typeof InScreenSpace === "undefined") { InScreenSpace = false; }
if (typeof Camera === "undefined") { Camera = null; }
if(ObjectOrGroup.isGroup) {
var results = false;
var i = 0;
var members = ObjectOrGroup.members;
while(i < length) {
if(this.overlaps(members[i++], InScreenSpace, Camera)) {
results = true;
}
}
return results;
}
/*
if (typeof ObjectOrGroup === 'Tilemap')
{
//Since tilemap's have to be the caller, not the target, to do proper tile-based collisions,
// we redirect the call to the tilemap overlap here.
return ObjectOrGroup.overlaps(this, InScreenSpace, Camera);
}
*/
//var object: GameObject = ObjectOrGroup;
if(!InScreenSpace) {
return (ObjectOrGroup.x + ObjectOrGroup.width > this.x) && (ObjectOrGroup.x < this.x + this.width) && (ObjectOrGroup.y + ObjectOrGroup.height > this.y) && (ObjectOrGroup.y < this.y + this.height);
}
if(Camera == null) {
Camera = this._game.camera;
}
var objectScreenPos = ObjectOrGroup.getScreenXY(null, Camera);
this.getScreenXY(this._point, Camera);
return (objectScreenPos.x + ObjectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && (objectScreenPos.y + ObjectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height);
};
GameObject.prototype.overlapsAt = /**
* Checks to see if this <code>GameObject</code> were located at the given position, would it overlap the <code>GameObject</code> or <code>Group</code>?
* This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size numbero account.
* WARNING: Currently tilemaps do NOT support screen space overlap checks!
*
* @param X The X position you want to check. Pretends this object (the caller, not the parameter) is located here.
* @param Y The Y position you want to check. Pretends this object (the caller, not the parameter) is located here.
* @param ObjectOrGroup The object or group being tested.
* @param InScreenSpace Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space."
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether or not the two objects overlap.
*/
function (X, Y, ObjectOrGroup, InScreenSpace, Camera) {
if (typeof InScreenSpace === "undefined") { InScreenSpace = false; }
if (typeof Camera === "undefined") { Camera = null; }
if(ObjectOrGroup.isGroup) {
var results = false;
var basic;
var i = 0;
var members = ObjectOrGroup.members;
while(i < length) {
if(this.overlapsAt(X, Y, members[i++], InScreenSpace, Camera)) {
results = true;
}
}
return results;
}
/*
if (typeof ObjectOrGroup === 'Tilemap')
{
//Since tilemap's have to be the caller, not the target, to do proper tile-based collisions,
// we redirect the call to the tilemap overlap here.
//However, since this is overlapsAt(), we also have to invent the appropriate position for the tilemap.
//So we calculate the offset between the player and the requested position, and subtract that from the tilemap.
var tilemap: Tilemap = ObjectOrGroup;
return tilemap.overlapsAt(tilemap.x - (X - this.x), tilemap.y - (Y - this.y), this, InScreenSpace, Camera);
}
*/
//var object: GameObject = ObjectOrGroup;
if(!InScreenSpace) {
return (ObjectOrGroup.x + ObjectOrGroup.width > X) && (ObjectOrGroup.x < X + this.width) && (ObjectOrGroup.y + ObjectOrGroup.height > Y) && (ObjectOrGroup.y < Y + this.height);
}
if(Camera == null) {
Camera = this._game.camera;
}
var objectScreenPos = ObjectOrGroup.getScreenXY(null, Camera);
this._point.x = X - Camera.scroll.x * this.scrollFactor.x//copied from getScreenXY()
;
this._point.y = Y - Camera.scroll.y * this.scrollFactor.y;
this._point.x += (this._point.x > 0) ? 0.0000001 : -0.0000001;
this._point.y += (this._point.y > 0) ? 0.0000001 : -0.0000001;
return (objectScreenPos.x + ObjectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && (objectScreenPos.y + ObjectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height);
};
GameObject.prototype.overlapsPoint = /**
* Checks to see if a point in 2D world space overlaps this <code>GameObject</code>.
*
* @param Point The point in world space you want to check.
* @param InScreenSpace Whether to take scroll factors numbero account when checking for overlap.
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether or not the point overlaps this object.
*/
function (point, InScreenSpace, Camera) {
if (typeof InScreenSpace === "undefined") { InScreenSpace = false; }
if (typeof Camera === "undefined") { Camera = null; }
if(!InScreenSpace) {
return (point.x > this.x) && (point.x < this.x + this.width) && (point.y > this.y) && (point.y < this.y + this.height);
}
if(Camera == null) {
Camera = this._game.camera;
}
var X = point.x - Camera.scroll.x;
var Y = point.y - Camera.scroll.y;
this.getScreenXY(this._point, Camera);
return (X > this._point.x) && (X < this._point.x + this.width) && (Y > this._point.y) && (Y < this._point.y + this.height);
};
GameObject.prototype.onScreen = /**
* Check and see if this object is currently on screen.
*
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether the object is on screen or not.
*/
function (Camera) {
if (typeof Camera === "undefined") { Camera = null; }
if(Camera == null) {
Camera = this._game.camera;
}
this.getScreenXY(this._point, Camera);
return (this._point.x + this.width > 0) && (this._point.x < Camera.width) && (this._point.y + this.height > 0) && (this._point.y < Camera.height);
};
GameObject.prototype.getScreenXY = /**
* Call this to figure out the on-screen position of the object.
*
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
* @param Point Takes a <code>MicroPoint</code> object and assigns the post-scrolled X and Y values of this object to it.
*
* @return The <code>MicroPoint</code> you passed in, or a new <code>Point</code> if you didn't pass one, containing the screen X and Y position of this object.
*/
function (point, Camera) {
if (typeof point === "undefined") { point = null; }
if (typeof Camera === "undefined") { Camera = null; }
if(point == null) {
point = new Phaser.MicroPoint();
}
if(Camera == null) {
Camera = this._game.camera;
}
point.x = this.x - Camera.scroll.x * this.scrollFactor.x;
point.y = this.y - Camera.scroll.y * this.scrollFactor.y;
point.x += (point.x > 0) ? 0.0000001 : -0.0000001;
point.y += (point.y > 0) ? 0.0000001 : -0.0000001;
return point;
};
Object.defineProperty(GameObject.prototype, "solid", {
get: /**
* Whether the object collides or not. For more control over what directions
* the object will collide from, use collision constants (like LEFT, FLOOR, etc)
* to set the value of allowCollisions directly.
*/
function () {
return (this.allowCollisions & Phaser.Collision.ANY) > Phaser.Collision.NONE;
},
set: /**
* @private
*/
function (Solid) {
if(Solid) {
this.allowCollisions = Phaser.Collision.ANY;
} else {
this.allowCollisions = Phaser.Collision.NONE;
}
},
enumerable: true,
configurable: true
});
GameObject.prototype.getMidpoint = /**
* Retrieve the midpoint of this object in world coordinates.
*
* @Point Allows you to pass in an existing <code>Point</code> object if you're so inclined. Otherwise a new one is created.
*
* @return A <code>Point</code> object containing the midpoint of this object in world coordinates.
*/
function (point) {
if (typeof point === "undefined") { point = null; }
if(point == null) {
point = new Phaser.MicroPoint();
}
point.copyFrom(this.bounds.center);
return point;
};
GameObject.prototype.reset = /**
* Handy for reviving game objects.
* Resets their existence flags and position.
*
* @param X The new X position of this object.
* @param Y The new Y position of this object.
*/
function (X, Y) {
this.revive();
this.touching = Phaser.Collision.NONE;
this.wasTouching = Phaser.Collision.NONE;
this.x = X;
this.y = Y;
this.last.x = X;
this.last.y = Y;
this.velocity.x = 0;
this.velocity.y = 0;
};
GameObject.prototype.isTouching = /**
* Handy for checking if this object is touching a particular surface.
* For slightly better performance you can just & the value directly numbero <code>touching</code>.
* However, this method is good for readability and accessibility.
*
* @param Direction Any of the collision flags (e.g. LEFT, FLOOR, etc).
*
* @return Whether the object is touching an object in (any of) the specified direction(s) this frame.
*/
function (Direction) {
return (this.touching & Direction) > Phaser.Collision.NONE;
};
GameObject.prototype.justTouched = /**
* Handy for checking if this object is just landed on a particular surface.
*
* @param Direction Any of the collision flags (e.g. LEFT, FLOOR, etc).
*
* @return Whether the object just landed on (any of) the specified surface(s) this frame.
*/
function (Direction) {
return ((this.touching & Direction) > Phaser.Collision.NONE) && ((this.wasTouching & Direction) <= Phaser.Collision.NONE);
};
GameObject.prototype.hurt = /**
* Reduces the "health" variable of this sprite by the amount specified in Damage.
* Calls kill() if health drops to or below zero.
*
* @param Damage How much health to take away (use a negative number to give a health bonus).
*/
function (Damage) {
this.health = this.health - Damage;
if(this.health <= 0) {
this.kill();
}
};
GameObject.prototype.destroy = function () {
};
Object.defineProperty(GameObject.prototype, "x", {
get: function () {
return this.bounds.x;
},
set: function (value) {
this.bounds.x = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GameObject.prototype, "y", {
get: function () {
return this.bounds.y;
},
set: function (value) {
this.bounds.y = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GameObject.prototype, "rotation", {
get: function () {
return this._angle;
},
set: function (value) {
this._angle = this._game.math.wrap(value, 360, 0);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GameObject.prototype, "angle", {
get: function () {
return this._angle;
},
set: function (value) {
this._angle = this._game.math.wrap(value, 360, 0);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GameObject.prototype, "width", {
get: function () {
return this.bounds.width;
},
set: function (value) {
this.bounds.width = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GameObject.prototype, "height", {
get: function () {
return this.bounds.height;
},
set: function (value) {
this.bounds.height = value;
},
enumerable: true,
configurable: true
});
return GameObject;
})(Phaser.Basic);
Phaser.GameObject = GameObject;
})(Phaser || (Phaser = {}));
/// <reference path="../gameobjects/Sprite.ts" />
/// <reference path="../Game.ts" />
/**
* Phaser - Camera
*
* A Camera is your view into the game world. It has a position, size, scale and rotation and renders only those objects
* within its field of view. The game automatically creates a single Stage sized camera on boot, but it can be changed and
* additional cameras created via the CameraManager.
*/
var Phaser;
(function (Phaser) {
var Camera = (function () {
/**
* Instantiates a new camera at the specified location, with the specified size and zoom level.
*
* @param X X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom.
* @param Y Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom.
* @param Width The width of the camera display in pixels.
* @param Height The height of the camera display in pixels.
* @param Zoom The initial zoom level of the camera. A zoom level of 2 will make all pixels display at 2x resolution.
*/
function Camera(game, id, x, y, width, height) {
this._clip = false;
this._rotation = 0;
this._target = null;
this._sx = 0;
this._sy = 0;
this._fxFlashComplete = null;
this._fxFlashDuration = 0;
this._fxFlashAlpha = 0;
this._fxFadeComplete = null;
this._fxFadeDuration = 0;
this._fxFadeAlpha = 0;
this._fxShakeIntensity = 0;
this._fxShakeDuration = 0;
this._fxShakeComplete = null;
this._fxShakeOffset = new Phaser.Point(0, 0);
this._fxShakeDirection = 0;
this._fxShakePrevX = 0;
this._fxShakePrevY = 0;
this.scale = new Phaser.Point(1, 1);
this.scroll = new Phaser.Point(0, 0);
this.bounds = null;
this.deadzone = null;
// Camera Border
this.showBorder = false;
this.borderColor = 'rgb(255,255,255)';
// Camera Background Color
this.opaque = true;
this._bgColor = 'rgb(0,0,0)';
this._bgTextureRepeat = 'repeat';
// Camera Shadow
this.showShadow = false;
this.shadowColor = 'rgb(0,0,0)';
this.shadowBlur = 10;
this.shadowOffset = new Phaser.Point(4, 4);
this.visible = true;
this.alpha = 1;
// The x/y position of the current input event in world coordinates
this.inputX = 0;
this.inputY = 0;
this._game = game;
this.ID = id;
this._stageX = x;
this._stageY = y;
// The view into the world canvas we wish to render
this.worldView = new Phaser.Rectangle(0, 0, width, height);
this.checkClip();
}
Camera.STYLE_LOCKON = 0;
Camera.STYLE_PLATFORMER = 1;
Camera.STYLE_TOPDOWN = 2;
Camera.STYLE_TOPDOWN_TIGHT = 3;
Camera.SHAKE_BOTH_AXES = 0;
Camera.SHAKE_HORIZONTAL_ONLY = 1;
Camera.SHAKE_VERTICAL_ONLY = 2;
Camera.prototype.flash = /**
* The camera is filled with this color and returns to normal at the given duration.
*
* @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white.
* @param Duration How long it takes for the flash to fade.
* @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback.
* @param Force Force an already running flash effect to reset.
*/
function (color, duration, onComplete, force) {
if (typeof color === "undefined") { color = 0xffffff; }
if (typeof duration === "undefined") { duration = 1; }
if (typeof onComplete === "undefined") { onComplete = null; }
if (typeof force === "undefined") { force = false; }
if(force === false && this._fxFlashAlpha > 0) {
// You can't flash again unless you force it
return;
}
if(duration <= 0) {
duration = 1;
}
var red = color >> 16 & 0xFF;
var green = color >> 8 & 0xFF;
var blue = color & 0xFF;
this._fxFlashColor = 'rgba(' + red + ',' + green + ',' + blue + ',';
this._fxFlashDuration = duration;
this._fxFlashAlpha = 1;
this._fxFlashComplete = onComplete;
};
Camera.prototype.fade = /**
* The camera is gradually filled with this color.
*
* @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white.
* @param Duration How long it takes for the flash to fade.
* @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback.
* @param Force Force an already running flash effect to reset.
*/
function (color, duration, onComplete, force) {
if (typeof color === "undefined") { color = 0x000000; }
if (typeof duration === "undefined") { duration = 1; }
if (typeof onComplete === "undefined") { onComplete = null; }
if (typeof force === "undefined") { force = false; }
if(force === false && this._fxFadeAlpha > 0) {
// You can't fade again unless you force it
return;
}
if(duration <= 0) {
duration = 1;
}
var red = color >> 16 & 0xFF;
var green = color >> 8 & 0xFF;
var blue = color & 0xFF;
this._fxFadeColor = 'rgba(' + red + ',' + green + ',' + blue + ',';
this._fxFadeDuration = duration;
this._fxFadeAlpha = 0.01;
this._fxFadeComplete = onComplete;
};
Camera.prototype.shake = /**
* A simple screen-shake effect.
*
* @param Intensity Percentage of screen size representing the maximum distance that the screen can move while shaking.
* @param Duration The length in seconds that the shaking effect should last.
* @param OnComplete A function you want to run when the shake effect finishes.
* @param Force Force the effect to reset (default = true, unlike flash() and fade()!).
* @param Direction Whether to shake on both axes, just up and down, or just side to side (use class constants SHAKE_BOTH_AXES, SHAKE_VERTICAL_ONLY, or SHAKE_HORIZONTAL_ONLY).
*/
function (intensity, duration, onComplete, force, direction) {
if (typeof intensity === "undefined") { intensity = 0.05; }
if (typeof duration === "undefined") { duration = 0.5; }
if (typeof onComplete === "undefined") { onComplete = null; }
if (typeof force === "undefined") { force = true; }
if (typeof direction === "undefined") { direction = Camera.SHAKE_BOTH_AXES; }
if(!force && ((this._fxShakeOffset.x != 0) || (this._fxShakeOffset.y != 0))) {
return;
}
// If a shake is not already running we need to store the offsets here
if(this._fxShakeOffset.x == 0 && this._fxShakeOffset.y == 0) {
this._fxShakePrevX = this._stageX;
this._fxShakePrevY = this._stageY;
}
this._fxShakeIntensity = intensity;
this._fxShakeDuration = duration;
this._fxShakeComplete = onComplete;
this._fxShakeDirection = direction;
this._fxShakeOffset.setTo(0, 0);
};
Camera.prototype.stopFX = /**
* Just turns off all the camera effects instantly.
*/
function () {
this._fxFlashAlpha = 0;
this._fxFadeAlpha = 0;
if(this._fxShakeDuration !== 0) {
this._fxShakeDuration = 0;
this._fxShakeOffset.setTo(0, 0);
this._stageX = this._fxShakePrevX;
this._stageY = this._fxShakePrevY;
}
};
Camera.prototype.follow = function (target, style) {
if (typeof style === "undefined") { style = Camera.STYLE_LOCKON; }
this._target = target;
var helper;
switch(style) {
case Camera.STYLE_PLATFORMER:
var w = this.width / 8;
var h = this.height / 3;
this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
break;
case Camera.STYLE_TOPDOWN:
helper = Math.max(this.width, this.height) / 4;
this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
break;
case Camera.STYLE_TOPDOWN_TIGHT:
helper = Math.max(this.width, this.height) / 8;
this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
break;
case Camera.STYLE_LOCKON:
default:
this.deadzone = null;
break;
}
};
Camera.prototype.focusOnXY = function (x, y) {
x += (x > 0) ? 0.0000001 : -0.0000001;
y += (y > 0) ? 0.0000001 : -0.0000001;
this.scroll.x = Math.round(x - this.worldView.halfWidth);
this.scroll.y = Math.round(y - this.worldView.halfHeight);
};
Camera.prototype.focusOn = function (point) {
point.x += (point.x > 0) ? 0.0000001 : -0.0000001;
point.y += (point.y > 0) ? 0.0000001 : -0.0000001;
this.scroll.x = Math.round(point.x - this.worldView.halfWidth);
this.scroll.y = Math.round(point.y - this.worldView.halfHeight);
};
Camera.prototype.setBounds = /**
* Specify the boundaries of the world or where the camera is allowed to move.
*
* @param X The smallest X value of your world (usually 0).
* @param Y The smallest Y value of your world (usually 0).
* @param Width The largest X value of your world (usually the world width).
* @param Height The largest Y value of your world (usually the world height).
* @param UpdateWorld Whether the global quad-tree's dimensions should be updated to match (default: false).
*/
function (X, Y, Width, Height, UpdateWorld) {
if (typeof X === "undefined") { X = 0; }
if (typeof Y === "undefined") { Y = 0; }
if (typeof Width === "undefined") { Width = 0; }
if (typeof Height === "undefined") { Height = 0; }
if (typeof UpdateWorld === "undefined") { UpdateWorld = false; }
if(this.bounds == null) {
this.bounds = new Phaser.Rectangle();
}
this.bounds.setTo(X, Y, Width, Height);
//if(UpdateWorld)
// G.worldBounds.copyFrom(bounds);
this.update();
};
Camera.prototype.update = function () {
if(this._target !== null) {
if(this.deadzone == null) {
this.focusOnXY(this._target.x + this._target.origin.x, this._target.y + this._target.origin.y);
} else {
var edge;
var targetX = this._target.x + ((this._target.x > 0) ? 0.0000001 : -0.0000001);
var targetY = this._target.y + ((this._target.y > 0) ? 0.0000001 : -0.0000001);
edge = targetX - this.deadzone.x;
if(this.scroll.x > edge) {
this.scroll.x = edge;
}
edge = targetX + this._target.width - this.deadzone.x - this.deadzone.width;
if(this.scroll.x < edge) {
this.scroll.x = edge;
}
edge = targetY - this.deadzone.y;
if(this.scroll.y > edge) {
this.scroll.y = edge;
}
edge = targetY + this._target.height - this.deadzone.y - this.deadzone.height;
if(this.scroll.y < edge) {
this.scroll.y = edge;
}
}
}
// Make sure we didn't go outside the camera's bounds
if(this.bounds !== null) {
if(this.scroll.x < this.bounds.left) {
this.scroll.x = this.bounds.left;
}
if(this.scroll.x > this.bounds.right - this.width) {
this.scroll.x = this.bounds.right - this.width;
}
if(this.scroll.y < this.bounds.top) {
this.scroll.y = this.bounds.top;
}
if(this.scroll.y > this.bounds.bottom - this.height) {
this.scroll.y = this.bounds.bottom - this.height;
}
}
this.worldView.x = this.scroll.x;
this.worldView.y = this.scroll.y;
// Input values
this.inputX = this.worldView.x + this._game.input.x;
this.inputY = this.worldView.y + this._game.input.y;
// Update the Flash effect
if(this._fxFlashAlpha > 0) {
this._fxFlashAlpha -= this._game.time.elapsed / this._fxFlashDuration;
this._fxFlashAlpha = this._game.math.roundTo(this._fxFlashAlpha, -2);
if(this._fxFlashAlpha <= 0) {
this._fxFlashAlpha = 0;
if(this._fxFlashComplete !== null) {
this._fxFlashComplete();
}
}
}
// Update the Fade effect
if(this._fxFadeAlpha > 0) {
this._fxFadeAlpha += this._game.time.elapsed / this._fxFadeDuration;
this._fxFadeAlpha = this._game.math.roundTo(this._fxFadeAlpha, -2);
if(this._fxFadeAlpha >= 1) {
this._fxFadeAlpha = 1;
if(this._fxFadeComplete !== null) {
this._fxFadeComplete();
}
}
}
// Update the "shake" special effect
if(this._fxShakeDuration > 0) {
this._fxShakeDuration -= this._game.time.elapsed;
this._fxShakeDuration = this._game.math.roundTo(this._fxShakeDuration, -2);
if(this._fxShakeDuration <= 0) {
this._fxShakeDuration = 0;
this._fxShakeOffset.setTo(0, 0);
this._stageX = this._fxShakePrevX;
this._stageY = this._fxShakePrevY;
if(this._fxShakeComplete != null) {
this._fxShakeComplete();
}
} else {
if((this._fxShakeDirection == Camera.SHAKE_BOTH_AXES) || (this._fxShakeDirection == Camera.SHAKE_HORIZONTAL_ONLY)) {
//this._fxShakeOffset.x = ((this._game.math.random() * this._fxShakeIntensity * this.worldView.width * 2 - this._fxShakeIntensity * this.worldView.width) * this._zoom;
this._fxShakeOffset.x = (this._game.math.random() * this._fxShakeIntensity * this.worldView.width * 2 - this._fxShakeIntensity * this.worldView.width);
}
if((this._fxShakeDirection == Camera.SHAKE_BOTH_AXES) || (this._fxShakeDirection == Camera.SHAKE_VERTICAL_ONLY)) {
//this._fxShakeOffset.y = (this._game.math.random() * this._fxShakeIntensity * this.worldView.height * 2 - this._fxShakeIntensity * this.worldView.height) * this._zoom;
this._fxShakeOffset.y = (this._game.math.random() * this._fxShakeIntensity * this.worldView.height * 2 - this._fxShakeIntensity * this.worldView.height);
}
}
}
};
Camera.prototype.render = function () {
if(this.visible === false && this.alpha < 0.1) {
return;
}
if((this._fxShakeOffset.x != 0) || (this._fxShakeOffset.y != 0)) {
//this._stageX = this._fxShakePrevX + (this.worldView.halfWidth * this._zoom) + this._fxShakeOffset.x;
//this._stageY = this._fxShakePrevY + (this.worldView.halfHeight * this._zoom) + this._fxShakeOffset.y;
this._stageX = this._fxShakePrevX + (this.worldView.halfWidth) + this._fxShakeOffset.x;
this._stageY = this._fxShakePrevY + (this.worldView.halfHeight) + this._fxShakeOffset.y;
//console.log('shake', this._fxShakeDuration, this._fxShakeIntensity, this._fxShakeOffset.x, this._fxShakeOffset.y);
}
//if (this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1)
//{
//this._game.stage.context.save();
//}
// It may be safe/quicker to just save the context every frame regardless
this._game.stage.context.save();
if(this.alpha !== 1) {
this._game.stage.context.globalAlpha = this.alpha;
}
this._sx = this._stageX;
this._sy = this._stageY;
// Shadow
if(this.showShadow) {
this._game.stage.context.shadowColor = this.shadowColor;
this._game.stage.context.shadowBlur = this.shadowBlur;
this._game.stage.context.shadowOffsetX = this.shadowOffset.x;
this._game.stage.context.shadowOffsetY = this.shadowOffset.y;
}
// Scale on
if(this.scale.x !== 1 || this.scale.y !== 1) {
this._game.stage.context.scale(this.scale.x, this.scale.y);
this._sx = this._sx / this.scale.x;
this._sy = this._sy / this.scale.y;
}
// Rotation - translate to the mid-point of the camera
if(this._rotation !== 0) {
this._game.stage.context.translate(this._sx + this.worldView.halfWidth, this._sy + this.worldView.halfHeight);
this._game.stage.context.rotate(this._rotation * (Math.PI / 180));
// now shift back to where that should actually render
this._game.stage.context.translate(-(this._sx + this.worldView.halfWidth), -(this._sy + this.worldView.halfHeight));
}
// Background
if(this.opaque == true) {
if(this._bgTexture) {
this._game.stage.context.fillStyle = this._bgTexture;
this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height);
} else {
this._game.stage.context.fillStyle = this._bgColor;
this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height);
}
}
// Shadow off
if(this.showShadow) {
this._game.stage.context.shadowBlur = 0;
this._game.stage.context.shadowOffsetX = 0;
this._game.stage.context.shadowOffsetY = 0;
}
// Clip the camera so we don't get sprites appearing outside the edges
if(this._clip) {
this._game.stage.context.beginPath();
this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height);
this._game.stage.context.closePath();
this._game.stage.context.clip();
}
this._game.world.group.render(this, this._sx, this._sy);
if(this.showBorder) {
this._game.stage.context.strokeStyle = this.borderColor;
this._game.stage.context.lineWidth = 1;
this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height);
this._game.stage.context.stroke();
}
// "Flash" FX
if(this._fxFlashAlpha > 0) {
this._game.stage.context.fillStyle = this._fxFlashColor + this._fxFlashAlpha + ')';
this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height);
}
// "Fade" FX
if(this._fxFadeAlpha > 0) {
this._game.stage.context.fillStyle = this._fxFadeColor + this._fxFadeAlpha + ')';
this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height);
}
// Scale off
if(this.scale.x !== 1 || this.scale.y !== 1) {
this._game.stage.context.scale(1, 1);
}
if(this._rotation !== 0 || this._clip) {
this._game.stage.context.translate(0, 0);
//this._game.stage.context.restore();
}
// maybe just do this every frame regardless?
this._game.stage.context.restore();
if(this.alpha !== 1) {
this._game.stage.context.globalAlpha = 1;
}
};
Object.defineProperty(Camera.prototype, "backgroundColor", {
get: function () {
return this._bgColor;
},
set: function (color) {
this._bgColor = color;
},
enumerable: true,
configurable: true
});
Camera.prototype.setTexture = function (key, repeat) {
if (typeof repeat === "undefined") { repeat = 'repeat'; }
this._bgTexture = this._game.stage.context.createPattern(this._game.cache.getImage(key), repeat);
this._bgTextureRepeat = repeat;
};
Camera.prototype.setPosition = function (x, y) {
this._stageX = x;
this._stageY = y;
this.checkClip();
};
Camera.prototype.setSize = function (width, height) {
this.worldView.width = width;
this.worldView.height = height;
this.checkClip();
};
Camera.prototype.renderDebugInfo = function (x, y, color) {
if (typeof color === "undefined") { color = 'rgb(255,255,255)'; }
this._game.stage.context.fillStyle = color;
this._game.stage.context.fillText('Camera ID: ' + this.ID + ' (' + this.worldView.width + ' x ' + this.worldView.height + ')', x, y);
this._game.stage.context.fillText('X: ' + this._stageX + ' Y: ' + this._stageY + ' Rotation: ' + this._rotation, x, y + 14);
this._game.stage.context.fillText('World X: ' + this.scroll.x.toFixed(1) + ' World Y: ' + this.scroll.y.toFixed(1), x, y + 28);
if(this.bounds) {
this._game.stage.context.fillText('Bounds: ' + this.bounds.width + ' x ' + this.bounds.height, x, y + 56);
}
};
Object.defineProperty(Camera.prototype, "x", {
get: function () {
return this._stageX;
},
set: function (value) {
this._stageX = value;
this.checkClip();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "y", {
get: function () {
return this._stageY;
},
set: function (value) {
this._stageY = value;
this.checkClip();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "width", {
get: function () {
return this.worldView.width;
},
set: function (value) {
this.worldView.width = value;
this.checkClip();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "height", {
get: function () {
return this.worldView.height;
},
set: function (value) {
this.worldView.height = value;
this.checkClip();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "rotation", {
get: function () {
return this._rotation;
},
set: function (value) {
this._rotation = this._game.math.wrap(value, 360, 0);
},
enumerable: true,
configurable: true
});
Camera.prototype.checkClip = function () {
if(this._stageX !== 0 || this._stageY !== 0 || this.worldView.width < this._game.stage.width || this.worldView.height < this._game.stage.height) {
this._clip = true;
} else {
this._clip = false;
}
};
return Camera;
})();
Phaser.Camera = Camera;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="../AnimationManager.ts" />
/// <reference path="GameObject.ts" />
/// <reference path="../system/Camera.ts" />
/**
* Phaser - Sprite
*
* The Sprite GameObject is an extension of the core GameObject that includes support for animation and dynamic textures.
* It's probably the most used GameObject of all.
*/
var Phaser;
(function (Phaser) {
var Sprite = (function (_super) {
__extends(Sprite, _super);
function Sprite(game, x, y, key) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof key === "undefined") { key = null; }
_super.call(this, game, x, y);
this._dynamicTexture = false;
// local rendering related temp vars to help avoid gc spikes
this._sx = 0;
this._sy = 0;
this._sw = 0;
this._sh = 0;
this._dx = 0;
this._dy = 0;
this._dw = 0;
this._dh = 0;
this.renderDebug = false;
this.renderDebugColor = 'rgba(0,255,0,0.5)';
this.renderDebugPointColor = 'rgba(255,255,255,1)';
this.flipped = false;
this._texture = null;
this.animations = new Phaser.AnimationManager(this._game, this);
if(key !== null) {
this.loadGraphic(key);
} else {
this.bounds.width = 16;
this.bounds.height = 16;
}
}
Sprite.prototype.loadGraphic = function (key) {
if(this._game.cache.getImage(key) !== null) {
if(this._game.cache.isSpriteSheet(key) == false) {
this._texture = this._game.cache.getImage(key);
this.bounds.width = this._texture.width;
this.bounds.height = this._texture.height;
} else {
this._texture = this._game.cache.getImage(key);
this.animations.loadFrameData(this._game.cache.getFrameData(key));
}
this._dynamicTexture = false;
}
return this;
};
Sprite.prototype.loadDynamicTexture = function (texture) {
this._texture = texture;
this.bounds.width = this._texture.width;
this.bounds.height = this._texture.height;
this._dynamicTexture = true;
return this;
};
Sprite.prototype.makeGraphic = function (width, height, color) {
if (typeof color === "undefined") { color = 0xffffffff; }
this._texture = null;
this.width = width;
this.height = height;
this._dynamicTexture = false;
return this;
};
Sprite.prototype.inCamera = function (camera) {
if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) {
this._dx = this.bounds.x - (camera.x * this.scrollFactor.x);
this._dy = this.bounds.y - (camera.y * this.scrollFactor.x);
this._dw = this.bounds.width * this.scale.x;
this._dh = this.bounds.height * this.scale.y;
return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh);
} else {
return camera.intersects(this.bounds, this.bounds.length);
}
};
Sprite.prototype.postUpdate = function () {
this.animations.update();
_super.prototype.postUpdate.call(this);
};
Object.defineProperty(Sprite.prototype, "frame", {
get: function () {
return this.animations.frame;
},
set: function (value) {
this.animations.frame = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Sprite.prototype, "frameName", {
get: function () {
return this.animations.frameName;
},
set: function (value) {
this.animations.frameName = value;
},
enumerable: true,
configurable: true
});
Sprite.prototype.render = function (camera, cameraOffsetX, cameraOffsetY) {
// Render checks
if(this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.inCamera(camera.worldView) == false) {
return false;
}
// Alpha
if(this.alpha !== 1) {
var globalAlpha = this._game.stage.context.globalAlpha;
this._game.stage.context.globalAlpha = this.alpha;
}
this._sx = 0;
this._sy = 0;
this._sw = this.bounds.width;
this._sh = this.bounds.height;
this._dx = cameraOffsetX + (this.bounds.topLeft.x - camera.worldView.x);
this._dy = cameraOffsetY + (this.bounds.topLeft.y - camera.worldView.y);
this._dw = this.bounds.width * this.scale.x;
this._dh = this.bounds.height * this.scale.y;
if(this.align == Phaser.GameObject.ALIGN_TOP_CENTER) {
this._dx -= this.bounds.halfWidth * this.scale.x;
} else if(this.align == Phaser.GameObject.ALIGN_TOP_RIGHT) {
this._dx -= this.bounds.width * this.scale.x;
} else if(this.align == Phaser.GameObject.ALIGN_CENTER_LEFT) {
this._dy -= this.bounds.halfHeight * this.scale.y;
} else if(this.align == Phaser.GameObject.ALIGN_CENTER) {
this._dx -= this.bounds.halfWidth * this.scale.x;
this._dy -= this.bounds.halfHeight * this.scale.y;
} else if(this.align == Phaser.GameObject.ALIGN_CENTER_RIGHT) {
this._dx -= this.bounds.width * this.scale.x;
this._dy -= this.bounds.halfHeight * this.scale.y;
} else if(this.align == Phaser.GameObject.ALIGN_BOTTOM_LEFT) {
this._dy -= this.bounds.height * this.scale.y;
} else if(this.align == Phaser.GameObject.ALIGN_BOTTOM_CENTER) {
this._dx -= this.bounds.halfWidth * this.scale.x;
this._dy -= this.bounds.height * this.scale.y;
} else if(this.align == Phaser.GameObject.ALIGN_BOTTOM_RIGHT) {
this._dx -= this.bounds.width * this.scale.x;
this._dy -= this.bounds.height * this.scale.y;
}
if(this._dynamicTexture == false && this.animations.currentFrame !== null) {
this._sx = this.animations.currentFrame.x;
this._sy = this.animations.currentFrame.y;
if(this.animations.currentFrame.trimmed) {
this._dx += this.animations.currentFrame.spriteSourceSizeX;
this._dy += this.animations.currentFrame.spriteSourceSizeY;
}
}
// Apply camera difference
if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) {
this._dx -= (camera.worldView.x * this.scrollFactor.x);
this._dy -= (camera.worldView.y * this.scrollFactor.y);
}
// Rotation - needs to work from origin point really, but for now from center
if(this.angle !== 0 || this.flipped == true) {
this._game.stage.context.save();
this._game.stage.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2));
if(this.angle !== 0) {
this._game.stage.context.rotate(this.angle * (Math.PI / 180));
}
this._dx = -(this._dw / 2);
this._dy = -(this._dh / 2);
if(this.flipped == true) {
this._game.stage.context.scale(-1, 1);
}
}
this._sx = Math.round(this._sx);
this._sy = Math.round(this._sy);
this._sw = Math.round(this._sw);
this._sh = Math.round(this._sh);
this._dx = Math.round(this._dx);
this._dy = Math.round(this._dy);
this._dw = Math.round(this._dw);
this._dh = Math.round(this._dh);
if(this._texture != null) {
if(this._dynamicTexture) {
this._game.stage.context.drawImage(this._texture.canvas, // Source Image
this._sx, // Source X (location within the source image)
this._sy, // Source Y
this._sw, // Source Width
this._sh, // Source Height
this._dx, // Destination X (where on the canvas it'll be drawn)
this._dy, // Destination Y
this._dw, // Destination Width (always same as Source Width unless scaled)
this._dh);
// Destination Height (always same as Source Height unless scaled)
} else {
this._game.stage.context.drawImage(this._texture, // Source Image
this._sx, // Source X (location within the source image)
this._sy, // Source Y
this._sw, // Source Width
this._sh, // Source Height
this._dx, // Destination X (where on the canvas it'll be drawn)
this._dy, // Destination Y
this._dw, // Destination Width (always same as Source Width unless scaled)
this._dh);
// Destination Height (always same as Source Height unless scaled)
}
} else {
this._game.stage.context.fillStyle = 'rgb(255,255,255)';
this._game.stage.context.fillRect(this._dx, this._dy, this._dw, this._dh);
}
if(this.flipped === true || this.rotation !== 0) {
//this._game.stage.context.translate(0, 0);
this._game.stage.context.restore();
}
if(this.renderDebug) {
this.renderBounds(camera, cameraOffsetX, cameraOffsetY);
}
if(globalAlpha > -1) {
this._game.stage.context.globalAlpha = globalAlpha;
}
return true;
};
Sprite.prototype.renderBounds = // Renders the bounding box around this Sprite and the contact points. Useful for visually debugging.
function (camera, cameraOffsetX, cameraOffsetY) {
this._dx = cameraOffsetX + (this.bounds.topLeft.x - camera.worldView.x);
this._dy = cameraOffsetY + (this.bounds.topLeft.y - camera.worldView.y);
this._game.stage.context.fillStyle = this.renderDebugColor;
this._game.stage.context.fillRect(this._dx, this._dy, this._dw, this._dh);
this._game.stage.context.fillStyle = this.renderDebugPointColor;
var hw = this.bounds.halfWidth * this.scale.x;
var hh = this.bounds.halfHeight * this.scale.y;
var sw = (this.bounds.width * this.scale.x) - 1;
var sh = (this.bounds.height * this.scale.y) - 1;
this._game.stage.context.fillRect(this._dx, this._dy, 1, 1)// top left
;
this._game.stage.context.fillRect(this._dx + hw, this._dy, 1, 1)// top center
;
this._game.stage.context.fillRect(this._dx + sw, this._dy, 1, 1)// top right
;
this._game.stage.context.fillRect(this._dx, this._dy + hh, 1, 1)// left center
;
this._game.stage.context.fillRect(this._dx + hw, this._dy + hh, 1, 1)// center
;
this._game.stage.context.fillRect(this._dx + sw, this._dy + hh, 1, 1)// right center
;
this._game.stage.context.fillRect(this._dx, this._dy + sh, 1, 1)// bottom left
;
this._game.stage.context.fillRect(this._dx + hw, this._dy + sh, 1, 1)// bottom center
;
this._game.stage.context.fillRect(this._dx + sw, this._dy + sh, 1, 1)// bottom right
;
};
Sprite.prototype.renderDebugInfo = function (x, y, color) {
if (typeof color === "undefined") { color = 'rgb(255,255,255)'; }
this._game.stage.context.fillStyle = color;
this._game.stage.context.fillText('Sprite: ' + this.name + ' (' + this.bounds.width + ' x ' + this.bounds.height + ')', x, y);
this._game.stage.context.fillText('x: ' + this.bounds.x.toFixed(1) + ' y: ' + this.bounds.y.toFixed(1) + ' rotation: ' + this.angle.toFixed(1), x, y + 14);
this._game.stage.context.fillText('dx: ' + this._dx.toFixed(1) + ' dy: ' + this._dy.toFixed(1) + ' dw: ' + this._dw.toFixed(1) + ' dh: ' + this._dh.toFixed(1), x, y + 28);
this._game.stage.context.fillText('sx: ' + this._sx.toFixed(1) + ' sy: ' + this._sy.toFixed(1) + ' sw: ' + this._sw.toFixed(1) + ' sh: ' + this._sh.toFixed(1), x, y + 42);
};
return Sprite;
})(Phaser.GameObject);
Phaser.Sprite = Sprite;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - Animation
*
* An Animation is a single animation. It is created by the AnimationManager and belongs to Sprite objects.
*/
var Phaser;
(function (Phaser) {
var Animation = (function () {
function Animation(game, parent, frameData, name, frames, delay, looped) {
this._game = game;
this._parent = parent;
this._frames = frames;
this._frameData = frameData;
this.name = name;
this.delay = 1000 / delay;
this.looped = looped;
this.isFinished = false;
this.isPlaying = false;
}
Object.defineProperty(Animation.prototype, "frameTotal", {
get: function () {
return this._frames.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation.prototype, "frame", {
get: function () {
return this._frameIndex;
},
set: function (value) {
this.currentFrame = this._frameData.getFrame(value);
if(this.currentFrame !== null) {
this._parent.bounds.width = this.currentFrame.width;
this._parent.bounds.height = this.currentFrame.height;
this._frameIndex = value;
}
},
enumerable: true,
configurable: true
});
Animation.prototype.play = function (frameRate, loop) {
if (typeof frameRate === "undefined") { frameRate = null; }
if(frameRate !== null) {
this.delay = 1000 / frameRate;
}
if(loop !== undefined) {
this.looped = loop;
}
this.isPlaying = true;
this.isFinished = false;
this._timeLastFrame = this._game.time.now;
this._timeNextFrame = this._game.time.now + this.delay;
this._frameIndex = 0;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
};
Animation.prototype.restart = function () {
this.isPlaying = true;
this.isFinished = false;
this._timeLastFrame = this._game.time.now;
this._timeNextFrame = this._game.time.now + this.delay;
this._frameIndex = 0;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
};
Animation.prototype.stop = function () {
this.isPlaying = false;
this.isFinished = true;
};
Animation.prototype.update = function () {
if(this.isPlaying == true && this._game.time.now >= this._timeNextFrame) {
this._frameIndex++;
if(this._frameIndex == this._frames.length) {
if(this.looped) {
this._frameIndex = 0;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
} else {
this.onComplete();
}
} else {
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
}
this._timeLastFrame = this._game.time.now;
this._timeNextFrame = this._game.time.now + this.delay;
return true;
}
return false;
};
Animation.prototype.destroy = function () {
this._game = null;
this._parent = null;
this._frames = null;
this._frameData = null;
this.currentFrame = null;
this.isPlaying = false;
};
Animation.prototype.onComplete = function () {
this.isPlaying = false;
this.isFinished = true;
// callback
};
return Animation;
})();
Phaser.Animation = Animation;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - AnimationLoader
*
* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
*/
var Phaser;
(function (Phaser) {
var AnimationLoader = (function () {
function AnimationLoader() { }
AnimationLoader.parseSpriteSheet = function parseSpriteSheet(game, key, frameWidth, frameHeight, frameMax) {
// How big is our image?
var img = game.cache.getImage(key);
if(img == null) {
return null;
}
var width = img.width;
var height = img.height;
var row = Math.round(width / frameWidth);
var column = Math.round(height / frameHeight);
var total = row * column;
if(frameMax !== -1) {
total = frameMax;
}
// Zero or smaller than frame sizes?
if(width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0) {
return null;
}
// Let's create some frames then
var data = new Phaser.FrameData();
var x = 0;
var y = 0;
for(var i = 0; i < total; i++) {
data.addFrame(new Phaser.Frame(x, y, frameWidth, frameHeight, ''));
x += frameWidth;
if(x === width) {
x = 0;
y += frameHeight;
}
}
return data;
};
AnimationLoader.parseJSONData = function parseJSONData(game, json) {
// Let's create some frames then
var data = new Phaser.FrameData();
// By this stage frames is a fully parsed array
var frames = json;
var newFrame;
for(var i = 0; i < frames.length; i++) {
newFrame = data.addFrame(new Phaser.Frame(frames[i].frame.x, frames[i].frame.y, frames[i].frame.w, frames[i].frame.h, frames[i].filename));
newFrame.setTrim(frames[i].trimmed, frames[i].sourceSize.w, frames[i].sourceSize.h, frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].spriteSourceSize.w, frames[i].spriteSourceSize.h);
}
return data;
};
return AnimationLoader;
})();
Phaser.AnimationLoader = AnimationLoader;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - Frame
*
* A Frame is a single frame of an animation and is part of a FrameData collection.
*/
var Phaser;
(function (Phaser) {
var Frame = (function () {
function Frame(x, y, width, height, name) {
// Useful for Texture Atlas files (is set to the filename value)
this.name = '';
// Rotated? (not yet implemented)
this.rotated = false;
// Either cw or ccw, rotation is always 90 degrees
this.rotationDirection = 'cw';
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.name = name;
this.rotated = false;
this.trimmed = false;
}
Frame.prototype.setRotation = function (rotated, rotationDirection) {
// Not yet supported
};
Frame.prototype.setTrim = function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
this.trimmed = trimmed;
this.sourceSizeW = actualWidth;
this.sourceSizeH = actualHeight;
this.spriteSourceSizeX = destX;
this.spriteSourceSizeY = destY;
this.spriteSourceSizeW = destWidth;
this.spriteSourceSizeH = destHeight;
};
return Frame;
})();
Phaser.Frame = Frame;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - FrameData
*
* FrameData is a container for Frame objects, the internal representation of animation data in Phaser.
*/
var Phaser;
(function (Phaser) {
var FrameData = (function () {
function FrameData() {
this._frames = [];
this._frameNames = [];
}
Object.defineProperty(FrameData.prototype, "total", {
get: function () {
return this._frames.length;
},
enumerable: true,
configurable: true
});
FrameData.prototype.addFrame = function (frame) {
frame.index = this._frames.length;
this._frames.push(frame);
if(frame.name !== '') {
this._frameNames[frame.name] = frame.index;
}
return frame;
};
FrameData.prototype.getFrame = function (index) {
if(this._frames[index]) {
return this._frames[index];
}
return null;
};
FrameData.prototype.getFrameByName = function (name) {
if(this._frameNames[name] >= 0) {
return this._frames[this._frameNames[name]];
}
return null;
};
FrameData.prototype.checkFrameName = function (name) {
if(this._frameNames[name] >= 0) {
return true;
}
return false;
};
FrameData.prototype.getFrameRange = function (start, end, output) {
if (typeof output === "undefined") { output = []; }
for(var i = start; i <= end; i++) {
output.push(this._frames[i]);
}
return output;
};
FrameData.prototype.getFrameIndexes = function (output) {
if (typeof output === "undefined") { output = []; }
output.length = 0;
for(var i = 0; i < this._frames.length; i++) {
output.push(i);
}
return output;
};
FrameData.prototype.getFrameIndexesByName = function (input) {
var output = [];
for(var i = 0; i < input.length; i++) {
if(this.getFrameByName(input[i])) {
output.push(this.getFrameByName(input[i]).index);
}
}
return output;
};
FrameData.prototype.getAllFrames = function () {
return this._frames;
};
FrameData.prototype.getFrames = function (range) {
var output = [];
for(var i = 0; i < range.length; i++) {
output.push(this._frames[i]);
}
return output;
};
return FrameData;
})();
Phaser.FrameData = FrameData;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/// <reference path="gameobjects/Sprite.ts" />
/// <reference path="system/animation/Animation.ts" />
/// <reference path="system/animation/AnimationLoader.ts" />
/// <reference path="system/animation/Frame.ts" />
/// <reference path="system/animation/FrameData.ts" />
/**
* Phaser - AnimationManager
*
* Any Sprite that has animation contains an instance of the AnimationManager, which is used to add, play and update
* sprite specific animations.
*/
var Phaser;
(function (Phaser) {
var AnimationManager = (function () {
function AnimationManager(game, parent) {
this._frameData = null;
this.currentFrame = null;
this._game = game;
this._parent = parent;
this._anims = {
};
}
AnimationManager.prototype.loadFrameData = function (frameData) {
this._frameData = frameData;
this.frame = 0;
};
AnimationManager.prototype.add = function (name, frames, frameRate, loop, useNumericIndex) {
if (typeof frames === "undefined") { frames = null; }
if (typeof frameRate === "undefined") { frameRate = 60; }
if (typeof loop === "undefined") { loop = false; }
if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
if(this._frameData == null) {
return;
}
if(frames == null) {
frames = this._frameData.getFrameIndexes();
} else {
if(this.validateFrames(frames, useNumericIndex) == false) {
return;
}
}
if(useNumericIndex == false) {
frames = this._frameData.getFrameIndexesByName(frames);
}
this._anims[name] = new Phaser.Animation(this._game, this._parent, this._frameData, name, frames, frameRate, loop);
this.currentAnim = this._anims[name];
};
AnimationManager.prototype.validateFrames = function (frames, useNumericIndex) {
for(var i = 0; i < frames.length; i++) {
if(useNumericIndex == true) {
if(frames[i] > this._frameData.total) {
return false;
}
} else {
if(this._frameData.checkFrameName(frames[i]) == false) {
return false;
}
}
}
return true;
};
AnimationManager.prototype.play = function (name, frameRate, loop) {
if (typeof frameRate === "undefined") { frameRate = null; }
if(this._anims[name]) {
if(this.currentAnim == this._anims[name]) {
if(this.currentAnim.isPlaying == false) {
this.currentAnim.play(frameRate, loop);
}
} else {
this.currentAnim = this._anims[name];
this.currentAnim.play(frameRate, loop);
}
}
};
AnimationManager.prototype.stop = function (name) {
if(this._anims[name]) {
this.currentAnim = this._anims[name];
this.currentAnim.stop();
}
};
AnimationManager.prototype.update = function () {
if(this.currentAnim && this.currentAnim.update() == true) {
this.currentFrame = this.currentAnim.currentFrame;
this._parent.bounds.width = this.currentFrame.width;
this._parent.bounds.height = this.currentFrame.height;
}
};
Object.defineProperty(AnimationManager.prototype, "frameData", {
get: function () {
return this._frameData;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationManager.prototype, "frameTotal", {
get: function () {
return this._frameData.total;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationManager.prototype, "frame", {
get: function () {
return this._frameIndex;
},
set: function (value) {
this.currentFrame = this._frameData.getFrame(value);
if(this.currentFrame !== null) {
this._parent.bounds.width = this.currentFrame.width;
this._parent.bounds.height = this.currentFrame.height;
this._frameIndex = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationManager.prototype, "frameName", {
get: function () {
return this.currentFrame.name;
},
set: function (value) {
this.currentFrame = this._frameData.getFrameByName(value);
if(this.currentFrame !== null) {
this._parent.bounds.width = this.currentFrame.width;
this._parent.bounds.height = this.currentFrame.height;
this._frameIndex = this.currentFrame.index;
}
},
enumerable: true,
configurable: true
});
return AnimationManager;
})();
Phaser.AnimationManager = AnimationManager;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - Cache
*
* A game only has one instance of a Cache and it is used to store all externally loaded assets such
* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up.
*/
var Phaser;
(function (Phaser) {
var Cache = (function () {
function Cache(game) {
this._game = game;
this._canvases = {
};
this._images = {
};
this._sounds = {
};
this._text = {
};
}
Cache.prototype.addCanvas = function (key, canvas, context) {
this._canvases[key] = {
canvas: canvas,
context: context
};
};
Cache.prototype.addSpriteSheet = function (key, url, data, frameWidth, frameHeight, frameMax) {
this._images[key] = {
url: url,
data: data,
spriteSheet: true,
frameWidth: frameWidth,
frameHeight: frameHeight
};
this._images[key].frameData = Phaser.AnimationLoader.parseSpriteSheet(this._game, key, frameWidth, frameHeight, frameMax);
};
Cache.prototype.addTextureAtlas = function (key, url, data, jsonData) {
this._images[key] = {
url: url,
data: data,
spriteSheet: true
};
this._images[key].frameData = Phaser.AnimationLoader.parseJSONData(this._game, jsonData);
};
Cache.prototype.addImage = function (key, url, data) {
this._images[key] = {
url: url,
data: data,
spriteSheet: false
};
};
Cache.prototype.addSound = function (key, url, data) {
this._sounds[key] = {
url: url,
data: data,
decoded: false
};
};
Cache.prototype.decodedSound = function (key, data) {
this._sounds[key].data = data;
this._sounds[key].decoded = true;
};
Cache.prototype.addText = function (key, url, data) {
this._text[key] = {
url: url,
data: data
};
};
Cache.prototype.getCanvas = function (key) {
if(this._canvases[key]) {
return this._canvases[key].canvas;
}
return null;
};
Cache.prototype.getImage = function (key) {
if(this._images[key]) {
return this._images[key].data;
}
return null;
};
Cache.prototype.getFrameData = function (key) {
if(this._images[key] && this._images[key].spriteSheet == true) {
return this._images[key].frameData;
}
return null;
};
Cache.prototype.getSound = function (key) {
if(this._sounds[key]) {
return this._sounds[key].data;
}
return null;
};
Cache.prototype.isSoundDecoded = function (key) {
if(this._sounds[key]) {
return this._sounds[key].decoded;
}
};
Cache.prototype.isSpriteSheet = function (key) {
if(this._images[key]) {
return this._images[key].spriteSheet;
}
};
Cache.prototype.getText = function (key) {
if(this._text[key]) {
return this._text[key].data;
}
return null;
};
Cache.prototype.destroy = function () {
for(var item in this._canvases) {
delete this._canvases[item['key']];
}
for(var item in this._images) {
delete this._images[item['key']];
}
for(var item in this._sounds) {
delete this._sounds[item['key']];
}
for(var item in this._text) {
delete this._text[item['key']];
}
};
return Cache;
})();
Phaser.Cache = Cache;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/// <reference path="system/Camera.ts" />
/**
* Phaser - CameraManager
*
* Your game only has one CameraManager instance and it's responsible for looking after, creating and destroying
* all of the cameras in the world.
*
* TODO: If the Camera is larger than the Stage size then the rotation offset isn't correct
* TODO: Texture Repeat doesn't scroll, because it's part of the camera not the world, need to think about this more
*/
var Phaser;
(function (Phaser) {
var CameraManager = (function () {
function CameraManager(game, x, y, width, height) {
this._game = game;
this._cameras = [];
this.current = this.addCamera(x, y, width, height);
}
CameraManager.prototype.getAll = function () {
return this._cameras;
};
CameraManager.prototype.update = function () {
this._cameras.forEach(function (camera) {
return camera.update();
});
};
CameraManager.prototype.render = function () {
this._cameras.forEach(function (camera) {
return camera.render();
});
};
CameraManager.prototype.addCamera = function (x, y, width, height) {
var newCam = new Phaser.Camera(this._game, this._cameras.length, x, y, width, height);
this._cameras.push(newCam);
return newCam;
};
CameraManager.prototype.removeCamera = function (id) {
if(this._cameras[id]) {
if(this.current === this._cameras[id]) {
this.current = null;
}
this._cameras.splice(id, 1);
return true;
} else {
return false;
}
};
CameraManager.prototype.destroy = function () {
this._cameras.length = 0;
this.current = this.addCamera(0, 0, this._game.stage.width, this._game.stage.height);
};
return CameraManager;
})();
Phaser.CameraManager = CameraManager;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - Point
*
* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
*/
var Phaser;
(function (Phaser) {
var Point = (function () {
/**
* Creates a new point. If you pass no parameters to this method, a point is created at (0,0).
* @class Point
* @constructor
* @param {Number} x The horizontal position of this point (default 0)
* @param {Number} y The vertical position of this point (default 0)
**/
function Point(x, y) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
this.setTo(x, y);
}
Point.prototype.add = /**
* Adds the coordinates of another point to the coordinates of this point to create a new point.
* @method add
* @param {Point} point - The point to be added.
* @return {Point} The new Point object.
**/
function (toAdd, output) {
if (typeof output === "undefined") { output = new Point(); }
return output.setTo(this.x + toAdd.x, this.y + toAdd.y);
};
Point.prototype.addTo = /**
* Adds the given values to the coordinates of this point and returns it
* @method addTo
* @param {Number} x - The amount to add to the x value of the point
* @param {Number} y - The amount to add to the x value of the point
* @return {Point} This Point object.
**/
function (x, y) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
return this.setTo(this.x + x, this.y + y);
};
Point.prototype.subtractFrom = /**
* Adds the given values to the coordinates of this point and returns it
* @method addTo
* @param {Number} x - The amount to add to the x value of the point
* @param {Number} y - The amount to add to the x value of the point
* @return {Point} This Point object.
**/
function (x, y) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
return this.setTo(this.x - x, this.y - y);
};
Point.prototype.invert = /**
* Inverts the x and y values of this point
* @method invert
* @return {Point} This Point object.
**/
function () {
return this.setTo(this.y, this.x);
};
Point.prototype.clamp = /**
* Clamps this Point object to be between the given min and max
* @method clamp
* @param {number} The minimum value to clamp this Point to
* @param {number} The maximum value to clamp this Point to
* @return {Point} This Point object.
**/
function (min, max) {
this.clampX(min, max);
this.clampY(min, max);
return this;
};
Point.prototype.clampX = /**
* Clamps the x value of this Point object to be between the given min and max
* @method clampX
* @param {number} The minimum value to clamp this Point to
* @param {number} The maximum value to clamp this Point to
* @return {Point} This Point object.
**/
function (min, max) {
this.x = Math.max(Math.min(this.x, max), min);
return this;
};
Point.prototype.clampY = /**
* Clamps the y value of this Point object to be between the given min and max
* @method clampY
* @param {number} The minimum value to clamp this Point to
* @param {number} The maximum value to clamp this Point to
* @return {Point} This Point object.
**/
function (min, max) {
this.x = Math.max(Math.min(this.x, max), min);
this.y = Math.max(Math.min(this.y, max), min);
return this;
};
Point.prototype.clone = /**
* Creates a copy of this Point.
* @method clone
* @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
* @return {Point} The new Point object.
**/
function (output) {
if (typeof output === "undefined") { output = new Point(); }
return output.setTo(this.x, this.y);
};
Point.prototype.copyFrom = /**
* Copies the point data from the source Point object into this Point object.
* @method copyFrom
* @param {Point} source - The point to copy from.
* @return {Point} This Point object. Useful for chaining method calls.
**/
function (source) {
return this.setTo(source.x, source.y);
};
Point.prototype.copyTo = /**
* Copies the point data from this Point object to the given target Point object.
* @method copyTo
* @param {Point} target - The point to copy to.
* @return {Point} The target Point object.
**/
function (target) {
return target.setTo(this.x, this.y);
};
Point.prototype.distanceTo = /**
* Returns the distance from this Point object to the given Point object.
* @method distanceFrom
* @param {Point} target - The destination Point object.
* @param {Boolean} round - Round the distance to the nearest integer (default false)
* @return {Number} The distance between this Point object and the destination Point object.
**/
function (target, round) {
if (typeof round === "undefined") { round = false; }
var dx = this.x - target.x;
var dy = this.y - target.y;
if(round === true) {
return Math.round(Math.sqrt(dx * dx + dy * dy));
} else {
return Math.sqrt(dx * dx + dy * dy);
}
};
Point.distanceBetween = /**
* Returns the distance between the two Point objects.
* @method distanceBetween
* @param {Point} pointA - The first Point object.
* @param {Point} pointB - The second Point object.
* @param {Boolean} round - Round the distance to the nearest integer (default false)
* @return {Number} The distance between the two Point objects.
**/
function distanceBetween(pointA, pointB, round) {
if (typeof round === "undefined") { round = false; }
var dx = pointA.x - pointB.x;
var dy = pointA.y - pointB.y;
if(round === true) {
return Math.round(Math.sqrt(dx * dx + dy * dy));
} else {
return Math.sqrt(dx * dx + dy * dy);
}
};
Point.prototype.distanceCompare = /**
* Returns true if the distance between this point and a target point is greater than or equal a specified distance.
* This avoids using a costly square root operation
* @method distanceCompare
* @param {Point} target - The Point object to use for comparison.
* @param {Number} distance - The distance to use for comparison.
* @return {Boolena} True if distance is >= specified distance.
**/
function (target, distance) {
if(this.distanceTo(target) >= distance) {
return true;
} else {
return false;
}
};
Point.prototype.equals = /**
* Determines whether this Point object and the given point object are equal. They are equal if they have the same x and y values.
* @method equals
* @param {Point} point - The point to compare against.
* @return {Boolean} A value of true if the object is equal to this Point object; false if it is not equal.
**/
function (toCompare) {
if(this.x === toCompare.x && this.y === toCompare.y) {
return true;
} else {
return false;
}
};
Point.prototype.interpolate = /**
* Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2.
* The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2).
* @method interpolate
* @param {Point} pointA - The first Point object.
* @param {Point} pointB - The second Point object.
* @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned.
* @return {Point} The new interpolated Point object.
**/
function (pointA, pointB, f) {
};
Point.prototype.offset = /**
* Offsets the Point object by the specified amount. The value of dx is added to the original value of x to create the new x value.
* The value of dy is added to the original value of y to create the new y value.
* @method offset
* @param {Number} dx - The amount by which to offset the horizontal coordinate, x.
* @param {Number} dy - The amount by which to offset the vertical coordinate, y.
* @return {Point} This Point object. Useful for chaining method calls.
**/
function (dx, dy) {
this.x += dx;
this.y += dy;
return this;
};
Point.prototype.polar = /**
* Converts a pair of polar coordinates to a Cartesian point coordinate.
* @method polar
* @param {Number} length - The length coordinate of the polar pair.
* @param {Number} angle - The angle, in radians, of the polar pair.
* @return {Point} The new Cartesian Point object.
**/
function (length, angle) {
};
Point.prototype.setTo = /**
* Sets the x and y values of this Point object to the given coordinates.
* @method setTo
* @param {Number} x - The horizontal position of this point.
* @param {Number} y - The vertical position of this point.
* @return {Point} This Point object. Useful for chaining method calls.
**/
function (x, y) {
this.x = x;
this.y = y;
return this;
};
Point.prototype.subtract = /**
* Subtracts the coordinates of another point from the coordinates of this point to create a new point.
* @method subtract
* @param {Point} point - The point to be subtracted.
* @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
* @return {Point} The new Point object.
**/
function (point, output) {
if (typeof output === "undefined") { output = new Point(); }
return output.setTo(this.x - point.x, this.y - point.y);
};
Point.prototype.toString = /**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the instance.
**/
function () {
return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
};
return Point;
})();
Phaser.Point = Point;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="MicroPoint.ts" />
/**
* Phaser - Rectangle
*
* A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height.
*/
var Phaser;
(function (Phaser) {
var Rectangle = (function () {
/**
* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created.
* @class Rectangle
* @constructor
* @param {Number} x The x coordinate of the top-left corner of the rectangle.
* @param {Number} y The y coordinate of the top-left corner of the rectangle.
* @param {Number} width The width of the rectangle in pixels.
* @param {Number} height The height of the rectangle in pixels.
* @return {Rectangle} This rectangle object
**/
function Rectangle(x, y, width, height) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof width === "undefined") { width = 0; }
if (typeof height === "undefined") { height = 0; }
this._tempX = null;
this._tempY = null;
this._tempWidth = null;
this._tempHeight = null;
/**
* The width of the rectangle
* @property width
* @type Number
**/
this._width = 0;
/**
* The height of the rectangle
* @property height
* @type Number
**/
this._height = 0;
/**
* Half of the width of the rectangle
* @property halfWidth
* @type Number
**/
this._halfWidth = 0;
/**
* Half of the height of the rectangle
* @property halfHeight
* @type Number
**/
this._halfHeight = 0;
/**
* The size of the longest side (width or height)
* @property length
* @type Number
**/
this.length = 0;
this._width = width;
if(width > 0) {
this._halfWidth = Math.round(width / 2);
}
this._height = height;
if(height > 0) {
this._halfHeight = Math.round(height / 2);
}
this.length = Math.max(this._width, this._height);
this.topLeft = new Phaser.MicroPoint(x, y, this);
this.topCenter = new Phaser.MicroPoint(x + this._halfWidth, y, this);
this.topRight = new Phaser.MicroPoint(x + this._width - 1, y, this);
this.leftCenter = new Phaser.MicroPoint(x, y + this._halfHeight, this);
this.center = new Phaser.MicroPoint(x + this._halfWidth, y + this._halfHeight, this);
this.rightCenter = new Phaser.MicroPoint(x + this._width - 1, y + this._halfHeight, this);
this.bottomLeft = new Phaser.MicroPoint(x, y + this._height - 1, this);
this.bottomCenter = new Phaser.MicroPoint(x + this._halfWidth, y + this._height - 1, this);
this.bottomRight = new Phaser.MicroPoint(x + this._width - 1, y + this._height - 1, this);
}
Object.defineProperty(Rectangle.prototype, "x", {
get: /**
* The x coordinate of the top-left corner of the rectangle
* @property x
* @type Number
**/
function () {
return this.topLeft.x;
},
set: /**
* The x coordinate of the top-left corner of the rectangle
* @property x
* @type Number
**/
function (value) {
this.topLeft.x = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "y", {
get: /**
* The y coordinate of the top-left corner of the rectangle
* @property y
* @type Number
**/
function () {
return this.topLeft.y;
},
set: /**
* The y coordinate of the top-left corner of the rectangle
* @property y
* @type Number
**/
function (value) {
this.topLeft.y = value;
},
enumerable: true,
configurable: true
});
Rectangle.prototype.updateBounds = /**
* Updates all of the MicroPoints based on the values of width and height.
* You should not normally call this directly.
**/
function () {
if(this._tempWidth !== null) {
this._width = this._tempWidth;
this._halfWidth = 0;
if(this._width > 0) {
this._halfWidth = Math.round(this._width / 2);
}
}
if(this._tempHeight !== null) {
this._height = this._tempHeight;
this._halfHeight = 0;
if(this._height > 0) {
this._halfHeight = Math.round(this._height / 2);
}
}
this.length = Math.max(this._width, this._height);
if(this._tempX !== null && this._tempY !== null) {
this.topLeft.setTo(this._tempX, this._tempY, false);
} else if(this._tempX !== null && this._tempY == null) {
this.topLeft.setTo(this._tempX, this.topLeft.y, false);
} else if(this._tempX == null && this._tempY !== null) {
this.topLeft.setTo(this.topLeft.x, this._tempY, false);
} else {
this.topLeft.setTo(this.x, this.y, false);
}
this.topCenter.setTo(this.x + this._halfWidth, this.y, false);
this.topRight.setTo(this.x + this._width - 1, this.y, false);
this.leftCenter.setTo(this.x, this.y + this._halfHeight, false);
this.center.setTo(this.x + this._halfWidth, this.y + this._halfHeight, false);
this.rightCenter.setTo(this.x + this._width - 1, this.y + this._halfHeight, false);
this.bottomLeft.setTo(this.x, this.y + this._height - 1, false);
this.bottomCenter.setTo(this.x + this._halfWidth, this.y + this._height - 1, false);
this.bottomRight.setTo(this.x + this._width - 1, this.y + this._height - 1, false);
this._tempX = null;
this._tempY = null;
this._tempWidth = null;
this._tempHeight = null;
};
Object.defineProperty(Rectangle.prototype, "width", {
get: /**
* The width of the rectangle
* @property width
* @type Number
**/
function () {
return this._width;
},
set: /**
* The width of the rectangle
* @property width
* @type Number
**/
function (value) {
this._width = value;
this._halfWidth = Math.round(value / 2);
this.updateBounds();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "height", {
get: /**
* The height of the rectangle
* @property height
* @type Number
**/
function () {
return this._height;
},
set: /**
* The height of the rectangle
* @property height
* @type Number
**/
function (value) {
this._height = value;
this._halfHeight = Math.round(value / 2);
this.updateBounds();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "halfWidth", {
get: /**
* Half of the width of the rectangle
* @property halfWidth
* @type Number
**/
function () {
return this._halfWidth;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "halfHeight", {
get: /**
* Half of the height of the rectangle
* @property halfHeight
* @type Number
**/
function () {
return this._halfHeight;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "bottom", {
get: /**
* The sum of the y and height properties.
* Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
* @method bottom
* @return {Number}
**/
function () {
return this.bottomCenter.y;
},
set: /**
* The sum of the y and height properties.
* Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
* @method bottom
* @param {Number} value
**/
function (value) {
if(value < this.y) {
this._tempHeight = 0;
} else {
this._tempHeight = this.y + value;
}
this.updateBounds();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "left", {
get: /**
* The x coordinate of the top-left corner of the rectangle.
* Changing the left property of a Rectangle object has no effect on the y and height properties.
* However it does affect the width property, whereas changing the x value does not affect the width property.
* @method left
* @ return {number}
**/
function () {
return this.x;
},
set: /**
* The x coordinate of the top-left corner of the rectangle.
* Changing the left property of a Rectangle object has no effect on the y and height properties.
* However it does affect the width property, whereas changing the x value does not affect the width property.
* @method left
* @param {Number} value
**/
function (value) {
var diff = this.x - value;
if(this._width + diff < 0) {
this._tempWidth = 0;
this._tempX = value;
} else {
this._tempWidth = this._width + diff;
this._tempX = value;
}
this.updateBounds();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "right", {
get: /**
* The sum of the x and width properties.
* Changing the right property of a Rectangle object has no effect on the x, y and height properties.
* However it does affect the width property.
* @method right
* @return {Number}
**/
function () {
return this.rightCenter.x;
},
set: /**
* The sum of the x and width properties.
* Changing the right property of a Rectangle object has no effect on the x, y and height properties.
* However it does affect the width property.
* @method right
* @param {Number} value
**/
function (value) {
if(value < this.topLeft.x) {
this._tempWidth = 0;
} else {
this._tempWidth = (value - this.topLeft.x);
}
this.updateBounds();
},
enumerable: true,
configurable: true
});
Rectangle.prototype.size = /**
* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
* @method size
* @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
* @return {Point} The size of the Rectangle object
**/
function (output) {
if (typeof output === "undefined") { output = new Phaser.Point(); }
return output.setTo(this._width, this._height);
};
Object.defineProperty(Rectangle.prototype, "volume", {
get: /**
* The volume of the Rectangle object in pixels, derived from width * height
* @method volume
* @return {Number}
**/
function () {
return this._width * this._height;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "perimeter", {
get: /**
* The perimeter size of the Rectangle object in pixels. This is the sum of all 4 sides.
* @method perimeter
* @return {Number}
**/
function () {
return (this._width * 2) + (this._height * 2);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rectangle.prototype, "top", {
get: /**
* The y coordinate of the top-left corner of the rectangle.
* Changing the top property of a Rectangle object has no effect on the x and width properties.
* However it does affect the height property, whereas changing the y value does not affect the height property.
* @method top
* @return {Number}
**/
function () {
return this.topCenter.y;
},
set: /**
* The y coordinate of the top-left corner of the rectangle.
* Changing the top property of a Rectangle object has no effect on the x and width properties.
* However it does affect the height property, whereas changing the y value does not affect the height property.
* @method top
* @param {Number} value
**/
function (value) {
var diff = this.topCenter.y - value;
if(this._height + diff < 0) {
this._tempHeight = 0;
this._tempY = value;
} else {
this._tempHeight = this._height + diff;
this._tempY = value;
}
this.updateBounds();
},
enumerable: true,
configurable: true
});
Rectangle.prototype.clone = /**
* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
* @method clone
* @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
* @return {Rectangle}
**/
function (output) {
if (typeof output === "undefined") { output = new Rectangle(); }
return output.setTo(this.x, this.y, this.width, this.height);
};
Rectangle.prototype.contains = /**
* Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
* @method contains
* @param {Number} x The x coordinate of the point to test.
* @param {Number} y The y coordinate of the point to test.
* @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
**/
function (x, y) {
if(x >= this.topLeft.x && x <= this.topRight.x && y >= this.topLeft.y && y <= this.bottomRight.y) {
return true;
}
return false;
};
Rectangle.prototype.containsPoint = /**
* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object.
* This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
* @method containsPoint
* @param {Point} point The point object being checked. Can be Point or any object with .x and .y values.
* @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
**/
function (point) {
return this.contains(point.x, point.y);
};
Rectangle.prototype.containsRect = /**
* Determines whether the Rectangle object specified by the rect parameter is contained within this Rectangle object.
* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
* @method containsRect
* @param {Rectangle} rect The rectangle object being checked.
* @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
**/
function (rect) {
// If the given rect has a larger volume than this one then it can never contain it
if(rect.volume > this.volume) {
return false;
}
if(rect.x >= this.topLeft.x && rect.y >= this.topLeft.y && rect.rightCenter.x <= this.rightCenter.x && rect.bottomCenter.y <= this.bottomCenter.y) {
return true;
}
return false;
};
Rectangle.prototype.copyFrom = /**
* Copies all of rectangle data from the source Rectangle object into the calling Rectangle object.
* @method copyFrom
* @param {Rectangle} rect The source rectangle object to copy from
* @return {Rectangle} This rectangle object
**/
function (source) {
return this.setTo(source.x, source.y, source.width, source.height);
};
Rectangle.prototype.copyTo = /**
* Copies all the rectangle data from this Rectangle object into the destination Rectangle object.
* @method copyTo
* @param {Rectangle} rect The destination rectangle object to copy in to
* @return {Rectangle} The destination rectangle object
**/
function (target) {
return target.copyFrom(this);
};
Rectangle.prototype.equals = /**
* Determines whether the object specified in the toCompare parameter is equal to this Rectangle object.
* This method compares the x, y, width, and height properties of an object against the same properties of this Rectangle object.
* @method equals
* @param {Rectangle} toCompare The rectangle to compare to this Rectangle object.
* @return {Boolean} A value of true if the object has exactly the same values for the x, y, width, and height properties as this Rectangle object; otherwise false.
**/
function (toCompare) {
if(this.topLeft.equals(toCompare.topLeft) && this.bottomRight.equals(toCompare.bottomRight)) {
return true;
}
return false;
};
Rectangle.prototype.inflate = /**
* Increases the size of the Rectangle object by the specified amounts.
* The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value,
* and to the top and the bottom by the dy value.
* @method inflate
* @param {Number} dx The amount to be added to the left side of this Rectangle.
* @param {Number} dy The amount to be added to the bottom side of this Rectangle.
* @return {Rectangle} This Rectangle object.
**/
function (dx, dy) {
this._tempX = this.topLeft.x - dx;
this._tempWidth = this._width + (2 * dx);
this._tempY = this.topLeft.y - dy;
this._tempHeight = this._height + (2 * dy);
this.updateBounds();
return this;
};
Rectangle.prototype.inflatePoint = /**
* Increases the size of the Rectangle object.
* This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
* @method inflatePoint
* @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
* @return {Rectangle} This Rectangle object.
**/
function (point) {
return this.inflate(point.x, point.y);
};
Rectangle.prototype.intersection = /**
* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object,
* returns the area of intersection as a Rectangle object. If the rectangles do not intersect, this method
* returns an empty Rectangle object with its properties set to 0.
* @method intersection
* @param {Rectangle} toIntersect The Rectangle object to compare against to see if it intersects with this Rectangle object.
* @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
* @return {Rectangle} A Rectangle object that equals the area of intersection. If the rectangles do not intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, y, width, and height properties set to 0.
**/
function (toIntersect, output) {
if (typeof output === "undefined") { output = new Rectangle(); }
if(this.intersects(toIntersect) === true) {
output.x = Math.max(toIntersect.topLeft.x, this.topLeft.x);
output.y = Math.max(toIntersect.topLeft.y, this.topLeft.y);
output.width = Math.min(toIntersect.rightCenter.x, this.rightCenter.x) - output.x;
output.height = Math.min(toIntersect.bottomCenter.y, this.bottomCenter.y) - output.y;
}
return output;
};
Rectangle.prototype.intersects = /**
* Determines whether the object specified intersects (overlaps) with this Rectangle object.
* This method checks the x, y, width, and height properties of the specified Rectangle object to see if it intersects with this Rectangle object.
* @method intersects
* @param {Rectangle} r2 The Rectangle object to compare against to see if it intersects with this Rectangle object.
* @param {Number} t A tolerance value to allow for an intersection test with padding, default to 0
* @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
**/
function (r2, t) {
if (typeof t === "undefined") { t = 0; }
return !(r2.left > this.right + t || r2.right < this.left - t || r2.top > this.bottom + t || r2.bottom < this.top - t);
};
Object.defineProperty(Rectangle.prototype, "isEmpty", {
get: /**
* Determines whether or not this Rectangle object is empty.
* @method isEmpty
* @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false.
**/
function () {
if(this.width < 1 || this.height < 1) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
Rectangle.prototype.offset = /**
* Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
* @method offset
* @param {Number} dx Moves the x value of the Rectangle object by this amount.
* @param {Number} dy Moves the y value of the Rectangle object by this amount.
* @return {Rectangle} This Rectangle object.
**/
function (dx, dy) {
if(!isNaN(dx) && !isNaN(dy)) {
this.x += dx;
this.y += dy;
}
return this;
};
Rectangle.prototype.offsetPoint = /**
* Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
* @method offsetPoint
* @param {Point} point A Point object to use to offset this Rectangle object.
* @return {Rectangle} This Rectangle object.
**/
function (point) {
return this.offset(point.x, point.y);
};
Rectangle.prototype.setEmpty = /**
* Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0.
* @method setEmpty
* @return {Rectangle} This rectangle object
**/
function () {
return this.setTo(0, 0, 0, 0);
};
Rectangle.prototype.setTo = /**
* Sets the members of Rectangle to the specified values.
* @method setTo
* @param {Number} x The x coordinate of the top-left corner of the rectangle.
* @param {Number} y The y coordinate of the top-left corner of the rectangle.
* @param {Number} width The width of the rectangle in pixels.
* @param {Number} height The height of the rectangle in pixels.
* @return {Rectangle} This rectangle object
**/
function (x, y, width, height) {
this._tempX = x;
this._tempY = y;
this._tempWidth = width;
this._tempHeight = height;
this.updateBounds();
return this;
};
Rectangle.prototype.union = /**
* Adds two rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two rectangles.
* @method union
* @param {Rectangle} toUnion A Rectangle object to add to this Rectangle object.
* @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
* @return {Rectangle} A Rectangle object that is the union of the two rectangles.
**/
function (toUnion, output) {
if (typeof output === "undefined") { output = new Rectangle(); }
return output.setTo(Math.min(toUnion.x, this.x), Math.min(toUnion.y, this.y), Math.max(toUnion.right, this.right), Math.max(toUnion.bottom, this.bottom));
};
Rectangle.prototype.toString = /**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the instance.
**/
function () {
return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.isEmpty + ")}]";
};
return Rectangle;
})();
Phaser.Rectangle = Rectangle;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - Circle
*
* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter.
*/
var Phaser;
(function (Phaser) {
var Circle = (function () {
/**
* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
* @class Circle
* @constructor
* @param {Number} x The x coordinate of the center of the circle.
* @param {Number} y The y coordinate of the center of the circle.
* @return {Circle} This circle object
**/
function Circle(x, y, diameter) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof diameter === "undefined") { diameter = 0; }
this._diameter = 0;
this._radius = 0;
/**
* The x coordinate of the center of the circle
* @property x
* @type Number
**/
this.x = 0;
/**
* The y coordinate of the center of the circle
* @property y
* @type Number
**/
this.y = 0;
this.setTo(x, y, diameter);
}
Object.defineProperty(Circle.prototype, "diameter", {
get: /**
* The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2.
* @method diameter
* @return {Number}
**/
function () {
return this._diameter;
},
set: /**
* The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2.
* @method diameter
* @param {Number} The diameter of the circle.
**/
function (value) {
if(value > 0) {
this._diameter = value;
this._radius = value * 0.5;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "radius", {
get: /**
* The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
* @method radius
* @return {Number}
**/
function () {
return this._radius;
},
set: /**
* The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
* @method radius
* @param {Number} The radius of the circle.
**/
function (value) {
if(value > 0) {
this._radius = value;
this._diameter = value * 2;
}
},
enumerable: true,
configurable: true
});
Circle.prototype.circumference = /**
* The circumference of the circle.
* @method circumference
* @return {Number}
**/
function () {
return 2 * (Math.PI * this._radius);
};
Object.defineProperty(Circle.prototype, "bottom", {
get: /**
* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
* @method bottom
* @return {Number}
**/
function () {
return this.y + this._radius;
},
set: /**
* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
* @method bottom
* @param {Number} The value to adjust the height of the circle by.
**/
function (value) {
if(!isNaN(value)) {
if(value < this.y) {
this._radius = 0;
this._diameter = 0;
} else {
this.radius = value - this.y;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "left", {
get: /**
* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
* @method left
* @return {Number} The x coordinate of the leftmost point of the circle.
**/
function () {
return this.x - this._radius;
},
set: /**
* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
* @method left
* @param {Number} The value to adjust the position of the leftmost point of the circle by.
**/
function (value) {
if(!isNaN(value)) {
if(value < this.x) {
this.radius = this.x - value;
} else {
this._radius = 0;
this._diameter = 0;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "right", {
get: /**
* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
* @method right
* @return {Number}
**/
function () {
return this.x + this._radius;
},
set: /**
* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
* @method right
* @param {Number} The amount to adjust the diameter of the circle by.
**/
function (value) {
if(!isNaN(value)) {
if(value > this.x) {
this.radius = value - this.x;
} else {
this._radius = 0;
this._diameter = 0;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "top", {
get: /**
* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
* @method bottom
* @return {Number}
**/
function () {
return this.y - this._radius;
},
set: /**
* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
* @method bottom
* @param {Number} The amount to adjust the height of the circle by.
**/
function (value) {
if(!isNaN(value)) {
if(value > this.y) {
this._radius = 0;
this._diameter = 0;
} else {
this.radius = this.y - value;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "area", {
get: /**
* Gets the area of this Circle.
* @method area
* @return {Number} This area of this circle.
**/
function () {
if(this._radius > 0) {
return Math.PI * this._radius * this._radius;
} else {
return 0;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Circle.prototype, "isEmpty", {
get: /**
* Determines whether or not this Circle object is empty.
* @method isEmpty
* @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false.
**/
function () {
if(this._diameter < 1) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
Circle.prototype.intersectCircleLine = /**
* Whether the circle intersects with a line. Checks against infinite line defined by the two points on the line, not the line segment.
* If you need details about the intersection then use Collision.lineToCircle instead.
* @method intersectCircleLine
* @param {Object} the line object to check.
* @return {Boolean}
**/
function (line) {
return Phaser.Collision.lineToCircle(line, this).result;
};
Circle.prototype.clone = /**
* Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object.
* @method clone
* @param {Circle} output Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
* @return {Phaser.Circle}
**/
function (output) {
if (typeof output === "undefined") { output = new Circle(); }
return output.setTo(this.x, this.y, this._diameter);
};
Circle.prototype.contains = /**
* Return true if the given x/y coordinates are within this Circle object.
* If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead.
* @method contains
* @param {Number} The X value of the coordinate to test.
* @param {Number} The Y value of the coordinate to test.
* @return {Boolean} True if the coordinates are within this circle, otherwise false.
**/
function (x, y) {
return Phaser.Collision.circleContainsPoint(this, {
x: x,
y: y
}).result;
};
Circle.prototype.containsPoint = /**
* Return true if the coordinates of the given Point object are within this Circle object.
* If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead.
* @method containsPoint
* @param {Phaser.Point} The Point object to test.
* @return {Boolean} True if the coordinates are within this circle, otherwise false.
**/
function (point) {
return Phaser.Collision.circleContainsPoint(this, point).result;
};
Circle.prototype.containsCircle = /**
* Return true if the given Circle is contained entirely within this Circle object.
* If you need details about the intersection then use Phaser.Intersect.circleToCircle instead.
* @method containsCircle
* @param {Phaser.Circle} The Circle object to test.
* @return {Boolean} True if the coordinates are within this circle, otherwise false.
**/
function (circle) {
return Phaser.Collision.circleToCircle(this, circle).result;
};
Circle.prototype.copyFrom = /**
* Copies all of circle data from the source Circle object into the calling Circle object.
* @method copyFrom
* @param {Circle} rect The source circle object to copy from
* @return {Circle} This circle object
**/
function (source) {
return this.setTo(source.x, source.y, source.diameter);
};
Circle.prototype.copyTo = /**
* Copies all of circle data from this Circle object into the destination Circle object.
* @method copyTo
* @param {Circle} circle The destination circle object to copy in to
* @return {Circle} The destination circle object
**/
function (target) {
return target.copyFrom(this);
};
Circle.prototype.distanceTo = /**
* Returns the distance from the center of this Circle object to the given object (can be Circle, Point or anything with x/y values)
* @method distanceFrom
* @param {Circle/Point} target - The destination Point object.
* @param {Boolean} round - Round the distance to the nearest integer (default false)
* @return {Number} The distance between this Point object and the destination Point object.
**/
function (target, round) {
if (typeof round === "undefined") { round = false; }
var dx = this.x - target.x;
var dy = this.y - target.y;
if(round === true) {
return Math.round(Math.sqrt(dx * dx + dy * dy));
} else {
return Math.sqrt(dx * dx + dy * dy);
}
};
Circle.prototype.equals = /**
* Determines whether the object specified in the toCompare parameter is equal to this Circle object. This method compares the x, y and diameter properties of an object against the same properties of this Circle object.
* @method equals
* @param {Circle} toCompare The circle to compare to this Circle object.
* @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false.
**/
function (toCompare) {
if(this.x === toCompare.x && this.y === toCompare.y && this.diameter === toCompare.diameter) {
return true;
}
return false;
};
Circle.prototype.intersects = /**
* Determines whether the Circle object specified in the toIntersect parameter intersects with this Circle object. This method checks the radius distances between the two Circle objects to see if they intersect.
* @method intersects
* @param {Circle} toIntersect The Circle object to compare against to see if it intersects with this Circle object.
* @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
**/
function (toIntersect) {
if(this.distanceTo(toIntersect, false) < (this._radius + toIntersect._radius)) {
return true;
}
return false;
};
Circle.prototype.circumferencePoint = /**
* Returns a Point object containing the coordinates of a point on the circumference of this Circle based on the given angle.
* @method circumferencePoint
* @param {Number} The angle in radians (unless asDegrees is true) to return the point from.
* @param {Boolean} Is the given angle in radians (false) or degrees (true)?
* @param {Phaser.Point} An optional Point object to put the result in to. If none specified a new Point object will be created.
* @return {Phaser.Point} The Point object holding the result.
**/
function (angle, asDegrees, output) {
if (typeof asDegrees === "undefined") { asDegrees = false; }
if (typeof output === "undefined") { output = new Phaser.Point(); }
if(asDegrees === true) {
angle = angle * Phaser.GameMath.DEG_TO_RAD;
}
output.x = this.x + this._radius * Math.cos(angle);
output.y = this.y + this._radius * Math.sin(angle);
return output;
};
Circle.prototype.offset = /**
* Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
* @method offset
* @param {Number} dx Moves the x value of the Circle object by this amount.
* @param {Number} dy Moves the y value of the Circle object by this amount.
* @return {Circle} This Circle object.
**/
function (dx, dy) {
if(!isNaN(dx) && !isNaN(dy)) {
this.x += dx;
this.y += dy;
}
return this;
};
Circle.prototype.offsetPoint = /**
* Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter.
* @method offsetPoint
* @param {Point} point A Point object to use to offset this Circle object.
* @return {Circle} This Circle object.
**/
function (point) {
return this.offset(point.x, point.y);
};
Circle.prototype.setTo = /**
* Sets the members of Circle to the specified values.
* @method setTo
* @param {Number} x The x coordinate of the center of the circle.
* @param {Number} y The y coordinate of the center of the circle.
* @param {Number} diameter The diameter of the circle in pixels.
* @return {Circle} This circle object
**/
function (x, y, diameter) {
this.x = x;
this.y = y;
this._diameter = diameter;
this._radius = diameter * 0.5;
return this;
};
Circle.prototype.toString = /**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the instance.
**/
function () {
return "[{Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
};
return Circle;
})();
Phaser.Circle = Circle;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - Line
*
* A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment.
*/
var Phaser;
(function (Phaser) {
var Line = (function () {
/**
*
* @constructor
* @param {Number} x1
* @param {Number} y1
* @param {Number} x2
* @param {Number} y2
* @return {Phaser.Line} This Object
*/
function Line(x1, y1, x2, y2) {
if (typeof x1 === "undefined") { x1 = 0; }
if (typeof y1 === "undefined") { y1 = 0; }
if (typeof x2 === "undefined") { x2 = 0; }
if (typeof y2 === "undefined") { y2 = 0; }
/**
*
* @property x1
* @type Number
*/
this.x1 = 0;
/**
*
* @property y1
* @type Number
*/
this.y1 = 0;
/**
*
* @property x2
* @type Number
*/
this.x2 = 0;
/**
*
* @property y2
* @type Number
*/
this.y2 = 0;
this.setTo(x1, y1, x2, y2);
}
Line.prototype.clone = /**
*
* @method clone
* @param {Phaser.Line} [output]
* @return {Phaser.Line}
*/
function (output) {
if (typeof output === "undefined") { output = new Line(); }
return output.setTo(this.x1, this.y1, this.x2, this.y2);
};
Line.prototype.copyFrom = /**
*
* @method copyFrom
* @param {Phaser.Line} source
* @return {Phaser.Line}
*/
function (source) {
return this.setTo(source.x1, source.y1, source.x2, source.y2);
};
Line.prototype.copyTo = /**
*
* @method copyTo
* @param {Phaser.Line} target
* @return {Phaser.Line}
*/
function (target) {
return target.copyFrom(this);
};
Line.prototype.setTo = /**
*
* @method setTo
* @param {Number} x1
* @param {Number} y1
* @param {Number} x2
* @param {Number} y2
* @return {Phaser.Line}
*/
function (x1, y1, x2, y2) {
if (typeof x1 === "undefined") { x1 = 0; }
if (typeof y1 === "undefined") { y1 = 0; }
if (typeof x2 === "undefined") { x2 = 0; }
if (typeof y2 === "undefined") { y2 = 0; }
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
};
Object.defineProperty(Line.prototype, "width", {
get: function () {
return Math.max(this.x1, this.x2) - Math.min(this.x1, this.x2);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "height", {
get: function () {
return Math.max(this.y1, this.y2) - Math.min(this.y1, this.y2);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "length", {
get: /**
*
* @method length
* @return {Number}
*/
function () {
return Math.sqrt((this.x2 - this.x1) * (this.x2 - this.x1) + (this.y2 - this.y1) * (this.y2 - this.y1));
},
enumerable: true,
configurable: true
});
Line.prototype.getY = /**
*
* @method getY
* @param {Number} x
* @return {Number}
*/
function (x) {
return this.slope * x + this.yIntercept;
};
Object.defineProperty(Line.prototype, "angle", {
get: /**
*
* @method angle
* @return {Number}
*/
function () {
return Math.atan2(this.x2 - this.x1, this.y2 - this.y1);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "slope", {
get: /**
*
* @method slope
* @return {Number}
*/
function () {
return (this.y2 - this.y1) / (this.x2 - this.x1);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "perpSlope", {
get: /**
*
* @method perpSlope
* @return {Number}
*/
function () {
return -((this.x2 - this.x1) / (this.y2 - this.y1));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Line.prototype, "yIntercept", {
get: /**
*
* @method yIntercept
* @return {Number}
*/
function () {
return (this.y1 - this.slope * this.x1);
},
enumerable: true,
configurable: true
});
Line.prototype.isPointOnLine = /**
*
* @method isPointOnLine
* @param {Number} x
* @param {Number} y
* @return {Boolean}
*/
function (x, y) {
if((x - this.x1) * (this.y2 - this.y1) === (this.x2 - this.x1) * (y - this.y1)) {
return true;
} else {
return false;
}
};
Line.prototype.isPointOnLineSegment = /**
*
* @method isPointOnLineSegment
* @param {Number} x
* @param {Number} y
* @return {Boolean}
*/
function (x, y) {
var xMin = Math.min(this.x1, this.x2);
var xMax = Math.max(this.x1, this.x2);
var yMin = Math.min(this.y1, this.y2);
var yMax = Math.max(this.y1, this.y2);
if(this.isPointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax)) {
return true;
} else {
return false;
}
};
Line.prototype.intersectLineLine = /**
*
* @method intersectLineLine
* @param {Any} line
* @return {Any}
*/
function (line) {
//return Phaser.intersectLineLine(this,line);
};
Line.prototype.perp = /**
*
* @method perp
* @param {Number} x
* @param {Number} y
* @param {Phaser.Line} [output]
* @return {Phaser.Line}
*/
function (x, y, output) {
if(this.y1 === this.y2) {
if(output) {
output.setTo(x, y, x, this.y1);
} else {
return new Line(x, y, x, this.y1);
}
}
var yInt = (y - this.perpSlope * x);
var pt = this.intersectLineLine({
x1: x,
y1: y,
x2: 0,
y2: yInt
});
if(output) {
output.setTo(x, y, pt.x, pt.y);
} else {
return new Line(x, y, pt.x, pt.y);
}
};
Line.prototype.toString = /*
intersectLineCircle (circle:Circle)
{
var perp = this.perp()
return Phaser.intersectLineCircle(this,circle);
}
*/
/**
*
* @method toString
* @return {String}
*/
function () {
return "[{Line (x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " y2=" + this.y2 + ")}]";
};
return Line;
})();
Phaser.Line = Line;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - IntersectResult
*
* A light-weight result object to hold the results of an intersection. For when you need more than just true/false.
*/
var Phaser;
(function (Phaser) {
var IntersectResult = (function () {
function IntersectResult() {
/**
* Did they intersect or not?
* @property result
* @type Boolean
*/
this.result = false;
}
IntersectResult.prototype.setTo = /**
*
* @method setTo
* @param {Number} x1
* @param {Number} y1
* @param {Number} [x2]
* @param {Number} [y2]
* @param {Number} [width]
* @param {Number} [height]
*/
function (x1, y1, x2, y2, width, height) {
if (typeof x2 === "undefined") { x2 = 0; }
if (typeof y2 === "undefined") { y2 = 0; }
if (typeof width === "undefined") { width = 0; }
if (typeof height === "undefined") { height = 0; }
this.x = x1;
this.y = y1;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.width = width;
this.height = height;
};
return IntersectResult;
})();
Phaser.IntersectResult = IntersectResult;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - LinkedList
*
* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks!
*/
var Phaser;
(function (Phaser) {
var LinkedList = (function () {
/**
* Creates a new link, and sets <code>object</code> and <code>next</code> to <code>null</code>.
*/
function LinkedList() {
this.object = null;
this.next = null;
}
LinkedList.prototype.destroy = /**
* Clean up memory.
*/
function () {
this.object = null;
if(this.next != null) {
this.next.destroy();
}
this.next = null;
};
return LinkedList;
})();
Phaser.LinkedList = LinkedList;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="LinkedList.ts" />
/**
* Phaser - QuadTree
*
* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation.
* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself,
* or the A list against the B list. Handy for different things!
*/
var Phaser;
(function (Phaser) {
var QuadTree = (function (_super) {
__extends(QuadTree, _super);
/**
* Instantiate a new Quad Tree node.
*
* @param X The X-coordinate of the point in space.
* @param Y The Y-coordinate of the point in space.
* @param Width Desired width of this node.
* @param Height Desired height of this node.
* @param Parent The parent branch or node. Pass null to create a root.
*/
function QuadTree(X, Y, Width, Height, Parent) {
if (typeof Parent === "undefined") { Parent = null; }
_super.call(this, X, Y, Width, Height);
//console.log('-------- QuadTree',X,Y,Width,Height);
this._headA = this._tailA = new Phaser.LinkedList();
this._headB = this._tailB = new Phaser.LinkedList();
//Copy the parent's children (if there are any)
if(Parent != null) {
//console.log('Parent not null');
var iterator;
var ot;
if(Parent._headA.object != null) {
iterator = Parent._headA;
//console.log('iterator set to parent headA');
while(iterator != null) {
if(this._tailA.object != null) {
ot = this._tailA;
this._tailA = new Phaser.LinkedList();
ot.next = this._tailA;
}
this._tailA.object = iterator.object;
iterator = iterator.next;
}
}
if(Parent._headB.object != null) {
iterator = Parent._headB;
//console.log('iterator set to parent headB');
while(iterator != null) {
if(this._tailB.object != null) {
ot = this._tailB;
this._tailB = new Phaser.LinkedList();
ot.next = this._tailB;
}
this._tailB.object = iterator.object;
iterator = iterator.next;
}
}
} else {
QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions);
}
this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min);
//console.log('canSubdivided', this._canSubdivide);
//Set up comparison/sort helpers
this._northWestTree = null;
this._northEastTree = null;
this._southEastTree = null;
this._southWestTree = null;
this._leftEdge = this.x;
this._rightEdge = this.x + this.width;
this._halfWidth = this.width / 2;
this._midpointX = this._leftEdge + this._halfWidth;
this._topEdge = this.y;
this._bottomEdge = this.y + this.height;
this._halfHeight = this.height / 2;
this._midpointY = this._topEdge + this._halfHeight;
}
QuadTree.A_LIST = 0;
QuadTree.B_LIST = 1;
QuadTree.prototype.destroy = /**
* Clean up memory.
*/
function () {
this._tailA.destroy();
this._tailB.destroy();
this._headA.destroy();
this._headB.destroy();
this._tailA = null;
this._tailB = null;
this._headA = null;
this._headB = null;
if(this._northWestTree != null) {
this._northWestTree.destroy();
}
if(this._northEastTree != null) {
this._northEastTree.destroy();
}
if(this._southEastTree != null) {
this._southEastTree.destroy();
}
if(this._southWestTree != null) {
this._southWestTree.destroy();
}
this._northWestTree = null;
this._northEastTree = null;
this._southEastTree = null;
this._southWestTree = null;
QuadTree._object = null;
QuadTree._processingCallback = null;
QuadTree._notifyCallback = null;
};
QuadTree.prototype.load = /**
* Load objects and/or groups into the quad tree, and register notify and processing callbacks.
*
* @param ObjectOrGroup1 Any object that is or extends GameObject or Group.
* @param ObjectOrGroup2 Any object that is or extends GameObject or Group. If null, the first parameter will be checked against itself.
* @param NotifyCallback A function with the form <code>myFunction(Object1:GameObject,Object2:GameObject)</code> that is called whenever two objects are found to overlap in world space, and either no ProcessCallback is specified, or the ProcessCallback returns true.
* @param ProcessCallback A function with the form <code>myFunction(Object1:GameObject,Object2:GameObject):bool</code> that is called whenever two objects are found to overlap in world space. The NotifyCallback is only called if this function returns true. See GameObject.separate().
*/
function (ObjectOrGroup1, ObjectOrGroup2, NotifyCallback, ProcessCallback) {
if (typeof ObjectOrGroup2 === "undefined") { ObjectOrGroup2 = null; }
if (typeof NotifyCallback === "undefined") { NotifyCallback = null; }
if (typeof ProcessCallback === "undefined") { ProcessCallback = null; }
//console.log('quadtree load', QuadTree.divisions, ObjectOrGroup1, ObjectOrGroup2);
this.add(ObjectOrGroup1, QuadTree.A_LIST);
if(ObjectOrGroup2 != null) {
this.add(ObjectOrGroup2, QuadTree.B_LIST);
QuadTree._useBothLists = true;
} else {
QuadTree._useBothLists = false;
}
QuadTree._notifyCallback = NotifyCallback;
QuadTree._processingCallback = ProcessCallback;
//console.log('use both', QuadTree._useBothLists);
//console.log('------------ end of load');
};
QuadTree.prototype.add = /**
* Call this function to add an object to the root of the tree.
* This function will recursively add all group members, but
* not the groups themselves.
*
* @param ObjectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly.
* @param List A <code>uint</code> flag indicating the list to which you want to add the objects. Options are <code>QuadTree.A_LIST</code> and <code>QuadTree.B_LIST</code>.
*/
function (ObjectOrGroup, List) {
QuadTree._list = List;
if(ObjectOrGroup.isGroup == true) {
var i = 0;
var basic;
var members = ObjectOrGroup['members'];
var l = ObjectOrGroup['length'];
while(i < l) {
basic = members[i++];
if((basic != null) && basic.exists) {
if(basic.isGroup) {
this.add(basic, List);
} else {
QuadTree._object = basic;
if(QuadTree._object.exists && QuadTree._object.allowCollisions) {
QuadTree._objectLeftEdge = QuadTree._object.x;
QuadTree._objectTopEdge = QuadTree._object.y;
QuadTree._objectRightEdge = QuadTree._object.x + QuadTree._object.width;
QuadTree._objectBottomEdge = QuadTree._object.y + QuadTree._object.height;
this.addObject();
}
}
}
}
} else {
QuadTree._object = ObjectOrGroup;
//console.log('add - not group:', ObjectOrGroup.name);
if(QuadTree._object.exists && QuadTree._object.allowCollisions) {
QuadTree._objectLeftEdge = QuadTree._object.x;
QuadTree._objectTopEdge = QuadTree._object.y;
QuadTree._objectRightEdge = QuadTree._object.x + QuadTree._object.width;
QuadTree._objectBottomEdge = QuadTree._object.y + QuadTree._object.height;
//console.log('object properties', QuadTree._objectLeftEdge, QuadTree._objectTopEdge, QuadTree._objectRightEdge, QuadTree._objectBottomEdge);
this.addObject();
}
}
};
QuadTree.prototype.addObject = /**
* Internal function for recursively navigating and creating the tree
* while adding objects to the appropriate nodes.
*/
function () {
//console.log('addObject');
//If this quad (not its children) lies entirely inside this object, add it here
if(!this._canSubdivide || ((this._leftEdge >= QuadTree._objectLeftEdge) && (this._rightEdge <= QuadTree._objectRightEdge) && (this._topEdge >= QuadTree._objectTopEdge) && (this._bottomEdge <= QuadTree._objectBottomEdge))) {
//console.log('add To List');
this.addToList();
return;
}
//See if the selected object fits completely inside any of the quadrants
if((QuadTree._objectLeftEdge > this._leftEdge) && (QuadTree._objectRightEdge < this._midpointX)) {
if((QuadTree._objectTopEdge > this._topEdge) && (QuadTree._objectBottomEdge < this._midpointY)) {
//console.log('Adding NW tree');
if(this._northWestTree == null) {
this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this);
}
this._northWestTree.addObject();
return;
}
if((QuadTree._objectTopEdge > this._midpointY) && (QuadTree._objectBottomEdge < this._bottomEdge)) {
//console.log('Adding SW tree');
if(this._southWestTree == null) {
this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this);
}
this._southWestTree.addObject();
return;
}
}
if((QuadTree._objectLeftEdge > this._midpointX) && (QuadTree._objectRightEdge < this._rightEdge)) {
if((QuadTree._objectTopEdge > this._topEdge) && (QuadTree._objectBottomEdge < this._midpointY)) {
//console.log('Adding NE tree');
if(this._northEastTree == null) {
this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this);
}
this._northEastTree.addObject();
return;
}
if((QuadTree._objectTopEdge > this._midpointY) && (QuadTree._objectBottomEdge < this._bottomEdge)) {
//console.log('Adding SE tree');
if(this._southEastTree == null) {
this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this);
}
this._southEastTree.addObject();
return;
}
}
//If it wasn't completely contained we have to check out the partial overlaps
if((QuadTree._objectRightEdge > this._leftEdge) && (QuadTree._objectLeftEdge < this._midpointX) && (QuadTree._objectBottomEdge > this._topEdge) && (QuadTree._objectTopEdge < this._midpointY)) {
if(this._northWestTree == null) {
this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this);
}
//console.log('added to north west partial tree');
this._northWestTree.addObject();
}
if((QuadTree._objectRightEdge > this._midpointX) && (QuadTree._objectLeftEdge < this._rightEdge) && (QuadTree._objectBottomEdge > this._topEdge) && (QuadTree._objectTopEdge < this._midpointY)) {
if(this._northEastTree == null) {
this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this);
}
//console.log('added to north east partial tree');
this._northEastTree.addObject();
}
if((QuadTree._objectRightEdge > this._midpointX) && (QuadTree._objectLeftEdge < this._rightEdge) && (QuadTree._objectBottomEdge > this._midpointY) && (QuadTree._objectTopEdge < this._bottomEdge)) {
if(this._southEastTree == null) {
this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this);
}
//console.log('added to south east partial tree');
this._southEastTree.addObject();
}
if((QuadTree._objectRightEdge > this._leftEdge) && (QuadTree._objectLeftEdge < this._midpointX) && (QuadTree._objectBottomEdge > this._midpointY) && (QuadTree._objectTopEdge < this._bottomEdge)) {
if(this._southWestTree == null) {
this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this);
}
//console.log('added to south west partial tree');
this._southWestTree.addObject();
}
};
QuadTree.prototype.addToList = /**
* Internal function for recursively adding objects to leaf lists.
*/
function () {
//console.log('Adding to List');
var ot;
if(QuadTree._list == QuadTree.A_LIST) {
//console.log('A LIST');
if(this._tailA.object != null) {
ot = this._tailA;
this._tailA = new Phaser.LinkedList();
ot.next = this._tailA;
}
this._tailA.object = QuadTree._object;
} else {
//console.log('B LIST');
if(this._tailB.object != null) {
ot = this._tailB;
this._tailB = new Phaser.LinkedList();
ot.next = this._tailB;
}
this._tailB.object = QuadTree._object;
}
if(!this._canSubdivide) {
return;
}
if(this._northWestTree != null) {
this._northWestTree.addToList();
}
if(this._northEastTree != null) {
this._northEastTree.addToList();
}
if(this._southEastTree != null) {
this._southEastTree.addToList();
}
if(this._southWestTree != null) {
this._southWestTree.addToList();
}
};
QuadTree.prototype.execute = /**
* <code>QuadTree</code>'s other main function. Call this after adding objects
* using <code>QuadTree.load()</code> to compare the objects that you loaded.
*
* @return Whether or not any overlaps were found.
*/
function () {
//console.log('quadtree execute');
var overlapProcessed = false;
var iterator;
if(this._headA.object != null) {
//console.log('---------------------------------------------------');
//console.log('headA iterator');
iterator = this._headA;
while(iterator != null) {
QuadTree._object = iterator.object;
if(QuadTree._useBothLists) {
QuadTree._iterator = this._headB;
} else {
QuadTree._iterator = iterator.next;
}
if(QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) {
//console.log('headA iterator overlapped true');
overlapProcessed = true;
}
iterator = iterator.next;
}
}
//Advance through the tree by calling overlap on each child
if((this._northWestTree != null) && this._northWestTree.execute()) {
//console.log('NW quadtree execute');
overlapProcessed = true;
}
if((this._northEastTree != null) && this._northEastTree.execute()) {
//console.log('NE quadtree execute');
overlapProcessed = true;
}
if((this._southEastTree != null) && this._southEastTree.execute()) {
//console.log('SE quadtree execute');
overlapProcessed = true;
}
if((this._southWestTree != null) && this._southWestTree.execute()) {
//console.log('SW quadtree execute');
overlapProcessed = true;
}
return overlapProcessed;
};
QuadTree.prototype.overlapNode = /**
* An private for comparing an object against the contents of a node.
*
* @return Whether or not any overlaps were found.
*/
function () {
//console.log('overlapNode');
//Walk the list and check for overlaps
var overlapProcessed = false;
var checkObject;
while(QuadTree._iterator != null) {
if(!QuadTree._object.exists || (QuadTree._object.allowCollisions <= 0)) {
//console.log('break 1');
break;
}
checkObject = QuadTree._iterator.object;
if((QuadTree._object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) {
//console.log('break 2');
QuadTree._iterator = QuadTree._iterator.next;
continue;
}
//calculate bulk hull for QuadTree._object
QuadTree._objectHullX = (QuadTree._object.x < QuadTree._object.last.x) ? QuadTree._object.x : QuadTree._object.last.x;
QuadTree._objectHullY = (QuadTree._object.y < QuadTree._object.last.y) ? QuadTree._object.y : QuadTree._object.last.y;
QuadTree._objectHullWidth = QuadTree._object.x - QuadTree._object.last.x;
QuadTree._objectHullWidth = QuadTree._object.width + ((QuadTree._objectHullWidth > 0) ? QuadTree._objectHullWidth : -QuadTree._objectHullWidth);
QuadTree._objectHullHeight = QuadTree._object.y - QuadTree._object.last.y;
QuadTree._objectHullHeight = QuadTree._object.height + ((QuadTree._objectHullHeight > 0) ? QuadTree._objectHullHeight : -QuadTree._objectHullHeight);
//calculate bulk hull for checkObject
QuadTree._checkObjectHullX = (checkObject.x < checkObject.last.x) ? checkObject.x : checkObject.last.x;
QuadTree._checkObjectHullY = (checkObject.y < checkObject.last.y) ? checkObject.y : checkObject.last.y;
QuadTree._checkObjectHullWidth = checkObject.x - checkObject.last.x;
QuadTree._checkObjectHullWidth = checkObject.width + ((QuadTree._checkObjectHullWidth > 0) ? QuadTree._checkObjectHullWidth : -QuadTree._checkObjectHullWidth);
QuadTree._checkObjectHullHeight = checkObject.y - checkObject.last.y;
QuadTree._checkObjectHullHeight = checkObject.height + ((QuadTree._checkObjectHullHeight > 0) ? QuadTree._checkObjectHullHeight : -QuadTree._checkObjectHullHeight);
//check for intersection of the two hulls
if((QuadTree._objectHullX + QuadTree._objectHullWidth > QuadTree._checkObjectHullX) && (QuadTree._objectHullX < QuadTree._checkObjectHullX + QuadTree._checkObjectHullWidth) && (QuadTree._objectHullY + QuadTree._objectHullHeight > QuadTree._checkObjectHullY) && (QuadTree._objectHullY < QuadTree._checkObjectHullY + QuadTree._checkObjectHullHeight)) {
//console.log('intersection!');
//Execute callback functions if they exist
if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, checkObject)) {
overlapProcessed = true;
}
if(overlapProcessed && (QuadTree._notifyCallback != null)) {
QuadTree._notifyCallback(QuadTree._object, checkObject);
}
}
QuadTree._iterator = QuadTree._iterator.next;
}
return overlapProcessed;
};
return QuadTree;
})(Phaser.Rectangle);
Phaser.QuadTree = QuadTree;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/// <reference path="geom/Point.ts" />
/// <reference path="geom/Rectangle.ts" />
/// <reference path="geom/Circle.ts" />
/// <reference path="geom/Line.ts" />
/// <reference path="geom/IntersectResult.ts" />
/// <reference path="system/QuadTree.ts" />
/**
* Phaser - Collision
*
* A set of extremely useful collision and geometry intersection functions.
*/
var Phaser;
(function (Phaser) {
var Collision = (function () {
function Collision(game) {
this._game = game;
}
Collision.LEFT = 0x0001;
Collision.RIGHT = 0x0010;
Collision.UP = 0x0100;
Collision.DOWN = 0x1000;
Collision.NONE = 0;
Collision.CEILING = Collision.UP;
Collision.FLOOR = Collision.DOWN;
Collision.WALL = Collision.LEFT | Collision.RIGHT;
Collision.ANY = Collision.LEFT | Collision.RIGHT | Collision.UP | Collision.DOWN;
Collision.OVERLAP_BIAS = 4;
Collision.lineToLine = /**
* -------------------------------------------------------------------------------------------
* Lines
* -------------------------------------------------------------------------------------------
**/
/**
* Check if the two given Line objects intersect
* @method lineToLine
* @param {Phaser.Line} The first line object to check
* @param {Phaser.Line} The second line object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineToLine(line1, line2, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var denom = (line1.x1 - line1.x2) * (line2.y1 - line2.y2) - (line1.y1 - line1.y2) * (line2.x1 - line2.x2);
if(denom !== 0) {
output.result = true;
output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (line2.x1 - line2.x2) - (line1.x1 - line1.x2) * (line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denom;
output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (line2.y1 - line2.y2) - (line1.y1 - line1.y2) * (line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denom;
}
return output;
};
Collision.lineToLineSegment = /**
* Check if the Line and Line Segment intersects
* @method lineToLineSegment
* @param {Phaser.Line} The line object to check
* @param {Phaser.Line} The line segment object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineToLineSegment(line1, seg, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var denom = (line1.x1 - line1.x2) * (seg.y1 - seg.y2) - (line1.y1 - line1.y2) * (seg.x1 - seg.x2);
if(denom !== 0) {
output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (seg.x1 - seg.x2) - (line1.x1 - line1.x2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denom;
output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (seg.y1 - seg.y2) - (line1.y1 - line1.y2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denom;
var maxX = Math.max(seg.x1, seg.x2);
var minX = Math.min(seg.x1, seg.x2);
var maxY = Math.max(seg.y1, seg.y2);
var minY = Math.min(seg.y1, seg.y2);
//if (!(output.x <= maxX && output.x >= minX) || !(output.y <= maxY && output.y >= minY))
if((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) {
output.result = true;
}
}
return output;
};
Collision.lineToRawSegment = /**
* Check if the Line and Line Segment intersects
* @method lineToLineSegment
* @param {Phaser.Line} The line object to check
* @param {number} The x1 value
* @param {number} The y1 value
* @param {number} The x2 value
* @param {number} The y2 value
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineToRawSegment(line, x1, y1, x2, y2, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var denom = (line.x1 - line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 - x2);
if(denom !== 0) {
output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (x1 - x2) - (line.x1 - line.x2) * (x1 * y2 - y1 * x2)) / denom;
output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 * y2 - y1 * x2)) / denom;
var maxX = Math.max(x1, x2);
var minX = Math.min(x1, x2);
var maxY = Math.max(y1, y2);
var minY = Math.min(y1, y2);
if((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) {
output.result = true;
}
}
return output;
};
Collision.lineToRay = /**
* Check if the Line and Ray intersects
* @method lineToRay
* @param {Phaser.Line} The Line object to check
* @param {Phaser.Line} The Ray object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineToRay(line1, ray, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var denom = (line1.x1 - line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 - ray.x2);
if(denom !== 0) {
output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.x1 - ray.x2) - (line1.x1 - line1.x2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denom;
output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denom;
output.result = true// true unless either of the 2 following conditions are met
;
if(!(ray.x1 >= ray.x2) && output.x < ray.x1) {
output.result = false;
}
if(!(ray.y1 >= ray.y2) && output.y < ray.y1) {
output.result = false;
}
}
return output;
};
Collision.lineToCircle = /**
* Check if the Line and Circle intersects
* @method lineToCircle
* @param {Phaser.Line} The Line object to check
* @param {Phaser.Circle} The Circle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection
**/
function lineToCircle(line, circle, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
// Get a perpendicular line running to the center of the circle
if(line.perp(circle.x, circle.y).length <= circle.radius) {
output.result = true;
}
return output;
};
Collision.lineToRectangle = /**
* Check if the Line intersects each side of the Rectangle
* @method lineToRectangle
* @param {Phaser.Line} The Line object to check
* @param {Phaser.Rectangle} The Rectangle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection
**/
function lineToRectangle(line, rect, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
// Top of the Rectangle vs the Line
this.lineToRawSegment(line, rect.x, rect.y, rect.right, rect.y, output);
if(output.result === true) {
return output;
}
// Left of the Rectangle vs the Line
this.lineToRawSegment(line, rect.x, rect.y, rect.x, rect.bottom, output);
if(output.result === true) {
return output;
}
// Bottom of the Rectangle vs the Line
this.lineToRawSegment(line, rect.x, rect.bottom, rect.right, rect.bottom, output);
if(output.result === true) {
return output;
}
// Right of the Rectangle vs the Line
this.lineToRawSegment(line, rect.right, rect.y, rect.right, rect.bottom, output);
return output;
};
Collision.lineSegmentToLineSegment = /**
* -------------------------------------------------------------------------------------------
* Line Segment
* -------------------------------------------------------------------------------------------
**/
/**
* Check if Line1 intersects with Line2
* @method lineSegmentToLineSegment
* @param {Phaser.Line} The first line object to check
* @param {Phaser.Line} The second line object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineSegmentToLineSegment(line1, line2, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
this.lineToLineSegment(line1, line2, output);
if(output.result === true) {
if(!(output.x >= Math.min(line1.x1, line1.x2) && output.x <= Math.max(line1.x1, line1.x2) && output.y >= Math.min(line1.y1, line1.y2) && output.y <= Math.max(line1.y1, line1.y2))) {
output.result = false;
}
}
return output;
};
Collision.lineSegmentToRay = /**
* Check if the Line Segment intersects with the Ray
* @method lineSegmentToRay
* @param {Phaser.Line} The Line object to check
* @param {Phaser.Line} The Line Ray object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineSegmentToRay(line1, ray, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
this.lineToRay(line1, ray, output);
if(output.result === true) {
if(!(output.x >= Math.min(line1.x1, line1.x2) && output.x <= Math.max(line1.x1, line1.x2) && output.y >= Math.min(line1.y1, line1.y2) && output.y <= Math.max(line1.y1, line1.y2))) {
output.result = false;
}
}
return output;
};
Collision.lineSegmentToCircle = /**
* Check if the Line Segment intersects with the Circle
* @method lineSegmentToCircle
* @param {Phaser.Line} The Line object to check
* @param {Phaser.Circle} The Circle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineSegmentToCircle(seg, circle, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var perp = seg.perp(circle.x, circle.y);
if(perp.length <= circle.radius) {
// Line intersects circle - check if segment does
var maxX = Math.max(seg.x1, seg.x2);
var minX = Math.min(seg.x1, seg.x2);
var maxY = Math.max(seg.y1, seg.y2);
var minY = Math.min(seg.y1, seg.y2);
if((perp.x2 <= maxX && perp.x2 >= minX) && (perp.y2 <= maxY && perp.y2 >= minY)) {
output.result = true;
} else {
// Worst case - segment doesn't traverse center, so no perpendicular connection.
if(this.circleContainsPoint(circle, {
x: seg.x1,
y: seg.y1
}) || this.circleContainsPoint(circle, {
x: seg.x2,
y: seg.y2
})) {
output.result = true;
}
}
}
return output;
};
Collision.lineSegmentToRectangle = /**
* Check if the Line Segment intersects with the Rectangle
* @method lineSegmentToCircle
* @param {Phaser.Line} The Line object to check
* @param {Phaser.Circle} The Circle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
**/
function lineSegmentToRectangle(seg, rect, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
if(rect.contains(seg.x1, seg.y1) && rect.contains(seg.x2, seg.y2)) {
output.result = true;
} else {
// Top of the Rectangle vs the Line
this.lineToRawSegment(seg, rect.x, rect.y, rect.right, rect.bottom, output);
if(output.result === true) {
return output;
}
// Left of the Rectangle vs the Line
this.lineToRawSegment(seg, rect.x, rect.y, rect.x, rect.bottom, output);
if(output.result === true) {
return output;
}
// Bottom of the Rectangle vs the Line
this.lineToRawSegment(seg, rect.x, rect.bottom, rect.right, rect.bottom, output);
if(output.result === true) {
return output;
}
// Right of the Rectangle vs the Line
this.lineToRawSegment(seg, rect.right, rect.y, rect.right, rect.bottom, output);
return output;
}
return output;
};
Collision.rayToRectangle = /**
* -------------------------------------------------------------------------------------------
* Ray
* -------------------------------------------------------------------------------------------
**/
/**
* Check if the two given Circle objects intersect
* @method circleToCircle
* @param {Phaser.Circle} The first circle object to check
* @param {Phaser.Circle} The second circle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection
**/
function rayToRectangle(ray, rect, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
// Currently just finds first intersection - might not be closest to ray pt1
this.lineToRectangle(ray, rect, output);
return output;
};
Collision.rayToLineSegment = /**
* Check whether a ray intersects a line segment, returns the parametric value where the intersection occurs.
* @method rayToLineSegment
* @static
* @param {Number} rayx1. The origin x of the ray.
* @param {Number} rayy1. The origin y of the ray.
* @param {Number} rayx2. The direction x of the ray.
* @param {Number} rayy2. The direction y of the ray.
* @param {Number} linex1. The x of the first point of the line segment.
* @param {Number} liney1. The y of the first point of the line segment.
* @param {Number} linex2. The x of the second point of the line segment.
* @param {Number} liney2. The y of the second point of the line segment.
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection stored in x
**/
function rayToLineSegment(rayx1, rayy1, rayx2, rayy2, linex1, liney1, linex2, liney2, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var r, s, d;
// Check lines are not parallel
if((rayy2 - rayy1) / (rayx2 - rayx1) != (liney2 - liney1) / (linex2 - linex1)) {
d = (((rayx2 - rayx1) * (liney2 - liney1)) - (rayy2 - rayy1) * (linex2 - linex1));
if(d != 0) {
r = (((rayy1 - liney1) * (linex2 - linex1)) - (rayx1 - linex1) * (liney2 - liney1)) / d;
s = (((rayy1 - liney1) * (rayx2 - rayx1)) - (rayx1 - linex1) * (rayy2 - rayy1)) / d;
if(r >= 0) {
if(s >= 0 && s <= 1) {
output.result = true;
output.x = rayx1 + r * (rayx2 - rayx1) , rayy1 + r * (rayy2 - rayy1);
}
}
}
}
return output;
};
Collision.pointToRectangle = /**
* -------------------------------------------------------------------------------------------
* Rectangles
* -------------------------------------------------------------------------------------------
**/
/**
* Determines whether the specified point is contained within the rectangular region defined by the Rectangle object.
* @method pointToRectangle
* @param {Point} point The point object being checked.
* @param {Rectangle} rect The rectangle object being checked.
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y/result
**/
function pointToRectangle(point, rect, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
output.setTo(point.x, point.y);
output.result = rect.containsPoint(point);
return output;
};
Collision.rectangleToRectangle = /**
* Check whether two axis aligned rectangles intersect. Return the intersecting rectangle dimensions if they do.
* @method rectangleToRectangle
* @param {Phaser.Rectangle} The first Rectangle object
* @param {Phaser.Rectangle} The second Rectangle object
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection in x/y/width/height
**/
function rectangleToRectangle(rect1, rect2, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var leftX = Math.max(rect1.x, rect2.x);
var rightX = Math.min(rect1.right, rect2.right);
var topY = Math.max(rect1.y, rect2.y);
var bottomY = Math.min(rect1.bottom, rect2.bottom);
output.setTo(leftX, topY, rightX - leftX, bottomY - topY, rightX - leftX, bottomY - topY);
var cx = output.x + output.width * .5;
var cy = output.y + output.height * .5;
if((cx > rect1.x && cx < rect1.right) && (cy > rect1.y && cy < rect1.bottom)) {
output.result = true;
}
return output;
};
Collision.rectangleToCircle = function rectangleToCircle(rect, circle, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
return this.circleToRectangle(circle, rect, output);
};
Collision.circleToCircle = /**
* -------------------------------------------------------------------------------------------
* Circle
* -------------------------------------------------------------------------------------------
**/
/**
* Check if the two given Circle objects intersect
* @method circleToCircle
* @param {Phaser.Circle} The first circle object to check
* @param {Phaser.Circle} The second circle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection
**/
function circleToCircle(circle1, circle2, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
output.result = ((circle1.radius + circle2.radius) * (circle1.radius + circle2.radius)) >= this.distanceSquared(circle1.x, circle1.y, circle2.x, circle2.y);
return output;
};
Collision.circleToRectangle = /**
* Check if the given Rectangle intersects with the given Circle
* @method circleToRectangle
* @param {Phaser.Circle} The circle object to check
* @param {Phaser.Rectangle} The Rectangle object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection
**/
function circleToRectangle(circle, rect, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
var inflatedRect = rect.clone();
inflatedRect.inflate(circle.radius, circle.radius);
output.result = inflatedRect.contains(circle.x, circle.y);
return output;
};
Collision.circleContainsPoint = /**
* Check if the given Point is found within the given Circle
* @method circleContainsPoint
* @param {Phaser.Circle} The circle object to check
* @param {Phaser.Point} The point object to check
* @param {Phaser.IntersectResult} An optional IntersectResult object to store the intersection values in (one is created if none given)
* @return {Phaser.IntersectResult} An IntersectResult object containing the results of this intersection
**/
function circleContainsPoint(circle, point, output) {
if (typeof output === "undefined") { output = new Phaser.IntersectResult(); }
output.result = circle.radius * circle.radius >= this.distanceSquared(circle.x, circle.y, point.x, point.y);
return output;
};
Collision.prototype.overlap = /**
* -------------------------------------------------------------------------------------------
* Game Object Collision
* -------------------------------------------------------------------------------------------
**/
/**
* Call this function to see if one <code>GameObject</code> overlaps another.
* Can be called with one object and one group, or two groups, or two objects,
* whatever floats your boat! For maximum performance try bundling a lot of objects
* together using a <code>Group</code> (or even bundling groups together!).
*
* <p>NOTE: does NOT take objects' scrollfactor into account, all overlaps are checked in world space.</p>
*
* @param ObjectOrGroup1 The first object or group you want to check.
* @param ObjectOrGroup2 The second object or group you want to check. If it is the same as the first it knows to just do a comparison within that group.
* @param NotifyCallback A function with two <code>GameObject</code> parameters - e.g. <code>myOverlapFunction(Object1:GameObject,Object2:GameObject)</code> - that is called if those two objects overlap.
* @param ProcessCallback A function with two <code>GameObject</code> parameters - e.g. <code>myOverlapFunction(Object1:GameObject,Object2:GameObject)</code> - that is called if those two objects overlap. If a ProcessCallback is provided, then NotifyCallback will only be called if ProcessCallback returns true for those objects!
*
* @return Whether any overlaps were detected.
*/
function (ObjectOrGroup1, ObjectOrGroup2, NotifyCallback, ProcessCallback) {
if (typeof ObjectOrGroup1 === "undefined") { ObjectOrGroup1 = null; }
if (typeof ObjectOrGroup2 === "undefined") { ObjectOrGroup2 = null; }
if (typeof NotifyCallback === "undefined") { NotifyCallback = null; }
if (typeof ProcessCallback === "undefined") { ProcessCallback = null; }
if(ObjectOrGroup1 == null) {
ObjectOrGroup1 = this._game.world.group;
}
if(ObjectOrGroup2 == ObjectOrGroup1) {
ObjectOrGroup2 = null;
}
Phaser.QuadTree.divisions = this._game.world.worldDivisions;
var quadTree = new Phaser.QuadTree(this._game.world.bounds.x, this._game.world.bounds.y, this._game.world.bounds.width, this._game.world.bounds.height);
quadTree.load(ObjectOrGroup1, ObjectOrGroup2, NotifyCallback, ProcessCallback);
var result = quadTree.execute();
quadTree.destroy();
quadTree = null;
return result;
};
Collision.separate = /**
* The main collision resolution in flixel.
*
* @param Object1 Any <code>Sprite</code>.
* @param Object2 Any other <code>Sprite</code>.
*
* @return Whether the objects in fact touched and were separated.
*/
function separate(Object1, Object2) {
var separatedX = Collision.separateX(Object1, Object2);
var separatedY = Collision.separateY(Object1, Object2);
return separatedX || separatedY;
};
Collision.separateX = /**
* The X-axis component of the object separation process.
*
* @param Object1 Any <code>Sprite</code>.
* @param Object2 Any other <code>Sprite</code>.
*
* @return Whether the objects in fact touched and were separated along the X axis.
*/
function separateX(Object1, Object2) {
//can't separate two immovable objects
var obj1immovable = Object1.immovable;
var obj2immovable = Object2.immovable;
if(obj1immovable && obj2immovable) {
return false;
}
//If one of the objects is a tilemap, just pass it off.
/*
if (typeof Object1 === 'Tilemap')
{
return Object1.overlapsWithCallback(Object2, separateX);
}
if (typeof Object2 === 'Tilemap')
{
return Object2.overlapsWithCallback(Object1, separateX, true);
}
*/
//First, get the two object deltas
var overlap = 0;
var obj1delta = Object1.x - Object1.last.x;
var obj2delta = Object2.x - Object2.last.x;
if(obj1delta != obj2delta) {
//Check if the X hulls actually overlap
var obj1deltaAbs = (obj1delta > 0) ? obj1delta : -obj1delta;
var obj2deltaAbs = (obj2delta > 0) ? obj2delta : -obj2delta;
var obj1rect = new Phaser.Rectangle(Object1.x - ((obj1delta > 0) ? obj1delta : 0), Object1.last.y, Object1.width + ((obj1delta > 0) ? obj1delta : -obj1delta), Object1.height);
var obj2rect = new Phaser.Rectangle(Object2.x - ((obj2delta > 0) ? obj2delta : 0), Object2.last.y, Object2.width + ((obj2delta > 0) ? obj2delta : -obj2delta), Object2.height);
if((obj1rect.x + obj1rect.width > obj2rect.x) && (obj1rect.x < obj2rect.x + obj2rect.width) && (obj1rect.y + obj1rect.height > obj2rect.y) && (obj1rect.y < obj2rect.y + obj2rect.height)) {
var maxOverlap = obj1deltaAbs + obj2deltaAbs + Collision.OVERLAP_BIAS;
//If they did overlap (and can), figure out by how much and flip the corresponding flags
if(obj1delta > obj2delta) {
overlap = Object1.x + Object1.width - Object2.x;
if((overlap > maxOverlap) || !(Object1.allowCollisions & Collision.RIGHT) || !(Object2.allowCollisions & Collision.LEFT)) {
overlap = 0;
} else {
Object1.touching |= Collision.RIGHT;
Object2.touching |= Collision.LEFT;
}
} else if(obj1delta < obj2delta) {
overlap = Object1.x - Object2.width - Object2.x;
if((-overlap > maxOverlap) || !(Object1.allowCollisions & Collision.LEFT) || !(Object2.allowCollisions & Collision.RIGHT)) {
overlap = 0;
} else {
Object1.touching |= Collision.LEFT;
Object2.touching |= Collision.RIGHT;
}
}
}
}
//Then adjust their positions and velocities accordingly (if there was any overlap)
if(overlap != 0) {
var obj1v = Object1.velocity.x;
var obj2v = Object2.velocity.x;
if(!obj1immovable && !obj2immovable) {
overlap *= 0.5;
Object1.x = Object1.x - overlap;
Object2.x += overlap;
var obj1velocity = Math.sqrt((obj2v * obj2v * Object2.mass) / Object1.mass) * ((obj2v > 0) ? 1 : -1);
var obj2velocity = Math.sqrt((obj1v * obj1v * Object1.mass) / Object2.mass) * ((obj1v > 0) ? 1 : -1);
var average = (obj1velocity + obj2velocity) * 0.5;
obj1velocity -= average;
obj2velocity -= average;
Object1.velocity.x = average + obj1velocity * Object1.elasticity;
Object2.velocity.x = average + obj2velocity * Object2.elasticity;
} else if(!obj1immovable) {
Object1.x = Object1.x - overlap;
Object1.velocity.x = obj2v - obj1v * Object1.elasticity;
} else if(!obj2immovable) {
Object2.x += overlap;
Object2.velocity.x = obj1v - obj2v * Object2.elasticity;
}
return true;
} else {
return false;
}
};
Collision.separateY = /**
* The Y-axis component of the object separation process.
*
* @param Object1 Any <code>Sprite</code>.
* @param Object2 Any other <code>Sprite</code>.
*
* @return Whether the objects in fact touched and were separated along the Y axis.
*/
function separateY(Object1, Object2) {
//can't separate two immovable objects
var obj1immovable = Object1.immovable;
var obj2immovable = Object2.immovable;
if(obj1immovable && obj2immovable) {
return false;
}
//If one of the objects is a tilemap, just pass it off.
/*
if (typeof Object1 === 'Tilemap')
{
return Object1.overlapsWithCallback(Object2, separateY);
}
if (typeof Object2 === 'Tilemap')
{
return Object2.overlapsWithCallback(Object1, separateY, true);
}
*/
//First, get the two object deltas
var overlap = 0;
var obj1delta = Object1.y - Object1.last.y;
var obj2delta = Object2.y - Object2.last.y;
if(obj1delta != obj2delta) {
//Check if the Y hulls actually overlap
var obj1deltaAbs = (obj1delta > 0) ? obj1delta : -obj1delta;
var obj2deltaAbs = (obj2delta > 0) ? obj2delta : -obj2delta;
var obj1rect = new Phaser.Rectangle(Object1.x, Object1.y - ((obj1delta > 0) ? obj1delta : 0), Object1.width, Object1.height + obj1deltaAbs);
var obj2rect = new Phaser.Rectangle(Object2.x, Object2.y - ((obj2delta > 0) ? obj2delta : 0), Object2.width, Object2.height + obj2deltaAbs);
if((obj1rect.x + obj1rect.width > obj2rect.x) && (obj1rect.x < obj2rect.x + obj2rect.width) && (obj1rect.y + obj1rect.height > obj2rect.y) && (obj1rect.y < obj2rect.y + obj2rect.height)) {
var maxOverlap = obj1deltaAbs + obj2deltaAbs + Collision.OVERLAP_BIAS;
//If they did overlap (and can), figure out by how much and flip the corresponding flags
if(obj1delta > obj2delta) {
overlap = Object1.y + Object1.height - Object2.y;
if((overlap > maxOverlap) || !(Object1.allowCollisions & Collision.DOWN) || !(Object2.allowCollisions & Collision.UP)) {
overlap = 0;
} else {
Object1.touching |= Collision.DOWN;
Object2.touching |= Collision.UP;
}
} else if(obj1delta < obj2delta) {
overlap = Object1.y - Object2.height - Object2.y;
if((-overlap > maxOverlap) || !(Object1.allowCollisions & Collision.UP) || !(Object2.allowCollisions & Collision.DOWN)) {
overlap = 0;
} else {
Object1.touching |= Collision.UP;
Object2.touching |= Collision.DOWN;
}
}
}
}
//Then adjust their positions and velocities accordingly (if there was any overlap)
if(overlap != 0) {
var obj1v = Object1.velocity.y;
var obj2v = Object2.velocity.y;
if(!obj1immovable && !obj2immovable) {
overlap *= 0.5;
Object1.y = Object1.y - overlap;
Object2.y += overlap;
var obj1velocity = Math.sqrt((obj2v * obj2v * Object2.mass) / Object1.mass) * ((obj2v > 0) ? 1 : -1);
var obj2velocity = Math.sqrt((obj1v * obj1v * Object1.mass) / Object2.mass) * ((obj1v > 0) ? 1 : -1);
var average = (obj1velocity + obj2velocity) * 0.5;
obj1velocity -= average;
obj2velocity -= average;
Object1.velocity.y = average + obj1velocity * Object1.elasticity;
Object2.velocity.y = average + obj2velocity * Object2.elasticity;
} else if(!obj1immovable) {
Object1.y = Object1.y - overlap;
Object1.velocity.y = obj2v - obj1v * Object1.elasticity;
//This is special case code that handles cases like horizontal moving platforms you can ride
if(Object2.active && Object2.moves && (obj1delta > obj2delta)) {
Object1.x += Object2.x - Object2.last.x;
}
} else if(!obj2immovable) {
Object2.y += overlap;
Object2.velocity.y = obj1v - obj2v * Object2.elasticity;
//This is special case code that handles cases like horizontal moving platforms you can ride
if(Object1.active && Object1.moves && (obj1delta < obj2delta)) {
Object2.x += Object1.x - Object1.last.x;
}
}
return true;
} else {
return false;
}
};
Collision.distance = /**
* -------------------------------------------------------------------------------------------
* Distance
* -------------------------------------------------------------------------------------------
**/
function distance(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
};
Collision.distanceSquared = function distanceSquared(x1, y1, x2, y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
};
return Collision;
})();
Phaser.Collision = Collision;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - DynamicTexture
*
* A DynamicTexture can be thought of as a mini canvas into which you can draw anything.
* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so
* based on the contents of the texture at the time. This allows you to create powerful effects
* once and have them replicated across as many game objects as you like.
*/
var Phaser;
(function (Phaser) {
var DynamicTexture = (function () {
function DynamicTexture(game, key, width, height) {
this._sx = 0;
this._sy = 0;
this._sw = 0;
this._sh = 0;
this._dx = 0;
this._dy = 0;
this._dw = 0;
this._dh = 0;
this._game = game;
this.canvas = document.createElement('canvas');
this.canvas.width = width;
this.canvas.height = height;
this.context = this.canvas.getContext('2d');
this.bounds = new Phaser.Rectangle(0, 0, width, height);
}
DynamicTexture.prototype.getPixel = function (x, y) {
//r = imageData.data[0];
//g = imageData.data[1];
//b = imageData.data[2];
//a = imageData.data[3];
var imageData = this.context.getImageData(x, y, 1, 1);
return this.getColor(imageData.data[0], imageData.data[1], imageData.data[2]);
};
DynamicTexture.prototype.getPixel32 = function (x, y) {
var imageData = this.context.getImageData(x, y, 1, 1);
return this.getColor32(imageData.data[3], imageData.data[0], imageData.data[1], imageData.data[2]);
};
DynamicTexture.prototype.getPixels = // Returns a CanvasPixelArray
function (rect) {
return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
};
DynamicTexture.prototype.setPixel = function (x, y, color) {
this.context.fillStyle = color;
this.context.fillRect(x, y, 1, 1);
};
DynamicTexture.prototype.setPixel32 = function (x, y, color) {
this.context.fillStyle = color;
this.context.fillRect(x, y, 1, 1);
};
DynamicTexture.prototype.setPixels = function (rect, input) {
this.context.putImageData(input, rect.x, rect.y);
};
DynamicTexture.prototype.fillRect = function (rect, color) {
this.context.fillStyle = color;
this.context.fillRect(rect.x, rect.y, rect.width, rect.height);
};
DynamicTexture.prototype.pasteImage = function (key, frame, destX, destY, destWidth, destHeight) {
if (typeof frame === "undefined") { frame = -1; }
if (typeof destX === "undefined") { destX = 0; }
if (typeof destY === "undefined") { destY = 0; }
if (typeof destWidth === "undefined") { destWidth = null; }
if (typeof destHeight === "undefined") { destHeight = null; }
var texture = null;
var frameData;
this._sx = 0;
this._sy = 0;
this._dx = destX;
this._dy = destY;
// TODO - Load a frame from a sprite sheet, otherwise we'll draw the whole lot
if(frame > -1) {
//if (this._game.cache.isSpriteSheet(key))
//{
// texture = this._game.cache.getImage(key);
//this.animations.loadFrameData(this._game.cache.getFrameData(key));
//}
} else {
texture = this._game.cache.getImage(key);
this._sw = texture.width;
this._sh = texture.height;
this._dw = texture.width;
this._dh = texture.height;
}
if(destWidth !== null) {
this._dw = destWidth;
}
if(destHeight !== null) {
this._dh = destHeight;
}
if(texture != null) {
this.context.drawImage(texture, // Source Image
this._sx, // Source X (location within the source image)
this._sy, // Source Y
this._sw, // Source Width
this._sh, // Source Height
this._dx, // Destination X (where on the canvas it'll be drawn)
this._dy, // Destination Y
this._dw, // Destination Width (always same as Source Width unless scaled)
this._dh);
// Destination Height (always same as Source Height unless scaled)
}
};
DynamicTexture.prototype.copyPixels = // TODO - Add in support for: alphaBitmapData: BitmapData = null, alphaPoint: Point = null, mergeAlpha: bool = false
function (sourceTexture, sourceRect, destPoint) {
// Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call
if(sourceRect.equals(this.bounds) == true) {
this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y);
} else {
this.context.putImageData(sourceTexture.getPixels(sourceRect), destPoint.x, destPoint.y);
}
};
DynamicTexture.prototype.clear = function () {
this.context.clearRect(0, 0, this.bounds.width, this.bounds.height);
};
Object.defineProperty(DynamicTexture.prototype, "width", {
get: function () {
return this.bounds.width;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DynamicTexture.prototype, "height", {
get: function () {
return this.bounds.height;
},
enumerable: true,
configurable: true
});
DynamicTexture.prototype.getColor32 = /**
* Given an alpha and 3 color values this will return an integer representation of it
*
* @param alpha The Alpha value (between 0 and 255)
* @param red The Red channel value (between 0 and 255)
* @param green The Green channel value (between 0 and 255)
* @param blue The Blue channel value (between 0 and 255)
*
* @return A native color value integer (format: 0xAARRGGBB)
*/
function (alpha, red, green, blue) {
return alpha << 24 | red << 16 | green << 8 | blue;
};
DynamicTexture.prototype.getColor = /**
* Given 3 color values this will return an integer representation of it
*
* @param red The Red channel value (between 0 and 255)
* @param green The Green channel value (between 0 and 255)
* @param blue The Blue channel value (between 0 and 255)
*
* @return A native color value integer (format: 0xRRGGBB)
*/
function (red, green, blue) {
return red << 16 | green << 8 | blue;
};
return DynamicTexture;
})();
Phaser.DynamicTexture = DynamicTexture;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - GameMath
*
* Adds a set of extra Math functions used through-out Phaser.
* Includes methods written by Dylan Engelman and Adam Saltsman.
*/
var Phaser;
(function (Phaser) {
var GameMath = (function () {
function GameMath(game) {
//arbitrary 8 digit epsilon
this.cosTable = [];
this.sinTable = [];
/**
* The global random number generator seed (for deterministic behavior in recordings and saves).
*/
this.globalSeed = Math.random();
this._game = game;
}
GameMath.PI = 3.141592653589793;
GameMath.PI_2 = 1.5707963267948965;
GameMath.PI_4 = 0.7853981633974483;
GameMath.PI_8 = 0.39269908169872413;
GameMath.PI_16 = 0.19634954084936206;
GameMath.TWO_PI = 6.283185307179586;
GameMath.THREE_PI_2 = 4.7123889803846895;
GameMath.E = 2.71828182845905;
GameMath.LN10 = 2.302585092994046;
GameMath.LN2 = 0.6931471805599453;
GameMath.LOG10E = 0.4342944819032518;
GameMath.LOG2E = 1.442695040888963387;
GameMath.SQRT1_2 = 0.7071067811865476;
GameMath.SQRT2 = 1.4142135623730951;
GameMath.DEG_TO_RAD = 0.017453292519943294444444444444444;
GameMath.RAD_TO_DEG = 57.295779513082325225835265587527;
GameMath.B_16 = 65536;
GameMath.B_31 = 2147483648;
GameMath.B_32 = 4294967296;
GameMath.B_48 = 281474976710656;
GameMath.B_53 = 9007199254740992;
GameMath.B_64 = 18446744073709551616;
GameMath.ONE_THIRD = 0.333333333333333333333333333333333;
GameMath.TWO_THIRDS = 0.666666666666666666666666666666666;
GameMath.ONE_SIXTH = 0.166666666666666666666666666666666;
GameMath.COS_PI_3 = 0.86602540378443864676372317075294;
GameMath.SIN_2PI_3 = 0.03654595;
GameMath.CIRCLE_ALPHA = 0.5522847498307933984022516322796;
GameMath.ON = true;
GameMath.OFF = false;
GameMath.SHORT_EPSILON = 0.1;
GameMath.PERC_EPSILON = 0.001;
GameMath.EPSILON = 0.0001;
GameMath.LONG_EPSILON = 0.00000001;
GameMath.prototype.fuzzyEqual = function (a, b, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return Math.abs(a - b) < epsilon;
};
GameMath.prototype.fuzzyLessThan = function (a, b, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return a < b + epsilon;
};
GameMath.prototype.fuzzyGreaterThan = function (a, b, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return a > b - epsilon;
};
GameMath.prototype.fuzzyCeil = function (val, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return Math.ceil(val - epsilon);
};
GameMath.prototype.fuzzyFloor = function (val, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return Math.floor(val + epsilon);
};
GameMath.prototype.average = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
var avg = 0;
for(var i = 0; i < args.length; i++) {
avg += args[i];
}
return avg / args.length;
};
GameMath.prototype.slam = function (value, target, epsilon) {
if (typeof epsilon === "undefined") { epsilon = 0.0001; }
return (Math.abs(value - target) < epsilon) ? target : value;
};
GameMath.prototype.percentageMinMax = /**
* ratio of value to a range
*/
function (val, max, min) {
if (typeof min === "undefined") { min = 0; }
val -= min;
max -= min;
if(!max) {
return 0;
} else {
return val / max;
}
};
GameMath.prototype.sign = /**
* a value representing the sign of the value.
* -1 for negative, +1 for positive, 0 if value is 0
*/
function (n) {
if(n) {
return n / Math.abs(n);
} else {
return 0;
}
};
GameMath.prototype.truncate = function (n) {
return (n > 0) ? Math.floor(n) : Math.ceil(n);
};
GameMath.prototype.shear = function (n) {
return n % 1;
};
GameMath.prototype.wrap = /**
* wrap a value around a range, similar to modulus with a floating minimum
*/
function (val, max, min) {
if (typeof min === "undefined") { min = 0; }
val -= min;
max -= min;
if(max == 0) {
return min;
}
val %= max;
val += min;
while(val < min) {
val += max;
}
return val;
};
GameMath.prototype.arithWrap = /**
* arithmetic version of wrap... need to decide which is more efficient
*/
function (value, max, min) {
if (typeof min === "undefined") { min = 0; }
max -= min;
if(max == 0) {
return min;
}
return value - max * Math.floor((value - min) / max);
};
GameMath.prototype.clamp = /**
* force a value within the boundaries of two values
*
* if max < min, min is returned
*/
function (input, max, min) {
if (typeof min === "undefined") { min = 0; }
return Math.max(min, Math.min(max, input));
};
GameMath.prototype.snapTo = /**
* Snap a value to nearest grid slice, using rounding.
*
* example if you have an interval gap of 5 and a position of 12... you will snap to 10. Where as 14 will snap to 15
*
* @param input - the value to snap
* @param gap - the interval gap of the grid
* @param start - optional starting offset for gap
*/
function (input, gap, start) {
if (typeof start === "undefined") { start = 0; }
if(gap == 0) {
return input;
}
input -= start;
input = gap * Math.round(input / gap);
return start + input;
};
GameMath.prototype.snapToFloor = /**
* Snap a value to nearest grid slice, using floor.
*
* example if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15
*
* @param input - the value to snap
* @param gap - the interval gap of the grid
* @param start - optional starting offset for gap
*/
function (input, gap, start) {
if (typeof start === "undefined") { start = 0; }
if(gap == 0) {
return input;
}
input -= start;
input = gap * Math.floor(input / gap);
return start + input;
};
GameMath.prototype.snapToCeil = /**
* Snap a value to nearest grid slice, using ceil.
*
* example if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20
*
* @param input - the value to snap
* @param gap - the interval gap of the grid
* @param start - optional starting offset for gap
*/
function (input, gap, start) {
if (typeof start === "undefined") { start = 0; }
if(gap == 0) {
return input;
}
input -= start;
input = gap * Math.ceil(input / gap);
return start + input;
};
GameMath.prototype.snapToInArray = /**
* Snaps a value to the nearest value in an array.
*/
function (input, arr, sort) {
if (typeof sort === "undefined") { sort = true; }
if(sort) {
arr.sort();
}
if(input < arr[0]) {
return arr[0];
}
var i = 1;
while(arr[i] < input) {
i++;
}
var low = arr[i - 1];
var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
return ((high - input) <= (input - low)) ? high : low;
};
GameMath.prototype.roundTo = /**
* roundTo some place comparative to a 'base', default is 10 for decimal place
*
* 'place' is represented by the power applied to 'base' to get that place
*
* @param value - the value to round
* @param place - the place to round to
* @param base - the base to round in... default is 10 for decimal
*
* e.g.
*
* 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
*
* roundTo(2000/7,3) == 0
* roundTo(2000/7,2) == 300
* roundTo(2000/7,1) == 290
* roundTo(2000/7,0) == 286
* roundTo(2000/7,-1) == 285.7
* roundTo(2000/7,-2) == 285.71
* roundTo(2000/7,-3) == 285.714
* roundTo(2000/7,-4) == 285.7143
* roundTo(2000/7,-5) == 285.71429
*
* roundTo(2000/7,3,2) == 288 -- 100100000
* roundTo(2000/7,2,2) == 284 -- 100011100
* roundTo(2000/7,1,2) == 286 -- 100011110
* roundTo(2000/7,0,2) == 286 -- 100011110
* roundTo(2000/7,-1,2) == 285.5 -- 100011101.1
* roundTo(2000/7,-2,2) == 285.75 -- 100011101.11
* roundTo(2000/7,-3,2) == 285.75 -- 100011101.11
* roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011
* roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
*
* note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
* because we are rounding 100011.1011011011011011 which rounds up.
*/
function (value, place, base) {
if (typeof place === "undefined") { place = 0; }
if (typeof base === "undefined") { base = 10; }
var p = Math.pow(base, -place);
return Math.round(value * p) / p;
};
GameMath.prototype.floorTo = function (value, place, base) {
if (typeof place === "undefined") { place = 0; }
if (typeof base === "undefined") { base = 10; }
var p = Math.pow(base, -place);
return Math.floor(value * p) / p;
};
GameMath.prototype.ceilTo = function (value, place, base) {
if (typeof place === "undefined") { place = 0; }
if (typeof base === "undefined") { base = 10; }
var p = Math.pow(base, -place);
return Math.ceil(value * p) / p;
};
GameMath.prototype.interpolateFloat = /**
* a one dimensional linear interpolation of a value.
*/
function (a, b, weight) {
return (b - a) * weight + a;
};
GameMath.prototype.radiansToDegrees = /**
* convert radians to degrees
*/
function (angle) {
return angle * GameMath.RAD_TO_DEG;
};
GameMath.prototype.degreesToRadians = /**
* convert degrees to radians
*/
function (angle) {
return angle * GameMath.DEG_TO_RAD;
};
GameMath.prototype.angleBetween = /**
* Find the angle of a segment from (x1, y1) -> (x2, y2 )
*/
function (x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1);
};
GameMath.prototype.normalizeAngle = /**
* set an angle with in the bounds of -PI to PI
*/
function (angle, radians) {
if (typeof radians === "undefined") { radians = true; }
var rd = (radians) ? GameMath.PI : 180;
return this.wrap(angle, rd, -rd);
};
GameMath.prototype.nearestAngleBetween = /**
* closest angle between two angles from a1 to a2
* absolute value the return for exact angle
*/
function (a1, a2, radians) {
if (typeof radians === "undefined") { radians = true; }
var rd = (radians) ? GameMath.PI : 180;
a1 = this.normalizeAngle(a1, radians);
a2 = this.normalizeAngle(a2, radians);
if(a1 < -rd / 2 && a2 > rd / 2) {
a1 += rd * 2;
}
if(a2 < -rd / 2 && a1 > rd / 2) {
a2 += rd * 2;
}
return a2 - a1;
};
GameMath.prototype.normalizeAngleToAnother = /**
* normalizes independent and then sets dep to the nearest value respective to independent
*
* for instance if dep=-170 and ind=170 then 190 will be returned as an alternative to -170
*/
function (dep, ind, radians) {
if (typeof radians === "undefined") { radians = true; }
return ind + this.nearestAngleBetween(ind, dep, radians);
};
GameMath.prototype.normalizeAngleAfterAnother = /**
* normalize independent and dependent and then set dependent to an angle relative to 'after/clockwise' independent
*
* for instance dep=-170 and ind=170, then 190 will be reutrned as alternative to -170
*/
function (dep, ind, radians) {
if (typeof radians === "undefined") { radians = true; }
dep = this.normalizeAngle(dep - ind, radians);
return ind + dep;
};
GameMath.prototype.normalizeAngleBeforeAnother = /**
* normalizes indendent and dependent and then sets dependent to an angle relative to 'before/counterclockwise' independent
*
* for instance dep = 190 and ind = 170, then -170 will be returned as an alternative to 190
*/
function (dep, ind, radians) {
if (typeof radians === "undefined") { radians = true; }
dep = this.normalizeAngle(ind - dep, radians);
return ind - dep;
};
GameMath.prototype.interpolateAngles = /**
* interpolate across the shortest arc between two angles
*/
function (a1, a2, weight, radians, ease) {
if (typeof radians === "undefined") { radians = true; }
if (typeof ease === "undefined") { ease = null; }
a1 = this.normalizeAngle(a1, radians);
a2 = this.normalizeAngleToAnother(a2, a1, radians);
return (typeof ease === 'function') ? ease(weight, a1, a2 - a1, 1) : this.interpolateFloat(a1, a2, weight);
};
GameMath.prototype.logBaseOf = /**
* Compute the logarithm of any value of any base
*
* a logarithm is the exponent that some constant (base) would have to be raised to
* to be equal to value.
*
* i.e.
* 4 ^ x = 16
* can be rewritten as to solve for x
* logB4(16) = x
* which with this function would be
* LoDMath.logBaseOf(16,4)
*
* which would return 2, because 4^2 = 16
*/
function (value, base) {
return Math.log(value) / Math.log(base);
};
GameMath.prototype.GCD = /**
* Greatest Common Denominator using Euclid's algorithm
*/
function (m, n) {
var r;
//make sure positive, GCD is always positive
m = Math.abs(m);
n = Math.abs(n);
//m must be >= n
if(m < n) {
r = m;
m = n;
n = r;
}
//now start loop
while(true) {
r = m % n;
if(!r) {
return n;
}
m = n;
n = r;
}
return 1;
};
GameMath.prototype.LCM = /**
* Lowest Common Multiple
*/
function (m, n) {
return (m * n) / this.GCD(m, n);
};
GameMath.prototype.factorial = /**
* Factorial - N!
*
* simple product series
*
* by definition:
* 0! == 1
*/
function (value) {
if(value == 0) {
return 1;
}
var res = value;
while(--value) {
res *= value;
}
return res;
};
GameMath.prototype.gammaFunction = /**
* gamma function
*
* defined: gamma(N) == (N - 1)!
*/
function (value) {
return this.factorial(value - 1);
};
GameMath.prototype.fallingFactorial = /**
* falling factorial
*
* defined: (N)! / (N - x)!
*
* written subscript: (N)x OR (base)exp
*/
function (base, exp) {
return this.factorial(base) / this.factorial(base - exp);
};
GameMath.prototype.risingFactorial = /**
* rising factorial
*
* defined: (N + x - 1)! / (N - 1)!
*
* written superscript N^(x) OR base^(exp)
*/
function (base, exp) {
//expanded from gammaFunction for speed
return this.factorial(base + exp - 1) / this.factorial(base - 1);
};
GameMath.prototype.binCoef = /**
* binomial coefficient
*
* defined: N! / (k!(N-k)!)
* reduced: N! / (N-k)! == (N)k (fallingfactorial)
* reduced: (N)k / k!
*/
function (n, k) {
return this.fallingFactorial(n, k) / this.factorial(k);
};
GameMath.prototype.risingBinCoef = /**
* rising binomial coefficient
*
* as one can notice in the analysis of binCoef(...) that
* binCoef is the (N)k divided by k!. Similarly rising binCoef
* is merely N^(k) / k!
*/
function (n, k) {
return this.risingFactorial(n, k) / this.factorial(k);
};
GameMath.prototype.chanceRoll = /**
* Generate a random boolean result based on the chance value
* <p>
* Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
* of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
* </p>
* @param chance The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%)
* @return true if the roll passed, or false
*/
function (chance) {
if (typeof chance === "undefined") { chance = 50; }
if(chance <= 0) {
return false;
} else if(chance >= 100) {
return true;
} else {
if(Math.random() * 100 >= chance) {
return false;
} else {
return true;
}
}
};
GameMath.prototype.maxAdd = /**
* Adds the given amount to the value, but never lets the value go over the specified maximum
*
* @param value The value to add the amount to
* @param amount The amount to add to the value
* @param max The maximum the value is allowed to be
* @return The new value
*/
function (value, amount, max) {
value += amount;
if(value > max) {
value = max;
}
return value;
};
GameMath.prototype.minSub = /**
* Subtracts the given amount from the value, but never lets the value go below the specified minimum
*
* @param value The base value
* @param amount The amount to subtract from the base value
* @param min The minimum the value is allowed to be
* @return The new value
*/
function (value, amount, min) {
value -= amount;
if(value < min) {
value = min;
}
return value;
};
GameMath.prototype.wrapValue = /**
* Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
* <p>Values must be positive integers, and are passed through Math.abs</p>
*
* @param value The value to add the amount to
* @param amount The amount to add to the value
* @param max The maximum the value is allowed to be
* @return The wrapped value
*/
function (value, amount, max) {
var diff;
value = Math.abs(value);
amount = Math.abs(amount);
max = Math.abs(max);
diff = (value + amount) % max;
return diff;
};
GameMath.prototype.randomSign = /**
* Randomly returns either a 1 or -1
*
* @return 1 or -1
*/
function () {
return (Math.random() > 0.5) ? 1 : -1;
};
GameMath.prototype.isOdd = /**
* Returns true if the number given is odd.
*
* @param n The number to check
*
* @return True if the given number is odd. False if the given number is even.
*/
function (n) {
if(n & 1) {
return true;
} else {
return false;
}
};
GameMath.prototype.isEven = /**
* Returns true if the number given is even.
*
* @param n The number to check
*
* @return True if the given number is even. False if the given number is odd.
*/
function (n) {
if(n & 1) {
return false;
} else {
return true;
}
};
GameMath.prototype.wrapAngle = /**
* Keeps an angle value between -180 and +180<br>
* Should be called whenever the angle is updated on the Sprite to stop it from going insane.
*
* @param angle The angle value to check
*
* @return The new angle value, returns the same as the input angle if it was within bounds
*/
function (angle) {
var result = angle;
// Nothing needs to change
if(angle >= -180 && angle <= 180) {
return angle;
}
// Else normalise it to -180, 180
result = (angle + 180) % 360;
if(result < 0) {
result += 360;
}
return result - 180;
};
GameMath.prototype.angleLimit = /**
* Keeps an angle value between the given min and max values
*
* @param angle The angle value to check. Must be between -180 and +180
* @param min The minimum angle that is allowed (must be -180 or greater)
* @param max The maximum angle that is allowed (must be 180 or less)
*
* @return The new angle value, returns the same as the input angle if it was within bounds
*/
function (angle, min, max) {
var result = angle;
if(angle > max) {
result = max;
} else if(angle < min) {
result = min;
}
return result;
};
GameMath.prototype.linearInterpolation = /**
* @method linear
* @param {Any} v
* @param {Any} k
* @static
*/
function (v, k) {
var m = v.length - 1;
var f = m * k;
var i = Math.floor(f);
if(k < 0) {
return this.linear(v[0], v[1], f);
}
if(k > 1) {
return this.linear(v[m], v[m - 1], m - f);
}
return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
};
GameMath.prototype.bezierInterpolation = /**
* @method Bezier
* @param {Any} v
* @param {Any} k
* @static
*/
function (v, k) {
var b = 0;
var n = v.length - 1;
for(var i = 0; i <= n; i++) {
b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
}
return b;
};
GameMath.prototype.catmullRomInterpolation = /**
* @method CatmullRom
* @param {Any} v
* @param {Any} k
* @static
*/
function (v, k) {
var m = v.length - 1;
var f = m * k;
var i = Math.floor(f);
if(v[0] === v[m]) {
if(k < 0) {
i = Math.floor(f = m * (1 + k));
}
return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
} else {
if(k < 0) {
return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
}
if(k > 1) {
return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
}
return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
}
};
GameMath.prototype.linear = /**
* @method Linear
* @param {Any} p0
* @param {Any} p1
* @param {Any} t
* @static
*/
function (p0, p1, t) {
return (p1 - p0) * t + p0;
};
GameMath.prototype.bernstein = /**
* @method Bernstein
* @param {Any} n
* @param {Any} i
* @static
*/
function (n, i) {
return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
};
GameMath.prototype.catmullRom = /**
* @method CatmullRom
* @param {Any} p0
* @param {Any} p1
* @param {Any} p2
* @param {Any} p3
* @param {Any} t
* @static
*/
function (p0, p1, p2, p3, t) {
var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
};
GameMath.prototype.difference = function (a, b) {
return Math.abs(a - b);
};
GameMath.prototype.random = /**
* Generates a random number. Deterministic, meaning safe
* to use if you want to record replays in random environments.
*
* @return A <code>Number</code> between 0 and 1.
*/
function () {
return this.globalSeed = this.srand(this.globalSeed);
};
GameMath.prototype.srand = /**
* Generates a random number based on the seed provided.
*
* @param Seed A number between 0 and 1, used to generate a predictable random number (very optional).
*
* @return A <code>Number</code> between 0 and 1.
*/
function (Seed) {
return ((69621 * (Seed * 0x7FFFFFFF)) % 0x7FFFFFFF) / 0x7FFFFFFF;
};
GameMath.prototype.getRandom = /**
* Fetch a random entry from the given array.
* Will return null if random selection is missing, or array has no entries.
* <code>G.getRandom()</code> is deterministic and safe for use with replays/recordings.
* HOWEVER, <code>U.getRandom()</code> is NOT deterministic and unsafe for use with replays/recordings.
*
* @param Objects An array of objects.
* @param StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* @param Length Optional restriction on the number of values you want to randomly select from.
*
* @return The random object that was selected.
*/
function (Objects, StartIndex, Length) {
if (typeof StartIndex === "undefined") { StartIndex = 0; }
if (typeof Length === "undefined") { Length = 0; }
if(Objects != null) {
var l = Length;
if((l == 0) || (l > Objects.length - StartIndex)) {
l = Objects.length - StartIndex;
}
if(l > 0) {
return Objects[StartIndex + Math.floor(Math.random() * l)];
}
}
return null;
};
GameMath.prototype.floor = /**
* Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2.
*
* @param Value Any number.
*
* @return The rounded value of that number.
*/
function (Value) {
var n = Value | 0;
return (Value > 0) ? (n) : ((n != Value) ? (n - 1) : (n));
};
GameMath.prototype.ceil = /**
* Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3.
*
* @param Value Any number.
*
* @return The rounded value of that number.
*/
function (Value) {
var n = Value | 0;
return (Value > 0) ? ((n != Value) ? (n + 1) : (n)) : (n);
};
GameMath.prototype.sinCosGenerator = /**
* Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at
* <p>
* The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function
* you should get the results via getSinTable() and getCosTable(). This generator is fast enough to be used in real-time.
* </p>
* @param length The length of the wave
* @param sinAmplitude The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
* @param cosAmplitude The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
* @param frequency The frequency of the sine and cosine table data
* @return Returns the sine table
* @see getSinTable
* @see getCosTable
*/
function (length, sinAmplitude, cosAmplitude, frequency) {
if (typeof sinAmplitude === "undefined") { sinAmplitude = 1.0; }
if (typeof cosAmplitude === "undefined") { cosAmplitude = 1.0; }
if (typeof frequency === "undefined") { frequency = 1.0; }
var sin = sinAmplitude;
var cos = cosAmplitude;
var frq = frequency * Math.PI / length;
this.cosTable = [];
this.sinTable = [];
for(var c = 0; c < length; c++) {
cos -= sin * frq;
sin += cos * frq;
this.cosTable[c] = cos;
this.sinTable[c] = sin;
}
return this.sinTable;
};
GameMath.prototype.vectorLength = /**
* Finds the length of the given vector
*
* @param dx
* @param dy
*
* @return
*/
function (dx, dy) {
return Math.sqrt(dx * dx + dy * dy);
};
GameMath.prototype.dotProduct = /**
* Finds the dot product value of two vectors
*
* @param ax Vector X
* @param ay Vector Y
* @param bx Vector X
* @param by Vector Y
*
* @return Dot product
*/
function (ax, ay, bx, by) {
return ax * bx + ay * by;
};
return GameMath;
})();
Phaser.GameMath = GameMath;
})(Phaser || (Phaser = {}));
/// <reference path="Basic.ts" />
/// <reference path="Game.ts" />
/**
* Phaser - Group
*
* This class is used for organising, updating and sorting game objects.
*
*/
var Phaser;
(function (Phaser) {
var Group = (function (_super) {
__extends(Group, _super);
function Group(game, MaxSize) {
if (typeof MaxSize === "undefined") { MaxSize = 0; }
_super.call(this, game);
this.isGroup = true;
this.members = [];
this.length = 0;
this._maxSize = MaxSize;
this._marker = 0;
this._sortIndex = null;
}
Group.ASCENDING = -1;
Group.DESCENDING = 1;
Group.prototype.destroy = /**
* Override this function to handle any deleting or "shutdown" type operations you might need,
* such as removing traditional Flash children like Basic objects.
*/
function () {
if(this.members != null) {
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if(basic != null) {
basic.destroy();
}
}
this.members.length = 0;
}
this._sortIndex = null;
};
Group.prototype.update = /**
* Automatically goes through and calls update on everything you added.
*/
function () {
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if((basic != null) && basic.exists && basic.active) {
basic.preUpdate();
basic.update();
basic.postUpdate();
}
}
};
Group.prototype.render = /**
* Automatically goes through and calls render on everything you added.
*/
function (camera, cameraOffsetX, cameraOffsetY) {
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if((basic != null) && basic.exists && basic.visible) {
basic.render(camera, cameraOffsetX, cameraOffsetY);
}
}
};
Object.defineProperty(Group.prototype, "maxSize", {
get: /**
* The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow.
*/
function () {
return this._maxSize;
},
set: /**
* @private
*/
function (Size) {
this._maxSize = Size;
if(this._marker >= this._maxSize) {
this._marker = 0;
}
if((this._maxSize == 0) || (this.members == null) || (this._maxSize >= this.members.length)) {
return;
}
//If the max size has shrunk, we need to get rid of some objects
var basic;
var i = this._maxSize;
var l = this.members.length;
while(i < l) {
basic = this.members[i++];
if(basic != null) {
basic.destroy();
}
}
this.length = this.members.length = this._maxSize;
},
enumerable: true,
configurable: true
});
Group.prototype.add = /**
* Adds a new <code>Basic</code> subclass (Basic, Basic, Enemy, etc) to the group.
* Group will try to replace a null member of the array first.
* Failing that, Group will add it to the end of the member array,
* assuming there is room for it, and doubling the size of the array if necessary.
*
* <p>WARNING: If the group has a maxSize that has already been met,
* the object will NOT be added to the group!</p>
*
* @param Object The object you want to add to the group.
*
* @return The same <code>Basic</code> object that was passed in.
*/
function (Object) {
//Don't bother adding an object twice.
if(this.members.indexOf(Object) >= 0) {
return Object;
}
//First, look for a null entry where we can add the object.
var i = 0;
var l = this.members.length;
while(i < l) {
if(this.members[i] == null) {
this.members[i] = Object;
if(i >= this.length) {
this.length = i + 1;
}
return Object;
}
i++;
}
//Failing that, expand the array (if we can) and add the object.
if(this._maxSize > 0) {
if(this.members.length >= this._maxSize) {
return Object;
} else if(this.members.length * 2 <= this._maxSize) {
this.members.length *= 2;
} else {
this.members.length = this._maxSize;
}
} else {
this.members.length *= 2;
}
//If we made it this far, then we successfully grew the group,
//and we can go ahead and add the object at the first open slot.
this.members[i] = Object;
this.length = i + 1;
return Object;
};
Group.prototype.recycle = /**
* Recycling is designed to help you reuse game objects without always re-allocating or "newing" them.
*
* <p>If you specified a maximum size for this group (like in Emitter),
* then recycle will employ what we're calling "rotating" recycling.
* Recycle() will first check to see if the group is at capacity yet.
* If group is not yet at capacity, recycle() returns a new object.
* If the group IS at capacity, then recycle() just returns the next object in line.</p>
*
* <p>If you did NOT specify a maximum size for this group,
* then recycle() will employ what we're calling "grow-style" recycling.
* Recycle() will return either the first object with exists == false,
* or, finding none, add a new object to the array,
* doubling the size of the array if necessary.</p>
*
* <p>WARNING: If this function needs to create a new object,
* and no object class was provided, it will return null
* instead of a valid object!</p>
*
* @param ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter!
*
* @return A reference to the object that was created. Don't forget to cast it back to the Class you want (e.g. myObject = myGroup.recycle(myObjectClass) as myObjectClass;).
*/
function (ObjectClass) {
if (typeof ObjectClass === "undefined") { ObjectClass = null; }
var basic;
if(this._maxSize > 0) {
if(this.length < this._maxSize) {
if(ObjectClass == null) {
return null;
}
return this.add(new ObjectClass());
} else {
basic = this.members[this._marker++];
if(this._marker >= this._maxSize) {
this._marker = 0;
}
return basic;
}
} else {
basic = this.getFirstAvailable(ObjectClass);
if(basic != null) {
return basic;
}
if(ObjectClass == null) {
return null;
}
return this.add(new ObjectClass());
}
};
Group.prototype.remove = /**
* Removes an object from the group.
*
* @param Object The <code>Basic</code> you want to remove.
* @param Splice Whether the object should be cut from the array entirely or not.
*
* @return The removed object.
*/
function (Object, Splice) {
if (typeof Splice === "undefined") { Splice = false; }
var index = this.members.indexOf(Object);
if((index < 0) || (index >= this.members.length)) {
return null;
}
if(Splice) {
this.members.splice(index, 1);
this.length--;
} else {
this.members[index] = null;
}
return Object;
};
Group.prototype.replace = /**
* Replaces an existing <code>Basic</code> with a new one.
*
* @param OldObject The object you want to replace.
* @param NewObject The new object you want to use instead.
*
* @return The new object.
*/
function (OldObject, NewObject) {
var index = this.members.indexOf(OldObject);
if((index < 0) || (index >= this.members.length)) {
return null;
}
this.members[index] = NewObject;
return NewObject;
};
Group.prototype.sort = /**
* Call this function to sort the group according to a particular value and order.
* For example, to sort game objects for Zelda-style overlaps you might call
* <code>myGroup.sort("y",Group.ASCENDING)</code> at the bottom of your
* <code>State.update()</code> override. To sort all existing objects after
* a big explosion or bomb attack, you might call <code>myGroup.sort("exists",Group.DESCENDING)</code>.
*
* @param Index The <code>string</code> name of the member variable you want to sort on. Default value is "y".
* @param Order A <code>Group</code> constant that defines the sort order. Possible values are <code>Group.ASCENDING</code> and <code>Group.DESCENDING</code>. Default value is <code>Group.ASCENDING</code>.
*/
function (Index, Order) {
if (typeof Index === "undefined") { Index = "y"; }
if (typeof Order === "undefined") { Order = Group.ASCENDING; }
this._sortIndex = Index;
this._sortOrder = Order;
this.members.sort(this.sortHandler);
};
Group.prototype.setAll = /**
* Go through and set the specified variable to the specified value on all members of the group.
*
* @param VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor".
* @param Value The value you want to assign to that variable.
* @param Recurse Default value is true, meaning if <code>setAll()</code> encounters a member that is a group, it will call <code>setAll()</code> on that group rather than modifying its variable.
*/
function (VariableName, Value, Recurse) {
if (typeof Recurse === "undefined") { Recurse = true; }
var basic;
var i = 0;
while(i < length) {
basic = this.members[i++];
if(basic != null) {
if(Recurse && (basic.isGroup == true)) {
basic['setAll'](VariableName, Value, Recurse);
} else {
basic[VariableName] = Value;
}
}
}
};
Group.prototype.callAll = /**
* Go through and call the specified function on all members of the group.
* Currently only works on functions that have no required parameters.
*
* @param FunctionName The string representation of the function you want to call on each object, for example "kill()" or "init()".
* @param Recurse Default value is true, meaning if <code>callAll()</code> encounters a member that is a group, it will call <code>callAll()</code> on that group rather than calling the group's function.
*/
function (FunctionName, Recurse) {
if (typeof Recurse === "undefined") { Recurse = true; }
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if(basic != null) {
if(Recurse && (basic.isGroup == true)) {
basic['callAll'](FunctionName, Recurse);
} else {
basic[FunctionName]();
}
}
}
};
Group.prototype.forEach = function (callback, Recurse) {
if (typeof Recurse === "undefined") { Recurse = false; }
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if(basic != null) {
if(Recurse && (basic.isGroup == true)) {
basic.forEach(callback, true);
} else {
callback.call(this, basic);
}
}
}
};
Group.prototype.getFirstAvailable = /**
* Call this function to retrieve the first object with exists == false in the group.
* This is handy for recycling in general, e.g. respawning enemies.
*
* @param ObjectClass An optional parameter that lets you narrow the results to instances of this particular class.
*
* @return A <code>Basic</code> currently flagged as not existing.
*/
function (ObjectClass) {
if (typeof ObjectClass === "undefined") { ObjectClass = null; }
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if((basic != null) && !basic.exists && ((ObjectClass == null) || (typeof basic === ObjectClass))) {
return basic;
}
}
return null;
};
Group.prototype.getFirstNull = /**
* Call this function to retrieve the first index set to 'null'.
* Returns -1 if no index stores a null object.
*
* @return An <code>int</code> indicating the first null slot in the group.
*/
function () {
var basic;
var i = 0;
var l = this.members.length;
while(i < l) {
if(this.members[i] == null) {
return i;
} else {
i++;
}
}
return -1;
};
Group.prototype.getFirstExtant = /**
* Call this function to retrieve the first object with exists == true in the group.
* This is handy for checking if everything's wiped out, or choosing a squad leader, etc.
*
* @return A <code>Basic</code> currently flagged as existing.
*/
function () {
var basic;
var i = 0;
while(i < length) {
basic = this.members[i++];
if((basic != null) && basic.exists) {
return basic;
}
}
return null;
};
Group.prototype.getFirstAlive = /**
* Call this function to retrieve the first object with dead == false in the group.
* This is handy for checking if everything's wiped out, or choosing a squad leader, etc.
*
* @return A <code>Basic</code> currently flagged as not dead.
*/
function () {
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if((basic != null) && basic.exists && basic.alive) {
return basic;
}
}
return null;
};
Group.prototype.getFirstDead = /**
* Call this function to retrieve the first object with dead == true in the group.
* This is handy for checking if everything's wiped out, or choosing a squad leader, etc.
*
* @return A <code>Basic</code> currently flagged as dead.
*/
function () {
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if((basic != null) && !basic.alive) {
return basic;
}
}
return null;
};
Group.prototype.countLiving = /**
* Call this function to find out how many members of the group are not dead.
*
* @return The number of <code>Basic</code>s flagged as not dead. Returns -1 if group is empty.
*/
function () {
var count = -1;
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if(basic != null) {
if(count < 0) {
count = 0;
}
if(basic.exists && basic.alive) {
count++;
}
}
}
return count;
};
Group.prototype.countDead = /**
* Call this function to find out how many members of the group are dead.
*
* @return The number of <code>Basic</code>s flagged as dead. Returns -1 if group is empty.
*/
function () {
var count = -1;
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if(basic != null) {
if(count < 0) {
count = 0;
}
if(!basic.alive) {
count++;
}
}
}
return count;
};
Group.prototype.getRandom = /**
* Returns a member at random from the group.
*
* @param StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array.
* @param Length Optional restriction on the number of values you want to randomly select from.
*
* @return A <code>Basic</code> from the members list.
*/
function (StartIndex, Length) {
if (typeof StartIndex === "undefined") { StartIndex = 0; }
if (typeof Length === "undefined") { Length = 0; }
if(Length == 0) {
Length = this.length;
}
return this._game.math.getRandom(this.members, StartIndex, Length);
};
Group.prototype.clear = /**
* Remove all instances of <code>Basic</code> subclass (Basic, Block, etc) from the list.
* WARNING: does not destroy() or kill() any of these objects!
*/
function () {
this.length = this.members.length = 0;
};
Group.prototype.kill = /**
* Calls kill on the group's members and then on the group itself.
*/
function () {
var basic;
var i = 0;
while(i < this.length) {
basic = this.members[i++];
if((basic != null) && basic.exists) {
basic.kill();
}
}
};
Group.prototype.sortHandler = /**
* Helper function for the sort process.
*
* @param Obj1 The first object being sorted.
* @param Obj2 The second object being sorted.
*
* @return An integer value: -1 (Obj1 before Obj2), 0 (same), or 1 (Obj1 after Obj2).
*/
function (Obj1, Obj2) {
if(Obj1[this._sortIndex] < Obj2[this._sortIndex]) {
return this._sortOrder;
} else if(Obj1[this._sortIndex] > Obj2[this._sortIndex]) {
return -this._sortOrder;
}
return 0;
};
return Group;
})(Phaser.Basic);
Phaser.Group = Group;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - Loader
*
* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks.
*/
var Phaser;
(function (Phaser) {
var Loader = (function () {
function Loader(game, callback) {
this._game = game;
this._gameCreateComplete = callback;
this._keys = [];
this._fileList = {
};
this._xhr = new XMLHttpRequest();
this._queueSize = 0;
}
Loader.prototype.reset = function () {
this._queueSize = 0;
};
Object.defineProperty(Loader.prototype, "queueSize", {
get: function () {
return this._queueSize;
},
enumerable: true,
configurable: true
});
Loader.prototype.addImageFile = function (key, url) {
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'image',
key: key,
url: url,
data: null,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.addSpriteSheet = function (key, url, frameWidth, frameHeight, frameMax) {
if (typeof frameMax === "undefined") { frameMax = -1; }
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'spritesheet',
key: key,
url: url,
data: null,
frameWidth: frameWidth,
frameHeight: frameHeight,
frameMax: frameMax,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.addTextureAtlas = function (key, url, jsonURL, jsonData) {
if (typeof jsonURL === "undefined") { jsonURL = null; }
if (typeof jsonData === "undefined") { jsonData = null; }
if(this.checkKeyExists(key) === false) {
if(jsonURL !== null) {
// A URL to a json file has been given
this._queueSize++;
this._fileList[key] = {
type: 'textureatlas',
key: key,
url: url,
data: null,
jsonURL: jsonURL,
jsonData: null,
error: false,
loaded: false
};
this._keys.push(key);
} else {
// A json string or object has been given
if(typeof jsonData === 'string') {
var data = JSON.parse(jsonData);
// Malformed?
if(data['frames']) {
this._queueSize++;
this._fileList[key] = {
type: 'textureatlas',
key: key,
url: url,
data: null,
jsonURL: null,
jsonData: data['frames'],
error: false,
loaded: false
};
this._keys.push(key);
}
} else {
// Malformed?
if(jsonData['frames']) {
this._queueSize++;
this._fileList[key] = {
type: 'textureatlas',
key: key,
url: url,
data: null,
jsonURL: null,
jsonData: jsonData['frames'],
error: false,
loaded: false
};
this._keys.push(key);
}
}
}
}
};
Loader.prototype.addAudioFile = function (key, url) {
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'audio',
key: key,
url: url,
data: null,
buffer: null,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.addTextFile = function (key, url) {
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'text',
key: key,
url: url,
data: null,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.removeFile = function (key) {
delete this._fileList[key];
};
Loader.prototype.removeAll = function () {
this._fileList = {
};
};
Loader.prototype.load = function (onFileLoadCallback, onCompleteCallback) {
if (typeof onFileLoadCallback === "undefined") { onFileLoadCallback = null; }
if (typeof onCompleteCallback === "undefined") { onCompleteCallback = null; }
this.progress = 0;
this.hasLoaded = false;
this._onComplete = onCompleteCallback;
if(onCompleteCallback == null) {
this._onComplete = this._game.onCreateCallback;
}
this._onFileLoad = onFileLoadCallback;
if(this._keys.length > 0) {
this._progressChunk = 100 / this._keys.length;
this.loadFile();
} else {
this.progress = 1;
this.hasLoaded = true;
this._gameCreateComplete.call(this._game);
if(this._onComplete !== null) {
this._onComplete.call(this._game.callbackContext);
}
}
};
Loader.prototype.loadFile = function () {
var _this = this;
var file = this._fileList[this._keys.pop()];
// Image or Data?
switch(file.type) {
case 'image':
case 'spritesheet':
case 'textureatlas':
file.data = new Image();
file.data.name = file.key;
file.data.onload = function () {
return _this.fileComplete(file.key);
};
file.data.onerror = function () {
return _this.fileError(file.key);
};
file.data.src = file.url;
break;
case 'audio':
this._xhr.open("GET", file.url, true);
this._xhr.responseType = "arraybuffer";
this._xhr.onload = function () {
return _this.fileComplete(file.key);
};
this._xhr.onerror = function () {
return _this.fileError(file.key);
};
this._xhr.send();
break;
case 'text':
this._xhr.open("GET", file.url, true);
this._xhr.responseType = "text";
this._xhr.onload = function () {
return _this.fileComplete(file.key);
};
this._xhr.onerror = function () {
return _this.fileError(file.key);
};
this._xhr.send();
break;
}
};
Loader.prototype.fileError = function (key) {
this._fileList[key].loaded = true;
this._fileList[key].error = true;
this.nextFile(key, false);
};
Loader.prototype.fileComplete = function (key) {
var _this = this;
this._fileList[key].loaded = true;
var file = this._fileList[key];
var loadNext = true;
switch(file.type) {
case 'image':
this._game.cache.addImage(file.key, file.url, file.data);
break;
case 'spritesheet':
this._game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax);
break;
case 'textureatlas':
if(file.jsonURL == null) {
this._game.cache.addTextureAtlas(file.key, file.url, file.data, file.jsonData);
} else {
// Load the JSON before carrying on with the next file
loadNext = false;
this._xhr.open("GET", file.jsonURL, true);
this._xhr.responseType = "text";
this._xhr.onload = function () {
return _this.jsonLoadComplete(file.key);
};
this._xhr.onerror = function () {
return _this.jsonLoadError(file.key);
};
this._xhr.send();
}
break;
case 'audio':
file.data = this._xhr.response;
this._game.cache.addSound(file.key, file.url, file.data);
break;
case 'text':
file.data = this._xhr.response;
this._game.cache.addText(file.key, file.url, file.data);
break;
}
if(loadNext) {
this.nextFile(key, true);
}
};
Loader.prototype.jsonLoadComplete = function (key) {
var data = JSON.parse(this._xhr.response);
// Malformed?
if(data['frames']) {
var file = this._fileList[key];
this._game.cache.addTextureAtlas(file.key, file.url, file.data, data['frames']);
}
this.nextFile(key, true);
};
Loader.prototype.jsonLoadError = function (key) {
var file = this._fileList[key];
file.error = true;
this.nextFile(key, true);
};
Loader.prototype.nextFile = function (previousKey, success) {
this.progress = Math.round(this.progress + this._progressChunk);
if(this.progress > 1) {
this.progress = 1;
}
if(this._onFileLoad) {
this._onFileLoad.call(this._game.callbackContext, this.progress, previousKey, success);
}
if(this._keys.length > 0) {
this.loadFile();
} else {
this.hasLoaded = true;
this.removeAll();
this._gameCreateComplete.call(this._game);
if(this._onComplete !== null) {
this._onComplete.call(this._game.callbackContext);
}
}
};
Loader.prototype.checkKeyExists = function (key) {
if(this._fileList[key]) {
return true;
} else {
return false;
}
};
return Loader;
})();
Phaser.Loader = Loader;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/// <reference path="gameobjects/GameObject.ts" />
/**
* Phaser - Motion
*
* The Motion class contains lots of useful functions for moving game objects around in world space.
*/
var Phaser;
(function (Phaser) {
var Motion = (function () {
function Motion(game) {
this._game = game;
}
Motion.prototype.computeVelocity = /**
* A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
*
* @param Velocity Any component of velocity (e.g. 20).
* @param Acceleration Rate at which the velocity is changing.
* @param Drag Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
* @param Max An absolute value cap for the velocity.
*
* @return The altered Velocity value.
*/
function (Velocity, Acceleration, Drag, Max) {
if (typeof Acceleration === "undefined") { Acceleration = 0; }
if (typeof Drag === "undefined") { Drag = 0; }
if (typeof Max === "undefined") { Max = 10000; }
if(Acceleration !== 0) {
Velocity += Acceleration * this._game.time.elapsed;
} else if(Drag !== 0) {
var drag = Drag * this._game.time.elapsed;
if(Velocity - drag > 0) {
Velocity = Velocity - drag;
} else if(Velocity + drag < 0) {
Velocity += drag;
} else {
Velocity = 0;
}
}
if((Velocity != 0) && (Max != 10000)) {
if(Velocity > Max) {
Velocity = Max;
} else if(Velocity < -Max) {
Velocity = -Max;
}
}
return Velocity;
};
Motion.prototype.velocityFromAngle = /**
* Given the angle and speed calculate the velocity and return it as a Point
*
* @param angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
* @param speed The speed it will move, in pixels per second sq
*
* @return A Point where Point.x contains the velocity x value and Point.y contains the velocity y value
*/
function (angle, speed) {
var a = this._game.math.degreesToRadians(angle);
return new Phaser.Point((Math.cos(a) * speed), (Math.sin(a) * speed));
};
Motion.prototype.moveTowardsObject = /**
* Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)<br>
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.<br>
* Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.<br>
* The source object doesn't stop moving automatically should it ever reach the destination coordinates.<br>
* If you need the object to accelerate, see accelerateTowardsObject() instead
* Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all)
*
* @param source The Sprite on which the velocity will be set
* @param dest The Sprite where the source object will move to
* @param speed The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms
*/
function (source, dest, speed, maxTime) {
if (typeof speed === "undefined") { speed = 60; }
if (typeof maxTime === "undefined") { maxTime = 0; }
var a = this.angleBetween(source, dest);
if(maxTime > 0) {
var d = this.distanceBetween(source, dest);
// We know how many pixels we need to move, but how fast?
speed = d / (maxTime / 1000);
}
source.velocity.x = Math.cos(a) * speed;
source.velocity.y = Math.sin(a) * speed;
};
Motion.prototype.accelerateTowardsObject = /**
* Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)<br>
* You must give a maximum speed value, beyond which the Sprite won't go any faster.<br>
* If you don't need acceleration look at moveTowardsObject() instead.
*
* @param source The Sprite on which the acceleration will be set
* @param dest The Sprite where the source object will move towards
* @param speed The speed it will accelerate in pixels per second
* @param xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally
* @param ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically
*/
function (source, dest, speed, xSpeedMax, ySpeedMax) {
var a = this.angleBetween(source, dest);
source.velocity.x = 0;
source.velocity.y = 0;
source.acceleration.x = Math.cos(a) * speed;
source.acceleration.y = Math.sin(a) * speed;
source.maxVelocity.x = xSpeedMax;
source.maxVelocity.y = ySpeedMax;
};
Motion.prototype.moveTowardsMouse = /**
* Move the given Sprite towards the mouse pointer coordinates at a steady velocity
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.<br>
* Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.<br>
* The source object doesn't stop moving automatically should it ever reach the destination coordinates.<br>
*
* @param source The Sprite to move
* @param speed The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms
*/
function (source, speed, maxTime) {
if (typeof speed === "undefined") { speed = 60; }
if (typeof maxTime === "undefined") { maxTime = 0; }
var a = this.angleBetweenMouse(source);
if(maxTime > 0) {
var d = this.distanceToMouse(source);
// We know how many pixels we need to move, but how fast?
speed = d / (maxTime / 1000);
}
source.velocity.x = Math.cos(a) * speed;
source.velocity.y = Math.sin(a) * speed;
};
Motion.prototype.accelerateTowardsMouse = /**
* Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)<br>
* You must give a maximum speed value, beyond which the Sprite won't go any faster.<br>
* If you don't need acceleration look at moveTowardsMouse() instead.
*
* @param source The Sprite on which the acceleration will be set
* @param speed The speed it will accelerate in pixels per second
* @param xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally
* @param ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically
*/
function (source, speed, xSpeedMax, ySpeedMax) {
var a = this.angleBetweenMouse(source);
source.velocity.x = 0;
source.velocity.y = 0;
source.acceleration.x = Math.cos(a) * speed;
source.acceleration.y = Math.sin(a) * speed;
source.maxVelocity.x = xSpeedMax;
source.maxVelocity.y = ySpeedMax;
};
Motion.prototype.moveTowardsPoint = /**
* Sets the x/y velocity on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)<br>
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.<br>
* Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.<br>
* The source object doesn't stop moving automatically should it ever reach the destination coordinates.<br>
*
* @param source The Sprite to move
* @param target The Point coordinates to move the source Sprite towards
* @param speed The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms
*/
function (source, target, speed, maxTime) {
if (typeof speed === "undefined") { speed = 60; }
if (typeof maxTime === "undefined") { maxTime = 0; }
var a = this.angleBetweenPoint(source, target);
if(maxTime > 0) {
var d = this.distanceToPoint(source, target);
// We know how many pixels we need to move, but how fast?
speed = d / (maxTime / 1000);
}
source.velocity.x = Math.cos(a) * speed;
source.velocity.y = Math.sin(a) * speed;
};
Motion.prototype.accelerateTowardsPoint = /**
* Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)<br>
* You must give a maximum speed value, beyond which the Sprite won't go any faster.<br>
* If you don't need acceleration look at moveTowardsPoint() instead.
*
* @param source The Sprite on which the acceleration will be set
* @param target The Point coordinates to move the source Sprite towards
* @param speed The speed it will accelerate in pixels per second
* @param xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally
* @param ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically
*/
function (source, target, speed, xSpeedMax, ySpeedMax) {
var a = this.angleBetweenPoint(source, target);
source.velocity.x = 0;
source.velocity.y = 0;
source.acceleration.x = Math.cos(a) * speed;
source.acceleration.y = Math.sin(a) * speed;
source.maxVelocity.x = xSpeedMax;
source.maxVelocity.y = ySpeedMax;
};
Motion.prototype.distanceBetween = /**
* Find the distance (in pixels, rounded) between two Sprites, taking their origin into account
*
* @param a The first Sprite
* @param b The second Sprite
* @return int Distance (in pixels)
*/
function (a, b) {
var dx = (a.x + a.origin.x) - (b.x + b.origin.x);
var dy = (a.y + a.origin.y) - (b.y + b.origin.y);
return this._game.math.vectorLength(dx, dy);
};
Motion.prototype.distanceToPoint = /**
* Find the distance (in pixels, rounded) from an Sprite to the given Point, taking the source origin into account
*
* @param a The Sprite
* @param target The Point
* @return int Distance (in pixels)
*/
function (a, target) {
var dx = (a.x + a.origin.x) - (target.x);
var dy = (a.y + a.origin.y) - (target.y);
return this._game.math.vectorLength(dx, dy);
};
Motion.prototype.distanceToMouse = /**
* Find the distance (in pixels, rounded) from the object x/y and the mouse x/y
*
* @param a The Sprite to test against
* @return int The distance between the given sprite and the mouse coordinates
*/
function (a) {
var dx = (a.x + a.origin.x) - this._game.input.x;
var dy = (a.y + a.origin.y) - this._game.input.y;
return this._game.math.vectorLength(dx, dy);
};
Motion.prototype.angleBetweenPoint = /**
* Find the angle (in radians) between an Sprite and an Point. The source sprite takes its x/y and origin into account.
* The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
*
* @param a The Sprite to test from
* @param target The Point to angle the Sprite towards
* @param asDegrees If you need the value in degrees instead of radians, set to true
*
* @return Number The angle (in radians unless asDegrees is true)
*/
function (a, target, asDegrees) {
if (typeof asDegrees === "undefined") { asDegrees = false; }
var dx = (target.x) - (a.x + a.origin.x);
var dy = (target.y) - (a.y + a.origin.y);
if(asDegrees) {
return this._game.math.radiansToDegrees(Math.atan2(dy, dx));
} else {
return Math.atan2(dy, dx);
}
};
Motion.prototype.angleBetween = /**
* Find the angle (in radians) between the two Sprite, taking their x/y and origin into account.
* The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
*
* @param a The Sprite to test from
* @param b The Sprite to test to
* @param asDegrees If you need the value in degrees instead of radians, set to true
*
* @return Number The angle (in radians unless asDegrees is true)
*/
function (a, b, asDegrees) {
if (typeof asDegrees === "undefined") { asDegrees = false; }
var dx = (b.x + b.origin.x) - (a.x + a.origin.x);
var dy = (b.y + b.origin.y) - (a.y + a.origin.y);
if(asDegrees) {
return this._game.math.radiansToDegrees(Math.atan2(dy, dx));
} else {
return Math.atan2(dy, dx);
}
};
Motion.prototype.velocityFromFacing = /**
* Given the GameObject and speed calculate the velocity and return it as an Point based on the direction the sprite is facing
*
* @param parent The Sprite to get the facing value from
* @param speed The speed it will move, in pixels per second sq
*
* @return An Point where Point.x contains the velocity x value and Point.y contains the velocity y value
*/
function (parent, speed) {
var a;
if(parent.facing == Phaser.Collision.LEFT) {
a = this._game.math.degreesToRadians(180);
} else if(parent.facing == Phaser.Collision.RIGHT) {
a = this._game.math.degreesToRadians(0);
} else if(parent.facing == Phaser.Collision.UP) {
a = this._game.math.degreesToRadians(-90);
} else if(parent.facing == Phaser.Collision.DOWN) {
a = this._game.math.degreesToRadians(90);
}
return new Phaser.Point(Math.cos(a) * speed, Math.sin(a) * speed);
};
Motion.prototype.angleBetweenMouse = /**
* Find the angle (in radians) between an Sprite and the mouse, taking their x/y and origin into account.
* The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
*
* @param a The Object to test from
* @param asDegrees If you need the value in degrees instead of radians, set to true
*
* @return Number The angle (in radians unless asDegrees is true)
*/
function (a, asDegrees) {
if (typeof asDegrees === "undefined") { asDegrees = false; }
// In order to get the angle between the object and mouse, we need the objects screen coordinates (rather than world coordinates)
var p = a.getScreenXY();
var dx = a._game.input.x - p.x;
var dy = a._game.input.y - p.y;
if(asDegrees) {
return this._game.math.radiansToDegrees(Math.atan2(dy, dx));
} else {
return Math.atan2(dy, dx);
}
};
return Motion;
})();
Phaser.Motion = Motion;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="../SoundManager.ts" />
/**
* Phaser - Sound
*
* A Sound file, used by the Game.SoundManager for playback.
*/
var Phaser;
(function (Phaser) {
var Sound = (function () {
function Sound(context, gainNode, data, volume, loop) {
if (typeof volume === "undefined") { volume = 1; }
if (typeof loop === "undefined") { loop = false; }
this.loop = false;
this.isPlaying = false;
this.isDecoding = false;
this._context = context;
this._gainNode = gainNode;
this._buffer = data;
this._volume = volume;
this.loop = loop;
// Local volume control
if(this._context !== null) {
this._localGainNode = this._context.createGainNode();
this._localGainNode.connect(this._gainNode);
this._localGainNode.gain.value = this._volume;
}
if(this._buffer === null) {
this.isDecoding = true;
} else {
this.play();
}
}
Sound.prototype.setDecodedBuffer = function (data) {
this._buffer = data;
this.isDecoding = false;
this.play();
};
Sound.prototype.play = function () {
if(this._buffer === null || this.isDecoding === true) {
return;
}
this._sound = this._context.createBufferSource();
this._sound.buffer = this._buffer;
this._sound.connect(this._localGainNode);
if(this.loop) {
this._sound.loop = true;
}
this._sound.noteOn(0)// the zero is vitally important, crashes iOS6 without it
;
this.duration = this._sound.buffer.duration;
this.isPlaying = true;
};
Sound.prototype.stop = function () {
if(this.isPlaying === true) {
this.isPlaying = false;
this._sound.noteOff(0);
}
};
Sound.prototype.mute = function () {
this._localGainNode.gain.value = 0;
};
Sound.prototype.unmute = function () {
this._localGainNode.gain.value = this._volume;
};
Object.defineProperty(Sound.prototype, "volume", {
get: function () {
return this._volume;
},
set: function (value) {
this._volume = value;
this._localGainNode.gain.value = this._volume;
},
enumerable: true,
configurable: true
});
return Sound;
})();
Phaser.Sound = Sound;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/// <reference path="system/Sound.ts" />
/**
* Phaser - SoundManager
*
* This is an embroyonic web audio sound management class. There is a lot of work still to do here.
*/
var Phaser;
(function (Phaser) {
var SoundManager = (function () {
function SoundManager(game) {
this._context = null;
this._game = game;
if(game.device.webaudio == true) {
if(!!window['AudioContext']) {
this._context = new window['AudioContext']();
} else if(!!window['webkitAudioContext']) {
this._context = new window['webkitAudioContext']();
}
if(this._context !== null) {
this._gainNode = this._context.createGainNode();
this._gainNode.connect(this._context.destination);
this._volume = 1;
}
}
}
SoundManager.prototype.mute = function () {
this._gainNode.gain.value = 0;
};
SoundManager.prototype.unmute = function () {
this._gainNode.gain.value = this._volume;
};
Object.defineProperty(SoundManager.prototype, "volume", {
get: function () {
return this._volume;
},
set: function (value) {
this._volume = value;
this._gainNode.gain.value = this._volume;
},
enumerable: true,
configurable: true
});
SoundManager.prototype.decode = function (key, callback, sound) {
if (typeof callback === "undefined") { callback = null; }
if (typeof sound === "undefined") { sound = null; }
var soundData = this._game.cache.getSound(key);
if(soundData) {
if(this._game.cache.isSoundDecoded(key) === false) {
var that = this;
this._context.decodeAudioData(soundData, function (buffer) {
that._game.cache.decodedSound(key, buffer);
if(sound) {
sound.setDecodedBuffer(buffer);
}
callback();
});
}
}
};
SoundManager.prototype.play = function (key, volume, loop) {
if (typeof volume === "undefined") { volume = 1; }
if (typeof loop === "undefined") { loop = false; }
var _this = this;
if(this._context === null) {
return;
}
var soundData = this._game.cache.getSound(key);
if(soundData) {
// Does the sound need decoding?
if(this._game.cache.isSoundDecoded(key) === true) {
return new Phaser.Sound(this._context, this._gainNode, soundData, volume, loop);
} else {
var tempSound = new Phaser.Sound(this._context, this._gainNode, null, volume, loop);
// this is an async process, so we can return the Sound object anyway, it just won't be playing yet
this.decode(key, function () {
return _this.play(key);
}, tempSound);
return tempSound;
}
}
};
return SoundManager;
})();
Phaser.SoundManager = SoundManager;
})(Phaser || (Phaser = {}));
/**
* Phaser
*
* v0.9.2 - April 20th 2013
*
* A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi.
*
* Richard Davey (@photonstorm)
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for the original Flixel AS3 code on which Phaser is based.
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
var Phaser;
(function (Phaser) {
Phaser.VERSION = 'Phaser version 0.9.2';
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - StageScaleMode
*
* This class controls the scaling of your game. On mobile devices it will also remove the URL bar and allow
* you to maintain proportion and aspect ratio.
* It is based on a technique taken from Viewporter v2.0 by Zynga Inc. http://github.com/zynga/viewporter
*/
var Phaser;
(function (Phaser) {
var StageScaleMode = (function () {
function StageScaleMode(game) {
var _this = this;
this._startHeight = 0;
this.width = 0;
this.height = 0;
this._game = game;
this.orientation = window['orientation'];
window.addEventListener('orientationchange', function (event) {
return _this.checkOrientation(event);
}, false);
}
StageScaleMode.EXACT_FIT = 0;
StageScaleMode.NO_SCALE = 1;
StageScaleMode.SHOW_ALL = 2;
StageScaleMode.prototype.update = function () {
if(this._game.stage.scaleMode !== StageScaleMode.NO_SCALE && (window.innerWidth !== this.width || window.innerHeight !== this.height)) {
this.refresh();
}
};
Object.defineProperty(StageScaleMode.prototype, "isLandscape", {
get: function () {
return window['orientation'] === 90 || window['orientation'] === -90;
},
enumerable: true,
configurable: true
});
StageScaleMode.prototype.checkOrientation = function (event) {
if(window['orientation'] !== this.orientation) {
this.refresh();
this.orientation = window['orientation'];
}
};
StageScaleMode.prototype.refresh = function () {
var _this = this;
// We can't do anything about the status bars in iPads, web apps or desktops
if(this._game.device.iPad == false && this._game.device.webApp == false && this._game.device.desktop == false) {
document.documentElement.style.minHeight = '5000px';
this._startHeight = window.innerHeight;
if(this._game.device.android && this._game.device.chrome == false) {
window.scrollTo(0, 1);
} else {
window.scrollTo(0, 0);
}
}
if(this._check == null) {
this._iterations = 40;
this._check = window.setInterval(function () {
return _this.setScreenSize();
}, 10);
}
};
StageScaleMode.prototype.setScreenSize = function () {
if(this._game.device.iPad == false && this._game.device.webApp == false && this._game.device.desktop == false) {
if(this._game.device.android && this._game.device.chrome == false) {
window.scrollTo(0, 1);
} else {
window.scrollTo(0, 0);
}
}
this._iterations--;
if(window.innerHeight > this._startHeight || this._iterations < 0) {
// Set minimum height of content to new window height
document.documentElement.style.minHeight = window.innerHeight + 'px';
if(this._game.stage.scaleMode == StageScaleMode.EXACT_FIT) {
if(this._game.stage.maxScaleX && window.innerWidth > this._game.stage.maxScaleX) {
this.width = this._game.stage.maxScaleX;
} else {
this.width = window.innerWidth;
}
if(this._game.stage.maxScaleY && window.innerHeight > this._game.stage.maxScaleY) {
this.height = this._game.stage.maxScaleY;
} else {
this.height = window.innerHeight;
}
} else if(this._game.stage.scaleMode == StageScaleMode.SHOW_ALL) {
var multiplier = Math.min((window.innerHeight / this._game.stage.height), (window.innerWidth / this._game.stage.width));
this.width = Math.round(this._game.stage.width * multiplier);
this.height = Math.round(this._game.stage.height * multiplier);
if(this._game.stage.maxScaleX && this.width > this._game.stage.maxScaleX) {
this.width = this._game.stage.maxScaleX;
}
if(this._game.stage.maxScaleY && this.height > this._game.stage.maxScaleY) {
this.height = this._game.stage.maxScaleY;
}
}
this._game.stage.canvas.style.width = this.width + 'px';
this._game.stage.canvas.style.height = this.height + 'px';
this._game.input.scaleX = this._game.stage.width / this.width;
this._game.input.scaleY = this._game.stage.height / this.height;
clearInterval(this._check);
this._check = null;
}
};
return StageScaleMode;
})();
Phaser.StageScaleMode = StageScaleMode;
})(Phaser || (Phaser = {}));
/// <reference path="Phaser.ts" />
/// <reference path="Game.ts" />
/// <reference path="system/StageScaleMode.ts" />
/**
* Phaser - Stage
*
* The Stage is the canvas on which everything is displayed. This class handles display within the web browser, focus handling,
* resizing, scaling and pause/boot screens.
*/
var Phaser;
(function (Phaser) {
var Stage = (function () {
function Stage(game, parent, width, height) {
var _this = this;
this.clear = true;
this.disablePauseScreen = false;
this.minScaleX = null;
this.maxScaleX = null;
this.minScaleY = null;
this.maxScaleY = null;
this._logo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAO1JREFUeNpi/P//PwM6YGRkxBQEAqBaRnQxFmwa10d6MAjrMqMofHv5L1we2SBGmAtAktg0ogOQQYHLd8ANYYFpPtTmzUAMAFmwnsEDrAdkCAvMZlIAsiFMMAEYsKvaSrQhIMCELkGsV2AAbIC8gCQYgwKIUABiNYBf9yoYH7n7n6CzN274g2IYEyFbsNmKLIaSkHpP7WSwUfbA0ASzFQRslBlxp0RcAF0TRhggA3zhAJIDpUKU5A9KyshpHDkjFZu5g2nJMFcwXVJSgqIGnBKx5bKenh4w/XzVbgbPtlIUcVgSxuoCUgHIIIAAAwArtXwJBABO6QAAAABJRU5ErkJggg==";
this._game = game;
this.canvas = document.createElement('canvas');
this.canvas.width = width;
this.canvas.height = height;
if(document.getElementById(parent)) {
document.getElementById(parent).appendChild(this.canvas);
document.getElementById(parent).style.overflow = 'hidden';
} else {
document.body.appendChild(this.canvas);
}
// Consume default actions on the canvas
this.canvas.style.msTouchAction = 'none';
this.canvas.style['touch-action'] = 'none';
this.context = this.canvas.getContext('2d');
this.offset = this.getOffset(this.canvas);
this.bounds = new Phaser.Rectangle(this.offset.x, this.offset.y, width, height);
this.aspectRatio = width / height;
this.scaleMode = Phaser.StageScaleMode.NO_SCALE;
this.scale = new Phaser.StageScaleMode(this._game);
//document.addEventListener('visibilitychange', (event) => this.visibilityChange(event), false);
//document.addEventListener('webkitvisibilitychange', (event) => this.visibilityChange(event), false);
window.onblur = function (event) {
return _this.visibilityChange(event);
};
window.onfocus = function (event) {
return _this.visibilityChange(event);
};
}
Stage.ORIENTATION_LANDSCAPE = 0;
Stage.ORIENTATION_PORTRAIT = 1;
Stage.prototype.update = function () {
this.scale.update();
if(this.clear) {
// implement dirty rect? could take up more cpu time than it saves. needs benching.
this.context.clearRect(0, 0, this.width, this.height);
}
};
Stage.prototype.renderDebugInfo = function () {
this.context.fillStyle = 'rgb(255,255,255)';
this.context.fillText(Phaser.VERSION, 10, 20);
this.context.fillText('Game Size: ' + this.width + ' x ' + this.height, 10, 40);
this.context.fillText('x: ' + this.x + ' y: ' + this.y, 10, 60);
};
Stage.prototype.visibilityChange = //if (document['hidden'] === true || document['webkitHidden'] === true)
function (event) {
if(this.disablePauseScreen) {
return;
}
if(event.type == 'blur' && this._game.paused == false && this._game.isBooted == true) {
this._game.paused = true;
this.drawPauseScreen();
} else if(event.type == 'focus') {
this._game.paused = false;
}
};
Stage.prototype.drawInitScreen = function () {
this.context.fillStyle = 'rgb(40, 40, 40)';
this.context.fillRect(0, 0, this.width, this.height);
this.context.fillStyle = 'rgb(255,255,255)';
this.context.font = 'bold 18px Arial';
this.context.textBaseline = 'top';
this.context.fillText(Phaser.VERSION, 54, 32);
this.context.fillText('Game Size: ' + this.width + ' x ' + this.height, 32, 64);
this.context.fillText('www.photonstorm.com', 32, 96);
this.context.font = '16px Arial';
this.context.fillText('You are seeing this screen because you didn\'t specify any default', 32, 160);
this.context.fillText('functions in the Game constructor, or use Game.loadState()', 32, 184);
var image = new Image();
var that = this;
image.onload = function () {
that.context.drawImage(image, 32, 32);
};
image.src = this._logo;
};
Stage.prototype.drawPauseScreen = function () {
this.saveCanvasValues();
this.context.fillStyle = 'rgba(0, 0, 0, 0.4)';
this.context.fillRect(0, 0, this.width, this.height);
// Draw a 'play' arrow
var arrowWidth = Math.round(this.width / 2);
var arrowHeight = Math.round(this.height / 2);
var sx = this.centerX - arrowWidth / 2;
var sy = this.centerY - arrowHeight / 2;
this.context.beginPath();
this.context.moveTo(sx, sy);
this.context.lineTo(sx, sy + arrowHeight);
this.context.lineTo(sx + arrowWidth, this.centerY);
this.context.fillStyle = 'rgba(255, 255, 255, 0.8)';
this.context.fill();
this.context.closePath();
this.restoreCanvasValues();
};
Stage.prototype.getOffset = function (element) {
var box = element.getBoundingClientRect();
var clientTop = element.clientTop || document.body.clientTop || 0;
var clientLeft = element.clientLeft || document.body.clientLeft || 0;
var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop;
var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft;
return new Phaser.Point(box.left + scrollLeft - clientLeft, box.top + scrollTop - clientTop);
};
Stage.prototype.saveCanvasValues = function () {
this.strokeStyle = this.context.strokeStyle;
this.lineWidth = this.context.lineWidth;
this.fillStyle = this.context.fillStyle;
};
Stage.prototype.restoreCanvasValues = function () {
this.context.strokeStyle = this.strokeStyle;
this.context.lineWidth = this.lineWidth;
this.context.fillStyle = this.fillStyle;
};
Object.defineProperty(Stage.prototype, "backgroundColor", {
get: function () {
return this._bgColor;
},
set: function (color) {
this.canvas.style.backgroundColor = color;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "x", {
get: function () {
return this.bounds.x;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "y", {
get: function () {
return this.bounds.y;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "width", {
get: function () {
return this.bounds.width;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "height", {
get: function () {
return this.bounds.height;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "centerX", {
get: function () {
return this.bounds.halfWidth;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "centerY", {
get: function () {
return this.bounds.halfHeight;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "randomX", {
get: function () {
return Math.round(Math.random() * this.bounds.width);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stage.prototype, "randomY", {
get: function () {
return Math.round(Math.random() * this.bounds.height);
},
enumerable: true,
configurable: true
});
return Stage;
})();
Phaser.Stage = Stage;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - Time
*
* This is the game clock and it manages elapsed time and calculation of delta values, used for game object motion.
*/
var Phaser;
(function (Phaser) {
var Time = (function () {
function Time(game) {
this.timeScale = 1.0;
this.elapsed = 0;
/**
*
* @property time
* @type Number
*/
this.time = 0;
/**
*
* @property now
* @type Number
*/
this.now = 0;
/**
*
* @property delta
* @type Number
*/
this.delta = 0;
this.fps = 0;
this.fpsMin = 1000;
this.fpsMax = 0;
this.msMin = 1000;
this.msMax = 0;
this.frames = 0;
this._timeLastSecond = 0;
this._started = Date.now();
this._timeLastSecond = this._started;
this.time = this._started;
}
Object.defineProperty(Time.prototype, "totalElapsedSeconds", {
get: /**
*
* @method totalElapsedSeconds
* @return {Number}
*/
function () {
return (this.now - this._started) * 0.001;
},
enumerable: true,
configurable: true
});
Time.prototype.update = /**
*
* @method update
*/
function () {
// Can we use performance.now() ?
this.now = Date.now()// mark
;
this.delta = this.now - this.time// elapsedMS
;
this.msMin = Math.min(this.msMin, this.delta);
this.msMax = Math.max(this.msMax, this.delta);
this.frames++;
if(this.now > this._timeLastSecond + 1000) {
this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
this.fpsMin = Math.min(this.fpsMin, this.fps);
this.fpsMax = Math.max(this.fpsMax, this.fps);
this._timeLastSecond = this.now;
this.frames = 0;
}
this.time = this.now// _total
;
//// Lock the delta at 0.1 to minimise fps tunneling
//if (this.delta > 0.1)
//{
// this.delta = 0.1;
//}
};
Time.prototype.elapsedSince = /**
*
* @method elapsedSince
* @param {Number} since
* @return {Number}
*/
function (since) {
return this.now - since;
};
Time.prototype.elapsedSecondsSince = /**
*
* @method elapsedSecondsSince
* @param {Number} since
* @return {Number}
*/
function (since) {
return (this.now - since) * 0.001;
};
Time.prototype.reset = /**
*
* @method reset
*/
function () {
this._started = this.now;
};
return Time;
})();
Phaser.Time = Time;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Back
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Back = (function () {
function Back() { }
Back.In = function In(k) {
var s = 1.70158;
return k * k * ((s + 1) * k - s);
};
Back.Out = function Out(k) {
var s = 1.70158;
return --k * k * ((s + 1) * k + s) + 1;
};
Back.InOut = function InOut(k) {
var s = 1.70158 * 1.525;
if((k *= 2) < 1) {
return 0.5 * (k * k * ((s + 1) * k - s));
}
return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
};
return Back;
})();
Easing.Back = Back;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Bounce
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Bounce = (function () {
function Bounce() { }
Bounce.In = function In(k) {
return 1 - Phaser.Easing.Bounce.Out(1 - k);
};
Bounce.Out = function Out(k) {
if(k < (1 / 2.75)) {
return 7.5625 * k * k;
} else if(k < (2 / 2.75)) {
return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
} else if(k < (2.5 / 2.75)) {
return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
} else {
return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
}
};
Bounce.InOut = function InOut(k) {
if(k < 0.5) {
return Phaser.Easing.Bounce.In(k * 2) * 0.5;
}
return Phaser.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;
};
return Bounce;
})();
Easing.Bounce = Bounce;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Circular
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Circular = (function () {
function Circular() { }
Circular.In = function In(k) {
return 1 - Math.sqrt(1 - k * k);
};
Circular.Out = function Out(k) {
return Math.sqrt(1 - (--k * k));
};
Circular.InOut = function InOut(k) {
if((k *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - k * k) - 1);
}
return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
};
return Circular;
})();
Easing.Circular = Circular;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Cubic
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Cubic = (function () {
function Cubic() { }
Cubic.In = function In(k) {
return k * k * k;
};
Cubic.Out = function Out(k) {
return --k * k * k + 1;
};
Cubic.InOut = function InOut(k) {
if((k *= 2) < 1) {
return 0.5 * k * k * k;
}
return 0.5 * ((k -= 2) * k * k + 2);
};
return Cubic;
})();
Easing.Cubic = Cubic;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Elastic
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Elastic = (function () {
function Elastic() { }
Elastic.In = function In(k) {
var s, a = 0.1, p = 0.4;
if(k === 0) {
return 0;
}
if(k === 1) {
return 1;
}
if(!a || a < 1) {
a = 1;
s = p / 4;
} else {
s = p * Math.asin(1 / a) / (2 * Math.PI);
}
return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
};
Elastic.Out = function Out(k) {
var s, a = 0.1, p = 0.4;
if(k === 0) {
return 0;
}
if(k === 1) {
return 1;
}
if(!a || a < 1) {
a = 1;
s = p / 4;
} else {
s = p * Math.asin(1 / a) / (2 * Math.PI);
}
return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
};
Elastic.InOut = function InOut(k) {
var s, a = 0.1, p = 0.4;
if(k === 0) {
return 0;
}
if(k === 1) {
return 1;
}
if(!a || a < 1) {
a = 1;
s = p / 4;
} else {
s = p * Math.asin(1 / a) / (2 * Math.PI);
}
if((k *= 2) < 1) {
return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
}
return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
};
return Elastic;
})();
Easing.Elastic = Elastic;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Exponential
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Exponential = (function () {
function Exponential() { }
Exponential.In = function In(k) {
return k === 0 ? 0 : Math.pow(1024, k - 1);
};
Exponential.Out = function Out(k) {
return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
};
Exponential.InOut = function InOut(k) {
if(k === 0) {
return 0;
}
if(k === 1) {
return 1;
}
if((k *= 2) < 1) {
return 0.5 * Math.pow(1024, k - 1);
}
return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
};
return Exponential;
})();
Easing.Exponential = Exponential;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Linear
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Linear = (function () {
function Linear() { }
Linear.None = function None(k) {
return k;
};
return Linear;
})();
Easing.Linear = Linear;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Quadratic
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Quadratic = (function () {
function Quadratic() { }
Quadratic.In = function In(k) {
return k * k;
};
Quadratic.Out = function Out(k) {
return k * (2 - k);
};
Quadratic.InOut = function InOut(k) {
if((k *= 2) < 1) {
return 0.5 * k * k;
}
return -0.5 * (--k * (k - 2) - 1);
};
return Quadratic;
})();
Easing.Quadratic = Quadratic;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Quartic
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Quartic = (function () {
function Quartic() { }
Quartic.In = function In(k) {
return k * k * k * k;
};
Quartic.Out = function Out(k) {
return 1 - (--k * k * k * k);
};
Quartic.InOut = function InOut(k) {
if((k *= 2) < 1) {
return 0.5 * k * k * k * k;
}
return -0.5 * ((k -= 2) * k * k * k - 2);
};
return Quartic;
})();
Easing.Quartic = Quartic;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Quintic
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Quintic = (function () {
function Quintic() { }
Quintic.In = function In(k) {
return k * k * k * k * k;
};
Quintic.Out = function Out(k) {
return --k * k * k * k * k + 1;
};
Quintic.InOut = function InOut(k) {
if((k *= 2) < 1) {
return 0.5 * k * k * k * k * k;
}
return 0.5 * ((k -= 2) * k * k * k * k + 2);
};
return Quintic;
})();
Easing.Quintic = Quintic;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
var Phaser;
(function (Phaser) {
/// <reference path="../../Game.ts" />
/**
* Phaser - Easing - Sinusoidal
*
* For use with Phaser.Tween
*/
(function (Easing) {
var Sinusoidal = (function () {
function Sinusoidal() { }
Sinusoidal.In = function In(k) {
return 1 - Math.cos(k * Math.PI / 2);
};
Sinusoidal.Out = function Out(k) {
return Math.sin(k * Math.PI / 2);
};
Sinusoidal.InOut = function InOut(k) {
return 0.5 * (1 - Math.cos(Math.PI * k));
};
return Sinusoidal;
})();
Easing.Sinusoidal = Sinusoidal;
})(Phaser.Easing || (Phaser.Easing = {}));
var Easing = Phaser.Easing;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="easing/Back.ts" />
/// <reference path="easing/Bounce.ts" />
/// <reference path="easing/Circular.ts" />
/// <reference path="easing/Cubic.ts" />
/// <reference path="easing/Elastic.ts" />
/// <reference path="easing/Exponential.ts" />
/// <reference path="easing/Linear.ts" />
/// <reference path="easing/Quadratic.ts" />
/// <reference path="easing/Quartic.ts" />
/// <reference path="easing/Quintic.ts" />
/// <reference path="easing/Sinusoidal.ts" />
/**
* Phaser - Tween
*
* Based heavily on tween.js by sole (https://github.com/sole/tween.js) converted to TypeScript and integrated into Phaser
*/
var Phaser;
(function (Phaser) {
var Tween = (function () {
function Tween(object, game) {
this._object = null;
this._pausedTime = 0;
this._valuesStart = {
};
this._valuesEnd = {
};
this._duration = 1000;
this._delayTime = 0;
this._startTime = null;
this._chainedTweens = [];
this._object = object;
this._game = game;
this._manager = this._game.tweens;
this._interpolationFunction = this._game.math.linearInterpolation;
this._easingFunction = Phaser.Easing.Linear.None;
this.onStart = new Phaser.Signal();
this.onUpdate = new Phaser.Signal();
this.onComplete = new Phaser.Signal();
}
Tween.prototype.to = function (properties, duration, ease, autoStart) {
if (typeof duration === "undefined") { duration = 1000; }
if (typeof ease === "undefined") { ease = null; }
if (typeof autoStart === "undefined") { autoStart = false; }
this._duration = duration;
// If properties isn't an object this will fail, sanity check it here somehow?
this._valuesEnd = properties;
if(ease !== null) {
this._easingFunction = ease;
}
if(autoStart === true) {
return this.start();
} else {
return this;
}
};
Tween.prototype.start = function () {
if(this._game === null || this._object === null) {
return;
}
this._manager.add(this);
this.onStart.dispatch(this._object);
this._startTime = this._game.time.now + this._delayTime;
for(var property in this._valuesEnd) {
// This prevents the interpolation of null values or of non-existing properties
if(this._object[property] === null || !(property in this._object)) {
throw Error('Phaser.Tween interpolation of null value of non-existing property');
continue;
}
// check if an Array was provided as property value
if(this._valuesEnd[property] instanceof Array) {
if(this._valuesEnd[property].length === 0) {
continue;
}
// create a local copy of the Array with the start value at the front
this._valuesEnd[property] = [
this._object[property]
].concat(this._valuesEnd[property]);
}
this._valuesStart[property] = this._object[property];
}
return this;
};
Tween.prototype.stop = function () {
if(this._manager !== null) {
this._manager.remove(this);
}
return this;
};
Object.defineProperty(Tween.prototype, "parent", {
set: function (value) {
this._game = value;
this._manager = this._game.tweens;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tween.prototype, "delay", {
get: function () {
return this._delayTime;
},
set: function (amount) {
this._delayTime = amount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tween.prototype, "easing", {
get: function () {
return this._easingFunction;
},
set: function (easing) {
this._easingFunction = easing;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tween.prototype, "interpolation", {
get: function () {
return this._interpolationFunction;
},
set: function (interpolation) {
this._interpolationFunction = interpolation;
},
enumerable: true,
configurable: true
});
Tween.prototype.chain = function (tween) {
this._chainedTweens.push(tween);
return this;
};
Tween.prototype.update = function (time) {
if(this._game.paused == true) {
if(this._pausedTime == 0) {
this._pausedTime = time;
}
} else {
// Ok we aren't paused, but was there some time gained?
if(this._pausedTime > 0) {
this._startTime += (time - this._pausedTime);
this._pausedTime = 0;
}
}
if(time < this._startTime) {
return true;
}
var elapsed = (time - this._startTime) / this._duration;
elapsed = elapsed > 1 ? 1 : elapsed;
var value = this._easingFunction(elapsed);
for(var property in this._valuesStart) {
// Add checks for object, array, numeric up front
if(this._valuesEnd[property] instanceof Array) {
this._object[property] = this._interpolationFunction(this._valuesEnd[property], value);
} else {
this._object[property] = this._valuesStart[property] + (this._valuesEnd[property] - this._valuesStart[property]) * value;
}
}
this.onUpdate.dispatch(this._object, value);
if(elapsed == 1) {
this.onComplete.dispatch(this._object);
for(var i = 0; i < this._chainedTweens.length; i++) {
this._chainedTweens[i].start();
}
return false;
}
return true;
};
return Tween;
})();
Phaser.Tween = Tween;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/// <reference path="system/Tween.ts" />
/**
* Phaser - TweenManager
*
* The Game has a single instance of the TweenManager through which all Tween objects are created and updated.
* Tweens are hooked into the game clock and pause system, adjusting based on the game state.
* TweenManager is based heavily on tween.js by sole (http://soledadpenades.com).
* I converted it to TypeScript, swapped the callbacks for signals and patched a few issues with regard
* to properties and completion errors. Please see https://github.com/sole/tween.js for a full list of contributors.
*/
var Phaser;
(function (Phaser) {
var TweenManager = (function () {
function TweenManager(game) {
this._game = game;
this._tweens = [];
}
TweenManager.prototype.getAll = function () {
return this._tweens;
};
TweenManager.prototype.removeAll = function () {
this._tweens.length = 0;
};
TweenManager.prototype.create = function (object) {
return new Phaser.Tween(object, this._game);
};
TweenManager.prototype.add = function (tween) {
tween.parent = this._game;
this._tweens.push(tween);
return tween;
};
TweenManager.prototype.remove = function (tween) {
var i = this._tweens.indexOf(tween);
if(i !== -1) {
this._tweens.splice(i, 1);
}
};
TweenManager.prototype.update = function () {
if(this._tweens.length === 0) {
return false;
}
var i = 0;
var numTweens = this._tweens.length;
while(i < numTweens) {
if(this._tweens[i].update(this._game.time.now)) {
i++;
} else {
this._tweens.splice(i, 1);
numTweens--;
}
}
return true;
};
return TweenManager;
})();
Phaser.TweenManager = TweenManager;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - World
*
* A game has only one world. The world is an abstract place in which all game objects live. It is not bound
* by stage limits and can be any size or dimension. You look into the world via cameras and all game objects
* live within the world at world-based coordinates. By default a world is created the same size as your Stage.
*/
var Phaser;
(function (Phaser) {
var World = (function () {
function World(game, width, height) {
this._game = game;
this._cameras = new Phaser.CameraManager(this._game, 0, 0, width, height);
this._game.camera = this._cameras.current;
this.group = new Phaser.Group(this._game, 0);
this.bounds = new Phaser.Rectangle(0, 0, width, height);
this.worldDivisions = 6;
}
World.prototype.update = function () {
this.group.preUpdate();
this.group.update();
this.group.postUpdate();
this._cameras.update();
};
World.prototype.render = function () {
// Unlike in flixel our render process is camera driven, not group driven
this._cameras.render();
};
World.prototype.destroy = function () {
this.group.destroy();
this._cameras.destroy();
};
World.prototype.setSize = // World methods
function (width, height, updateCameraBounds) {
if (typeof updateCameraBounds === "undefined") { updateCameraBounds = true; }
this.bounds.width = width;
this.bounds.height = height;
if(updateCameraBounds == true) {
this._game.camera.setBounds(0, 0, width, height);
}
};
Object.defineProperty(World.prototype, "width", {
get: function () {
return this.bounds.width;
},
set: function (value) {
this.bounds.width = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(World.prototype, "height", {
get: function () {
return this.bounds.height;
},
set: function (value) {
this.bounds.height = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(World.prototype, "centerX", {
get: function () {
return this.bounds.halfWidth;
},
enumerable: true,
configurable: true
});
Object.defineProperty(World.prototype, "centerY", {
get: function () {
return this.bounds.halfHeight;
},
enumerable: true,
configurable: true
});
Object.defineProperty(World.prototype, "randomX", {
get: function () {
return Math.round(Math.random() * this.bounds.width);
},
enumerable: true,
configurable: true
});
Object.defineProperty(World.prototype, "randomY", {
get: function () {
return Math.round(Math.random() * this.bounds.height);
},
enumerable: true,
configurable: true
});
World.prototype.addExistingCamera = // Cameras
function (cam) {
//return this._cameras.addCamera(x, y, width, height);
return cam;
};
World.prototype.createCamera = function (x, y, width, height) {
return this._cameras.addCamera(x, y, width, height);
};
World.prototype.removeCamera = function (id) {
return this._cameras.removeCamera(id);
};
World.prototype.getAllCameras = function () {
return this._cameras.getAll();
};
World.prototype.addExistingSprite = // Sprites
// Drop this?
function (sprite) {
return this.group.add(sprite);
};
World.prototype.createSprite = function (x, y, key) {
if (typeof key === "undefined") { key = ''; }
return this.group.add(new Phaser.Sprite(this._game, x, y, key));
};
World.prototype.createGeomSprite = function (x, y) {
return this.group.add(new Phaser.GeomSprite(this._game, x, y));
};
World.prototype.createDynamicTexture = function (key, width, height) {
return new Phaser.DynamicTexture(this._game, key, width, height);
};
World.prototype.createGroup = function (MaxSize) {
if (typeof MaxSize === "undefined") { MaxSize = 0; }
return this.group.add(new Phaser.Group(this._game, MaxSize));
};
World.prototype.createTilemap = // Tilemaps
function (key, mapData, format, tileWidth, tileHeight) {
return this.group.add(new Phaser.Tilemap(this._game, key, mapData, format, tileWidth, tileHeight));
};
World.prototype.createParticle = // Emitters
function () {
return new Phaser.Particle(this._game);
};
World.prototype.createEmitter = function (x, y, size) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof size === "undefined") { size = 0; }
return this.group.add(new Phaser.Emitter(this._game, x, y, size));
};
return World;
})();
Phaser.World = World;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - Device
*
* Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr
* https://github.com/Modernizr/Modernizr/blob/master/feature-detects/audio.js
*/
var Phaser;
(function (Phaser) {
var Device = (function () {
/**
*
* @constructor
* @return {Device} This Object
*/
function Device() {
// Operating System
this.desktop = false;
/**
*
* @property iOS
* @type Boolean
*/
this.iOS = false;
/**
*
* @property android
* @type Boolean
*/
this.android = false;
/**
*
* @property chromeOS
* @type Boolean
*/
this.chromeOS = false;
/**
*
* @property linux
* @type Boolean
*/
this.linux = false;
/**
*
* @property maxOS
* @type Boolean
*/
this.macOS = false;
/**
*
* @property windows
* @type Boolean
*/
this.windows = false;
// Features
/**
*
* @property canvas
* @type Boolean
*/
this.canvas = false;
/**
*
* @property file
* @type Boolean
*/
this.file = false;
/**
*
* @property fileSystem
* @type Boolean
*/
this.fileSystem = false;
/**
*
* @property localStorage
* @type Boolean
*/
this.localStorage = false;
/**
*
* @property webGL
* @type Boolean
*/
this.webGL = false;
/**
*
* @property worker
* @type Boolean
*/
this.worker = false;
/**
*
* @property touch
* @type Boolean
*/
this.touch = false;
/**
*
* @property css3D
* @type Boolean
*/
this.css3D = false;
// Browser
/**
*
* @property arora
* @type Boolean
*/
this.arora = false;
/**
*
* @property chrome
* @type Boolean
*/
this.chrome = false;
/**
*
* @property epiphany
* @type Boolean
*/
this.epiphany = false;
/**
*
* @property firefox
* @type Boolean
*/
this.firefox = false;
/**
*
* @property ie
* @type Boolean
*/
this.ie = false;
/**
*
* @property ieVersion
* @type Number
*/
this.ieVersion = 0;
/**
*
* @property mobileSafari
* @type Boolean
*/
this.mobileSafari = false;
/**
*
* @property midori
* @type Boolean
*/
this.midori = false;
/**
*
* @property opera
* @type Boolean
*/
this.opera = false;
/**
*
* @property safari
* @type Boolean
*/
this.safari = false;
this.webApp = false;
// Audio
/**
*
* @property audioData
* @type Boolean
*/
this.audioData = false;
/**
*
* @property webaudio
* @type Boolean
*/
this.webaudio = false;
/**
*
* @property ogg
* @type Boolean
*/
this.ogg = false;
/**
*
* @property mp3
* @type Boolean
*/
this.mp3 = false;
/**
*
* @property wav
* @type Boolean
*/
this.wav = false;
/**
*
* @property m4a
* @type Boolean
*/
this.m4a = false;
// Device
/**
*
* @property iPhone
* @type Boolean
*/
this.iPhone = false;
/**
*
* @property iPhone4
* @type Boolean
*/
this.iPhone4 = false;
/**
*
* @property iPad
* @type Boolean
*/
this.iPad = false;
/**
*
* @property pixelRatio
* @type Number
*/
this.pixelRatio = 0;
this._checkAudio();
this._checkBrowser();
this._checkCSS3D();
this._checkDevice();
this._checkFeatures();
this._checkOS();
}
Device.prototype._checkOS = /**
*
* @method _checkOS
* @private
*/
function () {
var ua = navigator.userAgent;
if(/Android/.test(ua)) {
this.android = true;
} else if(/CrOS/.test(ua)) {
this.chromeOS = true;
} else if(/iP[ao]d|iPhone/i.test(ua)) {
this.iOS = true;
} else if(/Linux/.test(ua)) {
this.linux = true;
} else if(/Mac OS/.test(ua)) {
this.macOS = true;
} else if(/Windows/.test(ua)) {
this.windows = true;
}
if(this.windows || this.macOS || this.linux) {
this.desktop = true;
}
};
Device.prototype._checkFeatures = /**
*
* @method _checkFeatures
* @private
*/
function () {
this.canvas = !!window['CanvasRenderingContext2D'];
try {
this.localStorage = !!localStorage.getItem;
} catch (error) {
this.localStorage = false;
}
this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
this.fileSystem = !!window['requestFileSystem'];
this.webGL = !!window['WebGLRenderingContext'];
this.worker = !!window['Worker'];
if('ontouchstart' in document.documentElement || window.navigator.msPointerEnabled) {
this.touch = true;
}
};
Device.prototype._checkBrowser = /**
*
* @method _checkBrowser
* @private
*/
function () {
var ua = navigator.userAgent;
if(/Arora/.test(ua)) {
this.arora = true;
} else if(/Chrome/.test(ua)) {
this.chrome = true;
} else if(/Epiphany/.test(ua)) {
this.epiphany = true;
} else if(/Firefox/.test(ua)) {
this.firefox = true;
} else if(/Mobile Safari/.test(ua)) {
this.mobileSafari = true;
} else if(/MSIE (\d+\.\d+);/.test(ua)) {
this.ie = true;
this.ieVersion = parseInt(RegExp.$1);
} else if(/Midori/.test(ua)) {
this.midori = true;
} else if(/Opera/.test(ua)) {
this.opera = true;
} else if(/Safari/.test(ua)) {
this.safari = true;
}
// WebApp mode in iOS
if(navigator['standalone']) {
this.webApp = true;
}
};
Device.prototype._checkAudio = /**
*
* @method _checkAudio
* @private
*/
function () {
this.audioData = !!(window['Audio']);
this.webaudio = !!(window['webkitAudioContext'] || window['AudioContext']);
var audioElement = document.createElement('audio');
var result = false;
try {
if(result = !!audioElement.canPlayType) {
if(audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
this.ogg = true;
}
if(audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) {
this.mp3 = true;
}
// Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// bit.ly/iphoneoscodecs
if(audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) {
this.wav = true;
}
if(audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) {
this.m4a = true;
}
}
} catch (e) {
}
};
Device.prototype._checkDevice = /**
*
* @method _checkDevice
* @private
*/
function () {
this.pixelRatio = window['devicePixelRatio'] || 1;
this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
this.iPhone4 = (this.pixelRatio == 2 && this.iPhone);
this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1;
};
Device.prototype._checkCSS3D = /**
*
* @method _checkCSS3D
* @private
*/
function () {
var el = document.createElement('p');
var has3d;
var transforms = {
'webkitTransform': '-webkit-transform',
'OTransform': '-o-transform',
'msTransform': '-ms-transform',
'MozTransform': '-moz-transform',
'transform': 'transform'
};
// Add it to the body to get the computed style.
document.body.insertBefore(el, null);
for(var t in transforms) {
if(el.style[t] !== undefined) {
el.style[t] = "translate3d(1px,1px,1px)";
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
this.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
};
Device.prototype.getAll = /**
*
* @method getAll
* @return {String}
*/
function () {
var output = '';
output = output.concat('Device\n');
output = output.concat('iPhone : ' + this.iPhone + '\n');
output = output.concat('iPhone4 : ' + this.iPhone4 + '\n');
output = output.concat('iPad : ' + this.iPad + '\n');
output = output.concat('\n');
output = output.concat('Operating System\n');
output = output.concat('iOS: ' + this.iOS + '\n');
output = output.concat('Android: ' + this.android + '\n');
output = output.concat('ChromeOS: ' + this.chromeOS + '\n');
output = output.concat('Linux: ' + this.linux + '\n');
output = output.concat('MacOS: ' + this.macOS + '\n');
output = output.concat('Windows: ' + this.windows + '\n');
output = output.concat('\n');
output = output.concat('Browser\n');
output = output.concat('Arora: ' + this.arora + '\n');
output = output.concat('Chrome: ' + this.chrome + '\n');
output = output.concat('Epiphany: ' + this.epiphany + '\n');
output = output.concat('Firefox: ' + this.firefox + '\n');
output = output.concat('Internet Explorer: ' + this.ie + ' (' + this.ieVersion + ')\n');
output = output.concat('Mobile Safari: ' + this.mobileSafari + '\n');
output = output.concat('Midori: ' + this.midori + '\n');
output = output.concat('Opera: ' + this.opera + '\n');
output = output.concat('Safari: ' + this.safari + '\n');
output = output.concat('\n');
output = output.concat('Features\n');
output = output.concat('Canvas: ' + this.canvas + '\n');
output = output.concat('File: ' + this.file + '\n');
output = output.concat('FileSystem: ' + this.fileSystem + '\n');
output = output.concat('LocalStorage: ' + this.localStorage + '\n');
output = output.concat('WebGL: ' + this.webGL + '\n');
output = output.concat('Worker: ' + this.worker + '\n');
output = output.concat('Touch: ' + this.touch + '\n');
output = output.concat('CSS 3D: ' + this.css3D + '\n');
output = output.concat('\n');
output = output.concat('Audio\n');
output = output.concat('Audio Data: ' + this.canvas + '\n');
output = output.concat('Web Audio: ' + this.canvas + '\n');
output = output.concat('Can play OGG: ' + this.canvas + '\n');
output = output.concat('Can play MP3: ' + this.canvas + '\n');
output = output.concat('Can play M4A: ' + this.canvas + '\n');
output = output.concat('Can play WAV: ' + this.canvas + '\n');
return output;
};
return Device;
})();
Phaser.Device = Device;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - RandomDataGenerator
*
* An extremely useful repeatable random data generator. Access it via Game.rnd
* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense
* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
*/
var Phaser;
(function (Phaser) {
var RandomDataGenerator = (function () {
/**
* @constructor
* @param {Array} seeds
* @return {Phaser.RandomDataGenerator}
*/
function RandomDataGenerator(seeds) {
if (typeof seeds === "undefined") { seeds = []; }
/**
* @property c
* @type Number
* @private
*/
this.c = 1;
this.sow(seeds);
}
RandomDataGenerator.prototype.uint32 = /**
* @method uint32
* @private
*/
function () {
return this.rnd.apply(this) * 0x100000000;// 2^32
};
RandomDataGenerator.prototype.fract32 = /**
* @method fract32
* @private
*/
function () {
return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53
};
RandomDataGenerator.prototype.rnd = // private random helper
/**
* @method rnd
* @private
*/
function () {
var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10;// 2^-32
this.c = t | 0;
this.s0 = this.s1;
this.s1 = this.s2;
this.s2 = t - this.c;
return this.s2;
};
RandomDataGenerator.prototype.hash = /**
* @method hash
* @param {Any} data
* @private
*/
function (data) {
var h, i, n;
n = 0xefc8249d;
data = data.toString();
for(i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000// 2^32
;
}
return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
};
RandomDataGenerator.prototype.sow = /**
* Reset the seed of the random data generator
* @method sow
* @param {Array} seeds
*/
function (seeds) {
if (typeof seeds === "undefined") { seeds = []; }
this.s0 = this.hash(' ');
this.s1 = this.hash(this.s0);
this.s2 = this.hash(this.s1);
var seed;
for(var i = 0; seed = seeds[i++]; ) {
this.s0 -= this.hash(seed);
this.s0 += ~~(this.s0 < 0);
this.s1 -= this.hash(seed);
this.s1 += ~~(this.s1 < 0);
this.s2 -= this.hash(seed);
this.s2 += ~~(this.s2 < 0);
}
};
Object.defineProperty(RandomDataGenerator.prototype, "integer", {
get: /**
* Returns a random integer between 0 and 2^32
* @method integer
* @return {Number}
*/
function () {
return this.uint32();
},
enumerable: true,
configurable: true
});
Object.defineProperty(RandomDataGenerator.prototype, "frac", {
get: /**
* Returns a random real number between 0 and 1
* @method frac
* @return {Number}
*/
function () {
return this.fract32();
},
enumerable: true,
configurable: true
});
Object.defineProperty(RandomDataGenerator.prototype, "real", {
get: /**
* Returns a random real number between 0 and 2^32
* @method real
* @return {Number}
*/
function () {
return this.uint32() + this.fract32();
},
enumerable: true,
configurable: true
});
RandomDataGenerator.prototype.integerInRange = /**
* Returns a random integer between min and max
* @method integerInRange
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
function (min, max) {
return Math.floor(this.realInRange(min, max));
};
RandomDataGenerator.prototype.realInRange = /**
* Returns a random real number between min and max
* @method realInRange
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
function (min, max) {
min = min || 0;
max = max || 0;
return this.frac * (max - min) + min;
};
Object.defineProperty(RandomDataGenerator.prototype, "normal", {
get: /**
* Returns a random real number between -1 and 1
* @method normal
* @return {Number}
*/
function () {
return 1 - 2 * this.frac;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RandomDataGenerator.prototype, "uuid", {
get: /**
* Returns a valid v4 UUID hex string (from https://gist.github.com/1308368)
* @method uuid
* @return {String}
*/
function () {
var a, b;
for(b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') {
;
}
return b;
},
enumerable: true,
configurable: true
});
RandomDataGenerator.prototype.pick = /**
* Returns a random member of `array`
* @method pick
* @param {Any} array
*/
function (array) {
return array[this.integerInRange(0, array.length)];
};
RandomDataGenerator.prototype.weightedPick = /**
* Returns a random member of `array`, favoring the earlier entries
* @method weightedPick
* @param {Any} array
*/
function (array) {
return array[~~(Math.pow(this.frac, 2) * array.length)];
};
RandomDataGenerator.prototype.timestamp = /**
* Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified
* @method timestamp
* @param {Number} min
* @param {Number} max
*/
function (min, max) {
if (typeof min === "undefined") { min = 946684800000; }
if (typeof max === "undefined") { max = 1577862000000; }
return this.realInRange(min, max);
};
Object.defineProperty(RandomDataGenerator.prototype, "angle", {
get: /**
* Returns a random angle between -180 and 180
* @method angle
*/
function () {
return this.integerInRange(-180, 180);
},
enumerable: true,
configurable: true
});
return RandomDataGenerator;
})();
Phaser.RandomDataGenerator = RandomDataGenerator;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - RequestAnimationFrame
*
* Abstracts away the use of RAF or setTimeOut for the core game update loop. The callback can be re-mapped on the fly.
*/
var Phaser;
(function (Phaser) {
var RequestAnimationFrame = (function () {
/**
* Constructor
* @param {Any} callback
* @return {RequestAnimationFrame} This object.
*/
function RequestAnimationFrame(callback, callbackContext) {
/**
*
* @property _isSetTimeOut
* @type Boolean
* @private
**/
this._isSetTimeOut = false;
/**
*
* @property lastTime
* @type Number
**/
this.lastTime = 0;
/**
*
* @property currentTime
* @type Number
**/
this.currentTime = 0;
/**
*
* @property isRunning
* @type Boolean
**/
this.isRunning = false;
this._callback = callback;
this._callbackContext = callbackContext;
var vendors = [
'ms',
'moz',
'webkit',
'o'
];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
}
this.start();
}
RequestAnimationFrame.prototype.setCallback = /**
*
* @method callback
* @param {Any} callback
**/
function (callback) {
this._callback = callback;
};
RequestAnimationFrame.prototype.isUsingSetTimeOut = /**
*
* @method usingSetTimeOut
* @return Boolean
**/
function () {
return this._isSetTimeOut;
};
RequestAnimationFrame.prototype.isUsingRAF = /**
*
* @method usingRAF
* @return Boolean
**/
function () {
if(this._isSetTimeOut === true) {
return false;
} else {
return true;
}
};
RequestAnimationFrame.prototype.start = /**
*
* @method start
* @param {Any} [callback]
**/
function (callback) {
if (typeof callback === "undefined") { callback = null; }
var _this = this;
if(callback) {
this._callback = callback;
}
if(!window.requestAnimationFrame) {
this._isSetTimeOut = true;
this._timeOutID = window.setTimeout(function () {
return _this.SetTimeoutUpdate();
}, 0);
} else {
this._isSetTimeOut = false;
window.requestAnimationFrame(function () {
return _this.RAFUpdate();
});
}
this.isRunning = true;
};
RequestAnimationFrame.prototype.stop = /**
*
* @method stop
**/
function () {
if(this._isSetTimeOut) {
clearTimeout(this._timeOutID);
} else {
window.cancelAnimationFrame;
}
this.isRunning = false;
};
RequestAnimationFrame.prototype.RAFUpdate = function () {
var _this = this;
// Not in IE8 (but neither is RAF) also doesn't use a high performance timer (window.performance.now)
this.currentTime = Date.now();
if(this._callback) {
this._callback.call(this._callbackContext);
}
var timeToCall = Math.max(0, 16 - (this.currentTime - this.lastTime));
window.requestAnimationFrame(function () {
return _this.RAFUpdate();
});
this.lastTime = this.currentTime + timeToCall;
};
RequestAnimationFrame.prototype.SetTimeoutUpdate = /**
*
* @method SetTimeoutUpdate
**/
function () {
var _this = this;
// Not in IE8
this.currentTime = Date.now();
if(this._callback) {
this._callback.call(this._callbackContext);
}
var timeToCall = Math.max(0, 16 - (this.currentTime - this.lastTime));
this._timeOutID = window.setTimeout(function () {
return _this.SetTimeoutUpdate();
}, timeToCall);
this.lastTime = this.currentTime + timeToCall;
};
return RequestAnimationFrame;
})();
Phaser.RequestAnimationFrame = RequestAnimationFrame;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/// <reference path="../../Signal.ts" />
/**
* Phaser - Input
*
* A game specific Input manager that looks after the mouse, keyboard and touch objects. This is updated by the core game loop.
*/
var Phaser;
(function (Phaser) {
var Input = (function () {
function Input(game) {
this.x = 0;
this.y = 0;
this.scaleX = 1;
this.scaleY = 1;
this.worldX = 0;
this.worldY = 0;
this._game = game;
this.mouse = new Phaser.Mouse(this._game);
this.keyboard = new Phaser.Keyboard(this._game);
this.touch = new Phaser.Touch(this._game);
this.onDown = new Phaser.Signal();
this.onUp = new Phaser.Signal();
}
Input.prototype.update = function () {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
this.worldX = this._game.camera.worldView.x + this.x;
this.worldY = this._game.camera.worldView.y + this.y;
this.mouse.update();
this.touch.update();
};
Input.prototype.reset = function () {
this.mouse.reset();
this.keyboard.reset();
this.touch.reset();
};
Input.prototype.getWorldX = function (camera) {
if (typeof camera === "undefined") { camera = this._game.camera; }
return camera.worldView.x + this.x;
};
Input.prototype.getWorldY = function (camera) {
if (typeof camera === "undefined") { camera = this._game.camera; }
return camera.worldView.y + this.y;
};
Input.prototype.renderDebugInfo = function (x, y, color) {
if (typeof color === "undefined") { color = 'rgb(255,255,255)'; }
this._game.stage.context.fillStyle = color;
this._game.stage.context.fillText('Input', x, y);
this._game.stage.context.fillText('Screen X: ' + this.x + ' Screen Y: ' + this.y, x, y + 14);
this._game.stage.context.fillText('World X: ' + this.worldX + ' World Y: ' + this.worldY, x, y + 28);
this._game.stage.context.fillText('Scale X: ' + this.scaleX.toFixed(1) + ' Scale Y: ' + this.scaleY.toFixed(1), x, y + 42);
};
return Input;
})();
Phaser.Input = Input;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - Keyboard
*
* The Keyboard class handles keyboard interactions with the game and the resulting events.
* The avoid stealing all browser input we don't use event.preventDefault. If you would like to trap a specific key however
* then use the addKeyCapture() method.
*/
var Phaser;
(function (Phaser) {
var Keyboard = (function () {
function Keyboard(game) {
this._keys = {
};
this._capture = {
};
this._game = game;
this.start();
}
Keyboard.prototype.start = function () {
var _this = this;
document.body.addEventListener('keydown', function (event) {
return _this.onKeyDown(event);
}, false);
document.body.addEventListener('keyup', function (event) {
return _this.onKeyUp(event);
}, false);
};
Keyboard.prototype.addKeyCapture = function (keycode) {
this._capture[keycode] = true;
};
Keyboard.prototype.removeKeyCapture = function (keycode) {
delete this._capture[keycode];
};
Keyboard.prototype.clearCaptures = function () {
this._capture = {
};
};
Keyboard.prototype.onKeyDown = function (event) {
if(this._capture[event.keyCode]) {
event.preventDefault();
}
if(!this._keys[event.keyCode]) {
this._keys[event.keyCode] = {
isDown: true,
timeDown: this._game.time.now,
timeUp: 0
};
} else {
this._keys[event.keyCode].isDown = true;
this._keys[event.keyCode].timeDown = this._game.time.now;
}
};
Keyboard.prototype.onKeyUp = function (event) {
if(this._capture[event.keyCode]) {
event.preventDefault();
}
if(!this._keys[event.keyCode]) {
this._keys[event.keyCode] = {
isDown: false,
timeDown: 0,
timeUp: this._game.time.now
};
} else {
this._keys[event.keyCode].isDown = false;
this._keys[event.keyCode].timeUp = this._game.time.now;
}
};
Keyboard.prototype.reset = function () {
for(var key in this._keys) {
this._keys[key].isDown = false;
}
};
Keyboard.prototype.justPressed = function (keycode, duration) {
if (typeof duration === "undefined") { duration = 250; }
if(this._keys[keycode] && this._keys[keycode].isDown === true && (this._game.time.now - this._keys[keycode].timeDown < duration)) {
return true;
} else {
return false;
}
};
Keyboard.prototype.justReleased = function (keycode, duration) {
if (typeof duration === "undefined") { duration = 250; }
if(this._keys[keycode] && this._keys[keycode].isDown === false && (this._game.time.now - this._keys[keycode].timeUp < duration)) {
return true;
} else {
return false;
}
};
Keyboard.prototype.isDown = function (keycode) {
if(this._keys[keycode]) {
return this._keys[keycode].isDown;
} else {
return false;
}
};
Keyboard.A = "A".charCodeAt(0);
Keyboard.B = "B".charCodeAt(0);
Keyboard.C = "C".charCodeAt(0);
Keyboard.D = "D".charCodeAt(0);
Keyboard.E = "E".charCodeAt(0);
Keyboard.F = "F".charCodeAt(0);
Keyboard.G = "G".charCodeAt(0);
Keyboard.H = "H".charCodeAt(0);
Keyboard.I = "I".charCodeAt(0);
Keyboard.J = "J".charCodeAt(0);
Keyboard.K = "K".charCodeAt(0);
Keyboard.L = "L".charCodeAt(0);
Keyboard.M = "M".charCodeAt(0);
Keyboard.N = "N".charCodeAt(0);
Keyboard.O = "O".charCodeAt(0);
Keyboard.P = "P".charCodeAt(0);
Keyboard.Q = "Q".charCodeAt(0);
Keyboard.R = "R".charCodeAt(0);
Keyboard.S = "S".charCodeAt(0);
Keyboard.T = "T".charCodeAt(0);
Keyboard.U = "U".charCodeAt(0);
Keyboard.V = "V".charCodeAt(0);
Keyboard.W = "W".charCodeAt(0);
Keyboard.X = "X".charCodeAt(0);
Keyboard.Y = "Y".charCodeAt(0);
Keyboard.Z = "Z".charCodeAt(0);
Keyboard.ZERO = "0".charCodeAt(0);
Keyboard.ONE = "1".charCodeAt(0);
Keyboard.TWO = "2".charCodeAt(0);
Keyboard.THREE = "3".charCodeAt(0);
Keyboard.FOUR = "4".charCodeAt(0);
Keyboard.FIVE = "5".charCodeAt(0);
Keyboard.SIX = "6".charCodeAt(0);
Keyboard.SEVEN = "7".charCodeAt(0);
Keyboard.EIGHT = "8".charCodeAt(0);
Keyboard.NINE = "9".charCodeAt(0);
Keyboard.NUMPAD_0 = 96;
Keyboard.NUMPAD_1 = 97;
Keyboard.NUMPAD_2 = 98;
Keyboard.NUMPAD_3 = 99;
Keyboard.NUMPAD_4 = 100;
Keyboard.NUMPAD_5 = 101;
Keyboard.NUMPAD_6 = 102;
Keyboard.NUMPAD_7 = 103;
Keyboard.NUMPAD_8 = 104;
Keyboard.NUMPAD_9 = 105;
Keyboard.NUMPAD_MULTIPLY = 106;
Keyboard.NUMPAD_ADD = 107;
Keyboard.NUMPAD_ENTER = 108;
Keyboard.NUMPAD_SUBTRACT = 109;
Keyboard.NUMPAD_DECIMAL = 110;
Keyboard.NUMPAD_DIVIDE = 111;
Keyboard.F1 = 112;
Keyboard.F2 = 113;
Keyboard.F3 = 114;
Keyboard.F4 = 115;
Keyboard.F5 = 116;
Keyboard.F6 = 117;
Keyboard.F7 = 118;
Keyboard.F8 = 119;
Keyboard.F9 = 120;
Keyboard.F10 = 121;
Keyboard.F11 = 122;
Keyboard.F12 = 123;
Keyboard.F13 = 124;
Keyboard.F14 = 125;
Keyboard.F15 = 126;
Keyboard.COLON = 186;
Keyboard.EQUALS = 187;
Keyboard.UNDERSCORE = 189;
Keyboard.QUESTION_MARK = 191;
Keyboard.TILDE = 192;
Keyboard.OPEN_BRACKET = 219;
Keyboard.BACKWARD_SLASH = 220;
Keyboard.CLOSED_BRACKET = 221;
Keyboard.QUOTES = 222;
Keyboard.BACKSPACE = 8;
Keyboard.TAB = 9;
Keyboard.CLEAR = 12;
Keyboard.ENTER = 13;
Keyboard.SHIFT = 16;
Keyboard.CONTROL = 17;
Keyboard.ALT = 18;
Keyboard.CAPS_LOCK = 20;
Keyboard.ESC = 27;
Keyboard.SPACEBAR = 32;
Keyboard.PAGE_UP = 33;
Keyboard.PAGE_DOWN = 34;
Keyboard.END = 35;
Keyboard.HOME = 36;
Keyboard.LEFT = 37;
Keyboard.UP = 38;
Keyboard.RIGHT = 39;
Keyboard.DOWN = 40;
Keyboard.INSERT = 45;
Keyboard.DELETE = 46;
Keyboard.HELP = 47;
Keyboard.NUM_LOCK = 144;
return Keyboard;
})();
Phaser.Keyboard = Keyboard;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - Mouse
*
* The Mouse class handles mouse interactions with the game and the resulting events.
*/
var Phaser;
(function (Phaser) {
var Mouse = (function () {
function Mouse(game) {
this._x = 0;
this._y = 0;
this.isDown = false;
this.isUp = true;
this.timeDown = 0;
this.duration = 0;
this.timeUp = 0;
this._game = game;
this.start();
}
Mouse.LEFT_BUTTON = 0;
Mouse.MIDDLE_BUTTON = 1;
Mouse.RIGHT_BUTTON = 2;
Mouse.prototype.start = function () {
var _this = this;
this._game.stage.canvas.addEventListener('mousedown', function (event) {
return _this.onMouseDown(event);
}, true);
this._game.stage.canvas.addEventListener('mousemove', function (event) {
return _this.onMouseMove(event);
}, true);
this._game.stage.canvas.addEventListener('mouseup', function (event) {
return _this.onMouseUp(event);
}, true);
};
Mouse.prototype.reset = function () {
this.isDown = false;
this.isUp = true;
};
Mouse.prototype.onMouseDown = function (event) {
this.button = event.button;
this._x = event.clientX - this._game.stage.x;
this._y = event.clientY - this._game.stage.y;
this._game.input.x = this._x * this._game.input.scaleX;
this._game.input.y = this._y * this._game.input.scaleY;
this.isDown = true;
this.isUp = false;
this.timeDown = this._game.time.now;
this._game.input.onDown.dispatch(this._game.input.x, this._game.input.y, this.timeDown);
};
Mouse.prototype.update = function () {
//this._game.input.x = this._x * this._game.input.scaleX;
//this._game.input.y = this._y * this._game.input.scaleY;
if(this.isDown) {
this.duration = this._game.time.now - this.timeDown;
}
};
Mouse.prototype.onMouseMove = function (event) {
this.button = event.button;
this._x = event.clientX - this._game.stage.x;
this._y = event.clientY - this._game.stage.y;
this._game.input.x = this._x * this._game.input.scaleX;
this._game.input.y = this._y * this._game.input.scaleY;
};
Mouse.prototype.onMouseUp = function (event) {
this.button = event.button;
this.isDown = false;
this.isUp = true;
this.timeUp = this._game.time.now;
this.duration = this.timeUp - this.timeDown;
this._x = event.clientX - this._game.stage.x;
this._y = event.clientY - this._game.stage.y;
this._game.input.x = this._x * this._game.input.scaleX;
this._game.input.y = this._y * this._game.input.scaleY;
this._game.input.onUp.dispatch(this._game.input.x, this._game.input.y, this.timeDown);
};
return Mouse;
})();
Phaser.Mouse = Mouse;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/**
* Phaser - Finger
*
* A Finger object is used by the Touch manager and represents a single finger on the touch screen.
*/
var Phaser;
(function (Phaser) {
var Finger = (function () {
/**
* Constructor
* @param {Phaser.Game} game.
* @return {Phaser.Finger} This object.
*/
function Finger(game) {
/**
*
* @property point
* @type Point
**/
this.point = null;
/**
*
* @property circle
* @type Circle
**/
this.circle = null;
/**
*
* @property withinGame
* @type Boolean
*/
this.withinGame = false;
/**
* The horizontal coordinate of point relative to the viewport in pixels, excluding any scroll offset
* @property clientX
* @type Number
*/
this.clientX = -1;
//
/**
* The vertical coordinate of point relative to the viewport in pixels, excluding any scroll offset
* @property clientY
* @type Number
*/
this.clientY = -1;
//
/**
* The horizontal coordinate of point relative to the viewport in pixels, including any scroll offset
* @property pageX
* @type Number
*/
this.pageX = -1;
/**
* The vertical coordinate of point relative to the viewport in pixels, including any scroll offset
* @property pageY
* @type Number
*/
this.pageY = -1;
/**
* The horizontal coordinate of point relative to the screen in pixels
* @property screenX
* @type Number
*/
this.screenX = -1;
/**
* The vertical coordinate of point relative to the screen in pixels
* @property screenY
* @type Number
*/
this.screenY = -1;
/**
* The horizontal coordinate of point relative to the game element
* @property x
* @type Number
*/
this.x = -1;
/**
* The vertical coordinate of point relative to the game element
* @property y
* @type Number
*/
this.y = -1;
/**
*
* @property isDown
* @type Boolean
**/
this.isDown = false;
/**
*
* @property isUp
* @type Boolean
**/
this.isUp = false;
/**
*
* @property timeDown
* @type Number
**/
this.timeDown = 0;
/**
*
* @property duration
* @type Number
**/
this.duration = 0;
/**
*
* @property timeUp
* @type Number
**/
this.timeUp = 0;
/**
*
* @property justPressedRate
* @type Number
**/
this.justPressedRate = 200;
/**
*
* @property justReleasedRate
* @type Number
**/
this.justReleasedRate = 200;
this._game = game;
this.active = false;
}
Finger.prototype.start = /**
*
* @method start
* @param {Any} event
*/
function (event) {
this.identifier = event.identifier;
this.target = event.target;
// populate geom objects
if(this.point === null) {
this.point = new Phaser.Point();
}
if(this.circle === null) {
this.circle = new Phaser.Circle(0, 0, 44);
}
this.move(event);
this.active = true;
this.withinGame = true;
this.isDown = true;
this.isUp = false;
this.timeDown = this._game.time.now;
};
Finger.prototype.move = /**
*
* @method move
* @param {Any} event
*/
function (event) {
this.clientX = event.clientX;
this.clientY = event.clientY;
this.pageX = event.pageX;
this.pageY = event.pageY;
this.screenX = event.screenX;
this.screenY = event.screenY;
this.x = this.pageX - this._game.stage.offset.x;
this.y = this.pageY - this._game.stage.offset.y;
this.point.setTo(this.x, this.y);
this.circle.setTo(this.x, this.y, 44);
// Droppings history (used for gestures and motion tracking)
this.duration = this._game.time.now - this.timeDown;
};
Finger.prototype.leave = /**
*
* @method leave
* @param {Any} event
*/
function (event) {
this.withinGame = false;
this.move(event);
};
Finger.prototype.stop = /**
*
* @method stop
* @param {Any} event
*/
function (event) {
this.active = false;
this.withinGame = false;
this.isDown = false;
this.isUp = true;
this.timeUp = this._game.time.now;
this.duration = this.timeUp - this.timeDown;
};
Finger.prototype.justPressed = /**
*
* @method justPressed
* @param {Number} [duration].
* @return {Boolean}
*/
function (duration) {
if (typeof duration === "undefined") { duration = this.justPressedRate; }
if(this.isDown === true && (this.timeDown + duration) > this._game.time.now) {
return true;
} else {
return false;
}
};
Finger.prototype.justReleased = /**
*
* @method justReleased
* @param {Number} [duration].
* @return {Boolean}
*/
function (duration) {
if (typeof duration === "undefined") { duration = this.justReleasedRate; }
if(this.isUp === true && (this.timeUp + duration) > this._game.time.now) {
return true;
} else {
return false;
}
};
Finger.prototype.toString = /**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the instance.
**/
function () {
return "[{Finger (identifer=" + this.identifier + " active=" + this.active + " duration=" + this.duration + " withinGame=" + this.withinGame + " x=" + this.x + " y=" + this.y + " clientX=" + this.clientX + " clientY=" + this.clientY + " screenX=" + this.screenX + " screenY=" + this.screenY + " pageX=" + this.pageX + " pageY=" + this.pageY + ")}]";
};
return Finger;
})();
Phaser.Finger = Finger;
})(Phaser || (Phaser = {}));
/// <reference path="../../Game.ts" />
/// <reference path="Finger.ts" />
/**
* Phaser - Touch
*
* The Touch class handles touch interactions with the game and the resulting Finger objects.
* http://www.w3.org/TR/touch-events/
* https://developer.mozilla.org/en-US/docs/DOM/TouchList
* http://www.html5rocks.com/en/mobile/touchandmouse/
* Note: Android 2.x only supports 1 touch event at once, no multi-touch
*
* @todo Try and resolve update lag in Chrome/Android
* Gestures (pinch, zoom, swipe)
* GameObject Touch
* Touch point within GameObject
* Input Zones (mouse and touch) - lock entities within them + axis aligned drags
*/
var Phaser;
(function (Phaser) {
var Touch = (function () {
/**
* Constructor
* @param {Game} game.
* @return {Touch} This object.
*/
function Touch(game) {
/**
*
* @property x
* @type Number
**/
this.x = 0;
/**
*
* @property y
* @type Number
**/
this.y = 0;
/**
*
* @property isDown
* @type Boolean
**/
this.isDown = false;
/**
*
* @property isUp
* @type Boolean
**/
this.isUp = true;
this._game = game;
this.finger1 = new Phaser.Finger(this._game);
this.finger2 = new Phaser.Finger(this._game);
this.finger3 = new Phaser.Finger(this._game);
this.finger4 = new Phaser.Finger(this._game);
this.finger5 = new Phaser.Finger(this._game);
this.finger6 = new Phaser.Finger(this._game);
this.finger7 = new Phaser.Finger(this._game);
this.finger8 = new Phaser.Finger(this._game);
this.finger9 = new Phaser.Finger(this._game);
this.finger10 = new Phaser.Finger(this._game);
this._fingers = [
this.finger1,
this.finger2,
this.finger3,
this.finger4,
this.finger5,
this.finger6,
this.finger7,
this.finger8,
this.finger9,
this.finger10
];
this.touchDown = new Phaser.Signal();
this.touchUp = new Phaser.Signal();
this.start();
}
Touch.prototype.start = /**
*
* @method start
*/
function () {
var _this = this;
this._game.stage.canvas.addEventListener('touchstart', function (event) {
return _this.onTouchStart(event);
}, false);
this._game.stage.canvas.addEventListener('touchmove', function (event) {
return _this.onTouchMove(event);
}, false);
this._game.stage.canvas.addEventListener('touchend', function (event) {
return _this.onTouchEnd(event);
}, false);
this._game.stage.canvas.addEventListener('touchenter', function (event) {
return _this.onTouchEnter(event);
}, false);
this._game.stage.canvas.addEventListener('touchleave', function (event) {
return _this.onTouchLeave(event);
}, false);
this._game.stage.canvas.addEventListener('touchcancel', function (event) {
return _this.onTouchCancel(event);
}, false);
document.addEventListener('touchmove', function (event) {
return _this.consumeTouchMove(event);
}, false);
};
Touch.prototype.consumeTouchMove = /**
* Prevent iOS bounce-back (doesn't work?)
* @method consumeTouchMove
* @param {Any} event
**/
function (event) {
event.preventDefault();
};
Touch.prototype.onTouchStart = /**
*
* @method onTouchStart
* @param {Any} event
**/
function (event) {
event.preventDefault();
// A list of all the touch points that BECAME active with the current event
// https://developer.mozilla.org/en-US/docs/DOM/TouchList
// event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
// event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for(var i = 0; i < event.changedTouches.length; i++) {
for(var f = 0; f < this._fingers.length; f++) {
if(this._fingers[f].active === false) {
this._fingers[f].start(event.changedTouches[i]);
this.x = this._fingers[f].x;
this.y = this._fingers[f].y;
this._game.input.x = this.x * this._game.input.scaleX;
this._game.input.y = this.y * this._game.input.scaleY;
this.touchDown.dispatch(this._fingers[f].x, this._fingers[f].y, this._fingers[f].timeDown, this._fingers[f].timeUp, this._fingers[f].duration);
this._game.input.onDown.dispatch(this._game.input.x, this._game.input.y, this._fingers[f].timeDown);
this.isDown = true;
this.isUp = false;
break;
}
}
}
};
Touch.prototype.onTouchCancel = /**
* Doesn't appear to be supported by most browsers yet
* @method onTouchCancel
* @param {Any} event
**/
function (event) {
event.preventDefault();
// Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
// http://www.w3.org/TR/touch-events/#dfn-touchcancel
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for(var i = 0; i < event.changedTouches.length; i++) {
for(var f = 0; f < this._fingers.length; f++) {
if(this._fingers[f].identifier === event.changedTouches[i].identifier) {
this._fingers[f].stop(event.changedTouches[i]);
break;
}
}
}
};
Touch.prototype.onTouchEnter = /**
* Doesn't appear to be supported by most browsers yet
* @method onTouchEnter
* @param {Any} event
**/
function (event) {
event.preventDefault();
// For touch enter and leave its a list of the touch points that have entered or left the target
// event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
// event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for(var i = 0; i < event.changedTouches.length; i++) {
for(var f = 0; f < this._fingers.length; f++) {
if(this._fingers[f].active === false) {
this._fingers[f].start(event.changedTouches[i]);
break;
}
}
}
};
Touch.prototype.onTouchLeave = /**
* Doesn't appear to be supported by most browsers yet
* @method onTouchLeave
* @param {Any} event
**/
function (event) {
event.preventDefault();
// For touch enter and leave its a list of the touch points that have entered or left the target
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for(var i = 0; i < event.changedTouches.length; i++) {
for(var f = 0; f < this._fingers.length; f++) {
if(this._fingers[f].identifier === event.changedTouches[i].identifier) {
this._fingers[f].leave(event.changedTouches[i]);
break;
}
}
}
};
Touch.prototype.onTouchMove = /**
*
* @method onTouchMove
* @param {Any} event
**/
function (event) {
event.preventDefault();
// event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
// event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for(var i = 0; i < event.changedTouches.length; i++) {
for(var f = 0; f < this._fingers.length; f++) {
if(this._fingers[f].identifier === event.changedTouches[i].identifier) {
this._fingers[f].move(event.changedTouches[i]);
this.x = this._fingers[f].x;
this.y = this._fingers[f].y;
this._game.input.x = this.x * this._game.input.scaleX;
this._game.input.y = this.y * this._game.input.scaleY;
break;
}
}
}
};
Touch.prototype.onTouchEnd = /**
*
* @method onTouchEnd
* @param {Any} event
**/
function (event) {
event.preventDefault();
// For touch end its a list of the touch points that have been removed from the surface
// https://developer.mozilla.org/en-US/docs/DOM/TouchList
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
for(var i = 0; i < event.changedTouches.length; i++) {
for(var f = 0; f < this._fingers.length; f++) {
if(this._fingers[f].identifier === event.changedTouches[i].identifier) {
this._fingers[f].stop(event.changedTouches[i]);
this.x = this._fingers[f].x;
this.y = this._fingers[f].y;
this._game.input.x = this.x * this._game.input.scaleX;
this._game.input.y = this.y * this._game.input.scaleY;
this.touchUp.dispatch(this._fingers[f].x, this._fingers[f].y, this._fingers[f].timeDown, this._fingers[f].timeUp, this._fingers[f].duration);
this._game.input.onUp.dispatch(this._game.input.x, this._game.input.y, this._fingers[f].timeUp);
this.isDown = false;
this.isUp = true;
break;
}
}
}
};
Touch.prototype.calculateDistance = /**
*
* @method calculateDistance
* @param {Finger} finger1
* @param {Finger} finger2
**/
function (finger1, finger2) {
};
Touch.prototype.calculateAngle = /**
*
* @method calculateAngle
* @param {Finger} finger1
* @param {Finger} finger2
**/
function (finger1, finger2) {
};
Touch.prototype.checkOverlap = /**
*
* @method checkOverlap
* @param {Finger} finger1
* @param {Finger} finger2
**/
function (finger1, finger2) {
};
Touch.prototype.update = /**
*
* @method update
*/
function () {
};
Touch.prototype.stop = /**
*
* @method stop
*/
function () {
//this._domElement.addEventListener('touchstart', (event) => this.onTouchStart(event), false);
//this._domElement.addEventListener('touchmove', (event) => this.onTouchMove(event), false);
//this._domElement.addEventListener('touchend', (event) => this.onTouchEnd(event), false);
//this._domElement.addEventListener('touchenter', (event) => this.onTouchEnter(event), false);
//this._domElement.addEventListener('touchleave', (event) => this.onTouchLeave(event), false);
//this._domElement.addEventListener('touchcancel', (event) => this.onTouchCancel(event), false);
};
Touch.prototype.reset = /**
*
* @method reset
**/
function () {
this.isDown = false;
this.isUp = false;
};
return Touch;
})();
Phaser.Touch = Touch;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="../Group.ts" />
/**
* Phaser - Emitter
*
* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
* continuous effects like rain and fire. All it really does is launch Particle objects out
* at set intervals, and fixes their positions and velocities accorindgly.
*/
var Phaser;
(function (Phaser) {
var Emitter = (function (_super) {
__extends(Emitter, _super);
/**
* Creates a new <code>Emitter</code> object at a specific position.
* Does NOT automatically generate or attach particles!
*
* @param X The X position of the emitter.
* @param Y The Y position of the emitter.
* @param Size Optional, specifies a maximum capacity for this emitter.
*/
function Emitter(game, X, Y, Size) {
if (typeof X === "undefined") { X = 0; }
if (typeof Y === "undefined") { Y = 0; }
if (typeof Size === "undefined") { Size = 0; }
_super.call(this, game, Size);
this.x = X;
this.y = Y;
this.width = 0;
this.height = 0;
this.minParticleSpeed = new Phaser.Point(-100, -100);
this.maxParticleSpeed = new Phaser.Point(100, 100);
this.minRotation = -360;
this.maxRotation = 360;
this.gravity = 0;
this.particleClass = null;
this.particleDrag = new Phaser.Point();
this.frequency = 0.1;
this.lifespan = 3;
this.bounce = 0;
this._quantity = 0;
this._counter = 0;
this._explode = true;
this.on = false;
this._point = new Phaser.Point();
}
Emitter.prototype.destroy = /**
* Clean up memory.
*/
function () {
this.minParticleSpeed = null;
this.maxParticleSpeed = null;
this.particleDrag = null;
this.particleClass = null;
this._point = null;
_super.prototype.destroy.call(this);
};
Emitter.prototype.makeParticles = /**
* This function generates a new array of particle sprites to attach to the emitter.
*
* @param Graphics If you opted to not pre-configure an array of Sprite objects, you can simply pass in a particle image or sprite sheet.
* @param Quantity The number of particles to generate when using the "create from image" option.
* @param BakedRotations How many frames of baked rotation to use (boosts performance). Set to zero to not use baked rotations.
* @param Multiple Whether the image in the Graphics param is a single particle or a bunch of particles (if it's a bunch, they need to be square!).
* @param Collide Whether the particles should be flagged as not 'dead' (non-colliding particles are higher performance). 0 means no collisions, 0-1 controls scale of particle's bounding box.
*
* @return This Emitter instance (nice for chaining stuff together, if you're into that).
*/
function (Graphics, Quantity, BakedRotations, Multiple, Collide) {
if (typeof Quantity === "undefined") { Quantity = 50; }
if (typeof BakedRotations === "undefined") { BakedRotations = 16; }
if (typeof Multiple === "undefined") { Multiple = false; }
if (typeof Collide === "undefined") { Collide = 0.8; }
this.maxSize = Quantity;
var totalFrames = 1;
/*
if(Multiple)
{
var sprite:Sprite = new Sprite(this._game);
sprite.loadGraphic(Graphics,true);
totalFrames = sprite.frames;
sprite.destroy();
}
*/
var randomFrame;
var particle;
var i = 0;
while(i < Quantity) {
if(this.particleClass == null) {
particle = new Phaser.Particle(this._game);
} else {
particle = new this.particleClass(this._game);
}
if(Multiple) {
/*
randomFrame = this._game.math.random()*totalFrames;
if(BakedRotations > 0)
particle.loadRotatedGraphic(Graphics,BakedRotations,randomFrame);
else
{
particle.loadGraphic(Graphics,true);
particle.frame = randomFrame;
}
*/
} else {
/*
if (BakedRotations > 0)
particle.loadRotatedGraphic(Graphics,BakedRotations);
else
particle.loadGraphic(Graphics);
*/
if(Graphics) {
particle.loadGraphic(Graphics);
}
}
if(Collide > 0) {
particle.width *= Collide;
particle.height *= Collide;
//particle.centerOffsets();
} else {
particle.allowCollisions = Phaser.Collision.NONE;
}
particle.exists = false;
this.add(particle);
i++;
}
return this;
};
Emitter.prototype.update = /**
* Called automatically by the game loop, decides when to launch particles and when to "die".
*/
function () {
if(this.on) {
if(this._explode) {
this.on = false;
var i = 0;
var l = this._quantity;
if((l <= 0) || (l > this.length)) {
l = this.length;
}
while(i < l) {
this.emitParticle();
i++;
}
this._quantity = 0;
} else {
this._timer += this._game.time.elapsed;
while((this.frequency > 0) && (this._timer > this.frequency) && this.on) {
this._timer -= this.frequency;
this.emitParticle();
if((this._quantity > 0) && (++this._counter >= this._quantity)) {
this.on = false;
this._quantity = 0;
}
}
}
}
_super.prototype.update.call(this);
};
Emitter.prototype.kill = /**
* Call this function to turn off all the particles and the emitter.
*/
function () {
this.on = false;
_super.prototype.kill.call(this);
};
Emitter.prototype.start = /**
* Call this function to start emitting particles.
*
* @param Explode Whether the particles should all burst out at once.
* @param Lifespan How long each particle lives once emitted. 0 = forever.
* @param Frequency Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds.
* @param Quantity How many particles to launch. 0 = "all of the particles".
*/
function (Explode, Lifespan, Frequency, Quantity) {
if (typeof Explode === "undefined") { Explode = true; }
if (typeof Lifespan === "undefined") { Lifespan = 0; }
if (typeof Frequency === "undefined") { Frequency = 0.1; }
if (typeof Quantity === "undefined") { Quantity = 0; }
this.revive();
this.visible = true;
this.on = true;
this._explode = Explode;
this.lifespan = Lifespan;
this.frequency = Frequency;
this._quantity += Quantity;
this._counter = 0;
this._timer = 0;
};
Emitter.prototype.emitParticle = /**
* This function can be used both internally and externally to emit the next particle.
*/
function () {
var particle = this.recycle(Phaser.Particle);
particle.lifespan = this.lifespan;
particle.elasticity = this.bounce;
particle.reset(this.x - (particle.width >> 1) + this._game.math.random() * this.width, this.y - (particle.height >> 1) + this._game.math.random() * this.height);
particle.visible = true;
if(this.minParticleSpeed.x != this.maxParticleSpeed.x) {
particle.velocity.x = this.minParticleSpeed.x + this._game.math.random() * (this.maxParticleSpeed.x - this.minParticleSpeed.x);
} else {
particle.velocity.x = this.minParticleSpeed.x;
}
if(this.minParticleSpeed.y != this.maxParticleSpeed.y) {
particle.velocity.y = this.minParticleSpeed.y + this._game.math.random() * (this.maxParticleSpeed.y - this.minParticleSpeed.y);
} else {
particle.velocity.y = this.minParticleSpeed.y;
}
particle.acceleration.y = this.gravity;
if(this.minRotation != this.maxRotation) {
particle.angularVelocity = this.minRotation + this._game.math.random() * (this.maxRotation - this.minRotation);
} else {
particle.angularVelocity = this.minRotation;
}
if(particle.angularVelocity != 0) {
particle.angle = this._game.math.random() * 360 - 180;
}
particle.drag.x = this.particleDrag.x;
particle.drag.y = this.particleDrag.y;
particle.onEmit();
};
Emitter.prototype.setSize = /**
* A more compact way of setting the width and height of the emitter.
*
* @param Width The desired width of the emitter (particles are spawned randomly within these dimensions).
* @param Height The desired height of the emitter.
*/
function (Width, Height) {
this.width = Width;
this.height = Height;
};
Emitter.prototype.setXSpeed = /**
* A more compact way of setting the X velocity range of the emitter.
*
* @param Min The minimum value for this range.
* @param Max The maximum value for this range.
*/
function (Min, Max) {
if (typeof Min === "undefined") { Min = 0; }
if (typeof Max === "undefined") { Max = 0; }
this.minParticleSpeed.x = Min;
this.maxParticleSpeed.x = Max;
};
Emitter.prototype.setYSpeed = /**
* A more compact way of setting the Y velocity range of the emitter.
*
* @param Min The minimum value for this range.
* @param Max The maximum value for this range.
*/
function (Min, Max) {
if (typeof Min === "undefined") { Min = 0; }
if (typeof Max === "undefined") { Max = 0; }
this.minParticleSpeed.y = Min;
this.maxParticleSpeed.y = Max;
};
Emitter.prototype.setRotation = /**
* A more compact way of setting the angular velocity constraints of the emitter.
*
* @param Min The minimum value for this range.
* @param Max The maximum value for this range.
*/
function (Min, Max) {
if (typeof Min === "undefined") { Min = 0; }
if (typeof Max === "undefined") { Max = 0; }
this.minRotation = Min;
this.maxRotation = Max;
};
Emitter.prototype.at = /**
* Change the emitter's midpoint to match the midpoint of a <code>Object</code>.
*
* @param Object The <code>Object</code> that you want to sync up with.
*/
function (Object) {
Object.getMidpoint(this._point);
this.x = this._point.x - (this.width >> 1);
this.y = this._point.y - (this.height >> 1);
};
return Emitter;
})(Phaser.Group);
Phaser.Emitter = Emitter;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - GeomSprite
*
* A GeomSprite is a special kind of GameObject that contains a base geometry class (Circle, Line, Point, Rectangle).
* They can be rendered in the game and used for collision just like any other game object. Display of them is controlled
* via the lineWidth / lineColor / fillColor and renderOutline / renderFill properties.
*/
var Phaser;
(function (Phaser) {
var GeomSprite = (function (_super) {
__extends(GeomSprite, _super);
function GeomSprite(game, x, y) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
_super.call(this, game, x, y);
// local rendering related temp vars to help avoid gc spikes
this._dx = 0;
this._dy = 0;
this._dw = 0;
this._dh = 0;
this.type = 0;
this.renderOutline = true;
this.renderFill = true;
this.lineWidth = 1;
this.lineColor = 'rgb(0,255,0)';
this.fillColor = 'rgb(0,100,0)';
this.type = GeomSprite.UNASSIGNED;
return this;
}
GeomSprite.UNASSIGNED = 0;
GeomSprite.CIRCLE = 1;
GeomSprite.LINE = 2;
GeomSprite.POINT = 3;
GeomSprite.RECTANGLE = 4;
GeomSprite.prototype.loadCircle = function (circle) {
this.refresh();
this.circle = circle;
this.type = GeomSprite.CIRCLE;
return this;
};
GeomSprite.prototype.loadLine = function (line) {
this.refresh();
this.line = line;
this.type = GeomSprite.LINE;
return this;
};
GeomSprite.prototype.loadPoint = function (point) {
this.refresh();
this.point = point;
this.type = GeomSprite.POINT;
return this;
};
GeomSprite.prototype.loadRectangle = function (rect) {
this.refresh();
this.rect = rect;
this.type = GeomSprite.RECTANGLE;
return this;
};
GeomSprite.prototype.createCircle = function (diameter) {
this.refresh();
this.circle = new Phaser.Circle(this.x, this.y, diameter);
this.type = GeomSprite.CIRCLE;
this.bounds.setTo(this.circle.x - this.circle.radius, this.circle.y - this.circle.radius, this.circle.diameter, this.circle.diameter);
return this;
};
GeomSprite.prototype.createLine = function (x, y) {
this.refresh();
this.line = new Phaser.Line(this.x, this.y, x, y);
this.type = GeomSprite.LINE;
this.bounds.setTo(this.x, this.y, this.line.width, this.line.height);
return this;
};
GeomSprite.prototype.createPoint = function () {
this.refresh();
this.point = new Phaser.Point(this.x, this.y);
this.type = GeomSprite.POINT;
this.bounds.width = 1;
this.bounds.height = 1;
return this;
};
GeomSprite.prototype.createRectangle = function (width, height) {
this.refresh();
this.rect = new Phaser.Rectangle(this.x, this.y, width, height);
this.type = GeomSprite.RECTANGLE;
this.bounds.copyFrom(this.rect);
return this;
};
GeomSprite.prototype.refresh = function () {
this.circle = null;
this.line = null;
this.point = null;
this.rect = null;
};
GeomSprite.prototype.update = function () {
// Update bounds and position?
if(this.type == GeomSprite.UNASSIGNED) {
return;
} else if(this.type == GeomSprite.CIRCLE) {
this.circle.x = this.x;
this.circle.y = this.y;
this.bounds.width = this.circle.diameter;
this.bounds.height = this.circle.diameter;
} else if(this.type == GeomSprite.LINE) {
this.line.x1 = this.x;
this.line.y1 = this.y;
this.bounds.setTo(this.x, this.y, this.line.width, this.line.height);
} else if(this.type == GeomSprite.POINT) {
this.point.x = this.x;
this.point.y = this.y;
} else if(this.type == GeomSprite.RECTANGLE) {
this.rect.x = this.x;
this.rect.y = this.y;
this.bounds.copyFrom(this.rect);
}
};
GeomSprite.prototype.inCamera = function (camera) {
if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) {
this._dx = this.bounds.x - (camera.x * this.scrollFactor.x);
this._dy = this.bounds.y - (camera.y * this.scrollFactor.x);
this._dw = this.bounds.width * this.scale.x;
this._dh = this.bounds.height * this.scale.y;
return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh);
} else {
return camera.intersects(this.bounds);
}
};
GeomSprite.prototype.render = function (camera, cameraOffsetX, cameraOffsetY) {
// Render checks
if(this.type == GeomSprite.UNASSIGNED || this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.inCamera(camera.worldView) == false) {
return false;
}
// Alpha
if(this.alpha !== 1) {
var globalAlpha = this._game.stage.context.globalAlpha;
this._game.stage.context.globalAlpha = this.alpha;
}
this._dx = cameraOffsetX + (this.bounds.x - camera.worldView.x);
this._dy = cameraOffsetY + (this.bounds.y - camera.worldView.y);
this._dw = this.bounds.width * this.scale.x;
this._dh = this.bounds.height * this.scale.y;
// Circles are drawn center based
if(this.type == GeomSprite.CIRCLE) {
this._dx += this.circle.radius;
this._dy += this.circle.radius;
}
// Apply camera difference
if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) {
this._dx -= (camera.worldView.x * this.scrollFactor.x);
this._dy -= (camera.worldView.y * this.scrollFactor.y);
}
// Rotation is disabled for now as I don't want it to be misleading re: collision
/*
if (this.angle !== 0)
{
this._game.stage.context.save();
this._game.stage.context.translate(this._dx + (this._dw / 2) - this.origin.x, this._dy + (this._dh / 2) - this.origin.y);
this._game.stage.context.rotate(this.angle * (Math.PI / 180));
this._dx = -(this._dw / 2);
this._dy = -(this._dh / 2);
}
*/
this._dx = Math.round(this._dx);
this._dy = Math.round(this._dy);
this._dw = Math.round(this._dw);
this._dh = Math.round(this._dh);
this._game.stage.saveCanvasValues();
// Debug
//this._game.stage.context.fillStyle = 'rgba(255,0,0,0.5)';
//this._game.stage.context.fillRect(this.bounds.x, this.bounds.y, this.bounds.width, this.bounds.height);
this._game.stage.context.lineWidth = this.lineWidth;
this._game.stage.context.strokeStyle = this.lineColor;
this._game.stage.context.fillStyle = this.fillColor;
if(this._game.stage.fillStyle !== this.fillColor) {
}
// Primitive Renderer
if(this.type == GeomSprite.CIRCLE) {
this._game.stage.context.beginPath();
this._game.stage.context.arc(this._dx, this._dy, this.circle.radius, 0, Math.PI * 2);
this._game.stage.context.stroke();
if(this.renderFill) {
this._game.stage.context.fill();
}
this._game.stage.context.closePath();
} else if(this.type == GeomSprite.LINE) {
this._game.stage.context.beginPath();
this._game.stage.context.moveTo(this._dx, this._dy);
this._game.stage.context.lineTo(this.line.x2, this.line.y2);
this._game.stage.context.stroke();
this._game.stage.context.closePath();
} else if(this.type == GeomSprite.POINT) {
this._game.stage.context.fillRect(this._dx, this._dy, 2, 2);
} else if(this.type == GeomSprite.RECTANGLE) {
// We can use the faster fillRect if we don't need the outline
if(this.renderOutline == false) {
this._game.stage.context.fillRect(this._dx, this._dy, this.rect.width, this.rect.height);
} else {
this._game.stage.context.beginPath();
this._game.stage.context.rect(this._dx, this._dy, this.rect.width, this.rect.height);
this._game.stage.context.stroke();
if(this.renderFill) {
this._game.stage.context.fill();
}
this._game.stage.context.closePath();
}
// And now the edge points
this._game.stage.context.fillStyle = 'rgb(255,255,255)';
this.renderPoint(this._dx, this._dy, this.rect.topLeft, 2);
this.renderPoint(this._dx, this._dy, this.rect.topCenter, 2);
this.renderPoint(this._dx, this._dy, this.rect.topRight, 2);
this.renderPoint(this._dx, this._dy, this.rect.leftCenter, 2);
this.renderPoint(this._dx, this._dy, this.rect.center, 2);
this.renderPoint(this._dx, this._dy, this.rect.rightCenter, 2);
this.renderPoint(this._dx, this._dy, this.rect.bottomLeft, 2);
this.renderPoint(this._dx, this._dy, this.rect.bottomCenter, 2);
this.renderPoint(this._dx, this._dy, this.rect.bottomRight, 2);
}
this._game.stage.restoreCanvasValues();
if(this.rotation !== 0) {
this._game.stage.context.translate(0, 0);
this._game.stage.context.restore();
}
if(globalAlpha > -1) {
this._game.stage.context.globalAlpha = globalAlpha;
}
return true;
};
GeomSprite.prototype.renderPoint = function (offsetX, offsetY, point, size) {
offsetX = 0;
offsetY = 0;
this._game.stage.context.fillRect(offsetX + point.x, offsetY + point.y, 1, 1);
};
GeomSprite.prototype.renderDebugInfo = function (x, y, color) {
if (typeof color === "undefined") { color = 'rgb(255,255,255)'; }
//this._game.stage.context.fillStyle = color;
//this._game.stage.context.fillText('Sprite: ' + this.name + ' (' + this.bounds.width + ' x ' + this.bounds.height + ')', x, y);
//this._game.stage.context.fillText('x: ' + this.bounds.x.toFixed(1) + ' y: ' + this.bounds.y.toFixed(1) + ' rotation: ' + this.angle.toFixed(1), x, y + 14);
//this._game.stage.context.fillText('dx: ' + this._dx.toFixed(1) + ' dy: ' + this._dy.toFixed(1) + ' dw: ' + this._dw.toFixed(1) + ' dh: ' + this._dh.toFixed(1), x, y + 28);
//this._game.stage.context.fillText('sx: ' + this._sx.toFixed(1) + ' sy: ' + this._sy.toFixed(1) + ' sw: ' + this._sw.toFixed(1) + ' sh: ' + this._sh.toFixed(1), x, y + 42);
};
GeomSprite.prototype.collide = // Gives a basic boolean response to a geometric collision.
// If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object.
function (source) {
// Circle vs. Circle
if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.CIRCLE) {
return Phaser.Collision.circleToCircle(this.circle, source.circle).result;
}
// Circle vs. Rect
if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.RECTANGLE) {
return Phaser.Collision.circleToRectangle(this.circle, source.rect).result;
}
// Circle vs. Point
if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.POINT) {
return Phaser.Collision.circleContainsPoint(this.circle, source.point).result;
}
// Circle vs. Line
if(this.type == GeomSprite.CIRCLE && source.type == GeomSprite.LINE) {
return Phaser.Collision.lineToCircle(source.line, this.circle).result;
}
// Rect vs. Rect
if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.RECTANGLE) {
return Phaser.Collision.rectangleToRectangle(this.rect, source.rect).result;
}
// Rect vs. Circle
if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.CIRCLE) {
return Phaser.Collision.circleToRectangle(source.circle, this.rect).result;
}
// Rect vs. Point
if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.POINT) {
return Phaser.Collision.pointToRectangle(source.point, this.rect).result;
}
// Rect vs. Line
if(this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.LINE) {
return Phaser.Collision.lineToRectangle(source.line, this.rect).result;
}
// Point vs. Point
if(this.type == GeomSprite.POINT && source.type == GeomSprite.POINT) {
return this.point.equals(source.point);
}
// Point vs. Circle
if(this.type == GeomSprite.POINT && source.type == GeomSprite.CIRCLE) {
return Phaser.Collision.circleContainsPoint(source.circle, this.point).result;
}
// Point vs. Rect
if(this.type == GeomSprite.POINT && source.type == GeomSprite.RECTANGLE) {
return Phaser.Collision.pointToRectangle(this.point, source.rect).result;
}
// Point vs. Line
if(this.type == GeomSprite.POINT && source.type == GeomSprite.LINE) {
return source.line.isPointOnLine(this.point.x, this.point.y);
}
// Line vs. Line
if(this.type == GeomSprite.LINE && source.type == GeomSprite.LINE) {
return Phaser.Collision.lineSegmentToLineSegment(this.line, source.line).result;
}
// Line vs. Circle
if(this.type == GeomSprite.LINE && source.type == GeomSprite.CIRCLE) {
return Phaser.Collision.lineToCircle(this.line, source.circle).result;
}
// Line vs. Rect
if(this.type == GeomSprite.LINE && source.type == GeomSprite.RECTANGLE) {
return Phaser.Collision.lineSegmentToRectangle(this.line, source.rect).result;
}
// Line vs. Point
if(this.type == GeomSprite.LINE && source.type == GeomSprite.POINT) {
return this.line.isPointOnLine(source.point.x, source.point.y);
}
return false;
};
return GeomSprite;
})(Phaser.GameObject);
Phaser.GeomSprite = GeomSprite;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="Sprite.ts" />
/**
* Phaser - Particle
*
* This is a simple particle class that extends a Sprite to have a slightly more
* specialised behaviour. It is used exclusively by the Emitter class and can be extended as required.
*/
var Phaser;
(function (Phaser) {
var Particle = (function (_super) {
__extends(Particle, _super);
/**
* Instantiate a new particle. Like <code>Sprite</code>, all meaningful creation
* happens during <code>loadGraphic()</code> or <code>makeGraphic()</code> or whatever.
*/
function Particle(game) {
_super.call(this, game);
this.lifespan = 0;
this.friction = 500;
}
Particle.prototype.update = /**
* The particle's main update logic. Basically it checks to see if it should
* be dead yet, and then has some special bounce behavior if there is some gravity on it.
*/
function () {
//lifespan behavior
if(this.lifespan <= 0) {
return;
}
this.lifespan -= this._game.time.elapsed;
if(this.lifespan <= 0) {
this.kill();
}
//simpler bounce/spin behavior for now
if(this.touching) {
if(this.angularVelocity != 0) {
this.angularVelocity = -this.angularVelocity;
}
}
if(this.acceleration.y > 0)//special behavior for particles with gravity
{
if(this.touching & Phaser.Collision.FLOOR) {
this.drag.x = this.friction;
if(!(this.wasTouching & Phaser.Collision.FLOOR)) {
if(this.velocity.y < -this.elasticity * 10) {
if(this.angularVelocity != 0) {
this.angularVelocity *= -this.elasticity;
}
} else {
this.velocity.y = 0;
this.angularVelocity = 0;
}
}
} else {
this.drag.x = 0;
}
}
};
Particle.prototype.onEmit = /**
* Triggered whenever this object is launched by a <code>Emitter</code>.
* You can override this to add custom behavior like a sound or AI or something.
*/
function () {
};
return Particle;
})(Phaser.Sprite);
Phaser.Particle = Particle;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - Tile
*
* A simple helper object for <code>Tilemap</code> that helps expand collision opportunities and control.
*/
var Phaser;
(function (Phaser) {
var Tile = (function (_super) {
__extends(Tile, _super);
/**
* Instantiate this new tile object. This is usually called from <code>Tilemap.loadMap()</code>.
*
* @param Tilemap A reference to the tilemap object creating the tile.
* @param Index The actual core map data index for this tile type.
* @param Width The width of the tile.
* @param Height The height of the tile.
* @param Visible Whether the tile is visible or not.
* @param AllowCollisions The collision flags for the object. By default this value is ANY or NONE depending on the parameters sent to loadMap().
*/
function Tile(game, Tilemap, Index, Width, Height, Visible, AllowCollisions) {
_super.call(this, game, 0, 0, Width, Height);
this.immovable = true;
this.moves = false;
this.callback = null;
this.filter = null;
this.tilemap = Tilemap;
this.index = Index;
this.visible = Visible;
this.allowCollisions = AllowCollisions;
this.mapIndex = 0;
}
Tile.prototype.destroy = /**
* Clean up memory.
*/
function () {
_super.prototype.destroy.call(this);
this.callback = null;
this.tilemap = null;
};
return Tile;
})(Phaser.GameObject);
Phaser.Tile = Tile;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - TilemapBuffer
*
* Responsible for rendering a portion of a tilemap to the given Camera.
*/
var Phaser;
(function (Phaser) {
var TilemapBuffer = (function () {
function TilemapBuffer(game, camera, tilemap, texture, tileOffsets) {
this._startX = 0;
this._maxX = 0;
this._startY = 0;
this._maxY = 0;
this._tx = 0;
this._ty = 0;
this._dx = 0;
this._dy = 0;
this._oldCameraX = 0;
this._oldCameraY = 0;
this._dirty = true;
//console.log('New TilemapBuffer created for Camera ' + camera.ID);
this._game = game;
this.camera = camera;
this._tilemap = tilemap;
this._texture = texture;
this._tileOffsets = tileOffsets;
//this.createCanvas();
}
TilemapBuffer.prototype.createCanvas = function () {
this.canvas = document.createElement('canvas');
this.canvas.width = this._game.stage.width;
this.canvas.height = this._game.stage.height;
this.context = this.canvas.getContext('2d');
};
TilemapBuffer.prototype.update = function () {
/*
if (this.camera.worldView.x !== this._oldCameraX || this.camera.worldView.y !== this._oldCameraY)
{
this._dirty = true;
}
this._oldCameraX = this.camera.worldView.x;
this._oldCameraY = this.camera.worldView.y;
*/
};
TilemapBuffer.prototype.renderDebugInfo = function (x, y, color) {
if (typeof color === "undefined") { color = 'rgb(255,255,255)'; }
this._game.stage.context.fillStyle = color;
this._game.stage.context.fillText('TilemapBuffer', x, y);
this._game.stage.context.fillText('startX: ' + this._startX + ' endX: ' + this._maxX, x, y + 14);
this._game.stage.context.fillText('startY: ' + this._startY + ' endY: ' + this._maxY, x, y + 28);
this._game.stage.context.fillText('dx: ' + this._dx + ' dy: ' + this._dy, x, y + 42);
this._game.stage.context.fillText('Dirty: ' + this._dirty, x, y + 56);
};
TilemapBuffer.prototype.render = function (dx, dy) {
/*
if (this._dirty == false)
{
this._game.stage.context.drawImage(this.canvas, 0, 0);
return true;
}
*/
// Work out how many tiles we can fit into our camera and round it up for the edges
this._maxX = this._game.math.ceil(this.camera.width / this._tilemap.tileWidth) + 1;
this._maxY = this._game.math.ceil(this.camera.height / this._tilemap.tileHeight) + 1;
// And now work out where in the tilemap the camera actually is
this._startX = this._game.math.floor(this.camera.worldView.x / this._tilemap.tileWidth);
this._startY = this._game.math.floor(this.camera.worldView.y / this._tilemap.tileHeight);
// Tilemap bounds check
if(this._startX < 0) {
this._startX = 0;
}
if(this._startY < 0) {
this._startY = 0;
}
if(this._startX + this._maxX > this._tilemap.widthInTiles) {
this._startX = this._tilemap.widthInTiles - this._maxX;
}
if(this._startY + this._maxY > this._tilemap.heightInTiles) {
this._startY = this._tilemap.heightInTiles - this._maxY;
}
// Finally get the offset to avoid the blocky movement
this._dx = dx;
this._dy = dy;
this._dx += -(this.camera.worldView.x - (this._startX * this._tilemap.tileWidth));
this._dy += -(this.camera.worldView.y - (this._startY * this._tilemap.tileHeight));
this._tx = this._dx;
this._ty = this._dy;
for(var row = this._startY; row < this._startY + this._maxY; row++) {
this._columnData = this._tilemap.mapData[row];
for(var tile = this._startX; tile < this._startX + this._maxX; tile++) {
if(this._tileOffsets[this._columnData[tile]]) {
//this.context.drawImage(
this._game.stage.context.drawImage(this._texture, // Source Image
this._tileOffsets[this._columnData[tile]].x, // Source X (location within the source image)
this._tileOffsets[this._columnData[tile]].y, // Source Y
this._tilemap.tileWidth, // Source Width
this._tilemap.tileHeight, // Source Height
this._tx, // Destination X (where on the canvas it'll be drawn)
this._ty, // Destination Y
this._tilemap.tileWidth, // Destination Width (always same as Source Width unless scaled)
this._tilemap.tileHeight);
// Destination Height (always same as Source Height unless scaled)
this._tx += this._tilemap.tileWidth;
}
}
this._tx = this._dx;
this._ty += this._tilemap.tileHeight;
}
//this._game.stage.context.drawImage(this.canvas, 0, 0);
//console.log('dirty cleaned');
//this._dirty = false;
return true;
};
return TilemapBuffer;
})();
Phaser.TilemapBuffer = TilemapBuffer;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/// <reference path="GameObject.ts" />
/// <reference path="../system/Tile.ts" />
/// <reference path="../system/TilemapBuffer.ts" />
/**
* Phaser - Tilemap
*
* This GameObject allows for the display of a tilemap within the game world. Tile maps consist of an image, tile data and a size.
* Internally it creates a TilemapBuffer for each camera in the world.
*/
var Phaser;
(function (Phaser) {
var Tilemap = (function (_super) {
__extends(Tilemap, _super);
function Tilemap(game, key, mapData, format, tileWidth, tileHeight) {
if (typeof tileWidth === "undefined") { tileWidth = 0; }
if (typeof tileHeight === "undefined") { tileHeight = 0; }
_super.call(this, game);
this._dx = 0;
this._dy = 0;
this.widthInTiles = 0;
this.heightInTiles = 0;
this.widthInPixels = 0;
this.heightInPixels = 0;
// How many extra tiles to draw around the edge of the screen (for fast scrolling games, or to optimise mobile performance try increasing this)
// The number is the amount of extra tiles PER SIDE, so a value of 10 would be (10 tiles + screen size + 10 tiles)
this.tileBoundary = 10;
this._texture = this._game.cache.getImage(key);
this._tilemapBuffers = [];
this.isGroup = false;
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
this.boundsInTiles = new Phaser.Rectangle();
this.mapFormat = format;
switch(format) {
case Tilemap.FORMAT_CSV:
this.parseCSV(game.cache.getText(mapData));
break;
case Tilemap.FORMAT_TILED_JSON:
this.parseTiledJSON(game.cache.getText(mapData));
break;
}
this.parseTileOffsets();
this.createTilemapBuffers();
}
Tilemap.FORMAT_CSV = 0;
Tilemap.FORMAT_TILED_JSON = 1;
Tilemap.prototype.parseCSV = function (data) {
//console.log('parseMapData');
this.mapData = [];
// Trim any rogue whitespace from the data
data = data.trim();
var rows = data.split("\n");
//console.log('rows', rows);
for(var i = 0; i < rows.length; i++) {
var column = rows[i].split(",");
//console.log('column', column);
var output = [];
if(column.length > 0) {
// Set the width based on the first row
if(this.widthInTiles == 0) {
// Maybe -1?
this.widthInTiles = column.length;
}
// We have a new row of tiles
this.heightInTiles++;
// Parse it
for(var c = 0; c < column.length; c++) {
output[c] = parseInt(column[c]);
}
this.mapData.push(output);
}
}
//console.log('final map array');
//console.log(this.mapData);
if(this.widthInTiles > 0) {
this.widthInPixels = this.tileWidth * this.widthInTiles;
}
if(this.heightInTiles > 0) {
this.heightInPixels = this.tileHeight * this.heightInTiles;
}
this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles);
};
Tilemap.prototype.parseTiledJSON = function (data) {
//console.log('parseTiledJSON');
this.mapData = [];
// Trim any rogue whitespace from the data
data = data.trim();
// We ought to change this soon, so we have layer support, but for now let's just get it working
var json = JSON.parse(data);
// Right now we assume no errors at all with the parsing (safe I know)
this.tileWidth = json.tilewidth;
this.tileHeight = json.tileheight;
// Parse the first layer only
this.widthInTiles = json.layers[0].width;
this.heightInTiles = json.layers[0].height;
this.widthInPixels = this.widthInTiles * this.tileWidth;
this.heightInPixels = this.heightInTiles * this.tileHeight;
this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles);
//console.log('width in tiles', this.widthInTiles);
//console.log('height in tiles', this.heightInTiles);
//console.log('width in px', this.widthInPixels);
//console.log('height in px', this.heightInPixels);
// Now let's get the data
var c = 0;
var row;
for(var i = 0; i < json.layers[0].data.length; i++) {
if(c == 0) {
row = [];
}
row.push(json.layers[0].data[i]);
c++;
if(c == this.widthInTiles) {
this.mapData.push(row);
c = 0;
}
}
//console.log('mapData');
//console.log(this.mapData);
};
Tilemap.prototype.getMapSegment = function (area) {
};
Tilemap.prototype.createTilemapBuffers = function () {
var cams = this._game.world.getAllCameras();
for(var i = 0; i < cams.length; i++) {
this._tilemapBuffers[cams[i].ID] = new Phaser.TilemapBuffer(this._game, cams[i], this, this._texture, this._tileOffsets);
}
};
Tilemap.prototype.parseTileOffsets = function () {
this._tileOffsets = [];
var i = 0;
if(this.mapFormat == Tilemap.FORMAT_TILED_JSON) {
// For some reason Tiled counts from 1 not 0
this._tileOffsets[0] = null;
i = 1;
}
for(var ty = 0; ty < this._texture.height; ty += this.tileHeight) {
for(var tx = 0; tx < this._texture.width; tx += this.tileWidth) {
this._tileOffsets[i] = {
x: tx,
y: ty
};
i++;
}
}
};
Tilemap.prototype.update = /*
// Use a Signal?
public addTilemapBuffers(camera:Camera) {
console.log('added new camera to tilemap');
this._tilemapBuffers[camera.ID] = new TilemapBuffer(this._game, camera, this, this._texture, this._tileOffsets);
}
*/
function () {
// Check if any of the cameras have scrolled far enough for us to need to refresh a TilemapBuffer
this._tilemapBuffers[0].update();
};
Tilemap.prototype.renderDebugInfo = function (x, y, color) {
if (typeof color === "undefined") { color = 'rgb(255,255,255)'; }
this._tilemapBuffers[0].renderDebugInfo(x, y, color);
};
Tilemap.prototype.render = function (camera, cameraOffsetX, cameraOffsetY) {
if(this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1) {
return false;
}
this._dx = cameraOffsetX + (this.bounds.x - camera.worldView.x);
this._dy = cameraOffsetY + (this.bounds.y - camera.worldView.y);
this._dx = Math.round(this._dx);
this._dy = Math.round(this._dy);
if(this._tilemapBuffers[camera.ID]) {
//this._tilemapBuffers[camera.ID].render(this._dx, this._dy);
this._tilemapBuffers[camera.ID].render(cameraOffsetX, cameraOffsetY);
}
return true;
};
return Tilemap;
})(Phaser.GameObject);
Phaser.Tilemap = Tilemap;
})(Phaser || (Phaser = {}));
/// <reference path="AnimationManager.ts" />
/// <reference path="Basic.ts" />
/// <reference path="Cache.ts" />
/// <reference path="CameraManager.ts" />
/// <reference path="Collision.ts" />
/// <reference path="DynamicTexture.ts" />
/// <reference path="GameMath.ts" />
/// <reference path="Group.ts" />
/// <reference path="Loader.ts" />
/// <reference path="Motion.ts" />
/// <reference path="Signal.ts" />
/// <reference path="SignalBinding.ts" />
/// <reference path="SoundManager.ts" />
/// <reference path="Stage.ts" />
/// <reference path="Time.ts" />
/// <reference path="TweenManager.ts" />
/// <reference path="World.ts" />
/// <reference path="system/Device.ts" />
/// <reference path="system/RandomDataGenerator.ts" />
/// <reference path="system/RequestAnimationFrame.ts" />
/// <reference path="system/input/Input.ts" />
/// <reference path="system/input/Keyboard.ts" />
/// <reference path="system/input/Mouse.ts" />
/// <reference path="system/input/Touch.ts" />
/// <reference path="gameobjects/Emitter.ts" />
/// <reference path="gameobjects/GameObject.ts" />
/// <reference path="gameobjects/GeomSprite.ts" />
/// <reference path="gameobjects/Particle.ts" />
/// <reference path="gameobjects/Sprite.ts" />
/// <reference path="gameobjects/Tilemap.ts" />
/**
* Phaser - Game
*
* This is where the magic happens. The Game object is the heart of your game, providing quick access to common
* functions and handling the boot process.
*/
var Phaser;
(function (Phaser) {
var Game = (function () {
function Game(callbackContext, parent, width, height, initCallback, createCallback, updateCallback, renderCallback) {
if (typeof parent === "undefined") { parent = ''; }
if (typeof width === "undefined") { width = 800; }
if (typeof height === "undefined") { height = 600; }
if (typeof initCallback === "undefined") { initCallback = null; }
if (typeof createCallback === "undefined") { createCallback = null; }
if (typeof updateCallback === "undefined") { updateCallback = null; }
if (typeof renderCallback === "undefined") { renderCallback = null; }
var _this = this;
this._maxAccumulation = 32;
this._accumulator = 0;
this._step = 0;
this._loadComplete = false;
this._paused = false;
this._pendingState = null;
this.onInitCallback = null;
this.onCreateCallback = null;
this.onUpdateCallback = null;
this.onRenderCallback = null;
this.onPausedCallback = null;
this.isBooted = false;
this.callbackContext = callbackContext;
this.onInitCallback = initCallback;
this.onCreateCallback = createCallback;
this.onUpdateCallback = updateCallback;
this.onRenderCallback = renderCallback;
if(document.readyState === 'complete' || document.readyState === 'interactive') {
this.boot(parent, width, height);
} else {
document.addEventListener('DOMContentLoaded', function () {
return _this.boot(parent, width, height);
}, false);
}
}
Game.prototype.boot = function (parent, width, height) {
var _this = this;
if(!document.body) {
window.setTimeout(function () {
return _this.boot(parent, width, height);
}, 13);
} else {
this.device = new Phaser.Device();
this.motion = new Phaser.Motion(this);
this.math = new Phaser.GameMath(this);
this.stage = new Phaser.Stage(this, parent, width, height);
this.world = new Phaser.World(this, width, height);
this.sound = new Phaser.SoundManager(this);
this.cache = new Phaser.Cache(this);
this.collision = new Phaser.Collision(this);
this.loader = new Phaser.Loader(this, this.loadComplete);
this.time = new Phaser.Time(this);
this.tweens = new Phaser.TweenManager(this);
this.input = new Phaser.Input(this);
this.rnd = new Phaser.RandomDataGenerator([
(Date.now() * Math.random()).toString()
]);
this.framerate = 60;
// Display the default game screen?
if(this.onInitCallback == null && this.onCreateCallback == null && this.onUpdateCallback == null && this.onRenderCallback == null && this._pendingState == null) {
this.isBooted = false;
this.stage.drawInitScreen();
} else {
this.isBooted = true;
this._loadComplete = false;
this._raf = new Phaser.RequestAnimationFrame(this.loop, this);
if(this._pendingState) {
this.switchState(this._pendingState, false, false);
} else {
this.startState();
}
}
}
};
Game.prototype.loadComplete = function () {
// Called when the loader has finished after init was run
this._loadComplete = true;
};
Game.prototype.loop = function () {
this.time.update();
this.tweens.update();
if(this._paused == true) {
if(this.onPausedCallback !== null) {
this.onPausedCallback.call(this.callbackContext);
}
return;
}
this.input.update();
this.stage.update();
this._accumulator += this.time.delta;
if(this._accumulator > this._maxAccumulation) {
this._accumulator = this._maxAccumulation;
}
while(this._accumulator >= this._step) {
this.time.elapsed = this.time.timeScale * (this._step / 1000);
this.world.update();
this._accumulator = this._accumulator - this._step;
}
if(this._loadComplete && this.onUpdateCallback) {
this.onUpdateCallback.call(this.callbackContext);
}
this.world.render();
if(this._loadComplete && this.onRenderCallback) {
this.onRenderCallback.call(this.callbackContext);
}
};
Game.prototype.startState = function () {
if(this.onInitCallback !== null) {
this.loader.reset();
this.onInitCallback.call(this.callbackContext);
// Is the loader empty?
if(this.loader.queueSize == 0) {
if(this.onCreateCallback !== null) {
this.onCreateCallback.call(this.callbackContext);
}
this._loadComplete = true;
}
} else {
// No init? Then there was nothing to load either
if(this.onCreateCallback !== null) {
this.onCreateCallback.call(this.callbackContext);
}
this._loadComplete = true;
}
};
Game.prototype.setCallbacks = function (initCallback, createCallback, updateCallback, renderCallback) {
if (typeof initCallback === "undefined") { initCallback = null; }
if (typeof createCallback === "undefined") { createCallback = null; }
if (typeof updateCallback === "undefined") { updateCallback = null; }
if (typeof renderCallback === "undefined") { renderCallback = null; }
this.onInitCallback = initCallback;
this.onCreateCallback = createCallback;
this.onUpdateCallback = updateCallback;
this.onRenderCallback = renderCallback;
};
Game.prototype.switchState = function (state, clearWorld, clearCache) {
if (typeof clearWorld === "undefined") { clearWorld = true; }
if (typeof clearCache === "undefined") { clearCache = false; }
if(this.isBooted == false) {
this._pendingState = state;
return;
}
// Prototype?
if(typeof state === 'function') {
state = new state(this);
}
// Ok, have we got the right functions?
if(state['create'] || state['update']) {
this.callbackContext = state;
this.onInitCallback = null;
this.onCreateCallback = null;
this.onUpdateCallback = null;
this.onRenderCallback = null;
this.onPausedCallback = null;
// Bingo, let's set them up
if(state['init']) {
this.onInitCallback = state['init'];
}
if(state['create']) {
this.onCreateCallback = state['create'];
}
if(state['update']) {
this.onUpdateCallback = state['update'];
}
if(state['render']) {
this.onRenderCallback = state['render'];
}
if(state['paused']) {
this.onPausedCallback = state['paused'];
}
if(clearWorld) {
this.world.destroy();
if(clearCache == true) {
this.cache.destroy();
}
}
this._loadComplete = false;
this.startState();
} else {
throw Error("Invalid State object given. Must contain at least a create or update function.");
return;
}
};
Game.prototype.destroy = // Nuke the whole game from orbit
function () {
this.callbackContext = null;
this.onInitCallback = null;
this.onCreateCallback = null;
this.onUpdateCallback = null;
this.onRenderCallback = null;
this.onPausedCallback = null;
this.camera = null;
this.cache = null;
this.input = null;
this.loader = null;
this.sound = null;
this.stage = null;
this.time = null;
this.world = null;
this.isBooted = false;
};
Object.defineProperty(Game.prototype, "paused", {
get: function () {
return this._paused;
},
set: function (value) {
if(value == true && this._paused == false) {
this._paused = true;
} else if(value == false && this._paused == true) {
this._paused = false;
this.time.time = Date.now();
this.input.reset();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Game.prototype, "framerate", {
get: function () {
return 1000 / this._step;
},
set: function (value) {
this._step = 1000 / value;
if(this._maxAccumulation < this._step) {
this._maxAccumulation = this._step;
}
},
enumerable: true,
configurable: true
});
Game.prototype.createCamera = // Handy Proxy methods
function (x, y, width, height) {
return this.world.createCamera(x, y, width, height);
};
Game.prototype.createGeomSprite = function (x, y) {
return this.world.createGeomSprite(x, y);
};
Game.prototype.createSprite = function (x, y, key) {
if (typeof key === "undefined") { key = ''; }
return this.world.createSprite(x, y, key);
};
Game.prototype.createDynamicTexture = function (key, width, height) {
return this.world.createDynamicTexture(key, width, height);
};
Game.prototype.createGroup = function (MaxSize) {
if (typeof MaxSize === "undefined") { MaxSize = 0; }
return this.world.createGroup(MaxSize);
};
Game.prototype.createParticle = function () {
return this.world.createParticle();
};
Game.prototype.createEmitter = function (x, y, size) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof size === "undefined") { size = 0; }
return this.world.createEmitter(x, y, size);
};
Game.prototype.createTilemap = function (key, mapData, format, tileWidth, tileHeight) {
return this.world.createTilemap(key, mapData, format, tileWidth, tileHeight);
};
Game.prototype.createTween = function (obj) {
return this.tweens.create(obj);
};
Game.prototype.collide = function (ObjectOrGroup1, ObjectOrGroup2, NotifyCallback) {
if (typeof ObjectOrGroup1 === "undefined") { ObjectOrGroup1 = null; }
if (typeof ObjectOrGroup2 === "undefined") { ObjectOrGroup2 = null; }
if (typeof NotifyCallback === "undefined") { NotifyCallback = null; }
return this.collision.overlap(ObjectOrGroup1, ObjectOrGroup2, NotifyCallback, Phaser.Collision.separate);
};
return Game;
})();
Phaser.Game = Game;
})(Phaser || (Phaser = {}));
/// <reference path="../Game.ts" />
/**
* Phaser - MicroPoint
*
* The MicroPoint object represents a location in a two-dimensional coordinate system,
* where x represents the horizontal axis and y represents the vertical axis.
* It is different to the Point class in that it doesn't contain any of the help methods like add/substract/distanceTo, etc.
* Use a MicroPoint when all you literally need is a solid container for x and y (such as in the Rectangle class).
*/
var Phaser;
(function (Phaser) {
var MicroPoint = (function () {
/**
* Creates a new point. If you pass no parameters to this method, a point is created at (0,0).
* @class MicroPoint
* @constructor
* @param {Number} x The horizontal position of this point (default 0)
* @param {Number} y The vertical position of this point (default 0)
**/
function MicroPoint(x, y, parent) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof parent === "undefined") { parent = null; }
this._x = x;
this._y = y;
this.parent = parent;
}
Object.defineProperty(MicroPoint.prototype, "x", {
get: /**
* The x coordinate of the top-left corner of the rectangle
* @property x
* @type Number
**/
function () {
return this._x;
},
set: /**
* The x coordinate of the top-left corner of the rectangle
* @property x
* @type Number
**/
function (value) {
this._x = value;
if(this.parent) {
this.parent.updateBounds();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MicroPoint.prototype, "y", {
get: /**
* The y coordinate of the top-left corner of the rectangle
* @property y
* @type Number
**/
function () {
return this._y;
},
set: /**
* The y coordinate of the top-left corner of the rectangle
* @property y
* @type Number
**/
function (value) {
this._y = value;
if(this.parent) {
this.parent.updateBounds();
}
},
enumerable: true,
configurable: true
});
MicroPoint.prototype.copyFrom = /**
* Copies the x and y values from any given object to this MicroPoint.
* @method copyFrom
* @param {any} source - The object to copy from.
* @return {MicroPoint} This MicroPoint object. Useful for chaining method calls.
**/
function (source) {
return this.setTo(source.x, source.y);
};
MicroPoint.prototype.copyTo = /**
* Copies the x and y values from this MicroPoint to any given object.
* @method copyTo
* @param {any} target - The object to copy to.
* @return {any} The target object.
**/
function (target) {
target.x = this._x;
target.y = this._y;
return target;
};
MicroPoint.prototype.setTo = /**
* Sets the x and y values of this MicroPoint object to the given coordinates.
* @method setTo
* @param {Number} x - The horizontal position of this point.
* @param {Number} y - The vertical position of this point.
* @return {MicroPoint} This MicroPoint object. Useful for chaining method calls.
**/
function (x, y, callParent) {
if (typeof callParent === "undefined") { callParent = true; }
this._x = x;
this._y = y;
if(this.parent != null && callParent == true) {
this.parent.updateBounds();
}
return this;
};
MicroPoint.prototype.equals = /**
* Determines whether this MicroPoint object and the given object are equal. They are equal if they have the same x and y values.
* @method equals
* @param {any} point - The object to compare against. Must have x and y properties.
* @return {Boolean} A value of true if the object is equal to this MicroPoin object; false if it is not equal.
**/
function (toCompare) {
if(this._x === toCompare.x && this._y === toCompare.y) {
return true;
} else {
return false;
}
};
MicroPoint.prototype.toString = /**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the instance.
**/
function () {
return '[{MicroPoint (x=' + this._x + ' y=' + this._y + ')}]';
};
return MicroPoint;
})();
Phaser.MicroPoint = MicroPoint;
})(Phaser || (Phaser = {}));
/// <reference path="Game.ts" />
/**
* Phaser - State
*
* This is a base State class which can be extended if you are creating your game using TypeScript.
*/
var Phaser;
(function (Phaser) {
var State = (function () {
function State(game) {
this.game = game;
this.camera = game.camera;
this.cache = game.cache;
this.collision = game.collision;
this.input = game.input;
this.loader = game.loader;
this.math = game.math;
this.motion = game.motion;
this.sound = game.sound;
this.stage = game.stage;
this.time = game.time;
this.tweens = game.tweens;
this.world = game.world;
}
State.prototype.init = // Overload these in your own States
function () {
};
State.prototype.create = function () {
};
State.prototype.update = function () {
};
State.prototype.render = function () {
};
State.prototype.paused = function () {
};
State.prototype.createCamera = // Handy Proxy methods
function (x, y, width, height) {
return this.game.world.createCamera(x, y, width, height);
};
State.prototype.createGeomSprite = function (x, y) {
return this.world.createGeomSprite(x, y);
};
State.prototype.createSprite = function (x, y, key) {
if (typeof key === "undefined") { key = ''; }
return this.game.world.createSprite(x, y, key);
};
State.prototype.createDynamicTexture = function (key, width, height) {
return this.game.world.createDynamicTexture(key, width, height);
};
State.prototype.createGroup = function (MaxSize) {
if (typeof MaxSize === "undefined") { MaxSize = 0; }
return this.game.world.createGroup(MaxSize);
};
State.prototype.createParticle = function () {
return this.game.world.createParticle();
};
State.prototype.createEmitter = function (x, y, size) {
if (typeof x === "undefined") { x = 0; }
if (typeof y === "undefined") { y = 0; }
if (typeof size === "undefined") { size = 0; }
return this.game.world.createEmitter(x, y, size);
};
State.prototype.createTilemap = function (key, mapData, format, tileWidth, tileHeight) {
return this.game.world.createTilemap(key, mapData, format, tileWidth, tileHeight);
};
State.prototype.createTween = function (obj) {
return this.game.tweens.create(obj);
};
State.prototype.collide = function (ObjectOrGroup1, ObjectOrGroup2, NotifyCallback) {
if (typeof ObjectOrGroup1 === "undefined") { ObjectOrGroup1 = null; }
if (typeof ObjectOrGroup2 === "undefined") { ObjectOrGroup2 = null; }
if (typeof NotifyCallback === "undefined") { NotifyCallback = null; }
return this.collision.overlap(ObjectOrGroup1, ObjectOrGroup2, NotifyCallback, Phaser.Collision.separate);
};
return State;
})();
Phaser.State = State;
})(Phaser || (Phaser = {}));
|
/**
* @requires GeoExt/Lang.js
*/
GeoExt.Lang.add("fr", {
"gxp.plugins.AddLayers.prototype": {
addActionMenuText: "Ajouter des calques",
addActionTip: "Ajouter des calques",
addServerText: "Ajouter un nouveau serveur",
untitledText: "Sans titre",
addLayerSourceErrorText: "Impossible d'obtenir les capacités WMS ({msg}).\nVeuillez vérifier l'URL et essayez à nouveau.",
availableLayersText: "Couches disponibles",
doneText: "Terminé",
uploadText: "Télécharger des données",
addFeedActionMenuText: "Add feeds",
searchText: "Search for layers"
},
"gxp.plugins.BingSource.prototype": {
title: "Calques Bing",
roadTitle: "Bing routes",
aerialTitle: "Bing images aériennes",
labeledAerialTitle: "Bing images aériennes avec étiquettes"
},
"gxp.plugins.FeatureEditor.prototype": {
splitButtonText: "Edit",
createFeatureActionText: "Create",
editFeatureActionText: "Modify",
createFeatureActionTip: "Créer un nouvel objet",
editFeatureActionTip: "Modifier un objet existant",
commitTitle: "Commit message",
commitText: "Please enter a commit message for this edit:"
},
"gxp.plugins.FeatureGrid.prototype": {
displayFeatureText: "Afficher sur la carte",
firstPageTip: "Première page",
previousPageTip: "Page précédente",
zoomPageExtentTip: "Zoom sur la page",
nextPageTip: "Page suivante",
lastPageTip: "Dernière page",
totalMsg: "Features {1} to {2} of {0}"
},
"gxp.plugins.GoogleEarth.prototype": {
menuText: "Passer à la visionneuse 3D",
tooltip: "Passer à la visionneuse 3D"
},
"gxp.plugins.GoogleSource.prototype": {
title: "Calques Google",
roadmapAbstract: "Carte routière",
satelliteAbstract: "Images satellite",
hybridAbstract: "Images avec routes",
terrainAbstract: "Carte routière avec le terrain"
},
"gxp.plugins.LayerProperties.prototype": {
menuText: "Propriétés de la couche",
toolTip: "Afficher les propriétés de la couche"
},
"gxp.plugins.LayerTree.prototype": {
shortTitle: "Layers",
rootNodeText: "Layers",
overlayNodeText: "Surimpressions",
baseNodeText: "Couches"
},
"gxp.plugins.LayerManager.prototype": {
baseNodeText: "Couche"
},
"gxp.plugins.Legend.prototype": {
menuText: "Légende",
tooltip: "Afficher la légende"
},
"gxp.plugins.Measure.prototype": {
buttonText: "Mesure",
lengthMenuText: "Longueur",
areaMenuText: "Surface",
lengthTooltip: "Mesurer une longueur",
areaTooltip: "Mesurer une surface",
measureTooltip: "Mesurer"
},
"gxp.plugins.Navigation.prototype": {
menuText: "Panner",
tooltip: "Faire glisser la carte"
},
"gxp.plugins.NavigationHistory.prototype": {
previousMenuText: "Position précédente",
nextMenuText: "Position suivante",
previousTooltip: "Retourner à la position précédente",
nextTooltip: "Aller à la position suivante"
},
"gxp.plugins.LoadingIndicator.prototype": {
loadingMapMessage: "Chargement de la carte..."
},
"gxp.plugins.MapBoxSource.prototype": {
title: "MapBox Layers",
blueMarbleTopoBathyJanTitle: "Blue Marble Topography & Bathymetry (January)",
blueMarbleTopoBathyJulTitle: "Blue Marble Topography & Bathymetry (July)",
blueMarbleTopoJanTitle: "Blue Marble Topography (January)",
blueMarbleTopoJulTitle: "Blue Marble Topography (July)",
controlRoomTitle: "Control Room",
geographyClassTitle: "Geography Class",
naturalEarthHypsoTitle: "Natural Earth Hypsometric",
naturalEarthHypsoBathyTitle: "Natural Earth Hypsometric & Bathymetry",
naturalEarth1Title: "Natural Earth I",
naturalEarth2Title: "Natural Earth II",
worldDarkTitle: "World Dark",
worldLightTitle: "World Light",
worldPrintTitle: "World Print"
},
"gxp.plugins.OSMSource.prototype": {
title: "Calques OpenStreetMap",
mapnikAttribution: "© <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors",
osmarenderAttribution: "Données CC-By-SA par <a href='http://openstreetmap.org/'>OpenStreetMap</a>"
},
"gxp.plugins.Print.prototype": {
buttonText:"Imprimer",
menuText: "Imprimer la carte",
tooltip: "Imprimer la carte",
previewText: "Aperçu avant impression",
notAllNotPrintableText: "Non, toutes les couches peuvent être imprimées",
nonePrintableText: "Aucune de vos couches ne peut être imprimée"
},
"gxp.plugins.MapQuestSource.prototype": {
title: "MapQuest Layers",
osmAttribution: "Avec la permission de tuiles <a href='http://open.mapquest.co.uk/' target='_blank'>MapQuest</a> <img src='http://developer.mapquest.com/content/osm/mq_logo.png' border='0'>",
osmTitle: "MapQuest OpenStreetMap",
naipAttribution: "Avec la permission de tuiles <a href='http://open.mapquest.co.uk/' target='_blank'>MapQuest</a> <img src='http://developer.mapquest.com/content/osm/mq_logo.png' border='0'>",
naipTitle: "MapQuest Imagery"
},
"gxp.plugins.QueryForm.prototype": {
queryActionText: "Interrogation",
queryMenuText: "Couche de requêtes",
queryActionTip: "Interroger la couche sélectionnée",
queryByLocationText: "Query by current map extent",
queryByAttributesText: "Requête par attributs"
},
"gxp.plugins.RemoveLayer.prototype": {
removeMenuText: "Enlever la couche",
removeActionTip: "Enlever la couche"
},
"gxp.plugins.WMSGetFeatureInfo.prototype": {
buttonText:"Identify",
infoActionTip: "Get Feature Info",
popupTitle: "Info sur l'objet"
},
"gxp.plugins.Zoom.prototype": {
zoomMenuText: "Zoom Box",
zoomInMenuText: "Zoom avant",
zoomOutMenuText: "Zoom arrière",
zoomTooltip: "Zoomer en dessinant un rectangle",
zoomInTooltip: "Zoomer",
zoomOutTooltip: "Dézoomer"
},
"gxp.plugins.ZoomToExtent.prototype": {
menuText: "Zoomer sur la carte max",
tooltip: "Zoomer sur la carte max"
},
"gxp.plugins.ZoomToDataExtent.prototype": {
menuText: "Zoomer sur la couche",
tooltip: "Zoomer sur la couche"
},
"gxp.plugins.ZoomToLayerExtent.prototype": {
menuText: "Zoomer sur la couche",
tooltip: "Zoomer sur la couche"
},
"gxp.plugins.ZoomToSelectedFeatures.prototype": {
menuText: "Zoomer sur les objets sélectionnés",
tooltip: "Zoomer sur les objets sélectionnés"
},
"gxp.FeatureEditPopup.prototype": {
closeMsgTitle: "Enregistrer les modifications ?",
closeMsg: "Cet objet a des modifications non enregistrées. Voulez-vous enregistrer vos modifications ?",
deleteMsgTitle: "Supprimer l'objet ?",
deleteMsg: "Etes-vous sûr de vouloir supprimer cet objet ?",
editButtonText: "Modifier",
editButtonTooltip: "Modifier cet objet",
deleteButtonText: "Supprimer",
deleteButtonTooltip: "Supprimer cet objet",
cancelButtonText: "Annuler",
cancelButtonTooltip: "Arrêter de modifier, annuler les modifications",
saveButtonText: "Enregistrer",
saveButtonTooltip: "Enregistrer les modifications"
},
"gxp.FillSymbolizer.prototype": {
fillText: "Remplir",
colorText: "Couleur",
opacityText: "Opacité"
},
"gxp.FilterBuilder.prototype": {
builderTypeNames: ["Tout", "tous", "aucun", "pas tout"],
preComboText: "Match",
postComboText: "de ce qui suit:",
addConditionText: "Ajouter la condition",
addGroupText: "Ajouter un groupe",
removeConditionText: "Supprimer la condition"
},
"gxp.grid.CapabilitiesGrid.prototype": {
nameHeaderText : "Nom",
titleHeaderText : "Titre",
queryableHeaderText : "Interrogeable",
layerSelectionLabel: "Voir les données disponibles à partir de :",
layerAdditionLabel: "ou ajouter un nouveau serveur.",
expanderTemplateText: "<p><b>Résumé:</b> {abstract}</p>"
},
"gxp.PointSymbolizer.prototype": {
graphicCircleText: "Cercle",
graphicSquareText: "Carré",
graphicTriangleText: "Triangle",
graphicStarText: "Étoile",
graphicCrossText: "Croix",
graphicXText: "x",
graphicExternalText: "Externe",
urlText: "URL",
opacityText: "Opacité",
symbolText: "Symbole",
sizeText: "Taille",
rotationText: "Rotation"
},
"gxp.QueryPanel.prototype": {
queryByLocationText: "Interrogation selon le lieu",
currentTextText: "Mesure actuelle",
queryByAttributesText: "Requête par attributs",
layerText: "Calque"
},
"gxp.RulePanel.prototype": {
scaleSliderTemplate: "{scaleType} échelle 1:{scale}",
labelFeaturesText: "Label Caractéristiques",
advancedText: "Avancé",
limitByScaleText: "Limiter par l'échelle",
limitByConditionText: "Limiter par condition",
symbolText: "Symbole",
nameText: "Nom"
},
"gxp.ScaleLimitPanel.prototype": {
scaleSliderTemplate: "{scaleType} échelle 1:{scale}",
maxScaleLimitText: "Échelle maximale"
},
"gxp.TextSymbolizer.prototype": {
labelValuesText: "Label valeurs",
haloText: "Halo",
sizeText: "Taille"
},
"gxp.WMSLayerPanel.prototype": {
attributionText: "Attribution",
aboutText: "A propos",
titleText: "Titre",
nameText: "Nom",
descriptionText: "Description",
displayText: "Affichage",
opacityText: "Opacité",
formatText: "Format",
transparentText: "Transparent",
cacheText: "Cache",
cacheFieldText: "Utiliser la version mise en cache",
stylesText: "Available styles",
infoFormatText: "Info format",
infoFormatEmptyText: "Choisissez un format",
displayOptionsText: "Display options",
queryText: "Limit with filters",
scaleText: "Limit by scale",
minScaleText: "Min scale",
maxScaleText: "Max scale",
switchToFilterBuilderText: "Switch back to filter builder",
cqlPrefixText: "or ",
cqlText: "use CQL filter instead",
singleTileText: "Single tile",
singleTileFieldText: "Use a single tile"
},
"gxp.EmbedMapDialog.prototype": {
publishMessage: "Votre carte est prête à être publiée sur le web. Il suffit de copier le code HTML suivant pour intégrer la carte dans votre site Web :",
heightLabel: 'Hauteur',
widthLabel: 'Largeur',
mapSizeLabel: 'Taille de la carte',
miniSizeLabel: 'Mini',
smallSizeLabel: 'Petit',
premiumSizeLabel: 'Premium',
largeSizeLabel: 'Large'
},
"gxp.LayerUploadPanel.prototype": {
titleLabel: "Titre",
titleEmptyText: "Titre de la couche",
abstractLabel: "Description",
abstractEmptyText: "Description couche",
fileLabel: "Données",
fieldEmptyText: "Parcourir pour ...",
uploadText: "Upload",
uploadFailedText: "Upload failed",
processingUploadText: "Processing upload...",
waitMsgText: "Transfert de vos données ...",
invalidFileExtensionText: "L'extension du fichier doit être : ",
optionsText: "Options",
workspaceLabel: "Espace de travail",
workspaceEmptyText: "Espace de travail par défaut",
dataStoreLabel: "Magasin de données",
dataStoreEmptyText: "Create new store",
defaultDataStoreEmptyText: "Magasin de données par défaut"
},
"gxp.NewSourceDialog.prototype": {
title: "Ajouter un nouveau serveur...",
cancelText: "Annuler",
addServerText: "Ajouter un serveur",
invalidURLText: "Indiquez l'URL valide d'un serveur WMS (e.g. http://example.com/geoserver/wms)",
contactingServerText: "Interrogation du serveur..."
},
"gxp.ScaleOverlay.prototype": {
zoomLevelText: "Niveau de zoom"
},
"gxp.Viewer.prototype": {
saveErrorText: "Sauver Trouble: "
},
"gxp.FeedSourceDialog.prototype": {
feedTypeText: "Source",
addPicasaText: "Picasa Photos",
addYouTubeText: "YouTube Vidéos",
addRSSText: "GeoRSS Autre",
addFeedText: "Ajouter à la carte",
addTitleText: "Titre",
keywordText: "Mot-clé",
doneText: "Terminé",
titletext: "Ajouter RSS",
maxResultsText: "Articles Max"
}
});
|
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
// update parent select
$.extend(cur_frm.cscript, {
refresh: function(doc) {
},
onload_post_render: function(doc) {
this.set_parent_label_options();
},
label: function(doc, cdt, cdn) {
var item = wn.model.get_doc(cdt, cdn);
if(item.parentfield === "top_bar_items") {
this.set_parent_label_options();
}
},
parent_label: function(doc, cdt, cdn) {
this.label(doc, cdt, cdn);
},
url: function(doc, cdt, cdn) {
this.label(doc, cdt, cdn);
},
set_parent_label_options: function() {
wn.meta.get_docfield("Top Bar Item", "parent_label", cur_frm.docname).options =
this.get_parent_options("top_bar_items");
if($(cur_frm.fields_dict.top_bar_items.grid.wrapper).find(".grid-row-open")) {
cur_frm.fields_dict.top_bar_items.grid.refresh();
}
},
// get labels of parent items
get_parent_options: function(table_field) {
var items = getchildren('Top Bar Item', cur_frm.doc.name, table_field);
var main_items = [''];
for(var i in items) {
var d = items[i];
if(!d.parent_label && !d.url && d.label) {
main_items.push(d.label);
}
}
return main_items.join('\n');
}
});
cur_frm.cscript.set_banner_from_image = function(doc) {
if(!doc.banner_image) {
msgprint(wn._("Select a Banner Image first."));
}
var src = doc.banner_image;
cur_frm.set_value("banner_html", "<a href='/'><img src='"+ src
+"' style='max-width: 200px;'></a>");
}
|
/**
* @class button - open elfinder window (not needed for image or link buttons).Used in ELDORADO.CMS for easy file manipulations.
*
* @param elRTE rte объект-редактор
* @param String name название кнопки
*
* @author: Dmitry Levashov (dio) dio@std42.ru
* @copyright: Studio 42, http://www.std42.ru
**/
(function($) {
elRTE.prototype.ui.prototype.buttons.elfinder = function(rte, name) {
this.constructor.prototype.constructor.call(this, rte, name);
var self = this,
rte = this.rte;
this.command = function() {
if (self.rte.options.fmAllow && typeof(self.rte.options.fmOpen) == 'function') {
self.rte.options.fmOpen( function(url) {
var name = decodeURIComponent(url.split('/').pop().replace(/\+/g, " "));
if (rte.selection.collapsed()) {
rte.selection.insertHtml('<a href="'+url+'" >'+name+'</a>');
} else {
rte.doc.execCommand('createLink', false, url);
}
} );
}
}
this.update = function() {
if (self.rte.options.fmAllow && typeof(self.rte.options.fmOpen) == 'function') {
this.domElem.removeClass('disabled');
} else {
this.domElem.addClass('disabled');
}
}
}
})(jQuery);
|
/**
* videojs-contrib-hls
* @version 3.6.14-experimental
* @copyright 2016 Brightcove, Inc
* @license Apache-2.0
*/
(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.videojsContribHls = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* @file aes.js
*
* This file contains an adaptation of the AES decryption algorithm
* from the Standford Javascript Cryptography Library. That work is
* covered by the following copyright and permissions notice:
*
* Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
/**
* Expand the S-box tables.
*
* @private
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var precompute = function precompute() {
var tables = [[[], [], [], [], []], [[], [], [], [], []]];
var encTable = tables[0];
var decTable = tables[1];
var sbox = encTable[4];
var sboxInv = decTable[4];
var i = undefined;
var x = undefined;
var xInv = undefined;
var d = [];
var th = [];
var x2 = undefined;
var x4 = undefined;
var x8 = undefined;
var s = undefined;
var tEnc = undefined;
var tDec = undefined;
// Compute double and third tables
for (i = 0; i < 256; i++) {
th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
}
for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
// Compute sbox
s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
s = s >> 8 ^ s & 255 ^ 99;
sbox[x] = s;
sboxInv[s] = x;
// Compute MixColumns
x8 = d[x4 = d[x2 = d[x]]];
tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
tEnc = d[s] * 0x101 ^ s * 0x1010100;
for (i = 0; i < 4; i++) {
encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
}
}
// Compactify. Considerable speedup on Firefox.
for (i = 0; i < 5; i++) {
encTable[i] = encTable[i].slice(0);
decTable[i] = decTable[i].slice(0);
}
return tables;
};
var aesTables = null;
/**
* Schedule out an AES key for both encryption and decryption. This
* is a low-level class. Use a cipher mode to do bulk encryption.
*
* @class AES
* @param key {Array} The key as an array of 4, 6 or 8 words.
*/
var AES = (function () {
function AES(key) {
_classCallCheck(this, AES);
/**
* The expanded S-box and inverse S-box tables. These will be computed
* on the client so that we don't have to send them down the wire.
*
* There are two tables, _tables[0] is for encryption and
* _tables[1] is for decryption.
*
* The first 4 sub-tables are the expanded S-box with MixColumns. The
* last (_tables[01][4]) is the S-box itself.
*
* @private
*/
// if we have yet to precompute the S-box tables
// do so now
if (!aesTables) {
aesTables = precompute();
}
// then make a copy of that object for use
this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
var i = undefined;
var j = undefined;
var tmp = undefined;
var encKey = undefined;
var decKey = undefined;
var sbox = this._tables[0][4];
var decTable = this._tables[1];
var keyLen = key.length;
var rcon = 1;
if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
throw new Error('Invalid aes key size');
}
encKey = key.slice(0);
decKey = [];
this._key = [encKey, decKey];
// schedule encryption keys
for (i = keyLen; i < 4 * keyLen + 28; i++) {
tmp = encKey[i - 1];
// apply sbox
if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
// shift rows and add rcon
if (i % keyLen === 0) {
tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
encKey[i] = encKey[i - keyLen] ^ tmp;
}
// schedule decryption keys
for (j = 0; i; j++, i--) {
tmp = encKey[j & 3 ? i : i - 4];
if (i <= 4 || j < 4) {
decKey[j] = tmp;
} else {
decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
}
}
}
/**
* Decrypt 16 bytes, specified as four 32-bit words.
*
* @param {Number} encrypted0 the first word to decrypt
* @param {Number} encrypted1 the second word to decrypt
* @param {Number} encrypted2 the third word to decrypt
* @param {Number} encrypted3 the fourth word to decrypt
* @param {Int32Array} out the array to write the decrypted words
* into
* @param {Number} offset the offset into the output array to start
* writing results
* @return {Array} The plaintext.
*/
_createClass(AES, [{
key: 'decrypt',
value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
var key = this._key[1];
// state variables a,b,c,d are loaded with pre-whitened data
var a = encrypted0 ^ key[0];
var b = encrypted3 ^ key[1];
var c = encrypted2 ^ key[2];
var d = encrypted1 ^ key[3];
var a2 = undefined;
var b2 = undefined;
var c2 = undefined;
// key.length === 2 ?
var nInnerRounds = key.length / 4 - 2;
var i = undefined;
var kIndex = 4;
var table = this._tables[1];
// load up the tables
var table0 = table[0];
var table1 = table[1];
var table2 = table[2];
var table3 = table[3];
var sbox = table[4];
// Inner rounds. Cribbed from OpenSSL.
for (i = 0; i < nInnerRounds; i++) {
a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
kIndex += 4;
a = a2;b = b2;c = c2;
}
// Last round.
for (i = 0; i < 4; i++) {
out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
a2 = a;a = b;b = c;c = d;d = a2;
}
}
}]);
return AES;
})();
exports['default'] = AES;
module.exports = exports['default'];
},{}],2:[function(require,module,exports){
/**
* @file async-stream.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _stream = require('./stream');
var _stream2 = _interopRequireDefault(_stream);
/**
* A wrapper around the Stream class to use setTiemout
* and run stream "jobs" Asynchronously
*
* @class AsyncStream
* @extends Stream
*/
var AsyncStream = (function (_Stream) {
_inherits(AsyncStream, _Stream);
function AsyncStream() {
_classCallCheck(this, AsyncStream);
_get(Object.getPrototypeOf(AsyncStream.prototype), 'constructor', this).call(this, _stream2['default']);
this.jobs = [];
this.delay = 1;
this.timeout_ = null;
}
/**
* process an async job
*
* @private
*/
_createClass(AsyncStream, [{
key: 'processJob_',
value: function processJob_() {
this.jobs.shift()();
if (this.jobs.length) {
this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
} else {
this.timeout_ = null;
}
}
/**
* push a job into the stream
*
* @param {Function} job the job to push into the stream
*/
}, {
key: 'push',
value: function push(job) {
this.jobs.push(job);
if (!this.timeout_) {
this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
}
}
}]);
return AsyncStream;
})(_stream2['default']);
exports['default'] = AsyncStream;
module.exports = exports['default'];
},{"./stream":5}],3:[function(require,module,exports){
/**
* @file decrypter.js
*
* An asynchronous implementation of AES-128 CBC decryption with
* PKCS#7 padding.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _aes = require('./aes');
var _aes2 = _interopRequireDefault(_aes);
var _asyncStream = require('./async-stream');
var _asyncStream2 = _interopRequireDefault(_asyncStream);
var _pkcs7 = require('pkcs7');
/**
* Convert network-order (big-endian) bytes into their little-endian
* representation.
*/
var ntoh = function ntoh(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
/**
* Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
*
* @param {Uint8Array} encrypted the encrypted bytes
* @param {Uint32Array} key the bytes of the decryption key
* @param {Uint32Array} initVector the initialization vector (IV) to
* use for the first round of CBC.
* @return {Uint8Array} the decrypted bytes
*
* @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
* @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
* @see https://tools.ietf.org/html/rfc2315
*/
var decrypt = function decrypt(encrypted, key, initVector) {
// word-level access to the encrypted bytes
var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
var decipher = new _aes2['default'](Array.prototype.slice.call(key));
// byte and word-level access for the decrypted output
var decrypted = new Uint8Array(encrypted.byteLength);
var decrypted32 = new Int32Array(decrypted.buffer);
// temporary variables for working with the IV, encrypted, and
// decrypted data
var init0 = undefined;
var init1 = undefined;
var init2 = undefined;
var init3 = undefined;
var encrypted0 = undefined;
var encrypted1 = undefined;
var encrypted2 = undefined;
var encrypted3 = undefined;
// iteration variable
var wordIx = undefined;
// pull out the words of the IV to ensure we don't modify the
// passed-in reference and easier access
init0 = initVector[0];
init1 = initVector[1];
init2 = initVector[2];
init3 = initVector[3];
// decrypt four word sequences, applying cipher-block chaining (CBC)
// to each decrypted block
for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
// convert big-endian (network order) words into little-endian
// (javascript order)
encrypted0 = ntoh(encrypted32[wordIx]);
encrypted1 = ntoh(encrypted32[wordIx + 1]);
encrypted2 = ntoh(encrypted32[wordIx + 2]);
encrypted3 = ntoh(encrypted32[wordIx + 3]);
// decrypt the block
decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
// XOR with the IV, and restore network byte-order to obtain the
// plaintext
decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3);
// setup the IV for the next round
init0 = encrypted0;
init1 = encrypted1;
init2 = encrypted2;
init3 = encrypted3;
}
return decrypted;
};
exports.decrypt = decrypt;
/**
* The `Decrypter` class that manages decryption of AES
* data through `AsyncStream` objects and the `decrypt`
* function
*
* @param {Uint8Array} encrypted the encrypted bytes
* @param {Uint32Array} key the bytes of the decryption key
* @param {Uint32Array} initVector the initialization vector (IV) to
* @param {Function} done the function to run when done
* @class Decrypter
*/
var Decrypter = (function () {
function Decrypter(encrypted, key, initVector, done) {
_classCallCheck(this, Decrypter);
var step = Decrypter.STEP;
var encrypted32 = new Int32Array(encrypted.buffer);
var decrypted = new Uint8Array(encrypted.byteLength);
var i = 0;
this.asyncStream_ = new _asyncStream2['default']();
// split up the encryption job and do the individual chunks asynchronously
this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
for (i = step; i < encrypted32.length; i += step) {
initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
}
// invoke the done() callback when everything is finished
this.asyncStream_.push(function () {
// remove pkcs#7 padding from the decrypted bytes
done(null, (0, _pkcs7.unpad)(decrypted));
});
}
/**
* a getter for step the maximum number of bytes to process at one time
*
* @return {Number} the value of step 32000
*/
_createClass(Decrypter, [{
key: 'decryptChunk_',
/**
* @private
*/
value: function decryptChunk_(encrypted, key, initVector, decrypted) {
return function () {
var bytes = decrypt(encrypted, key, initVector);
decrypted.set(bytes, encrypted.byteOffset);
};
}
}], [{
key: 'STEP',
get: function get() {
// 4 * 8000;
return 32000;
}
}]);
return Decrypter;
})();
exports.Decrypter = Decrypter;
exports['default'] = {
Decrypter: Decrypter,
decrypt: decrypt
};
},{"./aes":1,"./async-stream":2,"pkcs7":7}],4:[function(require,module,exports){
/**
* @file index.js
*
* Index module to easily import the primary components of AES-128
* decryption. Like this:
*
* ```js
* import {Decrypter, decrypt, AsyncStream} from 'aes-decrypter';
* ```
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _decrypter = require('./decrypter');
var _asyncStream = require('./async-stream');
var _asyncStream2 = _interopRequireDefault(_asyncStream);
exports['default'] = {
decrypt: _decrypter.decrypt,
Decrypter: _decrypter.Decrypter,
AsyncStream: _asyncStream2['default']
};
module.exports = exports['default'];
},{"./async-stream":2,"./decrypter":3}],5:[function(require,module,exports){
/**
* @file stream.js
*/
/**
* A lightweight readable stream implemention that handles event dispatching.
*
* @class Stream
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var Stream = (function () {
function Stream() {
_classCallCheck(this, Stream);
this.listeners = {};
}
/**
* Add a listener for a specified event type.
*
* @param {String} type the event name
* @param {Function} listener the callback to be invoked when an event of
* the specified type occurs
*/
_createClass(Stream, [{
key: 'on',
value: function on(type, listener) {
if (!this.listeners[type]) {
this.listeners[type] = [];
}
this.listeners[type].push(listener);
}
/**
* Remove a listener for a specified event type.
*
* @param {String} type the event name
* @param {Function} listener a function previously registered for this
* type of event through `on`
* @return {Boolean} if we could turn it off or not
*/
}, {
key: 'off',
value: function off(type, listener) {
var index = undefined;
if (!this.listeners[type]) {
return false;
}
index = this.listeners[type].indexOf(listener);
this.listeners[type].splice(index, 1);
return index > -1;
}
/**
* Trigger an event of the specified type on this stream. Any additional
* arguments to this function are passed as parameters to event listeners.
*
* @param {String} type the event name
*/
}, {
key: 'trigger',
value: function trigger(type) {
var callbacks = undefined;
var i = undefined;
var length = undefined;
var args = undefined;
callbacks = this.listeners[type];
if (!callbacks) {
return;
}
// Slicing the arguments on every invocation of this method
// can add a significant amount of overhead. Avoid the
// intermediate object creation for the common case of a
// single callback argument
if (arguments.length === 2) {
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].call(this, arguments[1]);
}
} else {
args = Array.prototype.slice.call(arguments, 1);
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].apply(this, args);
}
}
}
/**
* Destroys the stream and cleans up.
*/
}, {
key: 'dispose',
value: function dispose() {
this.listeners = {};
}
/**
* Forwards all `data` events on this stream to the destination stream. The
* destination stream should provide a method `push` to receive the data
* events as they arrive.
*
* @param {Stream} destination the stream that will receive all `data` events
* @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
*/
}, {
key: 'pipe',
value: function pipe(destination) {
this.on('data', function (data) {
destination.push(data);
});
}
}]);
return Stream;
})();
exports['default'] = Stream;
module.exports = exports['default'];
},{}],6:[function(require,module,exports){
/*
* pkcs7.pad
* https://github.com/brightcove/pkcs7
*
* Copyright (c) 2014 Brightcove
* Licensed under the apache2 license.
*/
'use strict';
var PADDING;
/**
* Returns a new Uint8Array that is padded with PKCS#7 padding.
* @param plaintext {Uint8Array} the input bytes before encryption
* @return {Uint8Array} the padded bytes
* @see http://tools.ietf.org/html/rfc5652
*/
module.exports = function pad(plaintext) {
var padding = PADDING[(plaintext.byteLength % 16) || 0],
result = new Uint8Array(plaintext.byteLength + padding.length);
result.set(plaintext);
result.set(padding, plaintext.byteLength);
return result;
};
// pre-define the padding values
PADDING = [
[16, 16, 16, 16,
16, 16, 16, 16,
16, 16, 16, 16,
16, 16, 16, 16],
[15, 15, 15, 15,
15, 15, 15, 15,
15, 15, 15, 15,
15, 15, 15],
[14, 14, 14, 14,
14, 14, 14, 14,
14, 14, 14, 14,
14, 14],
[13, 13, 13, 13,
13, 13, 13, 13,
13, 13, 13, 13,
13],
[12, 12, 12, 12,
12, 12, 12, 12,
12, 12, 12, 12],
[11, 11, 11, 11,
11, 11, 11, 11,
11, 11, 11],
[10, 10, 10, 10,
10, 10, 10, 10,
10, 10],
[9, 9, 9, 9,
9, 9, 9, 9,
9],
[8, 8, 8, 8,
8, 8, 8, 8],
[7, 7, 7, 7,
7, 7, 7],
[6, 6, 6, 6,
6, 6],
[5, 5, 5, 5,
5],
[4, 4, 4, 4],
[3, 3, 3],
[2, 2],
[1]
];
},{}],7:[function(require,module,exports){
/*
* pkcs7
* https://github.com/brightcove/pkcs7
*
* Copyright (c) 2014 Brightcove
* Licensed under the apache2 license.
*/
'use strict';
exports.pad = require('./pad.js');
exports.unpad = require('./unpad.js');
},{"./pad.js":6,"./unpad.js":8}],8:[function(require,module,exports){
/*
* pkcs7.unpad
* https://github.com/brightcove/pkcs7
*
* Copyright (c) 2014 Brightcove
* Licensed under the apache2 license.
*/
'use strict';
/**
* Returns the subarray of a Uint8Array without PKCS#7 padding.
* @param padded {Uint8Array} unencrypted bytes that have been padded
* @return {Uint8Array} the unpadded bytes
* @see http://tools.ietf.org/html/rfc5652
*/
module.exports = function unpad(padded) {
return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
};
},{}],9:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2016 Brightcove
* All rights reserved.
*
* A stream-based aac to mp4 converter. This utility can be used to
* deliver mp4s to a SourceBuffer on platforms that support native
* Media Source Extensions.
*/
'use strict';
var Stream = require('../utils/stream.js');
// Constants
var AacStream;
/**
* Splits an incoming stream of binary data into ADTS and ID3 Frames.
*/
AacStream = function() {
var
everything = new Uint8Array(),
timeStamp = 0;
AacStream.prototype.init.call(this);
this.setTimestamp = function(timestamp) {
timeStamp = timestamp;
};
this.parseId3TagSize = function(header, byteIndex) {
var
returnSize = (header[byteIndex + 6] << 21) |
(header[byteIndex + 7] << 14) |
(header[byteIndex + 8] << 7) |
(header[byteIndex + 9]),
flags = header[byteIndex + 5],
footerPresent = (flags & 16) >> 4;
if (footerPresent) {
return returnSize + 20;
}
return returnSize + 10;
};
this.parseAdtsSize = function(header, byteIndex) {
var
lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
middle = header[byteIndex + 4] << 3,
highTwo = header[byteIndex + 3] & 0x3 << 11;
return (highTwo | middle) | lowThree;
};
this.push = function(bytes) {
var
frameSize = 0,
byteIndex = 0,
bytesLeft,
chunk,
packet,
tempLength;
// If there are bytes remaining from the last segment, prepend them to the
// bytes that were pushed in
if (everything.length) {
tempLength = everything.length;
everything = new Uint8Array(bytes.byteLength + tempLength);
everything.set(everything.subarray(0, tempLength));
everything.set(bytes, tempLength);
} else {
everything = bytes;
}
while (everything.length - byteIndex >= 3) {
if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
(everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
(everything[byteIndex + 2] === '3'.charCodeAt(0))) {
// Exit early because we don't have enough to parse
// the ID3 tag header
if (everything.length - byteIndex < 10) {
break;
}
// check framesize
frameSize = this.parseId3TagSize(everything, byteIndex);
// Exit early if we don't have enough in the buffer
// to emit a full packet
if (frameSize > everything.length) {
break;
}
chunk = {
type: 'timed-metadata',
data: everything.subarray(byteIndex, byteIndex + frameSize)
};
this.trigger('data', chunk);
byteIndex += frameSize;
continue;
} else if ((everything[byteIndex] & 0xff === 0xff) &&
((everything[byteIndex + 1] & 0xf0) === 0xf0)) {
// Exit early because we don't have enough to parse
// the ADTS frame header
if (everything.length - byteIndex < 7) {
break;
}
frameSize = this.parseAdtsSize(everything, byteIndex);
// Exit early if we don't have enough in the buffer
// to emit a full packet
if (frameSize > everything.length) {
break;
}
packet = {
type: 'audio',
data: everything.subarray(byteIndex, byteIndex + frameSize),
pts: timeStamp,
dts: timeStamp
};
this.trigger('data', packet);
byteIndex += frameSize;
continue;
}
byteIndex++;
}
bytesLeft = everything.length - byteIndex;
if (bytesLeft > 0) {
everything = everything.subarray(byteIndex);
} else {
everything = new Uint8Array();
}
};
};
AacStream.prototype = new Stream();
module.exports = AacStream;
},{"../utils/stream.js":27}],10:[function(require,module,exports){
'use strict';
var Stream = require('../utils/stream.js');
var AdtsStream;
var
ADTS_SAMPLING_FREQUENCIES = [
96000,
88200,
64000,
48000,
44100,
32000,
24000,
22050,
16000,
12000,
11025,
8000,
7350
];
/*
* Accepts a ElementaryStream and emits data events with parsed
* AAC Audio Frames of the individual packets. Input audio in ADTS
* format is unpacked and re-emitted as AAC frames.
*
* @see http://wiki.multimedia.cx/index.php?title=ADTS
* @see http://wiki.multimedia.cx/?title=Understanding_AAC
*/
AdtsStream = function() {
var buffer;
AdtsStream.prototype.init.call(this);
this.push = function(packet) {
var
i = 0,
frameNum = 0,
frameLength,
protectionSkipBytes,
frameEnd,
oldBuffer,
sampleCount,
adtsFrameDuration;
if (packet.type !== 'audio') {
// ignore non-audio data
return;
}
// Prepend any data in the buffer to the input data so that we can parse
// aac frames the cross a PES packet boundary
if (buffer) {
oldBuffer = buffer;
buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
buffer.set(oldBuffer);
buffer.set(packet.data, oldBuffer.byteLength);
} else {
buffer = packet.data;
}
// unpack any ADTS frames which have been fully received
// for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
while (i + 5 < buffer.length) {
// Loook for the start of an ADTS header..
if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
// If a valid header was not found, jump one forward and attempt to
// find a valid ADTS header starting at the next byte
i++;
continue;
}
// The protection skip bit tells us if we have 2 bytes of CRC data at the
// end of the ADTS header
protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;
// Frame length is a 13 bit integer starting 16 bits from the
// end of the sync sequence
frameLength = ((buffer[i + 3] & 0x03) << 11) |
(buffer[i + 4] << 3) |
((buffer[i + 5] & 0xe0) >> 5);
sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
adtsFrameDuration = (sampleCount * 90000) /
ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
frameEnd = i + frameLength;
// If we don't have enough data to actually finish this ADTS frame, return
// and wait for more data
if (buffer.byteLength < frameEnd) {
return;
}
// Otherwise, deliver the complete AAC frame
this.trigger('data', {
pts: packet.pts + (frameNum * adtsFrameDuration),
dts: packet.dts + (frameNum * adtsFrameDuration),
sampleCount: sampleCount,
audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
channelcount: ((buffer[i + 2] & 1) << 2) |
((buffer[i + 3] & 0xc0) >>> 6),
samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
// assume ISO/IEC 14496-12 AudioSampleEntry default of 16
samplesize: 16,
data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
});
// If the buffer is empty, clear it and return
if (buffer.byteLength === frameEnd) {
buffer = undefined;
return;
}
frameNum++;
// Remove the finished frame from the buffer and start the process again
buffer = buffer.subarray(frameEnd);
}
};
this.flush = function() {
this.trigger('done');
};
};
AdtsStream.prototype = new Stream();
module.exports = AdtsStream;
},{"../utils/stream.js":27}],11:[function(require,module,exports){
'use strict';
var Stream = require('../utils/stream.js');
var ExpGolomb = require('../utils/exp-golomb.js');
var H264Stream, NalByteStream;
var PROFILES_WITH_OPTIONAL_SPS_DATA;
/**
* Accepts a NAL unit byte stream and unpacks the embedded NAL units.
*/
NalByteStream = function() {
var
syncPoint = 0,
i,
buffer;
NalByteStream.prototype.init.call(this);
this.push = function(data) {
var swapBuffer;
if (!buffer) {
buffer = data.data;
} else {
swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
swapBuffer.set(buffer);
swapBuffer.set(data.data, buffer.byteLength);
buffer = swapBuffer;
}
// Rec. ITU-T H.264, Annex B
// scan for NAL unit boundaries
// a match looks like this:
// 0 0 1 .. NAL .. 0 0 1
// ^ sync point ^ i
// or this:
// 0 0 1 .. NAL .. 0 0 0
// ^ sync point ^ i
// advance the sync point to a NAL start, if necessary
for (; syncPoint < buffer.byteLength - 3; syncPoint++) {
if (buffer[syncPoint + 2] === 1) {
// the sync point is properly aligned
i = syncPoint + 5;
break;
}
}
while (i < buffer.byteLength) {
// look at the current byte to determine if we've hit the end of
// a NAL unit boundary
switch (buffer[i]) {
case 0:
// skip past non-sync sequences
if (buffer[i - 1] !== 0) {
i += 2;
break;
} else if (buffer[i - 2] !== 0) {
i++;
break;
}
// deliver the NAL unit if it isn't empty
if (syncPoint + 3 !== i - 2) {
this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
}
// drop trailing zeroes
do {
i++;
} while (buffer[i] !== 1 && i < buffer.length);
syncPoint = i - 2;
i += 3;
break;
case 1:
// skip past non-sync sequences
if (buffer[i - 1] !== 0 ||
buffer[i - 2] !== 0) {
i += 3;
break;
}
// deliver the NAL unit
this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
syncPoint = i - 2;
i += 3;
break;
default:
// the current byte isn't a one or zero, so it cannot be part
// of a sync sequence
i += 3;
break;
}
}
// filter out the NAL units that were delivered
buffer = buffer.subarray(syncPoint);
i -= syncPoint;
syncPoint = 0;
};
this.flush = function() {
// deliver the last buffered NAL unit
if (buffer && buffer.byteLength > 3) {
this.trigger('data', buffer.subarray(syncPoint + 3));
}
// reset the stream state
buffer = null;
syncPoint = 0;
this.trigger('done');
};
};
NalByteStream.prototype = new Stream();
// values of profile_idc that indicate additional fields are included in the SPS
// see Recommendation ITU-T H.264 (4/2013),
// 7.3.2.1.1 Sequence parameter set data syntax
PROFILES_WITH_OPTIONAL_SPS_DATA = {
100: true,
110: true,
122: true,
244: true,
44: true,
83: true,
86: true,
118: true,
128: true,
138: true,
139: true,
134: true
};
/**
* Accepts input from a ElementaryStream and produces H.264 NAL unit data
* events.
*/
H264Stream = function() {
var
nalByteStream = new NalByteStream(),
self,
trackId,
currentPts,
currentDts,
discardEmulationPreventionBytes,
readSequenceParameterSet,
skipScalingList;
H264Stream.prototype.init.call(this);
self = this;
this.push = function(packet) {
if (packet.type !== 'video') {
return;
}
trackId = packet.trackId;
currentPts = packet.pts;
currentDts = packet.dts;
nalByteStream.push(packet);
};
nalByteStream.on('data', function(data) {
var
event = {
trackId: trackId,
pts: currentPts,
dts: currentDts,
data: data
};
switch (data[0] & 0x1f) {
case 0x05:
event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
break;
case 0x06:
event.nalUnitType = 'sei_rbsp';
event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
break;
case 0x07:
event.nalUnitType = 'seq_parameter_set_rbsp';
event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
event.config = readSequenceParameterSet(event.escapedRBSP);
break;
case 0x08:
event.nalUnitType = 'pic_parameter_set_rbsp';
break;
case 0x09:
event.nalUnitType = 'access_unit_delimiter_rbsp';
break;
default:
break;
}
self.trigger('data', event);
});
nalByteStream.on('done', function() {
self.trigger('done');
});
this.flush = function() {
nalByteStream.flush();
};
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count {number} the number of entries in this scaling list
* @param expGolombDecoder {object} an ExpGolomb pointed to the
* start of a scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
skipScalingList = function(count, expGolombDecoder) {
var
lastScale = 8,
nextScale = 8,
j,
deltaScale;
for (j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = expGolombDecoder.readExpGolomb();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = (nextScale === 0) ? lastScale : nextScale;
}
};
/**
* Expunge any "Emulation Prevention" bytes from a "Raw Byte
* Sequence Payload"
* @param data {Uint8Array} the bytes of a RBSP from a NAL
* unit
* @return {Uint8Array} the RBSP without any Emulation
* Prevention Bytes
*/
discardEmulationPreventionBytes = function(data) {
var
length = data.byteLength,
emulationPreventionBytesPositions = [],
i = 1,
newLength, newData;
// Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
emulationPreventionBytesPositions.push(i + 2);
i += 2;
} else {
i++;
}
}
// If no Emulation Prevention Bytes were found just return the original
// array
if (emulationPreventionBytesPositions.length === 0) {
return data;
}
// Create a new array to hold the NAL unit data
newLength = length - emulationPreventionBytesPositions.length;
newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === emulationPreventionBytesPositions[0]) {
// Skip this byte
sourceIndex++;
// Remove this position index
emulationPreventionBytesPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
};
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
readSequenceParameterSet = function(data) {
var
frameCropLeftOffset = 0,
frameCropRightOffset = 0,
frameCropTopOffset = 0,
frameCropBottomOffset = 0,
sarScale = 1,
expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
chromaFormatIdc, picOrderCntType,
numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
picHeightInMapUnitsMinus1,
frameMbsOnlyFlag,
scalingListCount,
sarRatio,
aspectRatioIdc,
i;
expGolombDecoder = new ExpGolomb(data);
profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
if (chromaFormatIdc === 3) {
expGolombDecoder.skipBits(1); // separate_colour_plane_flag
}
expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16, expGolombDecoder);
} else {
skipScalingList(64, expGolombDecoder);
}
}
}
}
}
expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
if (picOrderCntType === 0) {
expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
}
}
expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
frameMbsOnlyFlag = expGolombDecoder.readBits(1);
if (frameMbsOnlyFlag === 0) {
expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
}
expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
}
if (expGolombDecoder.readBoolean()) {
// vui_parameters_present_flag
if (expGolombDecoder.readBoolean()) {
// aspect_ratio_info_present_flag
aspectRatioIdc = expGolombDecoder.readUnsignedByte();
switch (aspectRatioIdc) {
case 1: sarRatio = [1, 1]; break;
case 2: sarRatio = [12, 11]; break;
case 3: sarRatio = [10, 11]; break;
case 4: sarRatio = [16, 11]; break;
case 5: sarRatio = [40, 33]; break;
case 6: sarRatio = [24, 11]; break;
case 7: sarRatio = [20, 11]; break;
case 8: sarRatio = [32, 11]; break;
case 9: sarRatio = [80, 33]; break;
case 10: sarRatio = [18, 11]; break;
case 11: sarRatio = [15, 11]; break;
case 12: sarRatio = [64, 33]; break;
case 13: sarRatio = [160, 99]; break;
case 14: sarRatio = [4, 3]; break;
case 15: sarRatio = [3, 2]; break;
case 16: sarRatio = [2, 1]; break;
case 255: {
sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
expGolombDecoder.readUnsignedByte(),
expGolombDecoder.readUnsignedByte() << 8 |
expGolombDecoder.readUnsignedByte() ];
break;
}
}
if (sarRatio) {
sarScale = sarRatio[0] / sarRatio[1];
}
}
}
return {
profileIdc: profileIdc,
levelIdc: levelIdc,
profileCompatibility: profileCompatibility,
width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2)
};
};
};
H264Stream.prototype = new Stream();
module.exports = {
H264Stream: H264Stream,
NalByteStream: NalByteStream
};
},{"../utils/exp-golomb.js":26,"../utils/stream.js":27}],12:[function(require,module,exports){
'use strict';
var Stream = require('../utils/stream.js');
/**
* The final stage of the transmuxer that emits the flv tags
* for audio, video, and metadata. Also tranlates in time and
* outputs caption data and id3 cues.
*/
var CoalesceStream = function(options) {
// Number of Tracks per output segment
// If greater than 1, we combine multiple
// tracks into a single segment
this.numberOfTracks = 0;
this.metadataStream = options.metadataStream;
this.videoTags = [];
this.audioTags = [];
this.videoTrack = null;
this.audioTrack = null;
this.pendingCaptions = [];
this.pendingMetadata = [];
this.pendingTracks = 0;
this.processedTracks = 0;
CoalesceStream.prototype.init.call(this);
// Take output from multiple
this.push = function(output) {
// buffer incoming captions until the associated video segment
// finishes
if (output.text) {
return this.pendingCaptions.push(output);
}
// buffer incoming id3 tags until the final flush
if (output.frames) {
return this.pendingMetadata.push(output);
}
if (output.track.type === 'video') {
this.videoTrack = output.track;
this.videoTags = output.tags;
this.pendingTracks++;
}
if (output.track.type === 'audio') {
this.audioTrack = output.track;
this.audioTags = output.tags;
this.pendingTracks++;
}
};
};
CoalesceStream.prototype = new Stream();
CoalesceStream.prototype.flush = function(flushSource) {
var
id3,
caption,
i,
timelineStartPts,
event = {
tags: {},
captions: [],
metadata: []
};
if (this.pendingTracks < this.numberOfTracks) {
if (flushSource !== 'VideoSegmentStream' &&
flushSource !== 'AudioSegmentStream') {
// Return because we haven't received a flush from a data-generating
// portion of the segment (meaning that we have only recieved meta-data
// or captions.)
return;
} else if (this.pendingTracks === 0) {
// In the case where we receive a flush without any data having been
// received we consider it an emitted track for the purposes of coalescing
// `done` events.
// We do this for the case where there is an audio and video track in the
// segment but no audio data. (seen in several playlists with alternate
// audio tracks and no audio present in the main TS segments.)
this.processedTracks++;
if (this.processedTracks < this.numberOfTracks) {
return;
}
}
}
this.processedTracks += this.pendingTracks;
this.pendingTracks = 0;
if (this.processedTracks < this.numberOfTracks) {
return;
}
if (this.videoTrack) {
timelineStartPts = this.videoTrack.timelineStartInfo.pts;
} else if (this.audioTrack) {
timelineStartPts = this.audioTrack.timelineStartInfo.pts;
}
event.tags.videoTags = this.videoTags;
event.tags.audioTags = this.audioTags;
// Translate caption PTS times into second offsets into the
// video timeline for the segment
for (i = 0; i < this.pendingCaptions.length; i++) {
caption = this.pendingCaptions[i];
caption.startTime = caption.startPts - timelineStartPts;
caption.startTime /= 90e3;
caption.endTime = caption.endPts - timelineStartPts;
caption.endTime /= 90e3;
event.captions.push(caption);
}
// Translate ID3 frame PTS times into second offsets into the
// video timeline for the segment
for (i = 0; i < this.pendingMetadata.length; i++) {
id3 = this.pendingMetadata[i];
id3.cueTime = id3.pts - timelineStartPts;
id3.cueTime /= 90e3;
event.metadata.push(id3);
}
// We add this to every single emitted segment even though we only need
// it for the first
event.metadata.dispatchType = this.metadataStream.dispatchType;
// Reset stream state
this.videoTrack = null;
this.audioTrack = null;
this.videoTags = [];
this.audioTags = [];
this.pendingCaptions.length = 0;
this.pendingMetadata.length = 0;
this.pendingTracks = 0;
this.processedTracks = 0;
// Emit the final segment
this.trigger('data', event);
this.trigger('done');
};
module.exports = CoalesceStream;
},{"../utils/stream.js":27}],13:[function(require,module,exports){
/**
* An object that stores the bytes of an FLV tag and methods for
* querying and manipulating that data.
* @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf
*/
'use strict';
var FlvTag;
// (type:uint, extraData:Boolean = false) extends ByteArray
FlvTag = function(type, extraData) {
var
// Counter if this is a metadata tag, nal start marker if this is a video
// tag. unused if this is an audio tag
adHoc = 0, // :uint
// The default size is 16kb but this is not enough to hold iframe
// data and the resizing algorithm costs a bit so we create a larger
// starting buffer for video tags
bufferStartSize = 16384,
// checks whether the FLV tag has enough capacity to accept the proposed
// write and re-allocates the internal buffers if necessary
prepareWrite = function(flv, count) {
var
bytes,
minLength = flv.position + count;
if (minLength < flv.bytes.byteLength) {
// there's enough capacity so do nothing
return;
}
// allocate a new buffer and copy over the data that will not be modified
bytes = new Uint8Array(minLength * 2);
bytes.set(flv.bytes.subarray(0, flv.position), 0);
flv.bytes = bytes;
flv.view = new DataView(flv.bytes.buffer);
},
// commonly used metadata properties
widthBytes = FlvTag.widthBytes || new Uint8Array('width'.length),
heightBytes = FlvTag.heightBytes || new Uint8Array('height'.length),
videocodecidBytes = FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length),
i;
if (!FlvTag.widthBytes) {
// calculating the bytes of common metadata names ahead of time makes the
// corresponding writes faster because we don't have to loop over the
// characters
// re-test with test/perf.html if you're planning on changing this
for (i = 0; i < 'width'.length; i++) {
widthBytes[i] = 'width'.charCodeAt(i);
}
for (i = 0; i < 'height'.length; i++) {
heightBytes[i] = 'height'.charCodeAt(i);
}
for (i = 0; i < 'videocodecid'.length; i++) {
videocodecidBytes[i] = 'videocodecid'.charCodeAt(i);
}
FlvTag.widthBytes = widthBytes;
FlvTag.heightBytes = heightBytes;
FlvTag.videocodecidBytes = videocodecidBytes;
}
this.keyFrame = false; // :Boolean
switch (type) {
case FlvTag.VIDEO_TAG:
this.length = 16;
// Start the buffer at 256k
bufferStartSize *= 6;
break;
case FlvTag.AUDIO_TAG:
this.length = 13;
this.keyFrame = true;
break;
case FlvTag.METADATA_TAG:
this.length = 29;
this.keyFrame = true;
break;
default:
throw new Error('Unknown FLV tag type');
}
this.bytes = new Uint8Array(bufferStartSize);
this.view = new DataView(this.bytes.buffer);
this.bytes[0] = type;
this.position = this.length;
this.keyFrame = extraData; // Defaults to false
// presentation timestamp
this.pts = 0;
// decoder timestamp
this.dts = 0;
// ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)
this.writeBytes = function(bytes, offset, length) {
var
start = offset || 0,
end;
length = length || bytes.byteLength;
end = start + length;
prepareWrite(this, length);
this.bytes.set(bytes.subarray(start, end), this.position);
this.position += length;
this.length = Math.max(this.length, this.position);
};
// ByteArray#writeByte(value:int):void
this.writeByte = function(byte) {
prepareWrite(this, 1);
this.bytes[this.position] = byte;
this.position++;
this.length = Math.max(this.length, this.position);
};
// ByteArray#writeShort(value:int):void
this.writeShort = function(short) {
prepareWrite(this, 2);
this.view.setUint16(this.position, short);
this.position += 2;
this.length = Math.max(this.length, this.position);
};
// Negative index into array
// (pos:uint):int
this.negIndex = function(pos) {
return this.bytes[this.length - pos];
};
// The functions below ONLY work when this[0] == VIDEO_TAG.
// We are not going to check for that because we dont want the overhead
// (nal:ByteArray = null):int
this.nalUnitSize = function() {
if (adHoc === 0) {
return 0;
}
return this.length - (adHoc + 4);
};
this.startNalUnit = function() {
// remember position and add 4 bytes
if (adHoc > 0) {
throw new Error('Attempted to create new NAL wihout closing the old one');
}
// reserve 4 bytes for nal unit size
adHoc = this.length;
this.length += 4;
this.position = this.length;
};
// (nal:ByteArray = null):void
this.endNalUnit = function(nalContainer) {
var
nalStart, // :uint
nalLength; // :uint
// Rewind to the marker and write the size
if (this.length === adHoc + 4) {
// we started a nal unit, but didnt write one, so roll back the 4 byte size value
this.length -= 4;
} else if (adHoc > 0) {
nalStart = adHoc + 4;
nalLength = this.length - nalStart;
this.position = adHoc;
this.view.setUint32(this.position, nalLength);
this.position = this.length;
if (nalContainer) {
// Add the tag to the NAL unit
nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength));
}
}
adHoc = 0;
};
/**
* Write out a 64-bit floating point valued metadata property. This method is
* called frequently during a typical parse and needs to be fast.
*/
// (key:String, val:Number):void
this.writeMetaDataDouble = function(key, val) {
var i;
prepareWrite(this, 2 + key.length + 9);
// write size of property name
this.view.setUint16(this.position, key.length);
this.position += 2;
// this next part looks terrible but it improves parser throughput by
// 10kB/s in my testing
// write property name
if (key === 'width') {
this.bytes.set(widthBytes, this.position);
this.position += 5;
} else if (key === 'height') {
this.bytes.set(heightBytes, this.position);
this.position += 6;
} else if (key === 'videocodecid') {
this.bytes.set(videocodecidBytes, this.position);
this.position += 12;
} else {
for (i = 0; i < key.length; i++) {
this.bytes[this.position] = key.charCodeAt(i);
this.position++;
}
}
// skip null byte
this.position++;
// write property value
this.view.setFloat64(this.position, val);
this.position += 8;
// update flv tag length
this.length = Math.max(this.length, this.position);
++adHoc;
};
// (key:String, val:Boolean):void
this.writeMetaDataBoolean = function(key, val) {
var i;
prepareWrite(this, 2);
this.view.setUint16(this.position, key.length);
this.position += 2;
for (i = 0; i < key.length; i++) {
// if key.charCodeAt(i) >= 255, handle error
prepareWrite(this, 1);
this.bytes[this.position] = key.charCodeAt(i);
this.position++;
}
prepareWrite(this, 2);
this.view.setUint8(this.position, 0x01);
this.position++;
this.view.setUint8(this.position, val ? 0x01 : 0x00);
this.position++;
this.length = Math.max(this.length, this.position);
++adHoc;
};
// ():ByteArray
this.finalize = function() {
var
dtsDelta, // :int
len; // :int
switch (this.bytes[0]) {
// Video Data
case FlvTag.VIDEO_TAG:
// We only support AVC, 1 = key frame (for AVC, a seekable
// frame), 2 = inter frame (for AVC, a non-seekable frame)
this.bytes[11] = ((this.keyFrame || extraData) ? 0x10 : 0x20) | 0x07;
this.bytes[12] = extraData ? 0x00 : 0x01;
dtsDelta = this.pts - this.dts;
this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16;
this.bytes[14] = (dtsDelta & 0x0000FF00) >>> 8;
this.bytes[15] = (dtsDelta & 0x000000FF) >>> 0;
break;
case FlvTag.AUDIO_TAG:
this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo
this.bytes[12] = extraData ? 0x00 : 0x01;
break;
case FlvTag.METADATA_TAG:
this.position = 11;
this.view.setUint8(this.position, 0x02); // String type
this.position++;
this.view.setUint16(this.position, 0x0A); // 10 Bytes
this.position += 2;
// set "onMetaData"
this.bytes.set([0x6f, 0x6e, 0x4d, 0x65,
0x74, 0x61, 0x44, 0x61,
0x74, 0x61], this.position);
this.position += 10;
this.bytes[this.position] = 0x08; // Array type
this.position++;
this.view.setUint32(this.position, adHoc);
this.position = this.length;
this.bytes.set([0, 0, 9], this.position);
this.position += 3; // End Data Tag
this.length = this.position;
break;
}
len = this.length - 11;
// write the DataSize field
this.bytes[ 1] = (len & 0x00FF0000) >>> 16;
this.bytes[ 2] = (len & 0x0000FF00) >>> 8;
this.bytes[ 3] = (len & 0x000000FF) >>> 0;
// write the Timestamp
this.bytes[ 4] = (this.dts & 0x00FF0000) >>> 16;
this.bytes[ 5] = (this.dts & 0x0000FF00) >>> 8;
this.bytes[ 6] = (this.dts & 0x000000FF) >>> 0;
this.bytes[ 7] = (this.dts & 0xFF000000) >>> 24;
// write the StreamID
this.bytes[ 8] = 0;
this.bytes[ 9] = 0;
this.bytes[10] = 0;
// Sometimes we're at the end of the view and have one slot to write a
// uint32, so, prepareWrite of count 4, since, view is uint8
prepareWrite(this, 4);
this.view.setUint32(this.length, this.length);
this.length += 4;
this.position += 4;
// trim down the byte buffer to what is actually being used
this.bytes = this.bytes.subarray(0, this.length);
this.frameTime = FlvTag.frameTime(this.bytes);
// if bytes.bytelength isn't equal to this.length, handle error
return this;
};
};
FlvTag.AUDIO_TAG = 0x08; // == 8, :uint
FlvTag.VIDEO_TAG = 0x09; // == 9, :uint
FlvTag.METADATA_TAG = 0x12; // == 18, :uint
// (tag:ByteArray):Boolean {
FlvTag.isAudioFrame = function(tag) {
return FlvTag.AUDIO_TAG === tag[0];
};
// (tag:ByteArray):Boolean {
FlvTag.isVideoFrame = function(tag) {
return FlvTag.VIDEO_TAG === tag[0];
};
// (tag:ByteArray):Boolean {
FlvTag.isMetaData = function(tag) {
return FlvTag.METADATA_TAG === tag[0];
};
// (tag:ByteArray):Boolean {
FlvTag.isKeyFrame = function(tag) {
if (FlvTag.isVideoFrame(tag)) {
return tag[11] === 0x17;
}
if (FlvTag.isAudioFrame(tag)) {
return true;
}
if (FlvTag.isMetaData(tag)) {
return true;
}
return false;
};
// (tag:ByteArray):uint {
FlvTag.frameTime = function(tag) {
var pts = tag[ 4] << 16; // :uint
pts |= tag[ 5] << 8;
pts |= tag[ 6] << 0;
pts |= tag[ 7] << 24;
return pts;
};
module.exports = FlvTag;
},{}],14:[function(require,module,exports){
var transmuxer = require('./transmuxer');
module.exports = {
tag: require('./flv-tag'),
Transmuxer: transmuxer.Transmuxer,
getFlvHeader: transmuxer.getFlvHeader
};
},{"./flv-tag":13,"./transmuxer":16}],15:[function(require,module,exports){
'use strict';
var TagList = function() {
this.list = [];
this.push = function(tag) {
this.list.push({
bytes: tag.bytes,
dts: tag.dts,
pts: tag.pts
});
}
};
module.exports = TagList;
},{}],16:[function(require,module,exports){
'use strict';
var Stream = require('../utils/stream.js');
var FlvTag = require('./flv-tag.js');
var m2ts = require('../m2ts/m2ts.js');
var AdtsStream = require('../codecs/adts.js');
var H264Stream = require('../codecs/h264').H264Stream;
var CoalesceStream = require('./coalesce-stream.js');
var TagList = require('./tag-list.js');
var
Transmuxer,
VideoSegmentStream,
AudioSegmentStream,
collectTimelineInfo,
metaDataTag,
extraDataTag;
/**
* Store information about the start and end of the tracka and the
* duration for each frame/sample we process in order to calculate
* the baseMediaDecodeTime
*/
collectTimelineInfo = function(track, data) {
if (typeof data.pts === 'number') {
if (track.timelineStartInfo.pts === undefined) {
track.timelineStartInfo.pts = data.pts;
} else {
track.timelineStartInfo.pts =
Math.min(track.timelineStartInfo.pts, data.pts);
}
}
if (typeof data.dts === 'number') {
if (track.timelineStartInfo.dts === undefined) {
track.timelineStartInfo.dts = data.dts;
} else {
track.timelineStartInfo.dts =
Math.min(track.timelineStartInfo.dts, data.dts);
}
}
};
metaDataTag = function(track, pts) {
var
tag = new FlvTag(FlvTag.METADATA_TAG); // :FlvTag
tag.dts = pts;
tag.pts = pts;
tag.writeMetaDataDouble('videocodecid', 7);
tag.writeMetaDataDouble('width', track.width);
tag.writeMetaDataDouble('height', track.height);
return tag;
};
extraDataTag = function(track, pts) {
var
i,
tag = new FlvTag(FlvTag.VIDEO_TAG, true);
tag.dts = pts;
tag.pts = pts;
tag.writeByte(0x01);// version
tag.writeByte(track.profileIdc);// profile
tag.writeByte(track.profileCompatibility);// compatibility
tag.writeByte(track.levelIdc);// level
tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits)
tag.writeByte(0xE0 | 0x01); // reserved (3 bits), num of SPS (5 bits)
tag.writeShort(track.sps[0].length); // data of SPS
tag.writeBytes(track.sps[0]); // SPS
tag.writeByte(track.pps.length); // num of PPS (will there ever be more that 1 PPS?)
for (i = 0; i < track.pps.length; ++i) {
tag.writeShort(track.pps[i].length); // 2 bytes for length of PPS
tag.writeBytes(track.pps[i]); // data of PPS
}
return tag;
};
/**
* Constructs a single-track, media segment from AAC data
* events. The output of this stream can be fed to flash.
*/
AudioSegmentStream = function(track) {
var
adtsFrames = [],
oldExtraData;
AudioSegmentStream.prototype.init.call(this);
this.push = function(data) {
collectTimelineInfo(track, data);
if (track && track.channelcount === undefined) {
track.audioobjecttype = data.audioobjecttype;
track.channelcount = data.channelcount;
track.samplerate = data.samplerate;
track.samplingfrequencyindex = data.samplingfrequencyindex;
track.samplesize = data.samplesize;
track.extraData = (track.audioobjecttype << 11) |
(track.samplingfrequencyindex << 7) |
(track.channelcount << 3);
}
data.pts = Math.round(data.pts / 90);
data.dts = Math.round(data.dts / 90);
// buffer audio data until end() is called
adtsFrames.push(data);
};
this.flush = function() {
var currentFrame, adtsFrame, lastMetaPts, tags = new TagList();
// return early if no audio data has been observed
if (adtsFrames.length === 0) {
this.trigger('done', 'AudioSegmentStream');
return;
}
lastMetaPts = -Infinity;
while (adtsFrames.length) {
currentFrame = adtsFrames.shift();
// write out metadata tags every 1 second so that the decoder
// is re-initialized quickly after seeking into a different
// audio configuration
if (track.extraData !== oldExtraData || currentFrame.pts - lastMetaPts >= 1000) {
adtsFrame = new FlvTag(FlvTag.METADATA_TAG);
adtsFrame.pts = currentFrame.pts;
adtsFrame.dts = currentFrame.dts;
// AAC is always 10
adtsFrame.writeMetaDataDouble('audiocodecid', 10);
adtsFrame.writeMetaDataBoolean('stereo', track.channelcount === 2);
adtsFrame.writeMetaDataDouble('audiosamplerate', track.samplerate);
// Is AAC always 16 bit?
adtsFrame.writeMetaDataDouble('audiosamplesize', 16);
tags.push(adtsFrame.finalize());
oldExtraData = track.extraData;
adtsFrame = new FlvTag(FlvTag.AUDIO_TAG, true);
// For audio, DTS is always the same as PTS. We want to set the DTS
// however so we can compare with video DTS to determine approximate
// packet order
adtsFrame.pts = currentFrame.pts;
adtsFrame.dts = currentFrame.dts;
adtsFrame.view.setUint16(adtsFrame.position, track.extraData);
adtsFrame.position += 2;
adtsFrame.length = Math.max(adtsFrame.length, adtsFrame.position);
tags.push(adtsFrame.finalize());
lastMetaPts = currentFrame.pts;
}
adtsFrame = new FlvTag(FlvTag.AUDIO_TAG);
adtsFrame.pts = currentFrame.pts;
adtsFrame.dts = currentFrame.dts;
adtsFrame.writeBytes(currentFrame.data);
tags.push(adtsFrame.finalize());
}
oldExtraData = null;
this.trigger('data', {track: track, tags: tags.list});
this.trigger('done', 'AudioSegmentStream');
};
};
AudioSegmentStream.prototype = new Stream();
/**
* Store FlvTags for the h264 stream
* @param track {object} track metadata configuration
*/
VideoSegmentStream = function(track) {
var
nalUnits = [],
config,
h264Frame;
VideoSegmentStream.prototype.init.call(this);
this.finishFrame = function(tags, frame) {
if (!frame) {
return;
}
// Check if keyframe and the length of tags.
// This makes sure we write metadata on the first frame of a segment.
if (config && track && track.newMetadata &&
(frame.keyFrame || tags.length === 0)) {
// Push extra data on every IDR frame in case we did a stream change + seek
tags.push(metaDataTag(config, frame.dts).finalize());
tags.push(extraDataTag(track, frame.dts).finalize());
track.newMetadata = false;
}
frame.endNalUnit();
tags.push(frame.finalize());
h264Frame = null;
};
this.push = function(data) {
collectTimelineInfo(track, data);
data.pts = Math.round(data.pts / 90);
data.dts = Math.round(data.dts / 90);
// buffer video until flush() is called
nalUnits.push(data);
};
this.flush = function() {
var
currentNal,
tags = new TagList();
// Throw away nalUnits at the start of the byte stream until we find
// the first AUD
while (nalUnits.length) {
if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
break;
}
nalUnits.shift();
}
// return early if no video data has been observed
if (nalUnits.length === 0) {
this.trigger('done', 'VideoSegmentStream');
return;
}
while (nalUnits.length) {
currentNal = nalUnits.shift();
// record the track config
if (currentNal.nalUnitType === 'seq_parameter_set_rbsp') {
track.newMetadata = true;
config = currentNal.config;
track.width = config.width;
track.height = config.height;
track.sps = [currentNal.data];
track.profileIdc = config.profileIdc;
track.levelIdc = config.levelIdc;
track.profileCompatibility = config.profileCompatibility;
h264Frame.endNalUnit();
} else if (currentNal.nalUnitType === 'pic_parameter_set_rbsp') {
track.newMetadata = true;
track.pps = [currentNal.data];
h264Frame.endNalUnit();
} else if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
if (h264Frame) {
this.finishFrame(tags, h264Frame);
}
h264Frame = new FlvTag(FlvTag.VIDEO_TAG);
h264Frame.pts = currentNal.pts;
h264Frame.dts = currentNal.dts;
} else {
if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
// the current sample is a key frame
h264Frame.keyFrame = true;
}
h264Frame.endNalUnit();
}
h264Frame.startNalUnit();
h264Frame.writeBytes(currentNal.data);
}
if (h264Frame) {
this.finishFrame(tags, h264Frame);
}
this.trigger('data', {track: track, tags: tags.list});
// Continue with the flush process now
this.trigger('done', 'VideoSegmentStream');
};
};
VideoSegmentStream.prototype = new Stream();
/**
* An object that incrementally transmuxes MPEG2 Trasport Stream
* chunks into an FLV.
*/
Transmuxer = function(options) {
var
self = this,
packetStream, parseStream, elementaryStream,
videoTimestampRolloverStream, audioTimestampRolloverStream,
timedMetadataTimestampRolloverStream,
adtsStream, h264Stream,
videoSegmentStream, audioSegmentStream, captionStream,
coalesceStream;
Transmuxer.prototype.init.call(this);
options = options || {};
// expose the metadata stream
this.metadataStream = new m2ts.MetadataStream();
options.metadataStream = this.metadataStream;
// set up the parsing pipeline
packetStream = new m2ts.TransportPacketStream();
parseStream = new m2ts.TransportParseStream();
elementaryStream = new m2ts.ElementaryStream();
videoTimestampRolloverStream = new m2ts.TimestampRolloverStream('video');
audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
adtsStream = new AdtsStream();
h264Stream = new H264Stream();
coalesceStream = new CoalesceStream(options);
// disassemble MPEG2-TS packets into elementary streams
packetStream
.pipe(parseStream)
.pipe(elementaryStream);
// !!THIS ORDER IS IMPORTANT!!
// demux the streams
elementaryStream
.pipe(videoTimestampRolloverStream)
.pipe(h264Stream);
elementaryStream
.pipe(audioTimestampRolloverStream)
.pipe(adtsStream);
elementaryStream
.pipe(timedMetadataTimestampRolloverStream)
.pipe(this.metadataStream)
.pipe(coalesceStream);
// if CEA-708 parsing is available, hook up a caption stream
captionStream = new m2ts.CaptionStream();
h264Stream.pipe(captionStream)
.pipe(coalesceStream);
// hook up the segment streams once track metadata is delivered
elementaryStream.on('data', function(data) {
var i, videoTrack, audioTrack;
if (data.type === 'metadata') {
i = data.tracks.length;
// scan the tracks listed in the metadata
while (i--) {
if (data.tracks[i].type === 'video') {
videoTrack = data.tracks[i];
} else if (data.tracks[i].type === 'audio') {
audioTrack = data.tracks[i];
}
}
// hook up the video segment stream to the first track with h264 data
if (videoTrack && !videoSegmentStream) {
coalesceStream.numberOfTracks++;
videoSegmentStream = new VideoSegmentStream(videoTrack);
// Set up the final part of the video pipeline
h264Stream
.pipe(videoSegmentStream)
.pipe(coalesceStream);
}
if (audioTrack && !audioSegmentStream) {
// hook up the audio segment stream to the first track with aac data
coalesceStream.numberOfTracks++;
audioSegmentStream = new AudioSegmentStream(audioTrack);
// Set up the final part of the audio pipeline
adtsStream
.pipe(audioSegmentStream)
.pipe(coalesceStream);
}
}
});
// feed incoming data to the front of the parsing pipeline
this.push = function(data) {
packetStream.push(data);
};
// flush any buffered data
this.flush = function() {
// Start at the top of the pipeline and flush all pending work
packetStream.flush();
};
// Re-emit any data coming from the coalesce stream to the outside world
coalesceStream.on('data', function(event) {
self.trigger('data', event);
});
// Let the consumer know we have finished flushing the entire pipeline
coalesceStream.on('done', function() {
self.trigger('done');
});
// For information on the FLV format, see
// http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
// Technically, this function returns the header and a metadata FLV tag
// if duration is greater than zero
// duration in seconds
// @return {object} the bytes of the FLV header as a Uint8Array
this.getFlvHeader = function(duration, audio, video) { // :ByteArray {
var
headBytes = new Uint8Array(3 + 1 + 1 + 4),
head = new DataView(headBytes.buffer),
metadata,
result,
metadataLength;
// default arguments
duration = duration || 0;
audio = audio === undefined ? true : audio;
video = video === undefined ? true : video;
// signature
head.setUint8(0, 0x46); // 'F'
head.setUint8(1, 0x4c); // 'L'
head.setUint8(2, 0x56); // 'V'
// version
head.setUint8(3, 0x01);
// flags
head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
// data offset, should be 9 for FLV v1
head.setUint32(5, headBytes.byteLength);
// init the first FLV tag
if (duration <= 0) {
// no duration available so just write the first field of the first
// FLV tag
result = new Uint8Array(headBytes.byteLength + 4);
result.set(headBytes);
result.set([0, 0, 0, 0], headBytes.byteLength);
return result;
}
// write out the duration metadata tag
metadata = new FlvTag(FlvTag.METADATA_TAG);
metadata.pts = metadata.dts = 0;
metadata.writeMetaDataDouble('duration', duration);
metadataLength = metadata.finalize().length;
result = new Uint8Array(headBytes.byteLength + metadataLength);
result.set(headBytes);
result.set(head.byteLength, metadataLength);
return result;
};
};
Transmuxer.prototype = new Stream();
var getFlvHeader = function(duration, audio, video) { // :ByteArray {
var
headBytes = new Uint8Array(3 + 1 + 1 + 4),
head = new DataView(headBytes.buffer),
metadata,
result,
metadataLength;
// default arguments
duration = duration || 0;
audio = audio === undefined ? true : audio;
video = video === undefined ? true : video;
// signature
head.setUint8(0, 0x46); // 'F'
head.setUint8(1, 0x4c); // 'L'
head.setUint8(2, 0x56); // 'V'
// version
head.setUint8(3, 0x01);
// flags
head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
// data offset, should be 9 for FLV v1
head.setUint32(5, headBytes.byteLength);
// init the first FLV tag
if (duration <= 0) {
// no duration available so just write the first field of the first
// FLV tag
result = new Uint8Array(headBytes.byteLength + 4);
result.set(headBytes);
result.set([0, 0, 0, 0], headBytes.byteLength);
return result;
}
// write out the duration metadata tag
metadata = new FlvTag(FlvTag.METADATA_TAG);
metadata.pts = metadata.dts = 0;
metadata.writeMetaDataDouble('duration', duration);
metadataLength = metadata.finalize().length;
result = new Uint8Array(headBytes.byteLength + metadataLength);
result.set(headBytes);
result.set(head.byteLength, metadataLength);
return result;
};
// forward compatibility
module.exports = {
Transmuxer: Transmuxer,
getFlvHeader: getFlvHeader
};
},{"../codecs/adts.js":10,"../codecs/h264":11,"../m2ts/m2ts.js":18,"../utils/stream.js":27,"./coalesce-stream.js":12,"./flv-tag.js":13,"./tag-list.js":15}],17:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* Reads in-band caption information from a video elementary
* stream. Captions must follow the CEA-708 standard for injection
* into an MPEG-2 transport streams.
* @see https://en.wikipedia.org/wiki/CEA-708
*/
'use strict';
// -----------------
// Link To Transport
// -----------------
// Supplemental enhancement information (SEI) NAL units have a
// payload type field to indicate how they are to be
// interpreted. CEAS-708 caption content is always transmitted with
// payload type 0x04.
var USER_DATA_REGISTERED_ITU_T_T35 = 4,
RBSP_TRAILING_BITS = 128,
Stream = require('../utils/stream');
/**
* Parse a supplemental enhancement information (SEI) NAL unit.
* Stops parsing once a message of type ITU T T35 has been found.
*
* @param bytes {Uint8Array} the bytes of a SEI NAL unit
* @return {object} the parsed SEI payload
* @see Rec. ITU-T H.264, 7.3.2.3.1
*/
var parseSei = function(bytes) {
var
i = 0,
result = {
payloadType: -1,
payloadSize: 0
},
payloadType = 0,
payloadSize = 0;
// go through the sei_rbsp parsing each each individual sei_message
while (i < bytes.byteLength) {
// stop once we have hit the end of the sei_rbsp
if (bytes[i] === RBSP_TRAILING_BITS) {
break;
}
// Parse payload type
while (bytes[i] === 0xFF) {
payloadType += 255;
i++;
}
payloadType += bytes[i++];
// Parse payload size
while (bytes[i] === 0xFF) {
payloadSize += 255;
i++;
}
payloadSize += bytes[i++];
// this sei_message is a 608/708 caption so save it and break
// there can only ever be one caption message in a frame's sei
if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
result.payloadType = payloadType;
result.payloadSize = payloadSize;
result.payload = bytes.subarray(i, i + payloadSize);
break;
}
// skip the payload and parse the next message
i += payloadSize;
payloadType = 0;
payloadSize = 0;
}
return result;
};
// see ANSI/SCTE 128-1 (2013), section 8.1
var parseUserData = function(sei) {
// itu_t_t35_contry_code must be 181 (United States) for
// captions
if (sei.payload[0] !== 181) {
return null;
}
// itu_t_t35_provider_code should be 49 (ATSC) for captions
if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
return null;
}
// the user_identifier should be "GA94" to indicate ATSC1 data
if (String.fromCharCode(sei.payload[3],
sei.payload[4],
sei.payload[5],
sei.payload[6]) !== 'GA94') {
return null;
}
// finally, user_data_type_code should be 0x03 for caption data
if (sei.payload[7] !== 0x03) {
return null;
}
// return the user_data_type_structure and strip the trailing
// marker bits
return sei.payload.subarray(8, sei.payload.length - 1);
};
// see CEA-708-D, section 4.4
var parseCaptionPackets = function(pts, userData) {
var results = [], i, count, offset, data;
// if this is just filler, return immediately
if (!(userData[0] & 0x40)) {
return results;
}
// parse out the cc_data_1 and cc_data_2 fields
count = userData[0] & 0x1f;
for (i = 0; i < count; i++) {
offset = i * 3;
data = {
type: userData[offset + 2] & 0x03,
pts: pts
};
// capture cc data when cc_valid is 1
if (userData[offset + 2] & 0x04) {
data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
results.push(data);
}
}
return results;
};
var CaptionStream = function() {
CaptionStream.prototype.init.call(this);
this.captionPackets_ = [];
this.field1_ = new Cea608Stream(); // eslint-disable-line no-use-before-define
// forward data and done events from field1_ to this CaptionStream
this.field1_.on('data', this.trigger.bind(this, 'data'));
this.field1_.on('done', this.trigger.bind(this, 'done'));
};
CaptionStream.prototype = new Stream();
CaptionStream.prototype.push = function(event) {
var sei, userData;
// only examine SEI NALs
if (event.nalUnitType !== 'sei_rbsp') {
return;
}
// parse the sei
sei = parseSei(event.escapedRBSP);
// ignore everything but user_data_registered_itu_t_t35
if (sei.payloadType !== USER_DATA_REGISTERED_ITU_T_T35) {
return;
}
// parse out the user data payload
userData = parseUserData(sei);
// ignore unrecognized userData
if (!userData) {
return;
}
// parse out CC data packets and save them for later
this.captionPackets_ = this.captionPackets_.concat(parseCaptionPackets(event.pts, userData));
};
CaptionStream.prototype.flush = function() {
// make sure we actually parsed captions before proceeding
if (!this.captionPackets_.length) {
this.field1_.flush();
return;
}
// In Chrome, the Array#sort function is not stable so add a
// presortIndex that we can use to ensure we get a stable-sort
this.captionPackets_.forEach(function(elem, idx) {
elem.presortIndex = idx;
});
// sort caption byte-pairs based on their PTS values
this.captionPackets_.sort(function(a, b) {
if (a.pts === b.pts) {
return a.presortIndex - b.presortIndex;
}
return a.pts - b.pts;
});
// Push each caption into Cea608Stream
this.captionPackets_.forEach(this.field1_.push, this.field1_);
this.captionPackets_.length = 0;
this.field1_.flush();
return;
};
// ----------------------
// Session to Application
// ----------------------
var BASIC_CHARACTER_TRANSLATION = {
0x2a: 0xe1,
0x5c: 0xe9,
0x5e: 0xed,
0x5f: 0xf3,
0x60: 0xfa,
0x7b: 0xe7,
0x7c: 0xf7,
0x7d: 0xd1,
0x7e: 0xf1,
0x7f: 0x2588
};
var getCharFromCode = function(code) {
if (code === null) {
return '';
}
code = BASIC_CHARACTER_TRANSLATION[code] || code;
return String.fromCharCode(code);
};
// Constants for the byte codes recognized by Cea608Stream. This
// list is not exhaustive. For a more comprehensive listing and
// semantics see
// http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
var PADDING = 0x0000,
// Pop-on Mode
RESUME_CAPTION_LOADING = 0x1420,
END_OF_CAPTION = 0x142f,
// Roll-up Mode
ROLL_UP_2_ROWS = 0x1425,
ROLL_UP_3_ROWS = 0x1426,
ROLL_UP_4_ROWS = 0x1427,
CARRIAGE_RETURN = 0x142d,
// Erasure
BACKSPACE = 0x1421,
ERASE_DISPLAYED_MEMORY = 0x142c,
ERASE_NON_DISPLAYED_MEMORY = 0x142e;
// the index of the last row in a CEA-608 display buffer
var BOTTOM_ROW = 14;
// CEA-608 captions are rendered onto a 34x15 matrix of character
// cells. The "bottom" row is the last element in the outer array.
var createDisplayBuffer = function() {
var result = [], i = BOTTOM_ROW + 1;
while (i--) {
result.push('');
}
return result;
};
var Cea608Stream = function() {
Cea608Stream.prototype.init.call(this);
this.mode_ = 'popOn';
// When in roll-up mode, the index of the last row that will
// actually display captions. If a caption is shifted to a row
// with a lower index than this, it is cleared from the display
// buffer
this.topRow_ = 0;
this.startPts_ = 0;
this.displayed_ = createDisplayBuffer();
this.nonDisplayed_ = createDisplayBuffer();
this.lastControlCode_ = null;
this.push = function(packet) {
// Ignore other channels
if (packet.type !== 0) {
return;
}
var data, swap, char0, char1;
// remove the parity bits
data = packet.ccData & 0x7f7f;
// ignore duplicate control codes
if (data === this.lastControlCode_) {
this.lastControlCode_ = null;
return;
}
// Store control codes
if ((data & 0xf000) === 0x1000) {
this.lastControlCode_ = data;
} else {
this.lastControlCode_ = null;
}
switch (data) {
case PADDING:
break;
case RESUME_CAPTION_LOADING:
this.mode_ = 'popOn';
break;
case END_OF_CAPTION:
// if a caption was being displayed, it's gone now
this.flushDisplayed(packet.pts);
// flip memory
swap = this.displayed_;
this.displayed_ = this.nonDisplayed_;
this.nonDisplayed_ = swap;
// start measuring the time to display the caption
this.startPts_ = packet.pts;
break;
case ROLL_UP_2_ROWS:
this.topRow_ = BOTTOM_ROW - 1;
this.mode_ = 'rollUp';
break;
case ROLL_UP_3_ROWS:
this.topRow_ = BOTTOM_ROW - 2;
this.mode_ = 'rollUp';
break;
case ROLL_UP_4_ROWS:
this.topRow_ = BOTTOM_ROW - 3;
this.mode_ = 'rollUp';
break;
case CARRIAGE_RETURN:
this.flushDisplayed(packet.pts);
this.shiftRowsUp_();
this.startPts_ = packet.pts;
break;
case BACKSPACE:
if (this.mode_ === 'popOn') {
this.nonDisplayed_[BOTTOM_ROW] = this.nonDisplayed_[BOTTOM_ROW].slice(0, -1);
} else {
this.displayed_[BOTTOM_ROW] = this.displayed_[BOTTOM_ROW].slice(0, -1);
}
break;
case ERASE_DISPLAYED_MEMORY:
this.flushDisplayed(packet.pts);
this.displayed_ = createDisplayBuffer();
break;
case ERASE_NON_DISPLAYED_MEMORY:
this.nonDisplayed_ = createDisplayBuffer();
break;
default:
char0 = data >>> 8;
char1 = data & 0xff;
// Look for a Channel 1 Preamble Address Code
if (char0 >= 0x10 && char0 <= 0x17 &&
char1 >= 0x40 && char1 <= 0x7F &&
(char0 !== 0x10 || char1 < 0x60)) {
// Follow Safari's lead and replace the PAC with a space
char0 = 0x20;
// we only want one space so make the second character null
// which will get become '' in getCharFromCode
char1 = null;
}
// Look for special character sets
if ((char0 === 0x11 || char0 === 0x19) &&
(char1 >= 0x30 && char1 <= 0x3F)) {
// Put in eigth note and space
char0 = 0x266A;
char1 = '';
}
// ignore unsupported control codes
if ((char0 & 0xf0) === 0x10) {
return;
}
// character handling is dependent on the current mode
this[this.mode_](packet.pts, char0, char1);
break;
}
};
};
Cea608Stream.prototype = new Stream();
// Trigger a cue point that captures the current state of the
// display buffer
Cea608Stream.prototype.flushDisplayed = function(pts) {
var content = this.displayed_
// remove spaces from the start and end of the string
.map(function(row) {
return row.trim();
})
// remove empty rows
.filter(function(row) {
return row.length;
})
// combine all text rows to display in one cue
.join('\n');
if (content.length) {
this.trigger('data', {
startPts: this.startPts_,
endPts: pts,
text: content
});
}
};
// Mode Implementations
Cea608Stream.prototype.popOn = function(pts, char0, char1) {
var baseRow = this.nonDisplayed_[BOTTOM_ROW];
// buffer characters
baseRow += getCharFromCode(char0);
baseRow += getCharFromCode(char1);
this.nonDisplayed_[BOTTOM_ROW] = baseRow;
};
Cea608Stream.prototype.rollUp = function(pts, char0, char1) {
var baseRow = this.displayed_[BOTTOM_ROW];
if (baseRow === '') {
// we're starting to buffer new display input, so flush out the
// current display
this.flushDisplayed(pts);
this.startPts_ = pts;
}
baseRow += getCharFromCode(char0);
baseRow += getCharFromCode(char1);
this.displayed_[BOTTOM_ROW] = baseRow;
};
Cea608Stream.prototype.shiftRowsUp_ = function() {
var i;
// clear out inactive rows
for (i = 0; i < this.topRow_; i++) {
this.displayed_[i] = '';
}
// shift displayed rows up
for (i = this.topRow_; i < BOTTOM_ROW; i++) {
this.displayed_[i] = this.displayed_[i + 1];
}
// clear out the bottom row
this.displayed_[BOTTOM_ROW] = '';
};
// exports
module.exports = {
CaptionStream: CaptionStream,
Cea608Stream: Cea608Stream
};
},{"../utils/stream":27}],18:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* A stream-based mp2t to mp4 converter. This utility can be used to
* deliver mp4s to a SourceBuffer on platforms that support native
* Media Source Extensions.
*/
'use strict';
var Stream = require('../utils/stream.js'),
CaptionStream = require('./caption-stream'),
StreamTypes = require('./stream-types'),
TimestampRolloverStream = require('./timestamp-rollover-stream').TimestampRolloverStream;
var m2tsStreamTypes = require('./stream-types.js');
// object types
var TransportPacketStream, TransportParseStream, ElementaryStream;
// constants
var
MP2T_PACKET_LENGTH = 188, // bytes
SYNC_BYTE = 0x47;
/**
* Splits an incoming stream of binary data into MPEG-2 Transport
* Stream packets.
*/
TransportPacketStream = function() {
var
buffer = new Uint8Array(MP2T_PACKET_LENGTH),
bytesInBuffer = 0;
TransportPacketStream.prototype.init.call(this);
// Deliver new bytes to the stream.
this.push = function(bytes) {
var
startIndex = 0,
endIndex = MP2T_PACKET_LENGTH,
everything;
// If there are bytes remaining from the last segment, prepend them to the
// bytes that were pushed in
if (bytesInBuffer) {
everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
everything.set(buffer.subarray(0, bytesInBuffer));
everything.set(bytes, bytesInBuffer);
bytesInBuffer = 0;
} else {
everything = bytes;
}
// While we have enough data for a packet
while (endIndex < everything.byteLength) {
// Look for a pair of start and end sync bytes in the data..
if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
// We found a packet so emit it and jump one whole packet forward in
// the stream
this.trigger('data', everything.subarray(startIndex, endIndex));
startIndex += MP2T_PACKET_LENGTH;
endIndex += MP2T_PACKET_LENGTH;
continue;
}
// If we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startIndex++;
endIndex++;
}
// If there was some data left over at the end of the segment that couldn't
// possibly be a whole packet, keep it because it might be the start of a packet
// that continues in the next segment
if (startIndex < everything.byteLength) {
buffer.set(everything.subarray(startIndex), 0);
bytesInBuffer = everything.byteLength - startIndex;
}
};
this.flush = function() {
// If the buffer contains a whole packet when we are being flushed, emit it
// and empty the buffer. Otherwise hold onto the data because it may be
// important for decoding the next segment
if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
this.trigger('data', buffer);
bytesInBuffer = 0;
}
this.trigger('done');
};
};
TransportPacketStream.prototype = new Stream();
/**
* Accepts an MP2T TransportPacketStream and emits data events with parsed
* forms of the individual transport stream packets.
*/
TransportParseStream = function() {
var parsePsi, parsePat, parsePmt, self;
TransportParseStream.prototype.init.call(this);
self = this;
this.packetsWaitingForPmt = [];
this.programMapTable = undefined;
parsePsi = function(payload, psi) {
var offset = 0;
// PSI packets may be split into multiple sections and those
// sections may be split into multiple packets. If a PSI
// section starts in this packet, the payload_unit_start_indicator
// will be true and the first byte of the payload will indicate
// the offset from the current position to the start of the
// section.
if (psi.payloadUnitStartIndicator) {
offset += payload[offset] + 1;
}
if (psi.type === 'pat') {
parsePat(payload.subarray(offset), psi);
} else {
parsePmt(payload.subarray(offset), psi);
}
};
parsePat = function(payload, pat) {
pat.section_number = payload[7]; // eslint-disable-line camelcase
pat.last_section_number = payload[8]; // eslint-disable-line camelcase
// skip the PSI header and parse the first PMT entry
self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
pat.pmtPid = self.pmtPid;
};
/**
* Parse out the relevant fields of a Program Map Table (PMT).
* @param payload {Uint8Array} the PMT-specific portion of an MP2T
* packet. The first byte in this array should be the table_id
* field.
* @param pmt {object} the object that should be decorated with
* fields parsed from the PMT.
*/
parsePmt = function(payload, pmt) {
var sectionLength, tableEnd, programInfoLength, offset;
// PMTs can be sent ahead of the time when they should actually
// take effect. We don't believe this should ever be the case
// for HLS but we'll ignore "forward" PMT declarations if we see
// them. Future PMT declarations have the current_next_indicator
// set to zero.
if (!(payload[5] & 0x01)) {
return;
}
// overwrite any existing program map table
self.programMapTable = {};
// the mapping table ends at the end of the current section
sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
tableEnd = 3 + sectionLength - 4;
// to determine where the table is, we have to figure out how
// long the program info descriptors are
programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];
// advance the offset to the first entry in the mapping table
offset = 12 + programInfoLength;
while (offset < tableEnd) {
// add an entry that maps the elementary_pid to the stream_type
self.programMapTable[(payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]] = payload[offset];
// move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
}
// record the map on the packet as well
pmt.programMapTable = self.programMapTable;
// if there are any packets waiting for a PMT to be found, process them now
while (self.packetsWaitingForPmt.length) {
self.processPes_.apply(self, self.packetsWaitingForPmt.shift());
}
};
/**
* Deliver a new MP2T packet to the stream.
*/
this.push = function(packet) {
var
result = {},
offset = 4;
result.payloadUnitStartIndicator = !!(packet[1] & 0x40);
// pid is a 13-bit field starting at the last bit of packet[1]
result.pid = packet[1] & 0x1f;
result.pid <<= 8;
result.pid |= packet[2];
// if an adaption field is present, its length is specified by the
// fifth byte of the TS packet header. The adaptation field is
// used to add stuffing to PES packets that don't fill a complete
// TS packet, and to specify some forms of timing and control data
// that we do not currently use.
if (((packet[3] & 0x30) >>> 4) > 0x01) {
offset += packet[offset] + 1;
}
// parse the rest of the packet based on the type
if (result.pid === 0) {
result.type = 'pat';
parsePsi(packet.subarray(offset), result);
this.trigger('data', result);
} else if (result.pid === this.pmtPid) {
result.type = 'pmt';
parsePsi(packet.subarray(offset), result);
this.trigger('data', result);
} else if (this.programMapTable === undefined) {
// When we have not seen a PMT yet, defer further processing of
// PES packets until one has been parsed
this.packetsWaitingForPmt.push([packet, offset, result]);
} else {
this.processPes_(packet, offset, result);
}
};
this.processPes_ = function(packet, offset, result) {
result.streamType = this.programMapTable[result.pid];
result.type = 'pes';
result.data = packet.subarray(offset);
this.trigger('data', result);
};
};
TransportParseStream.prototype = new Stream();
TransportParseStream.STREAM_TYPES = {
h264: 0x1b,
adts: 0x0f
};
/**
* Reconsistutes program elementary stream (PES) packets from parsed
* transport stream packets. That is, if you pipe an
* mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
* events will be events which capture the bytes for individual PES
* packets plus relevant metadata that has been extracted from the
* container.
*/
ElementaryStream = function() {
var
self = this,
// PES packet fragments
video = {
data: [],
size: 0
},
audio = {
data: [],
size: 0
},
timedMetadata = {
data: [],
size: 0
},
parsePes = function(payload, pes) {
var ptsDtsFlags;
// find out if this packets starts a new keyframe
pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
// PES packets may be annotated with a PTS value, or a PTS value
// and a DTS value. Determine what combination of values is
// available to work with.
ptsDtsFlags = payload[7];
// PTS and DTS are normally stored as a 33-bit number. Javascript
// performs all bitwise operations on 32-bit integers but javascript
// supports a much greater range (52-bits) of integer using standard
// mathematical operations.
// We construct a 31-bit value using bitwise operators over the 31
// most significant bits and then multiply by 4 (equal to a left-shift
// of 2) before we add the final 2 least significant bits of the
// timestamp (equal to an OR.)
if (ptsDtsFlags & 0xC0) {
// the PTS and DTS are not written out directly. For information
// on how they are encoded, see
// http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
pes.pts = (payload[9] & 0x0E) << 27 |
(payload[10] & 0xFF) << 20 |
(payload[11] & 0xFE) << 12 |
(payload[12] & 0xFF) << 5 |
(payload[13] & 0xFE) >>> 3;
pes.pts *= 4; // Left shift by 2
pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
pes.dts = pes.pts;
if (ptsDtsFlags & 0x40) {
pes.dts = (payload[14] & 0x0E) << 27 |
(payload[15] & 0xFF) << 20 |
(payload[16] & 0xFE) << 12 |
(payload[17] & 0xFF) << 5 |
(payload[18] & 0xFE) >>> 3;
pes.dts *= 4; // Left shift by 2
pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
}
}
// the data section starts immediately after the PES header.
// pes_header_data_length specifies the number of header bytes
// that follow the last byte of the field.
pes.data = payload.subarray(9 + payload[8]);
},
flushStream = function(stream, type) {
var
packetData = new Uint8Array(stream.size),
event = {
type: type
},
i = 0,
fragment;
// do nothing if there is no buffered data
if (!stream.data.length) {
return;
}
event.trackId = stream.data[0].pid;
// reassemble the packet
while (stream.data.length) {
fragment = stream.data.shift();
packetData.set(fragment.data, i);
i += fragment.data.byteLength;
}
// parse assembled packet's PES header
parsePes(packetData, event);
stream.size = 0;
self.trigger('data', event);
};
ElementaryStream.prototype.init.call(this);
this.push = function(data) {
({
pat: function() {
// we have to wait for the PMT to arrive as well before we
// have any meaningful metadata
},
pes: function() {
var stream, streamType;
switch (data.streamType) {
case StreamTypes.H264_STREAM_TYPE:
case m2tsStreamTypes.H264_STREAM_TYPE:
stream = video;
streamType = 'video';
break;
case StreamTypes.ADTS_STREAM_TYPE:
stream = audio;
streamType = 'audio';
break;
case StreamTypes.METADATA_STREAM_TYPE:
stream = timedMetadata;
streamType = 'timed-metadata';
break;
default:
// ignore unknown stream types
return;
}
// if a new packet is starting, we can flush the completed
// packet
if (data.payloadUnitStartIndicator) {
flushStream(stream, streamType);
}
// buffer this fragment until we are sure we've received the
// complete payload
stream.data.push(data);
stream.size += data.data.byteLength;
},
pmt: function() {
var
event = {
type: 'metadata',
tracks: []
},
programMapTable = data.programMapTable,
k,
track;
// translate streams to tracks
for (k in programMapTable) {
if (programMapTable.hasOwnProperty(k)) {
track = {
timelineStartInfo: {
baseMediaDecodeTime: 0
}
};
track.id = +k;
if (programMapTable[k] === m2tsStreamTypes.H264_STREAM_TYPE) {
track.codec = 'avc';
track.type = 'video';
} else if (programMapTable[k] === m2tsStreamTypes.ADTS_STREAM_TYPE) {
track.codec = 'adts';
track.type = 'audio';
}
event.tracks.push(track);
}
}
self.trigger('data', event);
}
})[data.type]();
};
/**
* Flush any remaining input. Video PES packets may be of variable
* length. Normally, the start of a new video packet can trigger the
* finalization of the previous packet. That is not possible if no
* more video is forthcoming, however. In that case, some other
* mechanism (like the end of the file) has to be employed. When it is
* clear that no additional data is forthcoming, calling this method
* will flush the buffered packets.
*/
this.flush = function() {
// !!THIS ORDER IS IMPORTANT!!
// video first then audio
flushStream(video, 'video');
flushStream(audio, 'audio');
flushStream(timedMetadata, 'timed-metadata');
this.trigger('done');
};
};
ElementaryStream.prototype = new Stream();
var m2ts = {
PAT_PID: 0x0000,
MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
TransportPacketStream: TransportPacketStream,
TransportParseStream: TransportParseStream,
ElementaryStream: ElementaryStream,
TimestampRolloverStream: TimestampRolloverStream,
CaptionStream: CaptionStream.CaptionStream,
Cea608Stream: CaptionStream.Cea608Stream,
MetadataStream: require('./metadata-stream')
};
for (var type in StreamTypes) {
if (StreamTypes.hasOwnProperty(type)) {
m2ts[type] = StreamTypes[type];
}
}
module.exports = m2ts;
},{"../utils/stream.js":27,"./caption-stream":17,"./metadata-stream":19,"./stream-types":20,"./stream-types.js":20,"./timestamp-rollover-stream":21}],19:[function(require,module,exports){
/**
* Accepts program elementary stream (PES) data events and parses out
* ID3 metadata from them, if present.
* @see http://id3.org/id3v2.3.0
*/
'use strict';
var
Stream = require('../utils/stream'),
StreamTypes = require('./stream-types'),
// return a percent-encoded representation of the specified byte range
// @see http://en.wikipedia.org/wiki/Percent-encoding
percentEncode = function(bytes, start, end) {
var i, result = '';
for (i = start; i < end; i++) {
result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
}
return result;
},
// return the string representation of the specified byte range,
// interpreted as UTf-8.
parseUtf8 = function(bytes, start, end) {
return decodeURIComponent(percentEncode(bytes, start, end));
},
// return the string representation of the specified byte range,
// interpreted as ISO-8859-1.
parseIso88591 = function(bytes, start, end) {
return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
},
parseSyncSafeInteger = function(data) {
return (data[0] << 21) |
(data[1] << 14) |
(data[2] << 7) |
(data[3]);
},
tagParsers = {
TXXX: function(tag) {
var i;
if (tag.data[0] !== 3) {
// ignore frames with unrecognized character encodings
return;
}
for (i = 1; i < tag.data.length; i++) {
if (tag.data[i] === 0) {
// parse the text fields
tag.description = parseUtf8(tag.data, 1, i);
// do not include the null terminator in the tag value
tag.value = parseUtf8(tag.data, i + 1, tag.data.length - 1);
break;
}
}
tag.data = tag.value;
},
WXXX: function(tag) {
var i;
if (tag.data[0] !== 3) {
// ignore frames with unrecognized character encodings
return;
}
for (i = 1; i < tag.data.length; i++) {
if (tag.data[i] === 0) {
// parse the description and URL fields
tag.description = parseUtf8(tag.data, 1, i);
tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
break;
}
}
},
PRIV: function(tag) {
var i;
for (i = 0; i < tag.data.length; i++) {
if (tag.data[i] === 0) {
// parse the description and URL fields
tag.owner = parseIso88591(tag.data, 0, i);
break;
}
}
tag.privateData = tag.data.subarray(i + 1);
tag.data = tag.privateData;
}
},
MetadataStream;
MetadataStream = function(options) {
var
settings = {
debug: !!(options && options.debug),
// the bytes of the program-level descriptor field in MP2T
// see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
// program element descriptors"
descriptor: options && options.descriptor
},
// the total size in bytes of the ID3 tag being parsed
tagSize = 0,
// tag data that is not complete enough to be parsed
buffer = [],
// the total number of bytes currently in the buffer
bufferSize = 0,
i;
MetadataStream.prototype.init.call(this);
// calculate the text track in-band metadata track dispatch type
// https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
if (settings.descriptor) {
for (i = 0; i < settings.descriptor.length; i++) {
this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
}
}
this.push = function(chunk) {
var tag, frameStart, frameSize, frame, i, frameHeader;
if (chunk.type !== 'timed-metadata') {
return;
}
// if data_alignment_indicator is set in the PES header,
// we must have the start of a new ID3 tag. Assume anything
// remaining in the buffer was malformed and throw it out
if (chunk.dataAlignmentIndicator) {
bufferSize = 0;
buffer.length = 0;
}
// ignore events that don't look like ID3 data
if (buffer.length === 0 &&
(chunk.data.length < 10 ||
chunk.data[0] !== 'I'.charCodeAt(0) ||
chunk.data[1] !== 'D'.charCodeAt(0) ||
chunk.data[2] !== '3'.charCodeAt(0))) {
if (settings.debug) {
// eslint-disable-next-line no-console
console.log('Skipping unrecognized metadata packet');
}
return;
}
// add this chunk to the data we've collected so far
buffer.push(chunk);
bufferSize += chunk.data.byteLength;
// grab the size of the entire frame from the ID3 header
if (buffer.length === 1) {
// the frame size is transmitted as a 28-bit integer in the
// last four bytes of the ID3 header.
// The most significant bit of each byte is dropped and the
// results concatenated to recover the actual value.
tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));
// ID3 reports the tag size excluding the header but it's more
// convenient for our comparisons to include it
tagSize += 10;
}
// if the entire frame has not arrived, wait for more data
if (bufferSize < tagSize) {
return;
}
// collect the entire frame so it can be parsed
tag = {
data: new Uint8Array(tagSize),
frames: [],
pts: buffer[0].pts,
dts: buffer[0].dts
};
for (i = 0; i < tagSize;) {
tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
i += buffer[0].data.byteLength;
bufferSize -= buffer[0].data.byteLength;
buffer.shift();
}
// find the start of the first frame and the end of the tag
frameStart = 10;
if (tag.data[5] & 0x40) {
// advance the frame start past the extended header
frameStart += 4; // header size field
frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));
// clip any padding off the end
tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
}
// parse one or more ID3 frames
// http://id3.org/id3v2.3.0#ID3v2_frame_overview
do {
// determine the number of bytes in this frame
frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
if (frameSize < 1) {
// eslint-disable-next-line no-console
return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
}
frameHeader = String.fromCharCode(tag.data[frameStart],
tag.data[frameStart + 1],
tag.data[frameStart + 2],
tag.data[frameStart + 3]);
frame = {
id: frameHeader,
data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
};
frame.key = frame.id;
if (tagParsers[frame.id]) {
tagParsers[frame.id](frame);
// handle the special PRIV frame used to indicate the start
// time for raw AAC data
if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
var
d = frame.data,
size = ((d[3] & 0x01) << 30) |
(d[4] << 22) |
(d[5] << 14) |
(d[6] << 6) |
(d[7] >>> 2);
size *= 4;
size += d[7] & 0x03;
frame.timeStamp = size;
// in raw AAC, all subsequent data will be timestamped based
// on the value of this frame
// we couldn't have known the appropriate pts and dts before
// parsing this ID3 tag so set those values now
if (tag.pts === undefined && tag.dts === undefined) {
tag.pts = frame.timeStamp;
tag.dts = frame.timeStamp;
}
this.trigger('timestamp', frame);
}
}
tag.frames.push(frame);
frameStart += 10; // advance past the frame header
frameStart += frameSize; // advance past the frame body
} while (frameStart < tagSize);
this.trigger('data', tag);
};
};
MetadataStream.prototype = new Stream();
module.exports = MetadataStream;
},{"../utils/stream":27,"./stream-types":20}],20:[function(require,module,exports){
'use strict';
module.exports = {
H264_STREAM_TYPE: 0x1B,
ADTS_STREAM_TYPE: 0x0F,
METADATA_STREAM_TYPE: 0x15
};
},{}],21:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2016 Brightcove
* All rights reserved.
*
* Accepts program elementary stream (PES) data events and corrects
* decode and presentation time stamps to account for a rollover
* of the 33 bit value.
*/
'use strict';
var Stream = require('../utils/stream');
var MAX_TS = 8589934592;
var RO_THRESH = 4294967296;
var handleRollover = function(value, reference) {
var direction = 1;
if (value > reference) {
// If the current timestamp value is greater than our reference timestamp and we detect a
// timestamp rollover, this means the roll over is happening in the opposite direction.
// Example scenario: Enter a long stream/video just after a rollover occurred. The reference
// point will be set to a small number, e.g. 1. The user then seeks backwards over the
// rollover point. In loading this segment, the timestamp values will be very large,
// e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
// the time stamp to be `value - 2^33`.
direction = -1;
}
// Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
// cause an incorrect adjustment.
while (Math.abs(reference - value) > RO_THRESH) {
value += (direction * MAX_TS);
}
return value;
};
var TimestampRolloverStream = function(type) {
var lastDTS, referenceDTS;
TimestampRolloverStream.prototype.init.call(this);
this.type_ = type;
this.push = function(data) {
if (data.type !== this.type_) {
return;
}
if (referenceDTS === undefined) {
referenceDTS = data.dts;
}
data.dts = handleRollover(data.dts, referenceDTS);
data.pts = handleRollover(data.pts, referenceDTS);
lastDTS = data.dts;
this.trigger('data', data);
};
this.flush = function() {
referenceDTS = lastDTS;
this.trigger('done');
};
};
TimestampRolloverStream.prototype = new Stream();
module.exports = {
TimestampRolloverStream: TimestampRolloverStream,
handleRollover: handleRollover
};
},{"../utils/stream":27}],22:[function(require,module,exports){
module.exports = {
generator: require('./mp4-generator'),
Transmuxer: require('./transmuxer').Transmuxer,
AudioSegmentStream: require('./transmuxer').AudioSegmentStream,
VideoSegmentStream: require('./transmuxer').VideoSegmentStream
};
},{"./mp4-generator":23,"./transmuxer":25}],23:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* Functions that generate fragmented MP4s suitable for use with Media
* Source Extensions.
*/
'use strict';
var UINT32_MAX = Math.pow(2, 32) - 1;
var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd,
trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex,
trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
// pre-calculate constants
(function() {
var i;
types = {
avc1: [], // codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [], // codingname
mvex: [],
mvhd: [],
sdtp: [],
smhd: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
styp: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: []
};
// In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
// don't throw an error
if (typeof Uint8Array === 'undefined') {
return;
}
for (i in types) {
if (types.hasOwnProperty(i)) {
types[i] = [
i.charCodeAt(0),
i.charCodeAt(1),
i.charCodeAt(2),
i.charCodeAt(3)
];
}
}
MAJOR_BRAND = new Uint8Array([
'i'.charCodeAt(0),
's'.charCodeAt(0),
'o'.charCodeAt(0),
'm'.charCodeAt(0)
]);
AVC1_BRAND = new Uint8Array([
'a'.charCodeAt(0),
'v'.charCodeAt(0),
'c'.charCodeAt(0),
'1'.charCodeAt(0)
]);
MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
VIDEO_HDLR = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65,
0x6f, 0x48, 0x61, 0x6e,
0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
AUDIO_HDLR = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e,
0x64, 0x48, 0x61, 0x6e,
0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
HDLR_TYPES = {
video: VIDEO_HDLR,
audio: AUDIO_HDLR
};
DREF = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
SMHD = new Uint8Array([
0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance, 0 means centered
0x00, 0x00 // reserved
]);
STCO = new Uint8Array([
0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
STSC = STCO;
STSZ = new Uint8Array([
0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00 // sample_count
]);
STTS = STCO;
VMHD = new Uint8Array([
0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00,
0x00, 0x00,
0x00, 0x00 // opcolor
]);
}());
box = function(type) {
var
payload = [],
size = 0,
i,
result,
view;
for (i = 1; i < arguments.length; i++) {
payload.push(arguments[i]);
}
i = payload.length;
// calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
result = new Uint8Array(size + 8);
view = new DataView(result.buffer, result.byteOffset, result.byteLength);
view.setUint32(0, result.byteLength);
result.set(type, 4);
// copy the payload into the result
for (i = 0, size = 8; i < payload.length; i++) {
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
};
dinf = function() {
return box(types.dinf, box(types.dref, DREF));
};
esds = function(track) {
return box(types.esds, new Uint8Array([
0x00, // version
0x00, 0x00, 0x00, // flags
// ES_Descriptor
0x03, // tag, ES_DescrTag
0x19, // length
0x00, 0x00, // ES_ID
0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
// DecoderConfigDescriptor
0x04, // tag, DecoderConfigDescrTag
0x11, // length
0x40, // object type
0x15, // streamType
0x00, 0x06, 0x00, // bufferSizeDB
0x00, 0x00, 0xda, 0xc0, // maxBitrate
0x00, 0x00, 0xda, 0xc0, // avgBitrate
// DecoderSpecificInfo
0x05, // tag, DecoderSpecificInfoTag
0x02, // length
// ISO/IEC 14496-3, AudioSpecificConfig
// for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
(track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
(track.samplingfrequencyindex << 7) | (track.channelcount << 3),
0x06, 0x01, 0x02 // GASpecificConfig
]));
};
ftyp = function() {
return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
};
hdlr = function(type) {
return box(types.hdlr, HDLR_TYPES[type]);
};
mdat = function(data) {
return box(types.mdat, data);
};
mdhd = function(track) {
var result = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x03, // modification_time
0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
(track.duration >>> 24) & 0xFF,
(track.duration >>> 16) & 0xFF,
(track.duration >>> 8) & 0xFF,
track.duration & 0xFF, // duration
0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00
]);
// Use the sample rate from the track metadata, when it is
// defined. The sample rate can be parsed out of an ADTS header, for
// instance.
if (track.samplerate) {
result[12] = (track.samplerate >>> 24) & 0xFF;
result[13] = (track.samplerate >>> 16) & 0xFF;
result[14] = (track.samplerate >>> 8) & 0xFF;
result[15] = (track.samplerate) & 0xFF;
}
return box(types.mdhd, result);
};
mdia = function(track) {
return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
};
mfhd = function(sequenceNumber) {
return box(types.mfhd, new Uint8Array([
0x00,
0x00, 0x00, 0x00, // flags
(sequenceNumber & 0xFF000000) >> 24,
(sequenceNumber & 0xFF0000) >> 16,
(sequenceNumber & 0xFF00) >> 8,
sequenceNumber & 0xFF // sequence_number
]));
};
minf = function(track) {
return box(types.minf,
track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
dinf(),
stbl(track));
};
moof = function(sequenceNumber, tracks) {
var
trackFragments = [],
i = tracks.length;
// build traf boxes for each track fragment
while (i--) {
trackFragments[i] = traf(tracks[i]);
}
return box.apply(null, [
types.moof,
mfhd(sequenceNumber)
].concat(trackFragments));
};
/**
* Returns a movie box.
* @param tracks {array} the tracks associated with this movie
* @see ISO/IEC 14496-12:2012(E), section 8.2.1
*/
moov = function(tracks) {
var
i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = trak(tracks[i]);
}
return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
};
mvex = function(tracks) {
var
i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = trex(tracks[i]);
}
return box.apply(null, [types.mvex].concat(boxes));
};
mvhd = function(duration) {
var
bytes = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // creation_time
0x00, 0x00, 0x00, 0x02, // modification_time
0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
(duration & 0xFF000000) >> 24,
(duration & 0xFF0000) >> 16,
(duration & 0xFF00) >> 8,
duration & 0xFF, // duration
0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return box(types.mvhd, bytes);
};
sdtp = function(track) {
var
samples = track.samples || [],
bytes = new Uint8Array(4 + samples.length),
flags,
i;
// leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = (flags.dependsOn << 4) |
(flags.isDependedOn << 2) |
(flags.hasRedundancy);
}
return box(types.sdtp,
bytes);
};
stbl = function(track) {
return box(types.stbl,
stsd(track),
box(types.stts, STTS),
box(types.stsc, STSC),
box(types.stsz, STSZ),
box(types.stco, STCO));
};
(function() {
var videoSample, audioSample;
stsd = function(track) {
return box(types.stsd, new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01
]), track.type === 'video' ? videoSample(track) : audioSample(track));
};
videoSample = function(track) {
var
sps = track.sps || [],
pps = track.pps || [],
sequenceParameterSets = [],
pictureParameterSets = [],
i;
// assemble the SPSs
for (i = 0; i < sps.length; i++) {
sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
}
// assemble the PPSs
for (i = 0; i < pps.length; i++) {
pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
pictureParameterSets.push((pps[i].byteLength & 0xFF));
pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
}
return box(types.avc1, new Uint8Array([
0x00, 0x00, 0x00,
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, // pre_defined
(track.width & 0xff00) >> 8,
track.width & 0xff, // width
(track.height & 0xff00) >> 8,
track.height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x13,
0x76, 0x69, 0x64, 0x65,
0x6f, 0x6a, 0x73, 0x2d,
0x63, 0x6f, 0x6e, 0x74,
0x72, 0x69, 0x62, 0x2d,
0x68, 0x6c, 0x73, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11 // pre_defined = -1
]), box(types.avcC, new Uint8Array([
0x01, // configurationVersion
track.profileIdc, // AVCProfileIndication
track.profileCompatibility, // profile_compatibility
track.levelIdc, // AVCLevelIndication
0xff // lengthSizeMinusOne, hard-coded to 4 bytes
].concat([
sps.length // numOfSequenceParameterSets
]).concat(sequenceParameterSets).concat([
pps.length // numOfPictureParameterSets
]).concat(pictureParameterSets))), // "PPS"
box(types.btrt, new Uint8Array([
0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0
])) // avgBitrate
);
};
audioSample = function(track) {
return box(types.mp4a, new Uint8Array([
// SampleEntry, ISO/IEC 14496-12
0x00, 0x00, 0x00,
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
// AudioSampleEntry, ISO/IEC 14496-12
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
(track.channelcount & 0xff00) >> 8,
(track.channelcount & 0xff), // channelcount
(track.samplesize & 0xff00) >> 8,
(track.samplesize & 0xff), // samplesize
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
(track.samplerate & 0xff00) >> 8,
(track.samplerate & 0xff),
0x00, 0x00 // samplerate, 16.16
// MP4AudioSampleEntry, ISO/IEC 14496-14
]), esds(track));
};
}());
tkhd = function(track) {
var result = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, // creation_time
0x00, 0x00, 0x00, 0x00, // modification_time
(track.id & 0xFF000000) >> 24,
(track.id & 0xFF0000) >> 16,
(track.id & 0xFF00) >> 8,
track.id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
(track.duration & 0xFF000000) >> 24,
(track.duration & 0xFF0000) >> 16,
(track.duration & 0xFF00) >> 8,
track.duration & 0xFF, // duration
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x01, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
(track.width & 0xFF00) >> 8,
track.width & 0xFF,
0x00, 0x00, // width
(track.height & 0xFF00) >> 8,
track.height & 0xFF,
0x00, 0x00 // height
]);
return box(types.tkhd, result);
};
/**
* Generate a track fragment (traf) box. A traf box collects metadata
* about tracks in a movie fragment (moof) box.
*/
traf = function(track) {
var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun,
sampleDependencyTable, dataOffset,
upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
trackFragmentHeader = box(types.tfhd, new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x3a, // flags
(track.id & 0xFF000000) >> 24,
(track.id & 0xFF0000) >> 16,
(track.id & 0xFF00) >> 8,
(track.id & 0xFF), // track_ID
0x00, 0x00, 0x00, 0x01, // sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x00, 0x00, 0x00 // default_sample_flags
]));
upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
0x01, // version 1
0x00, 0x00, 0x00, // flags
// baseMediaDecodeTime
(upperWordBaseMediaDecodeTime >>> 24) & 0xFF,
(upperWordBaseMediaDecodeTime >>> 16) & 0xFF,
(upperWordBaseMediaDecodeTime >>> 8) & 0xFF,
upperWordBaseMediaDecodeTime & 0xFF,
(lowerWordBaseMediaDecodeTime >>> 24) & 0xFF,
(lowerWordBaseMediaDecodeTime >>> 16) & 0xFF,
(lowerWordBaseMediaDecodeTime >>> 8) & 0xFF,
lowerWordBaseMediaDecodeTime & 0xFF
]));
// the data offset specifies the number of bytes from the start of
// the containing moof to the first payload byte of the associated
// mdat
dataOffset = (32 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8); // mdat header
// audio tracks require less metadata
if (track.type === 'audio') {
trackFragmentRun = trun(track, dataOffset);
return box(types.traf,
trackFragmentHeader,
trackFragmentDecodeTime,
trackFragmentRun);
}
// video tracks should contain an independent and disposable samples
// box (sdtp)
// generate one and adjust offsets to match
sampleDependencyTable = sdtp(track);
trackFragmentRun = trun(track,
sampleDependencyTable.length + dataOffset);
return box(types.traf,
trackFragmentHeader,
trackFragmentDecodeTime,
trackFragmentRun,
sampleDependencyTable);
};
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
trak = function(track) {
track.duration = track.duration || 0xffffffff;
return box(types.trak,
tkhd(track),
mdia(track));
};
trex = function(track) {
var result = new Uint8Array([
0x00, // version 0
0x00, 0x00, 0x00, // flags
(track.id & 0xFF000000) >> 24,
(track.id & 0xFF0000) >> 16,
(track.id & 0xFF00) >> 8,
(track.id & 0xFF), // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]);
// the last two bytes of default_sample_flags is the sample
// degradation priority, a hint about the importance of this sample
// relative to others. Lower the degradation priority for all sample
// types other than video.
if (track.type !== 'video') {
result[result.length - 1] = 0x00;
}
return box(types.trex, result);
};
(function() {
var audioTrun, videoTrun, trunHeader;
// This method assumes all samples are uniform. That is, if a
// duration is present for the first sample, it will be present for
// all subsequent samples.
// see ISO/IEC 14496-12:2012, Section 8.8.8.1
trunHeader = function(samples, offset) {
var durationPresent = 0, sizePresent = 0,
flagsPresent = 0, compositionTimeOffset = 0;
// trun flag constants
if (samples.length) {
if (samples[0].duration !== undefined) {
durationPresent = 0x1;
}
if (samples[0].size !== undefined) {
sizePresent = 0x2;
}
if (samples[0].flags !== undefined) {
flagsPresent = 0x4;
}
if (samples[0].compositionTimeOffset !== undefined) {
compositionTimeOffset = 0x8;
}
}
return [
0x00, // version 0
0x00,
durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
0x01, // flags
(samples.length & 0xFF000000) >>> 24,
(samples.length & 0xFF0000) >>> 16,
(samples.length & 0xFF00) >>> 8,
samples.length & 0xFF, // sample_count
(offset & 0xFF000000) >>> 24,
(offset & 0xFF0000) >>> 16,
(offset & 0xFF00) >>> 8,
offset & 0xFF // data_offset
];
};
videoTrun = function(track, offset) {
var bytes, samples, sample, i;
samples = track.samples || [];
offset += 8 + 12 + (16 * samples.length);
bytes = trunHeader(samples, offset);
for (i = 0; i < samples.length; i++) {
sample = samples[i];
bytes = bytes.concat([
(sample.duration & 0xFF000000) >>> 24,
(sample.duration & 0xFF0000) >>> 16,
(sample.duration & 0xFF00) >>> 8,
sample.duration & 0xFF, // sample_duration
(sample.size & 0xFF000000) >>> 24,
(sample.size & 0xFF0000) >>> 16,
(sample.size & 0xFF00) >>> 8,
sample.size & 0xFF, // sample_size
(sample.flags.isLeading << 2) | sample.flags.dependsOn,
(sample.flags.isDependedOn << 6) |
(sample.flags.hasRedundancy << 4) |
(sample.flags.paddingValue << 1) |
sample.flags.isNonSyncSample,
sample.flags.degradationPriority & 0xF0 << 8,
sample.flags.degradationPriority & 0x0F, // sample_flags
(sample.compositionTimeOffset & 0xFF000000) >>> 24,
(sample.compositionTimeOffset & 0xFF0000) >>> 16,
(sample.compositionTimeOffset & 0xFF00) >>> 8,
sample.compositionTimeOffset & 0xFF // sample_composition_time_offset
]);
}
return box(types.trun, new Uint8Array(bytes));
};
audioTrun = function(track, offset) {
var bytes, samples, sample, i;
samples = track.samples || [];
offset += 8 + 12 + (8 * samples.length);
bytes = trunHeader(samples, offset);
for (i = 0; i < samples.length; i++) {
sample = samples[i];
bytes = bytes.concat([
(sample.duration & 0xFF000000) >>> 24,
(sample.duration & 0xFF0000) >>> 16,
(sample.duration & 0xFF00) >>> 8,
sample.duration & 0xFF, // sample_duration
(sample.size & 0xFF000000) >>> 24,
(sample.size & 0xFF0000) >>> 16,
(sample.size & 0xFF00) >>> 8,
sample.size & 0xFF]); // sample_size
}
return box(types.trun, new Uint8Array(bytes));
};
trun = function(track, offset) {
if (track.type === 'audio') {
return audioTrun(track, offset);
}
return videoTrun(track, offset);
};
}());
module.exports = {
ftyp: ftyp,
mdat: mdat,
moof: moof,
moov: moov,
initSegment: function(tracks) {
var
fileType = ftyp(),
movie = moov(tracks),
result;
result = new Uint8Array(fileType.byteLength + movie.byteLength);
result.set(fileType);
result.set(movie, fileType.byteLength);
return result;
}
};
},{}],24:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* Utilities to detect basic properties and metadata about MP4s.
*/
'use strict';
var findBox, parseType, timescale, startTime;
// Find the data for a box specified by its path
findBox = function(data, path) {
var results = [],
i, size, type, end, subresults;
if (!path.length) {
// short-circuit the search for empty paths
return null;
}
for (i = 0; i < data.byteLength;) {
size = data[i] << 24;
size |= data[i + 1] << 16;
size |= data[i + 2] << 8;
size |= data[i + 3];
type = parseType(data.subarray(i + 4, i + 8));
end = size > 1 ? i + size : data.byteLength;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push(data.subarray(i + 8, end));
} else {
// recursively search for the next box along the path
subresults = findBox(data.subarray(i + 8, end), path.slice(1));
if (subresults.length) {
results = results.concat(subresults);
}
}
}
i = end;
}
// we've finished searching all of data
return results;
};
/**
* Returns the string representation of an ASCII encoded four byte buffer.
* @param buffer {Uint8Array} a four-byte buffer to translate
* @return {string} the corresponding string
*/
parseType = function(buffer) {
var result = '';
result += String.fromCharCode(buffer[0]);
result += String.fromCharCode(buffer[1]);
result += String.fromCharCode(buffer[2]);
result += String.fromCharCode(buffer[3]);
return result;
};
/**
* Parses an MP4 initialization segment and extracts the timescale
* values for any declared tracks. Timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the MP4.
*
* To determine the start time of an MP4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. Multiple timescales can be specified within an MP4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* ```
* @param init {Uint8Array} the bytes of the init segment
* @return {object} a hash of track ids to timescale values or null if
* the init segment is malformed.
*/
timescale = function(init) {
var
result = {},
traks = findBox(init, ['moov', 'trak']);
// mdhd timescale
return traks.reduce(function(result, trak) {
var tkhd, version, index, id, mdhd;
tkhd = findBox(trak, ['tkhd'])[0];
if (!tkhd) {
return null;
}
version = tkhd[0];
index = version === 0 ? 12 : 20;
id = tkhd[index] << 24 |
tkhd[index + 1] << 16 |
tkhd[index + 2] << 8 |
tkhd[index + 3];
mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
if (!mdhd) {
return null;
}
version = mdhd[0];
index = version === 0 ? 12 : 20;
result[id] = mdhd[index] << 24 |
mdhd[index + 1] << 16 |
mdhd[index + 2] << 8 |
mdhd[index + 3];
return result;
}, result);
};
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param timescale {object} a hash of track ids to timescale values.
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
startTime = function(timescale, fragment) {
var trafs, baseTimes, result;
// we need info from two childrend of each track fragment box
trafs = findBox(fragment, ['moof', 'traf']);
// determine the start times for each track
baseTimes = [].concat.apply([], trafs.map(function(traf) {
return findBox(traf, ['tfhd']).map(function(tfhd) {
var id, scale, baseTime;
// get the track id from the tfhd
id = tfhd[4] << 24 |
tfhd[5] << 16 |
tfhd[6] << 8 |
tfhd[7];
// assume a 90kHz clock if no timescale was specified
scale = timescale[id] || 90e3;
// get the base media decode time from the tfdt
baseTime = findBox(traf, ['tfdt']).map(function(tfdt) {
var version, result;
version = tfdt[0];
result = tfdt[4] << 24 |
tfdt[5] << 16 |
tfdt[6] << 8 |
tfdt[7];
if (version === 1) {
result *= Math.pow(2, 32);
result += tfdt[8] << 24 |
tfdt[9] << 16 |
tfdt[10] << 8 |
tfdt[11];
}
return result;
})[0];
baseTime = baseTime || Infinity;
// convert base time to seconds
return baseTime / scale;
});
}));
// return the minimum
result = Math.min.apply(null, baseTimes);
return isFinite(result) ? result : 0;
};
module.exports = {
parseType: parseType,
timescale: timescale,
startTime: startTime
};
},{}],25:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* A stream-based mp2t to mp4 converter. This utility can be used to
* deliver mp4s to a SourceBuffer on platforms that support native
* Media Source Extensions.
*/
'use strict';
var Stream = require('../utils/stream.js');
var mp4 = require('./mp4-generator.js');
var m2ts = require('../m2ts/m2ts.js');
var AdtsStream = require('../codecs/adts.js');
var H264Stream = require('../codecs/h264').H264Stream;
var AacStream = require('../aac');
// constants
var AUDIO_PROPERTIES = [
'audioobjecttype',
'channelcount',
'samplerate',
'samplingfrequencyindex',
'samplesize'
];
var VIDEO_PROPERTIES = [
'width',
'height',
'profileIdc',
'levelIdc',
'profileCompatibility'
];
// object types
var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
// Helper functions
var
createDefaultSample,
isLikelyAacData,
collectDtsInfo,
clearDtsInfo,
calculateTrackBaseMediaDecodeTime,
arrayEquals,
sumFrameByteLengths;
/**
* Default sample object
* see ISO/IEC 14496-12:2012, section 8.6.4.3
*/
createDefaultSample = function() {
return {
size: 0,
flags: {
isLeading: 0,
dependsOn: 1,
isDependedOn: 0,
hasRedundancy: 0,
degradationPriority: 0
}
};
};
isLikelyAacData = function(data) {
if ((data[0] === 'I'.charCodeAt(0)) &&
(data[1] === 'D'.charCodeAt(0)) &&
(data[2] === '3'.charCodeAt(0))) {
return true;
}
return false;
};
/**
* Compare two arrays (even typed) for same-ness
*/
arrayEquals = function(a, b) {
var
i;
if (a.length !== b.length) {
return false;
}
// compare the value of each element in the array
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
/**
* Sum the `byteLength` properties of the data in each AAC frame
*/
sumFrameByteLengths = function(array) {
var
i,
currentObj,
sum = 0;
// sum the byteLength's all each nal unit in the frame
for (i = 0; i < array.length; i++) {
currentObj = array[i];
sum += currentObj.data.byteLength;
}
return sum;
};
/**
* Constructs a single-track, ISO BMFF media segment from AAC data
* events. The output of this stream can be fed to a SourceBuffer
* configured with a suitable initialization segment.
*/
AudioSegmentStream = function(track) {
var
adtsFrames = [],
sequenceNumber = 0,
earliestAllowedDts = 0;
AudioSegmentStream.prototype.init.call(this);
this.push = function(data) {
collectDtsInfo(track, data);
if (track) {
AUDIO_PROPERTIES.forEach(function(prop) {
track[prop] = data[prop];
});
}
// buffer audio data until end() is called
adtsFrames.push(data);
};
this.setEarliestDts = function(earliestDts) {
earliestAllowedDts = earliestDts - track.timelineStartInfo.baseMediaDecodeTime;
};
this.flush = function() {
var
frames,
moof,
mdat,
boxes;
// return early if no audio data has been observed
if (adtsFrames.length === 0) {
this.trigger('done', 'AudioSegmentStream');
return;
}
frames = this.trimAdtsFramesByEarliestDts_(adtsFrames);
// we have to build the index from byte locations to
// samples (that is, adts frames) in the audio data
track.samples = this.generateSampleTable_(frames);
// concatenate the audio data to constuct the mdat
mdat = mp4.mdat(this.concatenateFrameData_(frames));
adtsFrames = [];
calculateTrackBaseMediaDecodeTime(track);
moof = mp4.moof(sequenceNumber, [track]);
boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
// bump the sequence number for next time
sequenceNumber++;
boxes.set(moof);
boxes.set(mdat, moof.byteLength);
clearDtsInfo(track);
this.trigger('data', {track: track, boxes: boxes});
this.trigger('done', 'AudioSegmentStream');
};
// If the audio segment extends before the earliest allowed dts
// value, remove AAC frames until starts at or after the earliest
// allowed DTS so that we don't end up with a negative baseMedia-
// DecodeTime for the audio track
this.trimAdtsFramesByEarliestDts_ = function(adtsFrames) {
if (track.minSegmentDts >= earliestAllowedDts) {
return adtsFrames;
}
// We will need to recalculate the earliest segment Dts
track.minSegmentDts = Infinity;
return adtsFrames.filter(function(currentFrame) {
// If this is an allowed frame, keep it and record it's Dts
if (currentFrame.dts >= earliestAllowedDts) {
track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
track.minSegmentPts = track.minSegmentDts;
return true;
}
// Otherwise, discard it
return false;
});
};
// generate the track's raw mdat data from an array of frames
this.generateSampleTable_ = function(frames) {
var
i,
currentFrame,
samples = [];
for (i = 0; i < frames.length; i++) {
currentFrame = frames[i];
samples.push({
size: currentFrame.data.byteLength,
duration: 1024 // For AAC audio, all samples contain 1024 samples
});
}
return samples;
};
// generate the track's sample table from an array of frames
this.concatenateFrameData_ = function(frames) {
var
i,
currentFrame,
dataOffset = 0,
data = new Uint8Array(sumFrameByteLengths(frames));
for (i = 0; i < frames.length; i++) {
currentFrame = frames[i];
data.set(currentFrame.data, dataOffset);
dataOffset += currentFrame.data.byteLength;
}
return data;
};
};
AudioSegmentStream.prototype = new Stream();
/**
* Constructs a single-track, ISO BMFF media segment from H264 data
* events. The output of this stream can be fed to a SourceBuffer
* configured with a suitable initialization segment.
* @param track {object} track metadata configuration
*/
VideoSegmentStream = function(track) {
var
sequenceNumber = 0,
nalUnits = [],
config,
pps;
VideoSegmentStream.prototype.init.call(this);
delete track.minPTS;
this.gopCache_ = [];
this.push = function(nalUnit) {
collectDtsInfo(track, nalUnit);
// record the track config
if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
config = nalUnit.config;
track.sps = [nalUnit.data];
VIDEO_PROPERTIES.forEach(function(prop) {
track[prop] = config[prop];
}, this);
}
if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
!pps) {
pps = nalUnit.data;
track.pps = [nalUnit.data];
}
// buffer video until flush() is called
nalUnits.push(nalUnit);
};
this.flush = function() {
var
frames,
gopForFusion,
gops,
moof,
mdat,
boxes;
// Throw away nalUnits at the start of the byte stream until
// we find the first AUD
while (nalUnits.length) {
if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
break;
}
nalUnits.shift();
}
// Return early if no video data has been observed
if (nalUnits.length === 0) {
this.resetStream_();
this.trigger('done', 'VideoSegmentStream');
return;
}
// Organize the raw nal-units into arrays that represent
// higher-level constructs such as frames and gops
// (group-of-pictures)
frames = this.groupNalsIntoFrames_(nalUnits);
gops = this.groupFramesIntoGops_(frames);
// If the first frame of this fragment is not a keyframe we have
// a problem since MSE (on Chrome) requires a leading keyframe.
//
// We have two approaches to repairing this situation:
// 1) GOP-FUSION:
// This is where we keep track of the GOPS (group-of-pictures)
// from previous fragments and attempt to find one that we can
// prepend to the current fragment in order to create a valid
// fragment.
// 2) KEYFRAME-PULLING:
// Here we search for the first keyframe in the fragment and
// throw away all the frames between the start of the fragment
// and that keyframe. We then extend the duration and pull the
// PTS of the keyframe forward so that it covers the time range
// of the frames that were disposed of.
//
// #1 is far prefereable over #2 which can cause "stuttering" but
// requires more things to be just right.
if (!gops[0][0].keyFrame) {
// Search for a gop for fusion from our gopCache
gopForFusion = this.getGopForFusion_(nalUnits[0], track);
if (gopForFusion) {
gops.unshift(gopForFusion);
// Adjust Gops' metadata to account for the inclusion of the
// new gop at the beginning
gops.byteLength += gopForFusion.byteLength;
gops.nalCount += gopForFusion.nalCount;
gops.pts = gopForFusion.pts;
gops.dts = gopForFusion.dts;
gops.duration += gopForFusion.duration;
} else {
// If we didn't find a candidate gop fall back to keyrame-pulling
gops = this.extendFirstKeyFrame_(gops);
}
}
collectDtsInfo(track, gops);
// First, we have to build the index from byte locations to
// samples (that is, frames) in the video data
track.samples = this.generateSampleTable_(gops);
// Concatenate the video data and construct the mdat
mdat = mp4.mdat(this.concatenateNalData_(gops));
// save all the nals in the last GOP into the gop cache
this.gopCache_.unshift({
gop: gops.pop(),
pps: track.pps,
sps: track.sps
});
// Keep a maximum of 6 GOPs in the cache
this.gopCache_.length = Math.min(6, this.gopCache_.length);
// Clear nalUnits
nalUnits = [];
calculateTrackBaseMediaDecodeTime(track);
this.trigger('timelineStartInfo', track.timelineStartInfo);
moof = mp4.moof(sequenceNumber, [track]);
// it would be great to allocate this array up front instead of
// throwing away hundreds of media segment fragments
boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
// Bump the sequence number for next time
sequenceNumber++;
boxes.set(moof);
boxes.set(mdat, moof.byteLength);
this.trigger('data', {track: track, boxes: boxes});
this.resetStream_();
// Continue with the flush process now
this.trigger('done', 'VideoSegmentStream');
};
this.resetStream_ = function() {
clearDtsInfo(track);
// reset config and pps because they may differ across segments
// for instance, when we are rendition switching
config = undefined;
pps = undefined;
};
// Search for a candidate Gop for gop-fusion from the gop cache and
// return it or return null if no good candidate was found
this.getGopForFusion_ = function(nalUnit) {
var
halfSecond = 45000, // Half-a-second in a 90khz clock
allowableOverlap = 10000, // About 3 frames @ 30fps
nearestDistance = Infinity,
dtsDistance,
nearestGopObj,
currentGop,
currentGopObj,
i;
// Search for the GOP nearest to the beginning of this nal unit
for (i = 0; i < this.gopCache_.length; i++) {
currentGopObj = this.gopCache_[i];
currentGop = currentGopObj.gop;
// Reject Gops with different SPS or PPS
if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
!(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
continue;
}
// Reject Gops that would require a negative baseMediaDecodeTime
if (currentGop.dts < track.timelineStartInfo.dts) {
continue;
}
// The distance between the end of the gop and the start of the nalUnit
dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
// Only consider GOPS that start before the nal unit and end within
// a half-second of the nal unit
if (dtsDistance >= -allowableOverlap &&
dtsDistance <= halfSecond) {
// Always use the closest GOP we found if there is more than
// one candidate
if (!nearestGopObj ||
nearestDistance > dtsDistance) {
nearestGopObj = currentGopObj;
nearestDistance = dtsDistance;
}
}
}
if (nearestGopObj) {
return nearestGopObj.gop;
}
return null;
};
this.extendFirstKeyFrame_ = function(gops) {
var currentGop;
if (!gops[0][0].keyFrame) {
// Remove the first GOP
currentGop = gops.shift();
gops.byteLength -= currentGop.byteLength;
gops.nalCount -= currentGop.nalCount;
// Extend the first frame of what is now the
// first gop to cover the time period of the
// frames we just removed
gops[0][0].dts = currentGop.dts;
gops[0][0].pts = currentGop.pts;
gops[0][0].duration += currentGop.duration;
}
return gops;
};
// Convert an array of nal units into an array of frames with each frame being
// composed of the nal units that make up that frame
// Also keep track of cummulative data about the frame from the nal units such
// as the frame duration, starting pts, etc.
this.groupNalsIntoFrames_ = function(nalUnits) {
var
i,
currentNal,
currentFrame = [],
frames = [];
currentFrame.byteLength = 0;
for (i = 0; i < nalUnits.length; i++) {
currentNal = nalUnits[i];
// Split on 'aud'-type nal units
if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
// Since the very first nal unit is expected to be an AUD
// only push to the frames array when currentFrame is not empty
if (currentFrame.length) {
currentFrame.duration = currentNal.dts - currentFrame.dts;
frames.push(currentFrame);
}
currentFrame = [currentNal];
currentFrame.byteLength = currentNal.data.byteLength;
currentFrame.pts = currentNal.pts;
currentFrame.dts = currentNal.dts;
} else {
// Specifically flag key frames for ease of use later
if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
currentFrame.keyFrame = true;
}
currentFrame.duration = currentNal.dts - currentFrame.dts;
currentFrame.byteLength += currentNal.data.byteLength;
currentFrame.push(currentNal);
}
}
// For the last frame, use the duration of the previous frame if we
// have nothing better to go on
if (frames.length &&
(!currentFrame.duration ||
currentFrame.duration <= 0)) {
currentFrame.duration = frames[frames.length - 1].duration;
}
// Push the final frame
frames.push(currentFrame);
return frames;
};
// Convert an array of frames into an array of Gop with each Gop being composed
// of the frames that make up that Gop
// Also keep track of cummulative data about the Gop from the frames such as the
// Gop duration, starting pts, etc.
this.groupFramesIntoGops_ = function(frames) {
var
i,
currentFrame,
currentGop = [],
gops = [];
// We must pre-set some of the values on the Gop since we
// keep running totals of these values
currentGop.byteLength = 0;
currentGop.nalCount = 0;
currentGop.duration = 0;
currentGop.pts = frames[0].pts;
currentGop.dts = frames[0].dts;
// store some metadata about all the Gops
gops.byteLength = 0;
gops.nalCount = 0;
gops.duration = 0;
gops.pts = frames[0].pts;
gops.dts = frames[0].dts;
for (i = 0; i < frames.length; i++) {
currentFrame = frames[i];
if (currentFrame.keyFrame) {
// Since the very first frame is expected to be an keyframe
// only push to the gops array when currentGop is not empty
if (currentGop.length) {
gops.push(currentGop);
gops.byteLength += currentGop.byteLength;
gops.nalCount += currentGop.nalCount;
gops.duration += currentGop.duration;
}
currentGop = [currentFrame];
currentGop.nalCount = currentFrame.length;
currentGop.byteLength = currentFrame.byteLength;
currentGop.pts = currentFrame.pts;
currentGop.dts = currentFrame.dts;
currentGop.duration = currentFrame.duration;
} else {
currentGop.duration += currentFrame.duration;
currentGop.nalCount += currentFrame.length;
currentGop.byteLength += currentFrame.byteLength;
currentGop.push(currentFrame);
}
}
if (gops.length && currentGop.duration <= 0) {
currentGop.duration = gops[gops.length - 1].duration;
}
gops.byteLength += currentGop.byteLength;
gops.nalCount += currentGop.nalCount;
gops.duration += currentGop.duration;
// push the final Gop
gops.push(currentGop);
return gops;
};
// generate the track's sample table from an array of gops
this.generateSampleTable_ = function(gops, baseDataOffset) {
var
h, i,
sample,
currentGop,
currentFrame,
dataOffset = baseDataOffset || 0,
samples = [];
for (h = 0; h < gops.length; h++) {
currentGop = gops[h];
for (i = 0; i < currentGop.length; i++) {
currentFrame = currentGop[i];
sample = createDefaultSample();
sample.dataOffset = dataOffset;
sample.compositionTimeOffset = currentFrame.pts - currentFrame.dts;
sample.duration = currentFrame.duration;
sample.size = 4 * currentFrame.length; // Space for nal unit size
sample.size += currentFrame.byteLength;
if (currentFrame.keyFrame) {
sample.flags.dependsOn = 2;
}
dataOffset += sample.size;
samples.push(sample);
}
}
return samples;
};
// generate the track's raw mdat data from an array of gops
this.concatenateNalData_ = function(gops) {
var
h, i, j,
currentGop,
currentFrame,
currentNal,
dataOffset = 0,
nalsByteLength = gops.byteLength,
numberOfNals = gops.nalCount,
totalByteLength = nalsByteLength + 4 * numberOfNals,
data = new Uint8Array(totalByteLength),
view = new DataView(data.buffer);
// For each Gop..
for (h = 0; h < gops.length; h++) {
currentGop = gops[h];
// For each Frame..
for (i = 0; i < currentGop.length; i++) {
currentFrame = currentGop[i];
// For each NAL..
for (j = 0; j < currentFrame.length; j++) {
currentNal = currentFrame[j];
view.setUint32(dataOffset, currentNal.data.byteLength);
dataOffset += 4;
data.set(currentNal.data, dataOffset);
dataOffset += currentNal.data.byteLength;
}
}
}
return data;
};
};
VideoSegmentStream.prototype = new Stream();
/**
* Store information about the start and end of the track and the
* duration for each frame/sample we process in order to calculate
* the baseMediaDecodeTime
*/
collectDtsInfo = function(track, data) {
if (typeof data.pts === 'number') {
if (track.timelineStartInfo.pts === undefined) {
track.timelineStartInfo.pts = data.pts;
}
if (track.minSegmentPts === undefined) {
track.minSegmentPts = data.pts;
} else {
track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
}
if (track.maxSegmentPts === undefined) {
track.maxSegmentPts = data.pts;
} else {
track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
}
}
if (typeof data.dts === 'number') {
if (track.timelineStartInfo.dts === undefined) {
track.timelineStartInfo.dts = data.dts;
}
if (track.minSegmentDts === undefined) {
track.minSegmentDts = data.dts;
} else {
track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
}
if (track.maxSegmentDts === undefined) {
track.maxSegmentDts = data.dts;
} else {
track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
}
}
};
/**
* Clear values used to calculate the baseMediaDecodeTime between
* tracks
*/
clearDtsInfo = function(track) {
delete track.minSegmentDts;
delete track.maxSegmentDts;
delete track.minSegmentPts;
delete track.maxSegmentPts;
};
/**
* Calculate the track's baseMediaDecodeTime based on the earliest
* DTS the transmuxer has ever seen and the minimum DTS for the
* current track
*/
calculateTrackBaseMediaDecodeTime = function(track) {
var
oneSecondInTS = 90000, // 90kHz clock
scale,
// Calculate the distance, in time, that this segment starts from the start
// of the timeline (earliest time seen since the transmuxer initialized)
timeSinceStartOfTimeline = track.minSegmentDts - track.timelineStartInfo.dts;
// track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
// we want the start of the first segment to be placed
track.baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
// Add to that the distance this segment is from the very first
track.baseMediaDecodeTime += timeSinceStartOfTimeline;
// baseMediaDecodeTime must not become negative
track.baseMediaDecodeTime = Math.max(0, track.baseMediaDecodeTime);
if (track.type === 'audio') {
// Audio has a different clock equal to the sampling_rate so we need to
// scale the PTS values into the clock rate of the track
scale = track.samplerate / oneSecondInTS;
track.baseMediaDecodeTime *= scale;
track.baseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime);
}
};
/**
* A Stream that can combine multiple streams (ie. audio & video)
* into a single output segment for MSE. Also supports audio-only
* and video-only streams.
*/
CoalesceStream = function(options, metadataStream) {
// Number of Tracks per output segment
// If greater than 1, we combine multiple
// tracks into a single segment
this.numberOfTracks = 0;
this.metadataStream = metadataStream;
if (typeof options.remux !== 'undefined') {
this.remuxTracks = !!options.remux;
} else {
this.remuxTracks = true;
}
this.pendingTracks = [];
this.videoTrack = null;
this.pendingBoxes = [];
this.pendingCaptions = [];
this.pendingMetadata = [];
this.pendingBytes = 0;
this.emittedTracks = 0;
CoalesceStream.prototype.init.call(this);
// Take output from multiple
this.push = function(output) {
// buffer incoming captions until the associated video segment
// finishes
if (output.text) {
return this.pendingCaptions.push(output);
}
// buffer incoming id3 tags until the final flush
if (output.frames) {
return this.pendingMetadata.push(output);
}
// Add this track to the list of pending tracks and store
// important information required for the construction of
// the final segment
this.pendingTracks.push(output.track);
this.pendingBoxes.push(output.boxes);
this.pendingBytes += output.boxes.byteLength;
if (output.track.type === 'video') {
this.videoTrack = output.track;
}
if (output.track.type === 'audio') {
this.audioTrack = output.track;
}
};
};
CoalesceStream.prototype = new Stream();
CoalesceStream.prototype.flush = function(flushSource) {
var
offset = 0,
event = {
captions: [],
metadata: [],
info: {}
},
caption,
id3,
initSegment,
timelineStartPts = 0,
i;
if (this.pendingTracks.length < this.numberOfTracks) {
if (flushSource !== 'VideoSegmentStream' &&
flushSource !== 'AudioSegmentStream') {
// Return because we haven't received a flush from a data-generating
// portion of the segment (meaning that we have only recieved meta-data
// or captions.)
return;
} else if (this.remuxTracks) {
// Return until we have enough tracks from the pipeline to remux (if we
// are remuxing audio and video into a single MP4)
return;
} else if (this.pendingTracks.length === 0) {
// In the case where we receive a flush without any data having been
// received we consider it an emitted track for the purposes of coalescing
// `done` events.
// We do this for the case where there is an audio and video track in the
// segment but no audio data. (seen in several playlists with alternate
// audio tracks and no audio present in the main TS segments.)
this.emittedTracks++;
if (this.emittedTracks >= this.numberOfTracks) {
this.trigger('done');
this.emittedTracks = 0;
}
return;
}
}
if (this.videoTrack) {
timelineStartPts = this.videoTrack.timelineStartInfo.pts;
VIDEO_PROPERTIES.forEach(function(prop) {
event.info[prop] = this.videoTrack[prop];
}, this);
} else if (this.audioTrack) {
timelineStartPts = this.audioTrack.timelineStartInfo.pts;
AUDIO_PROPERTIES.forEach(function(prop) {
event.info[prop] = this.audioTrack[prop];
}, this);
}
if (this.pendingTracks.length === 1) {
event.type = this.pendingTracks[0].type;
} else {
event.type = 'combined';
}
this.emittedTracks += this.pendingTracks.length;
initSegment = mp4.initSegment(this.pendingTracks);
// Create a new typed array to hold the init segment
event.initSegment = new Uint8Array(initSegment.byteLength);
// Create an init segment containing a moov
// and track definitions
event.initSegment.set(initSegment);
// Create a new typed array to hold the moof+mdats
event.data = new Uint8Array(this.pendingBytes);
// Append each moof+mdat (one per track) together
for (i = 0; i < this.pendingBoxes.length; i++) {
event.data.set(this.pendingBoxes[i], offset);
offset += this.pendingBoxes[i].byteLength;
}
// Translate caption PTS times into second offsets into the
// video timeline for the segment
for (i = 0; i < this.pendingCaptions.length; i++) {
caption = this.pendingCaptions[i];
caption.startTime = (caption.startPts - timelineStartPts);
caption.startTime /= 90e3;
caption.endTime = (caption.endPts - timelineStartPts);
caption.endTime /= 90e3;
event.captions.push(caption);
}
// Translate ID3 frame PTS times into second offsets into the
// video timeline for the segment
for (i = 0; i < this.pendingMetadata.length; i++) {
id3 = this.pendingMetadata[i];
id3.cueTime = (id3.pts - timelineStartPts);
id3.cueTime /= 90e3;
event.metadata.push(id3);
}
// We add this to every single emitted segment even though we only need
// it for the first
event.metadata.dispatchType = this.metadataStream.dispatchType;
// Reset stream state
this.pendingTracks.length = 0;
this.videoTrack = null;
this.pendingBoxes.length = 0;
this.pendingCaptions.length = 0;
this.pendingBytes = 0;
this.pendingMetadata.length = 0;
// Emit the built segment
this.trigger('data', event);
// Only emit `done` if all tracks have been flushed and emitted
if (this.emittedTracks >= this.numberOfTracks) {
this.trigger('done');
this.emittedTracks = 0;
}
};
/**
* A Stream that expects MP2T binary data as input and produces
* corresponding media segments, suitable for use with Media Source
* Extension (MSE) implementations that support the ISO BMFF byte
* stream format, like Chrome.
*/
Transmuxer = function(options) {
var
self = this,
hasFlushed = true,
videoTrack,
audioTrack;
Transmuxer.prototype.init.call(this);
options = options || {};
this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
this.transmuxPipeline_ = {};
this.setupAacPipeline = function() {
var pipeline = {};
this.transmuxPipeline_ = pipeline;
pipeline.type = 'aac';
pipeline.metadataStream = new m2ts.MetadataStream();
// set up the parsing pipeline
pipeline.aacStream = new AacStream();
pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
pipeline.adtsStream = new AdtsStream();
pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
pipeline.headOfPipeline = pipeline.aacStream;
pipeline.aacStream
.pipe(pipeline.audioTimestampRolloverStream)
.pipe(pipeline.adtsStream);
pipeline.aacStream
.pipe(pipeline.timedMetadataTimestampRolloverStream)
.pipe(pipeline.metadataStream)
.pipe(pipeline.coalesceStream);
pipeline.metadataStream.on('timestamp', function(frame) {
pipeline.aacStream.setTimestamp(frame.timeStamp);
});
pipeline.aacStream.on('data', function(data) {
if (data.type === 'timed-metadata' && !pipeline.audioSegmentStream) {
audioTrack = audioTrack || {
timelineStartInfo: {
baseMediaDecodeTime: self.baseMediaDecodeTime
},
codec: 'adts',
type: 'audio'
};
// hook up the audio segment stream to the first track with aac data
pipeline.coalesceStream.numberOfTracks++;
pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack);
// Set up the final part of the audio pipeline
pipeline.adtsStream
.pipe(pipeline.audioSegmentStream)
.pipe(pipeline.coalesceStream);
}
});
// Re-emit any data coming from the coalesce stream to the outside world
pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
// Let the consumer know we have finished flushing the entire pipeline
pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
};
this.setupTsPipeline = function() {
var pipeline = {};
this.transmuxPipeline_ = pipeline;
pipeline.type = 'ts';
pipeline.metadataStream = new m2ts.MetadataStream();
// set up the parsing pipeline
pipeline.packetStream = new m2ts.TransportPacketStream();
pipeline.parseStream = new m2ts.TransportParseStream();
pipeline.elementaryStream = new m2ts.ElementaryStream();
pipeline.videoTimestampRolloverStream = new m2ts.TimestampRolloverStream('video');
pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
pipeline.adtsStream = new AdtsStream();
pipeline.h264Stream = new H264Stream();
pipeline.captionStream = new m2ts.CaptionStream();
pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
pipeline.headOfPipeline = pipeline.packetStream;
// disassemble MPEG2-TS packets into elementary streams
pipeline.packetStream
.pipe(pipeline.parseStream)
.pipe(pipeline.elementaryStream);
// !!THIS ORDER IS IMPORTANT!!
// demux the streams
pipeline.elementaryStream
.pipe(pipeline.videoTimestampRolloverStream)
.pipe(pipeline.h264Stream);
pipeline.elementaryStream
.pipe(pipeline.audioTimestampRolloverStream)
.pipe(pipeline.adtsStream);
pipeline.elementaryStream
.pipe(pipeline.timedMetadataTimestampRolloverStream)
.pipe(pipeline.metadataStream)
.pipe(pipeline.coalesceStream);
// Hook up CEA-608/708 caption stream
pipeline.h264Stream.pipe(pipeline.captionStream)
.pipe(pipeline.coalesceStream);
pipeline.elementaryStream.on('data', function(data) {
var i;
if (data.type === 'metadata') {
i = data.tracks.length;
// scan the tracks listed in the metadata
while (i--) {
if (!videoTrack && data.tracks[i].type === 'video') {
videoTrack = data.tracks[i];
videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
} else if (!audioTrack && data.tracks[i].type === 'audio') {
audioTrack = data.tracks[i];
audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
}
}
// hook up the video segment stream to the first track with h264 data
if (videoTrack && !pipeline.videoSegmentStream) {
pipeline.coalesceStream.numberOfTracks++;
pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack);
pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
// When video emits timelineStartInfo data after a flush, we forward that
// info to the AudioSegmentStream, if it exists, because video timeline
// data takes precedence.
if (audioTrack) {
audioTrack.timelineStartInfo = timelineStartInfo;
// On the first segment we trim AAC frames that exist before the
// very earliest DTS we have seen in video because Chrome will
// interpret any video track with a baseMediaDecodeTime that is
// non-zero as a gap.
pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts);
}
});
// Set up the final part of the video pipeline
pipeline.h264Stream
.pipe(pipeline.videoSegmentStream)
.pipe(pipeline.coalesceStream);
}
if (audioTrack && !pipeline.audioSegmentStream) {
// hook up the audio segment stream to the first track with aac data
pipeline.coalesceStream.numberOfTracks++;
pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack);
// Set up the final part of the audio pipeline
pipeline.adtsStream
.pipe(pipeline.audioSegmentStream)
.pipe(pipeline.coalesceStream);
}
}
});
// Re-emit any data coming from the coalesce stream to the outside world
pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
// Let the consumer know we have finished flushing the entire pipeline
pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
};
// hook up the segment streams once track metadata is delivered
this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
var pipeline = this.transmuxPipeline_;
this.baseMediaDecodeTime = baseMediaDecodeTime;
if (audioTrack) {
audioTrack.timelineStartInfo.dts = undefined;
audioTrack.timelineStartInfo.pts = undefined;
clearDtsInfo(audioTrack);
audioTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
}
if (videoTrack) {
if (pipeline.videoSegmentStream) {
pipeline.videoSegmentStream.gopCache_ = [];
}
videoTrack.timelineStartInfo.dts = undefined;
videoTrack.timelineStartInfo.pts = undefined;
clearDtsInfo(videoTrack);
videoTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
}
};
// feed incoming data to the front of the parsing pipeline
this.push = function(data) {
if (hasFlushed) {
var isAac = isLikelyAacData(data);
if (isAac && this.transmuxPipeline_.type !== 'aac') {
this.setupAacPipeline();
} else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
this.setupTsPipeline();
}
hasFlushed = false;
}
this.transmuxPipeline_.headOfPipeline.push(data);
};
// flush any buffered data
this.flush = function() {
hasFlushed = true;
// Start at the top of the pipeline and flush all pending work
this.transmuxPipeline_.headOfPipeline.flush();
};
};
Transmuxer.prototype = new Stream();
module.exports = {
Transmuxer: Transmuxer,
VideoSegmentStream: VideoSegmentStream,
AudioSegmentStream: AudioSegmentStream,
AUDIO_PROPERTIES: AUDIO_PROPERTIES,
VIDEO_PROPERTIES: VIDEO_PROPERTIES
};
},{"../aac":9,"../codecs/adts.js":10,"../codecs/h264":11,"../m2ts/m2ts.js":18,"../utils/stream.js":27,"./mp4-generator.js":23}],26:[function(require,module,exports){
'use strict';
var ExpGolomb;
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding
* scheme used by h264.
*/
ExpGolomb = function(workingData) {
var
// the number of bytes left to examine in workingData
workingBytesAvailable = workingData.byteLength,
// the current word being examined
workingWord = 0, // :uint
// the number of bits left to examine in the current word
workingBitsAvailable = 0; // :uint;
// ():uint
this.length = function() {
return (8 * workingBytesAvailable);
};
// ():uint
this.bitsAvailable = function() {
return (8 * workingBytesAvailable) + workingBitsAvailable;
};
// ():void
this.loadWord = function() {
var
position = workingData.byteLength - workingBytesAvailable,
workingBytes = new Uint8Array(4),
availableBytes = Math.min(4, workingBytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(workingData.subarray(position,
position + availableBytes));
workingWord = new DataView(workingBytes.buffer).getUint32(0);
// track the amount of workingData that has been processed
workingBitsAvailable = availableBytes * 8;
workingBytesAvailable -= availableBytes;
};
// (count:int):void
this.skipBits = function(count) {
var skipBytes; // :int
if (workingBitsAvailable > count) {
workingWord <<= count;
workingBitsAvailable -= count;
} else {
count -= workingBitsAvailable;
skipBytes = Math.floor(count / 8);
count -= (skipBytes * 8);
workingBytesAvailable -= skipBytes;
this.loadWord();
workingWord <<= count;
workingBitsAvailable -= count;
}
};
// (size:int):uint
this.readBits = function(size) {
var
bits = Math.min(workingBitsAvailable, size), // :uint
valu = workingWord >>> (32 - bits); // :uint
// if size > 31, handle error
workingBitsAvailable -= bits;
if (workingBitsAvailable > 0) {
workingWord <<= bits;
} else if (workingBytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0) {
return valu << bits | this.readBits(bits);
}
return valu;
};
// ():uint
this.skipLeadingZeros = function() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
if ((workingWord & (0x80000000 >>> leadingZeroCount)) !== 0) {
// the first bit of working word is 1
workingWord <<= leadingZeroCount;
workingBitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
}
// we exhausted workingWord and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLeadingZeros();
};
// ():void
this.skipUnsignedExpGolomb = function() {
this.skipBits(1 + this.skipLeadingZeros());
};
// ():void
this.skipExpGolomb = function() {
this.skipBits(1 + this.skipLeadingZeros());
};
// ():uint
this.readUnsignedExpGolomb = function() {
var clz = this.skipLeadingZeros(); // :uint
return this.readBits(clz + 1) - 1;
};
// ():int
this.readExpGolomb = function() {
var valu = this.readUnsignedExpGolomb(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
}
return -1 * (valu >>> 1); // divide by two then make it negative
};
// Some convenience functions
// :Boolean
this.readBoolean = function() {
return this.readBits(1) === 1;
};
// ():int
this.readUnsignedByte = function() {
return this.readBits(8);
};
this.loadWord();
};
module.exports = ExpGolomb;
},{}],27:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) 2014 Brightcove
* All rights reserved.
*
* A lightweight readable stream implemention that handles event dispatching.
* Objects that inherit from streams should call init in their constructors.
*/
'use strict';
var Stream = function() {
this.init = function() {
var listeners = {};
/**
* Add a listener for a specified event type.
* @param type {string} the event name
* @param listener {function} the callback to be invoked when an event of
* the specified type occurs
*/
this.on = function(type, listener) {
if (!listeners[type]) {
listeners[type] = [];
}
listeners[type] = listeners[type].concat(listener);
};
/**
* Remove a listener for a specified event type.
* @param type {string} the event name
* @param listener {function} a function previously registered for this
* type of event through `on`
*/
this.off = function(type, listener) {
var index;
if (!listeners[type]) {
return false;
}
index = listeners[type].indexOf(listener);
listeners[type] = listeners[type].slice();
listeners[type].splice(index, 1);
return index > -1;
};
/**
* Trigger an event of the specified type on this stream. Any additional
* arguments to this function are passed as parameters to event listeners.
* @param type {string} the event name
*/
this.trigger = function(type) {
var callbacks, i, length, args;
callbacks = listeners[type];
if (!callbacks) {
return;
}
// Slicing the arguments on every invocation of this method
// can add a significant amount of overhead. Avoid the
// intermediate object creation for the common case of a
// single callback argument
if (arguments.length === 2) {
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].call(this, arguments[1]);
}
} else {
args = [];
i = arguments.length;
for (i = 1; i < arguments.length; ++i) {
args.push(arguments[i]);
}
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].apply(this, args);
}
}
};
/**
* Destroys the stream and cleans up.
*/
this.dispose = function() {
listeners = {};
};
};
};
/**
* Forwards all `data` events on this stream to the destination stream. The
* destination stream should provide a method `push` to receive the data
* events as they arrive.
* @param destination {stream} the stream that will receive all `data` events
* @param autoFlush {boolean} if false, we will not call `flush` on the destination
* when the current stream emits a 'done' event
* @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
*/
Stream.prototype.pipe = function(destination) {
this.on('data', function(data) {
destination.push(data);
});
this.on('done', function(flushSource) {
destination.flush(flushSource);
});
return destination;
};
// Default stream functions that are expected to be overridden to perform
// actual work. These are provided by the prototype as a sort of no-op
// implementation so that we don't have to check for their existence in the
// `pipe` function above.
Stream.prototype.push = function(data) {
this.trigger('data', data);
};
Stream.prototype.flush = function(flushSource) {
this.trigger('done', flushSource);
};
module.exports = Stream;
},{}],28:[function(require,module,exports){
/**
* @file ad-cue-tags.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Searches for an ad cue that overlaps with the given mediaTime
*/
var findAdCue = function findAdCue(track, mediaTime) {
var cues = track.cues;
for (var i = 0; i < cues.length; i++) {
var cue = cues[i];
if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
return cue;
}
}
return null;
};
var updateAdCues = function updateAdCues(media, track) {
var offset = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2];
if (!media.segments) {
return;
}
var mediaTime = offset;
var cue = undefined;
for (var i = 0; i < media.segments.length; i++) {
var segment = media.segments[i];
if (!cue) {
// Since the cues will span for at least the segment duration, adding a fudge
// factor of half segment duration will prevent duplicate cues from being
// created when timing info is not exact (e.g. cue start time initialized
// at 10.006677, but next call mediaTime is 10.003332 )
cue = findAdCue(track, mediaTime + segment.duration / 2);
}
if (cue) {
if ('cueIn' in segment) {
// Found a CUE-IN so end the cue
cue.endTime = mediaTime;
cue.adEndTime = mediaTime;
mediaTime += segment.duration;
cue = null;
continue;
}
if (mediaTime < cue.endTime) {
// Already processed this mediaTime for this cue
mediaTime += segment.duration;
continue;
}
// otherwise extend cue until a CUE-IN is found
cue.endTime += segment.duration;
} else {
if ('cueOut' in segment) {
cue = new _globalWindow2['default'].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
cue.adStartTime = mediaTime;
// Assumes tag format to be
// #EXT-X-CUE-OUT:30
cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
track.addCue(cue);
}
if ('cueOutCont' in segment) {
// Entered into the middle of an ad cue
var adOffset = undefined;
var adTotal = undefined;
// Assumes tag formate to be
// #EXT-X-CUE-OUT-CONT:10/30
var _segment$cueOutCont$split$map = segment.cueOutCont.split('/').map(parseFloat);
var _segment$cueOutCont$split$map2 = _slicedToArray(_segment$cueOutCont$split$map, 2);
adOffset = _segment$cueOutCont$split$map2[0];
adTotal = _segment$cueOutCont$split$map2[1];
cue = new _globalWindow2['default'].VTTCue(mediaTime, mediaTime + segment.duration, '');
cue.adStartTime = mediaTime - adOffset;
cue.adEndTime = cue.adStartTime + adTotal;
track.addCue(cue);
}
}
mediaTime += segment.duration;
}
};
exports['default'] = {
updateAdCues: updateAdCues,
findAdCue: findAdCue
};
module.exports = exports['default'];
},{"global/window":46}],29:[function(require,module,exports){
/**
* @file bin-utils.js
*/
/**
* convert a TimeRange to text
*
* @param {TimeRange} range the timerange to use for conversion
* @param {Number} i the iterator on the range to convert
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var textRange = function textRange(range, i) {
return range.start(i) + '-' + range.end(i);
};
/**
* format a number as hex string
*
* @param {Number} e The number
* @param {Number} i the iterator
*/
var formatHexString = function formatHexString(e, i) {
var value = e.toString(16);
return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
};
var formatAsciiString = function formatAsciiString(e) {
if (e >= 0x20 && e < 0x7e) {
return String.fromCharCode(e);
}
return '.';
};
/**
* utils to help dump binary data to the console
*/
var utils = {
hexDump: function hexDump(data) {
var bytes = Array.prototype.slice.call(data);
var step = 16;
var result = '';
var hex = undefined;
var ascii = undefined;
for (var j = 0; j < bytes.length / step; j++) {
hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
result += hex + ' ' + ascii + '\n';
}
return result;
},
tagDump: function tagDump(tag) {
return utils.hexDump(tag.bytes);
},
textRanges: function textRanges(ranges) {
var result = '';
var i = undefined;
for (i = 0; i < ranges.length; i++) {
result += textRange(ranges, i) + ' ';
}
return result;
}
};
exports['default'] = utils;
module.exports = exports['default'];
},{}],30:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = {
GOAL_BUFFER_LENGTH: 30
};
module.exports = exports["default"];
},{}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _aesDecrypter = require('aes-decrypter');
/**
* Our web wroker interface so that things can talk to aes-decrypter
* that will be running in a web worker. the scope is passed to this by
* webworkify.
*
* @param {Object} self the scope for the web worker
*/
var Worker = function Worker(self) {
self.onmessage = function (event) {
var data = event.data;
if (data.action === 'decrypt') {
var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
var fn = function fn(err, bytes) {
if (err) {
return;
}
_globalWindow2['default'].postMessage({
action: 'done',
bytes: bytes.buffer,
byteOffset: bytes.byteOffset,
byteLength: bytes.byteLength
}, [bytes.buffer]);
};
return new _aesDecrypter.Decrypter(encrypted, key, iv, fn);
}
};
};
exports['default'] = function (self) {
return new Worker(self);
};
module.exports = exports['default'];
},{"aes-decrypter":4,"global/window":46}],32:[function(require,module,exports){
(function (global){
/**
* @file master-playlist-controller.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x3, _x4, _x5) { var _again = true; _function: while (_again) { var object = _x3, property = _x4, receiver = _x5; _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 { _x3 = parent; _x4 = property; _x5 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _playlistLoader = require('./playlist-loader');
var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
var _segmentLoader = require('./segment-loader');
var _segmentLoader2 = _interopRequireDefault(_segmentLoader);
var _ranges = require('./ranges');
var _ranges2 = _interopRequireDefault(_ranges);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _adCueTags = require('./ad-cue-tags');
var _adCueTags2 = _interopRequireDefault(_adCueTags);
// 5 minute blacklist
var BLACKLIST_DURATION = 5 * 60 * 1000;
var Hls = undefined;
/**
* determine if an object a is differnt from
* and object b. both only having one dimensional
* properties
*
* @param {Object} a object one
* @param {Object} b object two
* @return {Boolean} if the object has changed or not
*/
var objectChanged = function objectChanged(a, b) {
if (typeof a !== typeof b) {
return true;
}
// if we have a different number of elements
// something has changed
if (Object.keys(a).length !== Object.keys(b).length) {
return true;
}
for (var prop in a) {
if (a[prop] !== b[prop]) {
return true;
}
}
return false;
};
/**
* Parses a codec string to retrieve the number of codecs specified,
* the video codec and object type indicator, and the audio profile.
*
* @private
*/
var parseCodecs = function parseCodecs(codecs) {
var result = {
codecCount: 0,
videoCodec: null,
videoObjectTypeIndicator: null,
audioProfile: null
};
var parsed = undefined;
result.codecCount = codecs.split(',').length;
result.codecCount = result.codecCount || 2;
// parse the video codec
parsed = /(^|\s|,)+(avc1)([^ ,]*)/i.exec(codecs);
if (parsed) {
result.videoCodec = parsed[2];
result.videoObjectTypeIndicator = parsed[3];
}
// parse the last field of the audio codec
result.audioProfile = /(^|\s|,)+mp4a.[0-9A-Fa-f]+\.([0-9A-Fa-f]+)/i.exec(codecs);
result.audioProfile = result.audioProfile && result.audioProfile[2];
return result;
};
/**
* Calculates the MIME type strings for a working configuration of
* SourceBuffers to play variant streams in a master playlist. If
* there is no possible working configuration, an empty array will be
* returned.
*
* @param master {Object} the m3u8 object for the master playlist
* @param media {Object} the m3u8 object for the variant playlist
* @return {Array} the MIME type strings. If the array has more than
* one entry, the first element should be applied to the video
* SourceBuffer and the second to the audio SourceBuffer.
*
* @private
*/
var mimeTypesForPlaylist_ = function mimeTypesForPlaylist_(master, media) {
var container = 'mp2t';
var codecs = {
videoCodec: 'avc1',
videoObjectTypeIndicator: '.4d400d',
audioProfile: '2'
};
var audioGroup = [];
var mediaAttributes = undefined;
var previousGroup = null;
if (!media) {
// not enough information, return an error
return [];
}
// An initialization segment means the media playlists is an iframe
// playlist or is using the mp4 container. We don't currently
// support iframe playlists, so assume this is signalling mp4
// fragments.
// the existence check for segments can be removed once
// https://github.com/videojs/m3u8-parser/issues/8 is closed
if (media.segments && media.segments.length && media.segments[0].map) {
container = 'mp4';
}
// if the codecs were explicitly specified, use them instead of the
// defaults
mediaAttributes = media.attributes || {};
if (mediaAttributes.CODECS) {
(function () {
var parsedCodecs = parseCodecs(mediaAttributes.CODECS);
Object.keys(parsedCodecs).forEach(function (key) {
codecs[key] = parsedCodecs[key] || codecs[key];
});
})();
}
if (master.mediaGroups.AUDIO) {
audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
}
// if audio could be muxed or unmuxed, use mime types appropriate
// for both scenarios
for (var groupId in audioGroup) {
if (previousGroup && !!audioGroup[groupId].uri !== !!previousGroup.uri) {
// one source buffer with muxed video and audio and another for
// the alternate audio
return ['video/' + container + '; codecs="' + codecs.videoCodec + codecs.videoObjectTypeIndicator + ', mp4a.40.' + codecs.audioProfile + '"', 'audio/' + container + '; codecs="mp4a.40.' + codecs.audioProfile + '"'];
}
previousGroup = audioGroup[groupId];
}
// if all video and audio is unmuxed, use two single-codec mime
// types
if (previousGroup && previousGroup.uri) {
return ['video/' + container + '; codecs="' + codecs.videoCodec + codecs.videoObjectTypeIndicator + '"', 'audio/' + container + '; codecs="mp4a.40.' + codecs.audioProfile + '"'];
}
// all video and audio are muxed, use a dual-codec mime type
return ['video/' + container + '; codecs="' + codecs.videoCodec + codecs.videoObjectTypeIndicator + ', mp4a.40.' + codecs.audioProfile + '"'];
};
exports.mimeTypesForPlaylist_ = mimeTypesForPlaylist_;
/**
* the master playlist controller controller all interactons
* between playlists and segmentloaders. At this time this mainly
* involves a master playlist and a series of audio playlists
* if they are available
*
* @class MasterPlaylistController
* @extends videojs.EventTarget
*/
var MasterPlaylistController = (function (_videojs$EventTarget) {
_inherits(MasterPlaylistController, _videojs$EventTarget);
function MasterPlaylistController(options) {
var _this = this;
_classCallCheck(this, MasterPlaylistController);
_get(Object.getPrototypeOf(MasterPlaylistController.prototype), 'constructor', this).call(this);
var url = options.url;
var withCredentials = options.withCredentials;
var mode = options.mode;
var tech = options.tech;
var bandwidth = options.bandwidth;
var externHls = options.externHls;
var useCueTags = options.useCueTags;
if (!url) {
throw new Error('A non-empty playlist URL is required');
}
Hls = externHls;
this.withCredentials = withCredentials;
this.tech_ = tech;
this.hls_ = tech.hls;
this.mode_ = mode;
this.useCueTags_ = useCueTags;
if (this.useCueTags_) {
this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
this.tech_.textTracks().addTrack_(this.cueTagsTrack_);
}
this.audioTracks_ = [];
this.requestOptions_ = {
withCredentials: this.withCredentials,
timeout: null
};
this.audioGroups_ = {};
this.mediaSource = new _videoJs2['default'].MediaSource({ mode: mode });
this.audioinfo_ = null;
this.mediaSource.on('audioinfo', this.handleAudioinfoUpdate_.bind(this));
// load the media source into the player
this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_.bind(this));
var segmentLoaderOptions = {
hls: this.hls_,
mediaSource: this.mediaSource,
currentTime: this.tech_.currentTime.bind(this.tech_),
seekable: function seekable() {
return _this.seekable();
},
seeking: function seeking() {
return _this.tech_.seeking();
},
setCurrentTime: function setCurrentTime(a) {
return _this.tech_.setCurrentTime(a);
},
hasPlayed: function hasPlayed() {
return _this.tech_.played().length !== 0;
},
bandwidth: bandwidth
};
// setup playlist loaders
this.masterPlaylistLoader_ = new _playlistLoader2['default'](url, this.hls_, this.withCredentials);
this.setupMasterPlaylistLoaderListeners_();
this.audioPlaylistLoader_ = null;
// setup segment loaders
// combined audio/video or just video when alternate audio track is selected
this.mainSegmentLoader_ = new _segmentLoader2['default'](segmentLoaderOptions);
// alternate audio track
this.audioSegmentLoader_ = new _segmentLoader2['default'](segmentLoaderOptions);
this.setupSegmentLoaderListeners_();
this.masterPlaylistLoader_.start();
}
/**
* Register event handlers on the master playlist loader. A helper
* function for construction time.
*
* @private
*/
_createClass(MasterPlaylistController, [{
key: 'setupMasterPlaylistLoaderListeners_',
value: function setupMasterPlaylistLoaderListeners_() {
var _this2 = this;
this.masterPlaylistLoader_.on('loadedmetadata', function () {
var media = _this2.masterPlaylistLoader_.media();
var requestTimeout = _this2.masterPlaylistLoader_.targetDuration * 1.5 * 1000;
_this2.requestOptions_.timeout = requestTimeout;
// if this isn't a live video and preload permits, start
// downloading segments
if (media.endList && _this2.tech_.preload() !== 'none') {
_this2.mainSegmentLoader_.playlist(media, _this2.requestOptions_);
_this2.mainSegmentLoader_.expired(_this2.masterPlaylistLoader_.expired_);
_this2.mainSegmentLoader_.load();
}
try {
_this2.setupSourceBuffers_();
} catch (e) {
_videoJs2['default'].log.warn('Failed to create SourceBuffers', e);
return _this2.mediaSource.endOfStream('decode');
}
_this2.setupFirstPlay();
_this2.fillAudioTracks_();
_this2.setupAudio();
_this2.trigger('audioupdate');
_this2.trigger('selectedinitialmedia');
});
this.masterPlaylistLoader_.on('loadedplaylist', function () {
var updatedPlaylist = _this2.masterPlaylistLoader_.media();
var seekable = undefined;
if (!updatedPlaylist) {
// select the initial variant
_this2.initialMedia_ = _this2.selectPlaylist();
_this2.masterPlaylistLoader_.media(_this2.initialMedia_);
return;
}
if (_this2.useCueTags_) {
_this2.updateAdCues_(updatedPlaylist, _this2.masterPlaylistLoader_.expired_);
}
// TODO: Create a new event on the PlaylistLoader that signals
// that the segments have changed in some way and use that to
// update the SegmentLoader instead of doing it twice here and
// on `mediachange`
_this2.mainSegmentLoader_.playlist(updatedPlaylist, _this2.requestOptions_);
_this2.mainSegmentLoader_.expired(_this2.masterPlaylistLoader_.expired_);
_this2.updateDuration();
// update seekable
seekable = _this2.seekable();
if (!updatedPlaylist.endList && seekable.length !== 0) {
_this2.mediaSource.addSeekableRange_(seekable.start(0), seekable.end(0));
}
});
this.masterPlaylistLoader_.on('error', function () {
_this2.blacklistCurrentPlaylist(_this2.masterPlaylistLoader_.error);
});
this.masterPlaylistLoader_.on('mediachanging', function () {
_this2.mainSegmentLoader_.abort();
_this2.mainSegmentLoader_.pause();
});
this.masterPlaylistLoader_.on('mediachange', function () {
var media = _this2.masterPlaylistLoader_.media();
var requestTimeout = _this2.masterPlaylistLoader_.targetDuration * 1.5 * 1000;
var activeAudioGroup = undefined;
var activeTrack = undefined;
// If we don't have any more available playlists, we don't want to
// timeout the request.
if (_this2.masterPlaylistLoader_.isLowestEnabledRendition_()) {
_this2.requestOptions_.timeout = 0;
} else {
_this2.requestOptions_.timeout = requestTimeout;
}
// TODO: Create a new event on the PlaylistLoader that signals
// that the segments have changed in some way and use that to
// update the SegmentLoader instead of doing it twice here and
// on `loadedplaylist`
_this2.mainSegmentLoader_.playlist(media, _this2.requestOptions_);
_this2.mainSegmentLoader_.expired(_this2.masterPlaylistLoader_.expired_);
_this2.mainSegmentLoader_.load();
// if the audio group has changed, a new audio track has to be
// enabled
activeAudioGroup = _this2.activeAudioGroup();
activeTrack = activeAudioGroup.filter(function (track) {
return track.enabled;
})[0];
if (!activeTrack) {
_this2.setupAudio();
_this2.trigger('audioupdate');
}
_this2.tech_.trigger({
type: 'mediachange',
bubbles: true
});
});
}
/**
* Register event handlers on the segment loaders. A helper function
* for construction time.
*
* @private
*/
}, {
key: 'setupSegmentLoaderListeners_',
value: function setupSegmentLoaderListeners_() {
var _this3 = this;
this.mainSegmentLoader_.on('progress', function () {
// figure out what stream the next segment should be downloaded from
// with the updated bandwidth information
_this3.masterPlaylistLoader_.media(_this3.selectPlaylist());
_this3.trigger('progress');
});
this.mainSegmentLoader_.on('error', function () {
_this3.blacklistCurrentPlaylist(_this3.mainSegmentLoader_.error());
});
this.audioSegmentLoader_.on('error', function () {
_videoJs2['default'].log.warn('Problem encountered with the current alternate audio track' + '. Switching back to default.');
_this3.audioSegmentLoader_.abort();
_this3.audioPlaylistLoader_ = null;
_this3.setupAudio();
});
}
}, {
key: 'handleAudioinfoUpdate_',
value: function handleAudioinfoUpdate_(event) {
if (Hls.supportsAudioInfoChange_() || !this.audioInfo_ || !objectChanged(this.audioInfo_, event.info)) {
this.audioInfo_ = event.info;
return;
}
var error = 'had different audio properties (channels, sample rate, etc.) ' + 'or changed in some other way. This behavior is currently ' + 'unsupported in Firefox 48 and below due to an issue: \n\n' + 'https://bugzilla.mozilla.org/show_bug.cgi?id=1247138\n\n';
var enabledIndex = this.activeAudioGroup().map(function (track) {
return track.enabled;
}).indexOf(true);
var enabledTrack = this.activeAudioGroup()[enabledIndex];
var defaultTrack = this.activeAudioGroup().filter(function (track) {
return track.properties_ && track.properties_['default'];
})[0];
// they did not switch audiotracks
// blacklist the current playlist
if (!this.audioPlaylistLoader_) {
error = 'The rendition that we tried to switch to ' + error + 'Unfortunately that means we will have to blacklist ' + 'the current playlist and switch to another. Sorry!';
this.blacklistCurrentPlaylist();
} else {
error = 'The audio track \'' + enabledTrack.label + '\' that we tried to ' + ('switch to ' + error + ' Unfortunately this means we will have to ') + ('return you to the main track \'' + defaultTrack.label + '\'. Sorry!');
defaultTrack.enabled = true;
this.activeAudioGroup().splice(enabledIndex, 1);
this.trigger('audioupdate');
}
_videoJs2['default'].log.warn(error);
this.setupAudio();
}
/**
* get the total number of media requests from the `audiosegmentloader_`
* and the `mainSegmentLoader_`
*
* @private
*/
}, {
key: 'mediaRequests_',
value: function mediaRequests_() {
return this.audioSegmentLoader_.mediaRequests + this.mainSegmentLoader_.mediaRequests;
}
/**
* get the total time that media requests have spent trnasfering
* from the `audiosegmentloader_` and the `mainSegmentLoader_`
*
* @private
*/
}, {
key: 'mediaTransferDuration_',
value: function mediaTransferDuration_() {
return this.audioSegmentLoader_.mediaTransferDuration + this.mainSegmentLoader_.mediaTransferDuration;
}
/**
* get the total number of bytes transfered during media requests
* from the `audiosegmentloader_` and the `mainSegmentLoader_`
*
* @private
*/
}, {
key: 'mediaBytesTransferred_',
value: function mediaBytesTransferred_() {
return this.audioSegmentLoader_.mediaBytesTransferred + this.mainSegmentLoader_.mediaBytesTransferred;
}
/**
* fill our internal list of HlsAudioTracks with data from
* the master playlist or use a default
*
* @private
*/
}, {
key: 'fillAudioTracks_',
value: function fillAudioTracks_() {
var master = this.master();
var mediaGroups = master.mediaGroups || {};
// force a default if we have none or we are not
// in html5 mode (the only mode to support more than one
// audio track)
if (!mediaGroups || !mediaGroups.AUDIO || Object.keys(mediaGroups.AUDIO).length === 0 || this.mode_ !== 'html5') {
// "main" audio group, track name "default"
mediaGroups.AUDIO = { main: { 'default': { 'default': true } } };
}
for (var mediaGroup in mediaGroups.AUDIO) {
if (!this.audioGroups_[mediaGroup]) {
this.audioGroups_[mediaGroup] = [];
}
for (var label in mediaGroups.AUDIO[mediaGroup]) {
var properties = mediaGroups.AUDIO[mediaGroup][label];
var track = new _videoJs2['default'].AudioTrack({
id: label,
kind: properties['default'] ? 'main' : 'alternative',
enabled: false,
language: properties.language,
label: label
});
track.properties_ = properties;
this.audioGroups_[mediaGroup].push(track);
}
}
// enable the default active track
(this.activeAudioGroup().filter(function (audioTrack) {
return audioTrack.properties_['default'];
})[0] || this.activeAudioGroup()[0]).enabled = true;
}
/**
* Call load on our SegmentLoaders
*/
}, {
key: 'load',
value: function load() {
this.mainSegmentLoader_.load();
if (this.audioPlaylistLoader_) {
this.audioSegmentLoader_.load();
}
}
/**
* Returns the audio group for the currently active primary
* media playlist.
*/
}, {
key: 'activeAudioGroup',
value: function activeAudioGroup() {
var videoPlaylist = this.masterPlaylistLoader_.media();
var result = undefined;
if (videoPlaylist.attributes && videoPlaylist.attributes.AUDIO) {
result = this.audioGroups_[videoPlaylist.attributes.AUDIO];
}
return result || this.audioGroups_.main;
}
/**
* Determine the correct audio rendition based on the active
* AudioTrack and initialize a PlaylistLoader and SegmentLoader if
* necessary. This method is called once automatically before
* playback begins to enable the default audio track and should be
* invoked again if the track is changed.
*/
}, {
key: 'setupAudio',
value: function setupAudio() {
var _this4 = this;
// determine whether seperate loaders are required for the audio
// rendition
var audioGroup = this.activeAudioGroup();
var track = audioGroup.filter(function (audioTrack) {
return audioTrack.enabled;
})[0];
if (!track) {
track = audioGroup.filter(function (audioTrack) {
return audioTrack.properties_['default'];
})[0] || audioGroup[0];
track.enabled = true;
}
// stop playlist and segment loading for audio
if (this.audioPlaylistLoader_) {
this.audioPlaylistLoader_.dispose();
this.audioPlaylistLoader_ = null;
}
this.audioSegmentLoader_.pause();
this.audioSegmentLoader_.clearBuffer();
if (!track.properties_.resolvedUri) {
return;
}
// startup playlist and segment loaders for the enabled audio
// track
this.audioPlaylistLoader_ = new _playlistLoader2['default'](track.properties_.resolvedUri, this.hls_, this.withCredentials);
this.audioPlaylistLoader_.start();
this.audioPlaylistLoader_.on('loadedmetadata', function () {
var audioPlaylist = _this4.audioPlaylistLoader_.media();
_this4.audioSegmentLoader_.playlist(audioPlaylist, _this4.requestOptions_);
// if the video is already playing, or if this isn't a live video and preload
// permits, start downloading segments
if (!_this4.tech_.paused() || audioPlaylist.endList && _this4.tech_.preload() !== 'none') {
_this4.audioSegmentLoader_.load();
}
if (!audioPlaylist.endList) {
// trigger the playlist loader to start "expired time"-tracking
_this4.audioPlaylistLoader_.trigger('firstplay');
}
});
this.audioPlaylistLoader_.on('loadedplaylist', function () {
var updatedPlaylist = undefined;
if (_this4.audioPlaylistLoader_) {
updatedPlaylist = _this4.audioPlaylistLoader_.media();
}
if (!updatedPlaylist) {
// only one playlist to select
_this4.audioPlaylistLoader_.media(_this4.audioPlaylistLoader_.playlists.master.playlists[0]);
return;
}
_this4.audioSegmentLoader_.playlist(updatedPlaylist, _this4.requestOptions_);
});
this.audioPlaylistLoader_.on('error', function () {
_videoJs2['default'].log.warn('Problem encountered loading the alternate audio track' + '. Switching back to default.');
_this4.audioSegmentLoader_.abort();
_this4.setupAudio();
});
}
/**
* Re-tune playback quality level for the current player
* conditions. This method may perform destructive actions, like
* removing already buffered content, to readjust the currently
* active playlist quickly.
*
* @private
*/
}, {
key: 'fastQualityChange_',
value: function fastQualityChange_() {
var media = this.selectPlaylist();
if (media !== this.masterPlaylistLoader_.media()) {
this.masterPlaylistLoader_.media(media);
this.mainSegmentLoader_.sourceUpdater_.remove(this.tech_.currentTime() + 5, Infinity);
}
}
/**
* Begin playback.
*/
}, {
key: 'play',
value: function play() {
if (this.setupFirstPlay()) {
return;
}
if (this.tech_.ended()) {
this.tech_.setCurrentTime(0);
}
this.load();
// if the viewer has paused and we fell out of the live window,
// seek forward to the earliest available position
if (this.tech_.duration() === Infinity) {
if (this.tech_.currentTime() < this.tech_.seekable().start(0)) {
return this.tech_.setCurrentTime(this.tech_.seekable().start(0));
}
}
}
/**
* Seek to the latest media position if this is a live video and the
* player and video are loaded and initialized.
*/
}, {
key: 'setupFirstPlay',
value: function setupFirstPlay() {
var seekable = undefined;
var media = this.masterPlaylistLoader_.media();
// check that everything is ready to begin buffering
// 1) the active media playlist is available
if (media &&
// 2) the video is a live stream
!media.endList &&
// 3) the player is not paused
!this.tech_.paused() &&
// 4) the player has not started playing
!this.hasPlayed_) {
// trigger the playlist loader to start "expired time"-tracking
this.masterPlaylistLoader_.trigger('firstplay');
this.hasPlayed_ = true;
// seek to the latest media position for live videos
seekable = this.seekable();
if (seekable.length) {
this.tech_.setCurrentTime(seekable.end(0));
}
// now that we seeked to the current time, load the segment
this.load();
return true;
}
return false;
}
/**
* handle the sourceopen event on the MediaSource
*
* @private
*/
}, {
key: 'handleSourceOpen_',
value: function handleSourceOpen_() {
// Only attempt to create the source buffer if none already exist.
// handleSourceOpen is also called when we are "re-opening" a source buffer
// after `endOfStream` has been called (in response to a seek for instance)
try {
this.setupSourceBuffers_();
} catch (e) {
_videoJs2['default'].log.warn('Failed to create Source Buffers', e);
return this.mediaSource.endOfStream('decode');
}
// if autoplay is enabled, begin playback. This is duplicative of
// code in video.js but is required because play() must be invoked
// *after* the media source has opened.
if (this.tech_.autoplay()) {
this.tech_.play();
}
this.trigger('sourceopen');
}
/**
* Blacklists a playlist when an error occurs for a set amount of time
* making it unavailable for selection by the rendition selection algorithm
* and then forces a new playlist (rendition) selection.
*
* @param {Object=} error an optional error that may include the playlist
* to blacklist
*/
}, {
key: 'blacklistCurrentPlaylist',
value: function blacklistCurrentPlaylist() {
var error = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var currentPlaylist = undefined;
var nextPlaylist = undefined;
// If the `error` was generated by the playlist loader, it will contain
// the playlist we were trying to load (but failed) and that should be
// blacklisted instead of the currently selected playlist which is likely
// out-of-date in this scenario
currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
// If there is no current playlist, then an error occurred while we were
// trying to load the master OR while we were disposing of the tech
if (!currentPlaylist) {
this.error = error;
return this.mediaSource.endOfStream('network');
}
// Blacklist this playlist
currentPlaylist.excludeUntil = Date.now() + BLACKLIST_DURATION;
// Select a new playlist
nextPlaylist = this.selectPlaylist();
if (nextPlaylist) {
_videoJs2['default'].log.warn('Problem encountered with the current ' + 'HLS playlist. Switching to another playlist.');
return this.masterPlaylistLoader_.media(nextPlaylist);
}
_videoJs2['default'].log.warn('Problem encountered with the current ' + 'HLS playlist. No suitable alternatives found.');
// We have no more playlists we can select so we must fail
this.error = error;
return this.mediaSource.endOfStream('network');
}
/**
* Pause all segment loaders
*/
}, {
key: 'pauseLoading',
value: function pauseLoading() {
this.mainSegmentLoader_.pause();
if (this.audioPlaylistLoader_) {
this.audioSegmentLoader_.pause();
}
}
/**
* set the current time on all segment loaders
*
* @param {TimeRange} currentTime the current time to set
* @return {TimeRange} the current time
*/
}, {
key: 'setCurrentTime',
value: function setCurrentTime(currentTime) {
var buffered = _ranges2['default'].findRange(this.tech_.buffered(), currentTime);
if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
// return immediately if the metadata is not ready yet
return 0;
}
// it's clearly an edge-case but don't thrown an error if asked to
// seek within an empty playlist
if (!this.masterPlaylistLoader_.media().segments) {
return 0;
}
// if the seek location is already buffered, continue buffering as
// usual
if (buffered && buffered.length) {
return currentTime;
}
// cancel outstanding requests so we begin buffering at the new
// location
this.mainSegmentLoader_.abort();
if (this.audioPlaylistLoader_) {
this.audioSegmentLoader_.abort();
}
if (!this.tech_.paused()) {
this.mainSegmentLoader_.load();
if (this.audioPlaylistLoader_) {
this.audioSegmentLoader_.load();
}
}
}
/**
* get the current duration
*
* @return {TimeRange} the duration
*/
}, {
key: 'duration',
value: function duration() {
if (!this.masterPlaylistLoader_) {
return 0;
}
if (this.mediaSource) {
return this.mediaSource.duration;
}
return Hls.Playlist.duration(this.masterPlaylistLoader_.media());
}
/**
* check the seekable range
*
* @return {TimeRange} the seekable range
*/
}, {
key: 'seekable',
value: function seekable() {
var media = undefined;
var mainSeekable = undefined;
var audioSeekable = undefined;
if (!this.masterPlaylistLoader_) {
return _videoJs2['default'].createTimeRanges();
}
media = this.masterPlaylistLoader_.media();
if (!media) {
return _videoJs2['default'].createTimeRanges();
}
mainSeekable = Hls.Playlist.seekable(media, this.masterPlaylistLoader_.expired_);
if (mainSeekable.length === 0) {
return mainSeekable;
}
if (this.audioPlaylistLoader_) {
audioSeekable = Hls.Playlist.seekable(this.audioPlaylistLoader_.media(), this.audioPlaylistLoader_.expired_);
if (audioSeekable.length === 0) {
return audioSeekable;
}
}
if (!audioSeekable) {
// seekable has been calculated based on buffering video data so it
// can be returned directly
return mainSeekable;
}
return _videoJs2['default'].createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
}
/**
* Update the player duration
*/
}, {
key: 'updateDuration',
value: function updateDuration() {
var _this5 = this;
var oldDuration = this.mediaSource.duration;
var newDuration = Hls.Playlist.duration(this.masterPlaylistLoader_.media());
var buffered = this.tech_.buffered();
var setDuration = function setDuration() {
_this5.mediaSource.duration = newDuration;
_this5.tech_.trigger('durationchange');
_this5.mediaSource.removeEventListener('sourceopen', setDuration);
};
if (buffered.length > 0) {
newDuration = Math.max(newDuration, buffered.end(buffered.length - 1));
}
// if the duration has changed, invalidate the cached value
if (oldDuration !== newDuration) {
// update the duration
if (this.mediaSource.readyState !== 'open') {
this.mediaSource.addEventListener('sourceopen', setDuration);
} else {
setDuration();
}
}
}
/**
* dispose of the MasterPlaylistController and everything
* that it controls
*/
}, {
key: 'dispose',
value: function dispose() {
this.masterPlaylistLoader_.dispose();
this.mainSegmentLoader_.dispose();
this.audioSegmentLoader_.dispose();
}
/**
* return the master playlist object if we have one
*
* @return {Object} the master playlist object that we parsed
*/
}, {
key: 'master',
value: function master() {
return this.masterPlaylistLoader_.master;
}
/**
* return the currently selected playlist
*
* @return {Object} the currently selected playlist object that we parsed
*/
}, {
key: 'media',
value: function media() {
// playlist loader will not return media if it has not been fully loaded
return this.masterPlaylistLoader_.media() || this.initialMedia_;
}
/**
* setup our internal source buffers on our segment Loaders
*
* @private
*/
}, {
key: 'setupSourceBuffers_',
value: function setupSourceBuffers_() {
var media = this.masterPlaylistLoader_.media();
var mimeTypes = undefined;
// wait until a media playlist is available and the Media Source is
// attached
if (!media || this.mediaSource.readyState !== 'open') {
return;
}
mimeTypes = mimeTypesForPlaylist_(this.masterPlaylistLoader_.master, media);
if (mimeTypes.length < 1) {
this.error = 'No compatible SourceBuffer configuration for the variant stream:' + media.resolvedUri;
return this.mediaSource.endOfStream('decode');
}
this.mainSegmentLoader_.mimeType(mimeTypes[0]);
if (mimeTypes[1]) {
this.audioSegmentLoader_.mimeType(mimeTypes[1]);
}
// exclude any incompatible variant streams from future playlist
// selection
this.excludeIncompatibleVariants_(media);
}
/**
* Blacklist playlists that are known to be codec or
* stream-incompatible with the SourceBuffer configuration. For
* instance, Media Source Extensions would cause the video element to
* stall waiting for video data if you switched from a variant with
* video and audio to an audio-only one.
*
* @param {Object} media a media playlist compatible with the current
* set of SourceBuffers. Variants in the current master playlist that
* do not appear to have compatible codec or stream configurations
* will be excluded from the default playlist selection algorithm
* indefinitely.
* @private
*/
}, {
key: 'excludeIncompatibleVariants_',
value: function excludeIncompatibleVariants_(media) {
var master = this.masterPlaylistLoader_.master;
var codecCount = 2;
var videoCodec = null;
var audioProfile = null;
var codecs = undefined;
if (media.attributes && media.attributes.CODECS) {
codecs = parseCodecs(media.attributes.CODECS);
videoCodec = codecs.videoCodec;
audioProfile = codecs.audioProfile;
codecCount = codecs.codecCount;
}
master.playlists.forEach(function (variant) {
var variantCodecs = {
codecCount: 2,
videoCodec: null,
audioProfile: null
};
if (variant.attributes && variant.attributes.CODECS) {
var codecString = variant.attributes.CODECS;
variantCodecs = parseCodecs(codecString);
if (window.MediaSource && window.MediaSource.isTypeSupported && !window.MediaSource.isTypeSupported('video/mp4; codecs="' + codecString + '"')) {
variant.excludeUntil = Infinity;
}
}
// if the streams differ in the presence or absence of audio or
// video, they are incompatible
if (variantCodecs.codecCount !== codecCount) {
variant.excludeUntil = Infinity;
}
// if h.264 is specified on the current playlist, some flavor of
// it must be specified on all compatible variants
if (variantCodecs.videoCodec !== videoCodec) {
variant.excludeUntil = Infinity;
}
// HE-AAC ("mp4a.40.5") is incompatible with all other versions of
// AAC audio in Chrome 46. Don't mix the two.
if (variantCodecs.audioProfile === '5' && audioProfile !== '5' || audioProfile === '5' && variantCodecs.audioProfile !== '5') {
variant.excludeUntil = Infinity;
}
});
}
}, {
key: 'updateAdCues_',
value: function updateAdCues_(media) {
var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
_adCueTags2['default'].updateAdCues(media, this.cueTagsTrack_, offset);
}
}]);
return MasterPlaylistController;
})(_videoJs2['default'].EventTarget);
exports.MasterPlaylistController = MasterPlaylistController;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./ad-cue-tags":28,"./playlist-loader":34,"./ranges":36,"./segment-loader":40}],33:[function(require,module,exports){
(function (global){
/**
* @file playback-watcher.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _ranges = require('./ranges');
var _ranges2 = _interopRequireDefault(_ranges);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
// Set of events that reset the playback-watcher time check logic and clear the timeout
var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
/**
* @class PlaybackWatcher
*/
var PlaybackWatcher = (function () {
/**
* Represents an PlaybackWatcher object.
* @constructor
* @param {object} options an object that includes the tech and settings
*/
function PlaybackWatcher(options) {
var _this = this;
_classCallCheck(this, PlaybackWatcher);
this.tech_ = options.tech;
this.seekable = options.seekable;
this.consecutiveUpdates = 0;
this.lastRecordedTime = null;
this.timer_ = null;
this.checkCurrentTimeTimeout_ = null;
if (options.debug) {
this.logger_ = _videoJs2['default'].log.bind(_videoJs2['default'], 'playback-watcher ->');
}
this.logger_('initialize');
var waitingHandler = function waitingHandler() {
return _this.waiting_();
};
var cancelTimerHandler = function cancelTimerHandler() {
return _this.cancelTimer_();
};
this.tech_.on('waiting', waitingHandler);
this.tech_.on(timerCancelEvents, cancelTimerHandler);
this.monitorCurrentTime_();
// Define the dispose function to clean up our events
this.dispose = function () {
_this.logger_('dispose');
_this.tech_.off('waiting', waitingHandler);
_this.tech_.off(timerCancelEvents, cancelTimerHandler);
if (_this.checkCurrentTimeTimeout_) {
clearTimeout(_this.checkCurrentTimeTimeout_);
}
_this.cancelTimer_();
};
}
/**
* Periodically check current time to see if playback stopped
*
* @private
*/
_createClass(PlaybackWatcher, [{
key: 'monitorCurrentTime_',
value: function monitorCurrentTime_() {
this.checkCurrentTime_();
if (this.checkCurrentTimeTimeout_) {
clearTimeout(this.checkCurrentTimeTimeout_);
}
// 42 = 24 fps // 250 is what Webkit uses // FF uses 15
this.checkCurrentTimeTimeout_ = setTimeout(this.monitorCurrentTime_.bind(this), 250);
}
/**
* The purpose of this function is to emulate the "waiting" event on
* browsers that do not emit it when they are waiting for more
* data to continue playback
*
* @private
*/
}, {
key: 'checkCurrentTime_',
value: function checkCurrentTime_() {
if (this.tech_.paused() || this.tech_.seeking()) {
return;
}
var currentTime = this.tech_.currentTime();
if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
this.consecutiveUpdates++;
this.waiting_();
} else if (currentTime === this.lastRecordedTime) {
this.consecutiveUpdates++;
} else {
this.consecutiveUpdates = 0;
this.lastRecordedTime = currentTime;
}
}
/**
* Cancels any pending timers and resets the 'timeupdate' mechanism
* designed to detect that we are stalled
*
* @private
*/
}, {
key: 'cancelTimer_',
value: function cancelTimer_() {
this.consecutiveUpdates = 0;
if (this.timer_) {
this.logger_('cancelTimer_');
clearTimeout(this.timer_);
}
this.timer_ = null;
}
/**
* Handler for situations when we determine the player is waiting
*
* @private
*/
}, {
key: 'waiting_',
value: function waiting_() {
var seekable = this.seekable();
var currentTime = this.tech_.currentTime();
if (this.tech_.seeking() || this.timer_ !== null) {
return;
}
if (this.fellOutOfLiveWindow_(seekable, currentTime)) {
var livePoint = seekable.end(seekable.length - 1);
this.logger_('Fell out of live window at time ' + currentTime + '. Seeking to ' + ('live point (seekable end) ' + livePoint));
this.cancelTimer_();
this.tech_.setCurrentTime(livePoint);
return;
}
var buffered = this.tech_.buffered();
var nextRange = _ranges2['default'].findNextRange(buffered, currentTime);
if (this.videoUnderflow_(nextRange, buffered, currentTime)) {
// Even though the video underflowed and was stuck in a gap, the audio overplayed
// the gap, leading currentTime into a buffered range. Seeking to currentTime
// allows the video to catch up to the audio position without losing any audio
// (only suffering ~3 seconds of frozen video and a pause in audio playback).
this.cancelTimer_();
this.tech_.setCurrentTime(currentTime);
return;
}
// check for gap
if (nextRange.length > 0) {
var difference = nextRange.start(0) - currentTime;
this.logger_('Stopped at ' + currentTime + ', setting timer for ' + difference + ', seeking ' + ('to ' + nextRange.start(0)));
this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
}
}
}, {
key: 'fellOutOfLiveWindow_',
value: function fellOutOfLiveWindow_(seekable, currentTime) {
if (seekable.length &&
// can't fall before 0 and 0 seekable start identifies VOD stream
seekable.start(0) > 0 && currentTime < seekable.start(0)) {
return true;
}
return false;
}
}, {
key: 'videoUnderflow_',
value: function videoUnderflow_(nextRange, buffered, currentTime) {
if (nextRange.length === 0) {
// Even if there is no available next range, there is still a possibility we are
// stuck in a gap due to video underflow.
var gap = this.gapFromVideoUnderflow_(buffered, currentTime);
if (gap) {
this.logger_('Encountered a gap in video from ' + gap.start + ' to ' + gap.end + '. ' + ('Seeking to current time ' + currentTime));
return true;
}
}
return false;
}
/**
* Timer callback. If playback still has not proceeded, then we seek
* to the start of the next buffered region.
*
* @private
*/
}, {
key: 'skipTheGap_',
value: function skipTheGap_(scheduledCurrentTime) {
var buffered = this.tech_.buffered();
var currentTime = this.tech_.currentTime();
var nextRange = _ranges2['default'].findNextRange(buffered, currentTime);
this.cancelTimer_();
if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
return;
}
this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0));
// only seek if we still have not played
this.tech_.setCurrentTime(nextRange.start(0) + _ranges2['default'].TIME_FUDGE_FACTOR);
}
}, {
key: 'gapFromVideoUnderflow_',
value: function gapFromVideoUnderflow_(buffered, currentTime) {
// At least in Chrome, if there is a gap in the video buffer, the audio will continue
// playing for ~3 seconds after the video gap starts. This is done to account for
// video buffer underflow/underrun (note that this is not done when there is audio
// buffer underflow/underrun -- in that case the video will stop as soon as it
// encounters the gap, as audio stalls are more noticeable/jarring to a user than
// video stalls). The player's time will reflect the playthrough of audio, so the
// time will appear as if we are in a buffered region, even if we are stuck in a
// "gap."
//
// Example:
// video buffer: 0 => 10.1, 10.2 => 20
// audio buffer: 0 => 20
// overall buffer: 0 => 10.1, 10.2 => 20
// current time: 13
//
// Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
// however, the audio continued playing until it reached ~3 seconds past the gap
// (13 seconds), at which point it stops as well. Since current time is past the
// gap, findNextRange will return no ranges.
//
// To check for this issue, we see if there is a gap that starts somewhere within
// a 3 second range (3 seconds +/- 1 second) back from our current time.
var gaps = _ranges2['default'].findGaps(buffered);
for (var i = 0; i < gaps.length; i++) {
var start = gaps.start(i);
var end = gaps.end(i);
// gap is starts no more than 4 seconds back
if (currentTime - start < 4 && currentTime - start > 2) {
return {
start: start,
end: end
};
}
}
return null;
}
/**
* A debugging logger noop that is set to console.log only if debugging
* is enabled globally
*
* @private
*/
}, {
key: 'logger_',
value: function logger_() {}
}]);
return PlaybackWatcher;
})();
exports['default'] = PlaybackWatcher;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./ranges":36}],34:[function(require,module,exports){
(function (global){
/**
* @file playlist-loader.js
*
* A state machine that manages the loading, caching, and updating of
* M3U8 playlists.
*
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _resolveUrl = require('./resolve-url');
var _resolveUrl2 = _interopRequireDefault(_resolveUrl);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _stream = require('./stream');
var _stream2 = _interopRequireDefault(_stream);
var _m3u8Parser = require('m3u8-parser');
var _m3u8Parser2 = _interopRequireDefault(_m3u8Parser);
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Returns a new array of segments that is the result of merging
* properties from an older list of segments onto an updated
* list. No properties on the updated playlist will be overridden.
*
* @param {Array} original the outdated list of segments
* @param {Array} update the updated list of segments
* @param {Number=} offset the index of the first update
* segment in the original segment list. For non-live playlists,
* this should always be zero and does not need to be
* specified. For live playlists, it should be the difference
* between the media sequence numbers in the original and updated
* playlists.
* @return a list of merged segment objects
*/
var updateSegments = function updateSegments(original, update, offset) {
var result = update.slice();
var length = undefined;
var i = undefined;
offset = offset || 0;
length = Math.min(original.length, update.length + offset);
for (i = offset; i < length; i++) {
result[i - offset] = (0, _videoJs.mergeOptions)(original[i], result[i - offset]);
}
return result;
};
/**
* Returns a new master playlist that is the result of merging an
* updated media playlist into the original version. If the
* updated media playlist does not match any of the playlist
* entries in the original master playlist, null is returned.
*
* @param {Object} master a parsed master M3U8 object
* @param {Object} media a parsed media M3U8 object
* @return {Object} a new object that represents the original
* master playlist with the updated media playlist merged in, or
* null if the merge produced no change.
*/
var updateMaster = function updateMaster(master, media) {
var changed = false;
var result = (0, _videoJs.mergeOptions)(master, {});
var i = master.playlists.length;
var playlist = undefined;
var segment = undefined;
var j = undefined;
while (i--) {
playlist = result.playlists[i];
if (playlist.uri === media.uri) {
// consider the playlist unchanged if the number of segments
// are equal and the media sequence number is unchanged
if (playlist.segments && media.segments && playlist.segments.length === media.segments.length && playlist.mediaSequence === media.mediaSequence) {
continue;
}
result.playlists[i] = (0, _videoJs.mergeOptions)(playlist, media);
result.playlists[media.uri] = result.playlists[i];
// if the update could overlap existing segment information,
// merge the two lists
if (playlist.segments) {
result.playlists[i].segments = updateSegments(playlist.segments, media.segments, media.mediaSequence - playlist.mediaSequence);
}
// resolve any missing segment and key URIs
j = 0;
if (result.playlists[i].segments) {
j = result.playlists[i].segments.length;
}
while (j--) {
segment = result.playlists[i].segments[j];
if (!segment.resolvedUri) {
segment.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.uri);
}
if (segment.key && !segment.key.resolvedUri) {
segment.key.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.key.uri);
}
if (segment.map && !segment.map.resolvedUri) {
segment.map.resolvedUri = (0, _resolveUrl2['default'])(playlist.resolvedUri, segment.map.uri);
}
}
changed = true;
}
}
return changed ? result : null;
};
/**
* Load a playlist from a remote loacation
*
* @class PlaylistLoader
* @extends Stream
* @param {String} srcUrl the url to start with
* @param {Boolean} withCredentials the withCredentials xhr option
* @constructor
*/
var PlaylistLoader = function PlaylistLoader(srcUrl, hls, withCredentials) {
var _this = this;
/* eslint-disable consistent-this */
var loader = this;
/* eslint-enable consistent-this */
var dispose = undefined;
var mediaUpdateTimeout = undefined;
var request = undefined;
var playlistRequestError = undefined;
var haveMetadata = undefined;
PlaylistLoader.prototype.constructor.call(this);
this.hls_ = hls;
// a flag that disables "expired time"-tracking this setting has
// no effect when not playing a live stream
this.trackExpiredTime_ = false;
if (!srcUrl) {
throw new Error('A non-empty playlist URL is required');
}
playlistRequestError = function (xhr, url, startingState) {
loader.setBandwidth(request || xhr);
// any in-flight request is now finished
request = null;
if (startingState) {
loader.state = startingState;
}
loader.error = {
playlist: loader.master.playlists[url],
status: xhr.status,
message: 'HLS playlist request error at URL: ' + url,
responseText: xhr.responseText,
code: xhr.status >= 500 ? 4 : 2
};
loader.trigger('error');
};
// update the playlist loader's state in response to a new or
// updated playlist.
haveMetadata = function (xhr, url) {
var parser = undefined;
var refreshDelay = undefined;
var update = undefined;
loader.setBandwidth(request || xhr);
// any in-flight request is now finished
request = null;
loader.state = 'HAVE_METADATA';
parser = new _m3u8Parser2['default'].Parser();
parser.push(xhr.responseText);
parser.end();
parser.manifest.uri = url;
// merge this playlist into the master
update = updateMaster(loader.master, parser.manifest);
refreshDelay = (parser.manifest.targetDuration || 10) * 1000;
loader.targetDuration = parser.manifest.targetDuration;
if (update) {
loader.master = update;
loader.updateMediaPlaylist_(parser.manifest);
} else {
// if the playlist is unchanged since the last reload,
// try again after half the target duration
refreshDelay /= 2;
}
// refresh live playlists after a target duration passes
if (!loader.media().endList) {
_globalWindow2['default'].clearTimeout(mediaUpdateTimeout);
mediaUpdateTimeout = _globalWindow2['default'].setTimeout(function () {
loader.trigger('mediaupdatetimeout');
}, refreshDelay);
}
loader.trigger('loadedplaylist');
};
// initialize the loader state
loader.state = 'HAVE_NOTHING';
// track the time that has expired from the live window
// this allows the seekable start range to be calculated even if
// all segments with timing information have expired
this.expired_ = 0;
// capture the prototype dispose function
dispose = this.dispose;
/**
* Abort any outstanding work and clean up.
*/
loader.dispose = function () {
loader.stopRequest();
_globalWindow2['default'].clearTimeout(mediaUpdateTimeout);
dispose.call(this);
};
loader.stopRequest = function () {
if (request) {
var oldRequest = request;
request = null;
oldRequest.onreadystatechange = null;
oldRequest.abort();
}
};
/**
* Returns the number of enabled playlists on the master playlist object
*
* @return {Number} number of eneabled playlists
*/
loader.enabledPlaylists_ = function () {
return loader.master.playlists.filter(function (element, index, array) {
return !element.excludeUntil || element.excludeUntil <= Date.now();
}).length;
};
/**
* Returns whether the current playlist is the lowest rendition
*
* @return {Boolean} true if on lowest rendition
*/
loader.isLowestEnabledRendition_ = function () {
var media = loader.media();
if (!media || !media.attributes) {
return false;
}
var currentBandwidth = loader.media().attributes.BANDWIDTH || 0;
return !(loader.master.playlists.filter(function (playlist) {
var enabled = typeof playlist.excludeUntil === 'undefined' || playlist.excludeUntil <= Date.now();
if (!enabled) {
return false;
}
var bandwidth = 0;
if (playlist && playlist.attributes) {
bandwidth = playlist.attributes.BANDWIDTH;
}
return bandwidth <= currentBandwidth;
}).length > 1);
};
/**
* When called without any arguments, returns the currently
* active media playlist. When called with a single argument,
* triggers the playlist loader to asynchronously switch to the
* specified media playlist. Calling this method while the
* loader is in the HAVE_NOTHING causes an error to be emitted
* but otherwise has no effect.
*
* @param {Object=} playlis tthe parsed media playlist
* object to switch to
* @return {Playlist} the current loaded media
*/
loader.media = function (playlist) {
var startingState = loader.state;
var mediaChange = undefined;
// getter
if (!playlist) {
return loader.media_;
}
// setter
if (loader.state === 'HAVE_NOTHING') {
throw new Error('Cannot switch media playlist from ' + loader.state);
}
// find the playlist object if the target playlist has been
// specified by URI
if (typeof playlist === 'string') {
if (!loader.master.playlists[playlist]) {
throw new Error('Unknown playlist URI: ' + playlist);
}
playlist = loader.master.playlists[playlist];
}
mediaChange = !loader.media_ || playlist.uri !== loader.media_.uri;
// switch to fully loaded playlists immediately
if (loader.master.playlists[playlist.uri].endList) {
// abort outstanding playlist requests
if (request) {
request.onreadystatechange = null;
request.abort();
request = null;
}
loader.state = 'HAVE_METADATA';
loader.media_ = playlist;
// trigger media change if the active media has been updated
if (mediaChange) {
loader.trigger('mediachanging');
loader.trigger('mediachange');
}
return;
}
// switching to the active playlist is a no-op
if (!mediaChange) {
return;
}
loader.state = 'SWITCHING_MEDIA';
// there is already an outstanding playlist request
if (request) {
if ((0, _resolveUrl2['default'])(loader.master.uri, playlist.uri) === request.url) {
// requesting to switch to the same playlist multiple times
// has no effect after the first
return;
}
request.onreadystatechange = null;
request.abort();
request = null;
}
// request the new playlist
if (this.media_) {
this.trigger('mediachanging');
}
request = this.hls_.xhr({
uri: (0, _resolveUrl2['default'])(loader.master.uri, playlist.uri),
withCredentials: withCredentials
}, function (error, req) {
// disposed
if (!request) {
return;
}
if (error) {
return playlistRequestError(request, playlist.uri, startingState);
}
haveMetadata(req, playlist.uri);
// fire loadedmetadata the first time a media playlist is loaded
if (startingState === 'HAVE_MASTER') {
loader.trigger('loadedmetadata');
} else {
loader.trigger('mediachange');
}
});
};
/**
* set the bandwidth on an xhr to the bandwidth on the playlist
*/
loader.setBandwidth = function (xhr) {
loader.bandwidth = xhr.bandwidth;
};
// In a live playlist, don't keep track of the expired time
// until HLS tells us that "first play" has commenced
loader.on('firstplay', function () {
this.trackExpiredTime_ = true;
});
// live playlist staleness timeout
loader.on('mediaupdatetimeout', function () {
if (loader.state !== 'HAVE_METADATA') {
// only refresh the media playlist if no other activity is going on
return;
}
loader.state = 'HAVE_CURRENT_METADATA';
request = this.hls_.xhr({
uri: (0, _resolveUrl2['default'])(loader.master.uri, loader.media().uri),
withCredentials: withCredentials
}, function (error, req) {
// disposed
if (!request) {
return;
}
if (error) {
return playlistRequestError(request, loader.media().uri);
}
haveMetadata(request, loader.media().uri);
});
});
/**
* pause loading of the playlist
*/
loader.pause = function () {
loader.stopRequest();
_globalWindow2['default'].clearTimeout(mediaUpdateTimeout);
};
/**
* start loading of the playlist
*/
loader.load = function () {
if (loader.started) {
if (!loader.media().endList) {
loader.trigger('mediaupdatetimeout');
} else {
loader.trigger('loadedplaylist');
}
} else {
loader.start();
}
};
/**
* start loading of the playlist
*/
loader.start = function () {
loader.started = true;
// request the specified URL
request = _this.hls_.xhr({
uri: srcUrl,
withCredentials: withCredentials
}, function (error, req) {
var parser = undefined;
var playlist = undefined;
var i = undefined;
// disposed
if (!request) {
return;
}
// clear the loader's request reference
request = null;
if (error) {
loader.error = {
status: req.status,
message: 'HLS playlist request error at URL: ' + srcUrl,
responseText: req.responseText,
// MEDIA_ERR_NETWORK
code: 2
};
return loader.trigger('error');
}
parser = new _m3u8Parser2['default'].Parser();
parser.push(req.responseText);
parser.end();
loader.state = 'HAVE_MASTER';
parser.manifest.uri = srcUrl;
// loaded a master playlist
if (parser.manifest.playlists) {
loader.master = parser.manifest;
// setup by-URI lookups and resolve media playlist URIs
i = loader.master.playlists.length;
while (i--) {
playlist = loader.master.playlists[i];
loader.master.playlists[playlist.uri] = playlist;
playlist.resolvedUri = (0, _resolveUrl2['default'])(loader.master.uri, playlist.uri);
}
// resolve any media group URIs
for (var groupKey in loader.master.mediaGroups.AUDIO) {
for (var labelKey in loader.master.mediaGroups.AUDIO[groupKey]) {
var alternateAudio = loader.master.mediaGroups.AUDIO[groupKey][labelKey];
if (alternateAudio.uri) {
alternateAudio.resolvedUri = (0, _resolveUrl2['default'])(loader.master.uri, alternateAudio.uri);
}
}
}
loader.trigger('loadedplaylist');
if (!request) {
// no media playlist was specifically selected so start
// from the first listed one
loader.media(parser.manifest.playlists[0]);
}
return;
}
// loaded a media playlist
// infer a master playlist if none was previously requested
loader.master = {
mediaGroups: {
'AUDIO': {},
'VIDEO': {},
'CLOSED-CAPTIONS': {},
'SUBTITLES': {}
},
uri: _globalWindow2['default'].location.href,
playlists: [{
uri: srcUrl
}]
};
loader.master.playlists[srcUrl] = loader.master.playlists[0];
loader.master.playlists[0].resolvedUri = srcUrl;
haveMetadata(req, srcUrl);
return loader.trigger('loadedmetadata');
});
};
};
PlaylistLoader.prototype = new _stream2['default']();
/**
* Update the PlaylistLoader state to reflect the changes in an
* update to the current media playlist.
*
* @param {Object} update the updated media playlist object
*/
PlaylistLoader.prototype.updateMediaPlaylist_ = function (update) {
var outdated = undefined;
var i = undefined;
var segment = undefined;
outdated = this.media_;
this.media_ = this.master.playlists[update.uri];
if (!outdated) {
return;
}
// don't track expired time until this flag is truthy
if (!this.trackExpiredTime_) {
return;
}
// if the update was the result of a rendition switch do not
// attempt to calculate expired_ since media-sequences need not
// correlate between renditions/variants
if (update.uri !== outdated.uri) {
return;
}
// try using precise timing from first segment of the updated
// playlist
if (update.segments.length) {
if (typeof update.segments[0].start !== 'undefined') {
this.expired_ = update.segments[0].start;
return;
} else if (typeof update.segments[0].end !== 'undefined') {
this.expired_ = update.segments[0].end - update.segments[0].duration;
return;
}
}
// calculate expired by walking the outdated playlist
i = update.mediaSequence - outdated.mediaSequence - 1;
for (; i >= 0; i--) {
segment = outdated.segments[i];
if (!segment) {
// we missed information on this segment completely between
// playlist updates so we'll have to take an educated guess
// once we begin buffering again, any error we introduce can
// be corrected
this.expired_ += outdated.targetDuration || 10;
continue;
}
if (typeof segment.end !== 'undefined') {
this.expired_ = segment.end;
return;
}
if (typeof segment.start !== 'undefined') {
this.expired_ = segment.start + segment.duration;
return;
}
this.expired_ += segment.duration;
}
};
exports['default'] = PlaylistLoader;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./resolve-url":39,"./stream":42,"global/window":46,"m3u8-parser":83}],35:[function(require,module,exports){
(function (global){
/**
* @file playlist.js
*
* Playlist related utilities.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var Playlist = {
/**
* The number of segments that are unsafe to start playback at in
* a live stream. Changing this value can cause playback stalls.
* See HTTP Live Streaming, "Playing the Media Playlist File"
* https://tools.ietf.org/html/draft-pantos-http-live-streaming-18#section-6.3.3
*/
UNSAFE_LIVE_SEGMENTS: 3
};
/**
* walk backward until we find a duration we can use
* or return a failure
*
* @param {Playlist} playlist the playlist to walk through
* @param {Number} endSequence the mediaSequence to stop walking on
*/
var backwardDuration = function backwardDuration(playlist, endSequence) {
var result = 0;
var i = endSequence - playlist.mediaSequence;
// if a start time is available for segment immediately following
// the interval, use it
var segment = playlist.segments[i];
// Walk backward until we find the latest segment with timeline
// information that is earlier than endSequence
if (segment) {
if (typeof segment.start !== 'undefined') {
return { result: segment.start, precise: true };
}
if (typeof segment.end !== 'undefined') {
return {
result: segment.end - segment.duration,
precise: true
};
}
}
while (i--) {
segment = playlist.segments[i];
if (typeof segment.end !== 'undefined') {
return { result: result + segment.end, precise: true };
}
result += segment.duration;
if (typeof segment.start !== 'undefined') {
return { result: result + segment.start, precise: true };
}
}
return { result: result, precise: false };
};
/**
* walk forward until we find a duration we can use
* or return a failure
*
* @param {Playlist} playlist the playlist to walk through
* @param {Number} endSequence the mediaSequence to stop walking on
*/
var forwardDuration = function forwardDuration(playlist, endSequence) {
var result = 0;
var segment = undefined;
var i = endSequence - playlist.mediaSequence;
// Walk forward until we find the earliest segment with timeline
// information
for (; i < playlist.segments.length; i++) {
segment = playlist.segments[i];
if (typeof segment.start !== 'undefined') {
return {
result: segment.start - result,
precise: true
};
}
result += segment.duration;
if (typeof segment.end !== 'undefined') {
return {
result: segment.end - result,
precise: true
};
}
}
// indicate we didn't find a useful duration estimate
return { result: -1, precise: false };
};
/**
* Calculate the media duration from the segments associated with a
* playlist. The duration of a subinterval of the available segments
* may be calculated by specifying an end index.
*
* @param {Object} playlist a media playlist object
* @param {Number=} endSequence an exclusive upper boundary
* for the playlist. Defaults to playlist length.
* @param {Number} expired the amount of time that has dropped
* off the front of the playlist in a live scenario
* @return {Number} the duration between the first available segment
* and end index.
*/
var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
var backward = undefined;
var forward = undefined;
if (typeof endSequence === 'undefined') {
endSequence = playlist.mediaSequence + playlist.segments.length;
}
if (endSequence < playlist.mediaSequence) {
return 0;
}
// do a backward walk to estimate the duration
backward = backwardDuration(playlist, endSequence);
if (backward.precise) {
// if we were able to base our duration estimate on timing
// information provided directly from the Media Source, return
// it
return backward.result;
}
// walk forward to see if a precise duration estimate can be made
// that way
forward = forwardDuration(playlist, endSequence);
if (forward.precise) {
// we found a segment that has been buffered and so it's
// position is known precisely
return forward.result;
}
// return the less-precise, playlist-based duration estimate
return backward.result + expired;
};
/**
* Calculates the duration of a playlist. If a start and end index
* are specified, the duration will be for the subset of the media
* timeline between those two indices. The total duration for live
* playlists is always Infinity.
*
* @param {Object} playlist a media playlist object
* @param {Number=} endSequence an exclusive upper
* boundary for the playlist. Defaults to the playlist media
* sequence number plus its length.
* @param {Number=} expired the amount of time that has
* dropped off the front of the playlist in a live scenario
* @return {Number} the duration between the start index and end
* index.
*/
var duration = function duration(playlist, endSequence, expired) {
if (!playlist) {
return 0;
}
if (typeof expired !== 'number') {
expired = 0;
}
// if a slice of the total duration is not requested, use
// playlist-level duration indicators when they're present
if (typeof endSequence === 'undefined') {
// if present, use the duration specified in the playlist
if (playlist.totalDuration) {
return playlist.totalDuration;
}
// duration should be Infinity for live playlists
if (!playlist.endList) {
return _globalWindow2['default'].Infinity;
}
}
// calculate the total duration based on the segment durations
return intervalDuration(playlist, endSequence, expired);
};
exports.duration = duration;
/**
* Calculates the interval of time that is currently seekable in a
* playlist. The returned time ranges are relative to the earliest
* moment in the specified playlist that is still available. A full
* seekable implementation for live streams would need to offset
* these values by the duration of content that has expired from the
* stream.
*
* @param {Object} playlist a media playlist object
* @param {Number=} expired the amount of time that has
* dropped off the front of the playlist in a live scenario
* @return {TimeRanges} the periods of time that are valid targets
* for seeking
*/
var seekable = function seekable(playlist, expired) {
var start = undefined;
var end = undefined;
var endSequence = undefined;
if (typeof expired !== 'number') {
expired = 0;
}
// without segments, there are no seekable ranges
if (!playlist || !playlist.segments) {
return (0, _videoJs.createTimeRange)();
}
// when the playlist is complete, the entire duration is seekable
if (playlist.endList) {
return (0, _videoJs.createTimeRange)(0, duration(playlist));
}
// live playlists should not expose three segment durations worth
// of content from the end of the playlist
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-16#section-6.3.3
start = intervalDuration(playlist, playlist.mediaSequence, expired);
endSequence = Math.max(0, playlist.segments.length - Playlist.UNSAFE_LIVE_SEGMENTS);
end = intervalDuration(playlist, playlist.mediaSequence + endSequence, expired);
return (0, _videoJs.createTimeRange)(start, end);
};
exports.seekable = seekable;
/**
* Determine the index of the segment that contains a specified
* playback position in a media playlist.
*
* @param {Object} playlist the media playlist to query
* @param {Number} time The number of seconds since the earliest
* possible position to determine the containing segment for
* @param {Number=} expired the duration of content, in
* seconds, that has been removed from this playlist because it
* expired
* @return {Number} The number of the media segment that contains
* that time position.
*/
var getMediaIndexForTime_ = function getMediaIndexForTime_(playlist, time, expired) {
var i = undefined;
var segment = undefined;
var originalTime = time;
var numSegments = playlist.segments.length;
var lastSegment = numSegments - 1;
var startIndex = undefined;
var endIndex = undefined;
var knownStart = undefined;
var knownEnd = undefined;
if (!playlist) {
return 0;
}
// when the requested position is earlier than the current set of
// segments, return the earliest segment index
if (time < 0) {
return 0;
}
if (time === 0 && !expired) {
return 0;
}
expired = expired || 0;
// find segments with known timing information that bound the
// target time
for (i = 0; i < numSegments; i++) {
segment = playlist.segments[i];
if (segment.end) {
if (segment.end > time) {
knownEnd = segment.end;
endIndex = i;
break;
} else {
knownStart = segment.end;
startIndex = i + 1;
}
}
}
// time was equal to or past the end of the last segment in the playlist
if (startIndex === numSegments) {
return numSegments;
}
// use the bounds we just found and playlist information to
// estimate the segment that contains the time we are looking for
if (typeof startIndex !== 'undefined') {
// We have a known-start point that is before our desired time so
// walk from that point forwards
time = time - knownStart;
for (i = startIndex; i < (endIndex || numSegments); i++) {
segment = playlist.segments[i];
time -= segment.duration;
if (time < 0) {
return i;
}
}
if (i >= endIndex) {
// We haven't found a segment but we did hit a known end point
// so fallback to interpolating between the segment index
// based on the known span of the timeline we are dealing with
// and the number of segments inside that span
return startIndex + Math.floor((originalTime - knownStart) / (knownEnd - knownStart) * (endIndex - startIndex));
}
// We _still_ haven't found a segment so load the last one
return lastSegment;
} else if (typeof endIndex !== 'undefined') {
// We _only_ have a known-end point that is after our desired time so
// walk from that point backwards
time = knownEnd - time;
for (i = endIndex; i >= 0; i--) {
segment = playlist.segments[i];
time -= segment.duration;
if (time < 0) {
return i;
}
}
// We haven't found a segment so load the first one if time is zero
if (time === 0) {
return 0;
}
return -1;
}
// We known nothing so walk from the front of the playlist,
// subtracting durations until we find a segment that contains
// time and return it
time = time - expired;
if (time < 0) {
return -1;
}
for (i = 0; i < numSegments; i++) {
segment = playlist.segments[i];
time -= segment.duration;
if (time < 0) {
return i;
}
}
// We are out of possible candidates so load the last one...
// The last one is the least likely to overlap a buffer and therefore
// the one most likely to tell us something about the timeline
return lastSegment;
};
exports.getMediaIndexForTime_ = getMediaIndexForTime_;
Playlist.duration = duration;
Playlist.seekable = seekable;
Playlist.getMediaIndexForTime_ = getMediaIndexForTime_;
// exports
exports['default'] = Playlist;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"global/window":46}],36:[function(require,module,exports){
(function (global){
/**
* ranges
*
* Utilities for working with TimeRanges.
*
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
// Fudge factor to account for TimeRanges rounding
var TIME_FUDGE_FACTOR = 1 / 30;
/**
* Clamps a value to within a range
* @param {Number} num - the value to clamp
* @param {Number} start - the start of the range to clamp within, inclusive
* @param {Number} end - the end of the range to clamp within, inclusive
* @return {Number}
*/
var clamp = function clamp(num, _ref) {
var _ref2 = _slicedToArray(_ref, 2);
var start = _ref2[0];
var end = _ref2[1];
return Math.min(Math.max(start, num), end);
};
var filterRanges = function filterRanges(timeRanges, predicate) {
var results = [];
var i = undefined;
if (timeRanges && timeRanges.length) {
// Search for ranges that match the predicate
for (i = 0; i < timeRanges.length; i++) {
if (predicate(timeRanges.start(i), timeRanges.end(i))) {
results.push([timeRanges.start(i), timeRanges.end(i)]);
}
}
}
return _videoJs2['default'].createTimeRanges(results);
};
/**
* Attempts to find the buffered TimeRange that contains the specified
* time.
* @param {TimeRanges} buffered - the TimeRanges object to query
* @param {number} time - the time to filter on.
* @returns {TimeRanges} a new TimeRanges object
*/
var findRange = function findRange(buffered, time) {
return filterRanges(buffered, function (start, end) {
return start - TIME_FUDGE_FACTOR <= time && end + TIME_FUDGE_FACTOR >= time;
});
};
/**
* Returns the TimeRanges that begin later than the specified time.
* @param {TimeRanges} timeRanges - the TimeRanges object to query
* @param {number} time - the time to filter on.
* @returns {TimeRanges} a new TimeRanges object.
*/
var findNextRange = function findNextRange(timeRanges, time) {
return filterRanges(timeRanges, function (start) {
return start - TIME_FUDGE_FACTOR >= time;
});
};
/**
* Returns gaps within a list of TimeRanges
* @param {TimeRanges} buffered - the TimeRanges object
* @return {TimeRanges} a TimeRanges object of gaps
*/
var findGaps = function findGaps(buffered) {
if (buffered.length < 2) {
return _videoJs2['default'].createTimeRanges();
}
var ranges = [];
for (var i = 1; i < buffered.length; i++) {
var start = buffered.end(i - 1);
var end = buffered.start(i);
ranges.push([start, end]);
}
return _videoJs2['default'].createTimeRanges(ranges);
};
/**
* Search for a likely end time for the segment that was just appened
* based on the state of the `buffered` property before and after the
* append. If we fin only one such uncommon end-point return it.
* @param {TimeRanges} original - the buffered time ranges before the update
* @param {TimeRanges} update - the buffered time ranges after the update
* @returns {Number|null} the end time added between `original` and `update`,
* or null if one cannot be unambiguously determined.
*/
var findSoleUncommonTimeRangesEnd = function findSoleUncommonTimeRangesEnd(original, update) {
var i = undefined;
var start = undefined;
var end = undefined;
var result = [];
var edges = [];
// In order to qualify as a possible candidate, the end point must:
// 1) Not have already existed in the `original` ranges
// 2) Not result from the shrinking of a range that already existed
// in the `original` ranges
// 3) Not be contained inside of a range that existed in `original`
var overlapsCurrentEnd = function overlapsCurrentEnd(span) {
return span[0] <= end && span[1] >= end;
};
if (original) {
// Save all the edges in the `original` TimeRanges object
for (i = 0; i < original.length; i++) {
start = original.start(i);
end = original.end(i);
edges.push([start, end]);
}
}
if (update) {
// Save any end-points in `update` that are not in the `original`
// TimeRanges object
for (i = 0; i < update.length; i++) {
start = update.start(i);
end = update.end(i);
if (edges.some(overlapsCurrentEnd)) {
continue;
}
// at this point it must be a unique non-shrinking end edge
result.push(end);
}
}
// we err on the side of caution and return null if didn't find
// exactly *one* differing end edge in the search above
if (result.length !== 1) {
return null;
}
return result[0];
};
/**
* Calculate the intersection of two TimeRanges
* @param {TimeRanges} bufferA
* @param {TimeRanges} bufferB
* @returns {TimeRanges} The interesection of `bufferA` with `bufferB`
*/
var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
var start = null;
var end = null;
var arity = 0;
var extents = [];
var ranges = [];
if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
return _videoJs2['default'].createTimeRange();
}
// Handle the case where we have both buffers and create an
// intersection of the two
var count = bufferA.length;
// A) Gather up all start and end times
while (count--) {
extents.push({ time: bufferA.start(count), type: 'start' });
extents.push({ time: bufferA.end(count), type: 'end' });
}
count = bufferB.length;
while (count--) {
extents.push({ time: bufferB.start(count), type: 'start' });
extents.push({ time: bufferB.end(count), type: 'end' });
}
// B) Sort them by time
extents.sort(function (a, b) {
return a.time - b.time;
});
// C) Go along one by one incrementing arity for start and decrementing
// arity for ends
for (count = 0; count < extents.length; count++) {
if (extents[count].type === 'start') {
arity++;
// D) If arity is ever incremented to 2 we are entering an
// overlapping range
if (arity === 2) {
start = extents[count].time;
}
} else if (extents[count].type === 'end') {
arity--;
// E) If arity is ever decremented to 1 we leaving an
// overlapping range
if (arity === 1) {
end = extents[count].time;
}
}
// F) Record overlapping ranges
if (start !== null && end !== null) {
ranges.push([start, end]);
start = null;
end = null;
}
}
return _videoJs2['default'].createTimeRanges(ranges);
};
/**
* Calculates the percentage of `segmentRange` that overlaps the
* `buffered` time ranges.
* @param {TimeRanges} segmentRange - the time range that the segment
* covers adjusted according to currentTime
* @param {TimeRanges} referenceRange - the original time range that the
* segment covers
* @param {Number} currentTime - time in seconds where the current playback
* is at
* @param {TimeRanges} buffered - the currently buffered time ranges
* @returns {Number} percent of the segment currently buffered
*/
var calculateBufferedPercent = function calculateBufferedPercent(adjustedRange, referenceRange, currentTime, buffered) {
var referenceDuration = referenceRange.end(0) - referenceRange.start(0);
var adjustedDuration = adjustedRange.end(0) - adjustedRange.start(0);
var bufferMissingFromAdjusted = referenceDuration - adjustedDuration;
var adjustedIntersection = bufferIntersection(adjustedRange, buffered);
var referenceIntersection = bufferIntersection(referenceRange, buffered);
var adjustedOverlap = 0;
var referenceOverlap = 0;
var count = adjustedIntersection.length;
while (count--) {
adjustedOverlap += adjustedIntersection.end(count) - adjustedIntersection.start(count);
// If the current overlap segment starts at currentTime, then increase the
// overlap duration so that it actually starts at the beginning of referenceRange
// by including the difference between the two Range's durations
// This is a work around for the way Flash has no buffer before currentTime
if (adjustedIntersection.start(count) === currentTime) {
adjustedOverlap += bufferMissingFromAdjusted;
}
}
count = referenceIntersection.length;
while (count--) {
referenceOverlap += referenceIntersection.end(count) - referenceIntersection.start(count);
}
// Use whichever value is larger for the percentage-buffered since that value
// is likely more accurate because the only way
return Math.max(adjustedOverlap, referenceOverlap) / referenceDuration * 100;
};
/**
* Return the amount of a range specified by the startOfSegment and segmentDuration
* overlaps the current buffered content.
*
* @param {Number} startOfSegment - the time where the segment begins
* @param {Number} segmentDuration - the duration of the segment in seconds
* @param {Number} currentTime - time in seconds where the current playback
* is at
* @param {TimeRanges} buffered - the state of the buffer
* @returns {Number} percentage of the segment's time range that is
* already in `buffered`
*/
var getSegmentBufferedPercent = function getSegmentBufferedPercent(startOfSegment, segmentDuration, currentTime, buffered) {
var endOfSegment = startOfSegment + segmentDuration;
// The entire time range of the segment
var originalSegmentRange = _videoJs2['default'].createTimeRanges([[startOfSegment, endOfSegment]]);
// The adjusted segment time range that is setup such that it starts
// no earlier than currentTime
// Flash has no notion of a back-buffer so adjustedSegmentRange adjusts
// for that and the function will still return 100% if a only half of a
// segment is actually in the buffer as long as the currentTime is also
// half-way through the segment
var adjustedSegmentRange = _videoJs2['default'].createTimeRanges([[clamp(startOfSegment, [currentTime, endOfSegment]), endOfSegment]]);
// This condition happens when the currentTime is beyond the segment's
// end time
if (adjustedSegmentRange.start(0) === adjustedSegmentRange.end(0)) {
return 0;
}
var percent = calculateBufferedPercent(adjustedSegmentRange, originalSegmentRange, currentTime, buffered);
// If the segment is reported as having a zero duration, return 0%
// since it is likely that we will need to fetch the segment
if (isNaN(percent) || percent === Infinity || percent === -Infinity) {
return 0;
}
return percent;
};
exports['default'] = {
findRange: findRange,
findNextRange: findNextRange,
findGaps: findGaps,
findSoleUncommonTimeRangesEnd: findSoleUncommonTimeRangesEnd,
getSegmentBufferedPercent: getSegmentBufferedPercent,
TIME_FUDGE_FACTOR: TIME_FUDGE_FACTOR
};
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],37:[function(require,module,exports){
(function (global){
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var defaultOptions = {
errorInterval: 30,
getSource: function getSource(next) {
var tech = this.tech({ IWillNotUseThisInPlugins: true });
var sourceObj = tech.currentSource_;
return next(sourceObj);
}
};
/**
* Main entry point for the plugin
*
* @param {Player} player a reference to a videojs Player instance
* @param {Object} [options] an object with plugin options
* @private
*/
var initPlugin = function initPlugin(player, options) {
var lastCalled = 0;
var seekTo = 0;
var localOptions = _videoJs2['default'].mergeOptions(defaultOptions, options);
/**
* Player modifications to perform that must wait until `loadedmetadata`
* has been triggered
*
* @private
*/
var loadedMetadataHandler = function loadedMetadataHandler() {
if (seekTo) {
player.currentTime(seekTo);
}
};
/**
* Set the source on the player element, play, and seek if necessary
*
* @param {Object} sourceObj An object specifying the source url and mime-type to play
* @private
*/
var setSource = function setSource(sourceObj) {
if (sourceObj === null || sourceObj === undefined) {
return;
}
seekTo = player.duration() !== Infinity && player.currentTime() || 0;
player.one('loadedmetadata', loadedMetadataHandler);
player.src(sourceObj);
player.play();
};
/**
* Attempt to get a source from either the built-in getSource function
* or a custom function provided via the options
*
* @private
*/
var errorHandler = function errorHandler() {
// Do not attempt to reload the source if a source-reload occurred before
// 'errorInterval' time has elapsed since the last source-reload
if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
return;
}
if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
_videoJs2['default'].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
return;
}
lastCalled = Date.now();
return localOptions.getSource.call(player, setSource);
};
/**
* Unbind any event handlers that were bound by the plugin
*
* @private
*/
var cleanupEvents = function cleanupEvents() {
player.off('loadedmetadata', loadedMetadataHandler);
player.off('error', errorHandler);
player.off('dispose', cleanupEvents);
};
/**
* Cleanup before re-initializing the plugin
*
* @param {Object} [newOptions] an object with plugin options
* @private
*/
var reinitPlugin = function reinitPlugin(newOptions) {
cleanupEvents();
initPlugin(player, newOptions);
};
player.on('error', errorHandler);
player.on('dispose', cleanupEvents);
// Overwrite the plugin function so that we can correctly cleanup before
// initializing the plugin
player.reloadSourceOnError = reinitPlugin;
};
/**
* Reload the source when an error is detected as long as there
* wasn't an error previously within the last 30 seconds
*
* @param {Object} [options] an object with plugin options
*/
var reloadSourceOnError = function reloadSourceOnError(options) {
initPlugin(this, options);
};
exports['default'] = reloadSourceOnError;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],38:[function(require,module,exports){
/**
* Enable/disable playlist function. It is intended to have the first two
* arguments partially-applied in order to create the final per-playlist
* function.
*
* @param {PlaylistLoader} playlist - The rendition or media-playlist
* @param {Function} changePlaylistFn - A function to be called after a
* playlist's enabled-state has been changed. Will NOT be called if a
* playlist's enabled-state is unchanged
* @param {Boolean=} enable - Value to set the playlist enabled-state to
* or if undefined returns the current enabled-state for the playlist
* @return {Boolean} The current enabled-state of the playlist
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var enableFunction = function enableFunction(playlist, changePlaylistFn, enable) {
var currentlyEnabled = typeof playlist.excludeUntil === 'undefined' || playlist.excludeUntil <= Date.now();
if (typeof enable === 'undefined') {
return currentlyEnabled;
}
if (enable !== currentlyEnabled) {
if (enable) {
delete playlist.excludeUntil;
} else {
playlist.excludeUntil = Infinity;
}
// Ensure the outside world knows about our changes
changePlaylistFn();
}
return enable;
};
/**
* The representation object encapsulates the publicly visible information
* in a media playlist along with a setter/getter-type function (enabled)
* for changing the enabled-state of a particular playlist entry
*
* @class Representation
*/
var Representation = function Representation(hlsHandler, playlist, id) {
_classCallCheck(this, Representation);
// Get a reference to a bound version of fastQualityChange_
var fastChangeFunction = hlsHandler.masterPlaylistController_.fastQualityChange_.bind(hlsHandler.masterPlaylistController_);
// Carefully descend into the playlist's attributes since most
// properties are optional
if (playlist.attributes) {
var attributes = playlist.attributes;
if (attributes.RESOLUTION) {
var resolution = attributes.RESOLUTION;
this.width = resolution.width;
this.height = resolution.height;
}
this.bandwidth = attributes.BANDWIDTH;
}
// The id is simply the ordinality of the media playlist
// within the master playlist
this.id = id;
// Partially-apply the enableFunction to create a playlist-
// specific variant
this.enabled = enableFunction.bind(this, playlist, fastChangeFunction);
}
/**
* A mixin function that adds the `representations` api to an instance
* of the HlsHandler class
* @param {HlsHandler} hlsHandler - An instance of HlsHandler to add the
* representation API into
*/
;
var renditionSelectionMixin = function renditionSelectionMixin(hlsHandler) {
var playlists = hlsHandler.playlists;
// Add a single API-specific function to the HlsHandler instance
hlsHandler.representations = function () {
return playlists.master.playlists.map(function (e, i) {
return new Representation(hlsHandler, e, i);
});
};
};
exports['default'] = renditionSelectionMixin;
module.exports = exports['default'];
},{}],39:[function(require,module,exports){
/**
* @file resolve-url.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _urlToolkit = require('url-toolkit');
var _urlToolkit2 = _interopRequireDefault(_urlToolkit);
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var resolveUrl = function resolveUrl(baseURL, relativeURL) {
// return early if we don't need to resolve
if (/^[a-z]+:/i.test(relativeURL)) {
return relativeURL;
}
// if the base URL is relative then combine with the current location
if (!/\/\//i.test(baseURL)) {
baseURL = _urlToolkit2['default'].buildAbsoluteURL(_globalWindow2['default'].location.href, baseURL);
}
return _urlToolkit2['default'].buildAbsoluteURL(baseURL, relativeURL);
};
exports['default'] = resolveUrl;
module.exports = exports['default'];
},{"global/window":46,"url-toolkit":88}],40:[function(require,module,exports){
(function (global){
/**
* @file segment-loader.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _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 { _x2 = parent; _x3 = property; _x4 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _ranges = require('./ranges');
var _ranges2 = _interopRequireDefault(_ranges);
var _playlist = require('./playlist');
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _sourceUpdater = require('./source-updater');
var _sourceUpdater2 = _interopRequireDefault(_sourceUpdater);
var _muxJsLibMp4Probe = require('mux.js/lib/mp4/probe');
var _muxJsLibMp4Probe2 = _interopRequireDefault(_muxJsLibMp4Probe);
var _config = require('./config');
var _config2 = _interopRequireDefault(_config);
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _webworkify = require('webworkify');
var _webworkify2 = _interopRequireDefault(_webworkify);
var _decrypterWorkerJs = require('./decrypter-worker.js');
var _decrypterWorkerJs2 = _interopRequireDefault(_decrypterWorkerJs);
// in ms
var CHECK_BUFFER_DELAY = 500;
/**
* Updates segment with information about its end-point in time and, optionally,
* the segment duration if we have enough information to determine a segment duration
* accurately.
*
* @param {Object} playlist a media playlist object
* @param {Number} segmentIndex the index of segment we last appended
* @param {Number} segmentEnd the known of the segment referenced by segmentIndex
*/
var updateSegmentMetadata = function updateSegmentMetadata(playlist, segmentIndex, segmentEnd) {
if (!playlist) {
return false;
}
var segment = playlist.segments[segmentIndex];
var previousSegment = playlist.segments[segmentIndex - 1];
if (segmentEnd && segment) {
segment.end = segmentEnd;
// fix up segment durations based on segment end data
if (!previousSegment) {
// first segment is always has a start time of 0 making its duration
// equal to the segment end
segment.duration = segment.end;
} else if (previousSegment.end) {
segment.duration = segment.end - previousSegment.end;
}
return true;
}
return false;
};
/**
* Determines if we should call endOfStream on the media source based
* on the state of the buffer or if appened segment was the final
* segment in the playlist.
*
* @param {Object} playlist a media playlist object
* @param {Object} mediaSource the MediaSource object
* @param {Number} segmentIndex the index of segment we last appended
* @returns {Boolean} do we need to call endOfStream on the MediaSource
*/
var detectEndOfStream = function detectEndOfStream(playlist, mediaSource, segmentIndex) {
if (!playlist) {
return false;
}
var segments = playlist.segments;
// determine a few boolean values to help make the branch below easier
// to read
var appendedLastSegment = segmentIndex === segments.length;
// if we've buffered to the end of the video, we need to call endOfStream
// so that MediaSources can trigger the `ended` event when it runs out of
// buffered data instead of waiting for me
return playlist.endList && mediaSource.readyState === 'open' && appendedLastSegment;
};
/**
* Turns segment byterange into a string suitable for use in
* HTTP Range requests
*/
var byterangeStr = function byterangeStr(byterange) {
var byterangeStart = undefined;
var byterangeEnd = undefined;
// `byterangeEnd` is one less than `offset + length` because the HTTP range
// header uses inclusive ranges
byterangeEnd = byterange.offset + byterange.length - 1;
byterangeStart = byterange.offset;
return 'bytes=' + byterangeStart + '-' + byterangeEnd;
};
/**
* Defines headers for use in the xhr request for a particular segment.
*/
var segmentXhrHeaders = function segmentXhrHeaders(segment) {
var headers = {};
if ('byterange' in segment) {
headers.Range = byterangeStr(segment.byterange);
}
return headers;
};
/**
* Returns a unique string identifier for a media initialization
* segment.
*/
var initSegmentId = function initSegmentId(initSegment) {
var byterange = initSegment.byterange || {
length: Infinity,
offset: 0
};
return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
};
/**
* An object that manages segment loading and appending.
*
* @class SegmentLoader
* @param {Object} options required and optional options
* @extends videojs.EventTarget
*/
var SegmentLoader = (function (_videojs$EventTarget) {
_inherits(SegmentLoader, _videojs$EventTarget);
function SegmentLoader(options) {
var _this = this;
_classCallCheck(this, SegmentLoader);
_get(Object.getPrototypeOf(SegmentLoader.prototype), 'constructor', this).call(this);
var settings = undefined;
// check pre-conditions
if (!options) {
throw new TypeError('Initialization options are required');
}
if (typeof options.currentTime !== 'function') {
throw new TypeError('No currentTime getter specified');
}
if (!options.mediaSource) {
throw new TypeError('No MediaSource specified');
}
settings = _videoJs2['default'].mergeOptions(_videoJs2['default'].options.hls, options);
// public properties
this.state = 'INIT';
this.bandwidth = settings.bandwidth;
this.throughput = { rate: 0, count: 0 };
this.roundTrip = NaN;
this.resetStats_();
// private settings
this.hasPlayed_ = settings.hasPlayed;
this.currentTime_ = settings.currentTime;
this.seekable_ = settings.seekable;
this.seeking_ = settings.seeking;
this.setCurrentTime_ = settings.setCurrentTime;
this.mediaSource_ = settings.mediaSource;
this.hls_ = settings.hls;
// private instance variables
this.checkBufferTimeout_ = null;
this.error_ = void 0;
this.expired_ = 0;
this.timeCorrection_ = 0;
this.currentTimeline_ = -1;
this.zeroOffset_ = NaN;
this.xhr_ = null;
this.pendingSegment_ = null;
this.mimeType_ = null;
this.sourceUpdater_ = null;
this.xhrOptions_ = null;
this.activeInitSegmentId_ = null;
this.initSegments_ = {};
this.decrypter_ = (0, _webworkify2['default'])(_decrypterWorkerJs2['default']);
this.decrypter_.onmessage = function (event) {
if (event.data.action === 'done') {
var segmentInfo = _this.pendingSegment_;
if (segmentInfo) {
var bytes = new Uint8Array(event.data.bytes, event.data.byteOffset, event.data.byteLength);
segmentInfo.bytes = bytes;
_this.handleSegment_();
}
}
};
}
/**
* reset all of our media stats
*
* @private
*/
_createClass(SegmentLoader, [{
key: 'resetStats_',
value: function resetStats_() {
this.mediaBytesTransferred = 0;
this.mediaRequests = 0;
this.mediaTransferDuration = 0;
}
/**
* dispose of the SegmentLoader and reset to the default state
*/
}, {
key: 'dispose',
value: function dispose() {
this.state = 'DISPOSED';
this.abort_();
if (this.sourceUpdater_) {
this.sourceUpdater_.dispose();
}
this.resetStats_();
}
/**
* abort anything that is currently doing on with the SegmentLoader
* and reset to a default state
*/
}, {
key: 'abort',
value: function abort() {
if (this.state !== 'WAITING') {
return;
}
this.abort_();
// don't wait for buffer check timeouts to begin fetching the
// next segment
if (!this.paused()) {
this.state = 'READY';
this.fillBuffer_();
}
}
/**
* set an error on the segment loader and null out any pending segements
*
* @param {Error} error the error to set on the SegmentLoader
* @return {Error} the error that was set or that is currently set
*/
}, {
key: 'error',
value: function error(_error) {
if (typeof _error !== 'undefined') {
this.error_ = _error;
}
this.pendingSegment_ = null;
return this.error_;
}
/**
* load a playlist and start to fill the buffer
*/
}, {
key: 'load',
value: function load() {
// un-pause
this.monitorBuffer_();
// if we don't have a playlist yet, keep waiting for one to be
// specified
if (!this.playlist_) {
return;
}
// if all the configuration is ready, initialize and begin loading
if (this.state === 'INIT' && this.mimeType_) {
return this.init_();
}
// if we're in the middle of processing a segment already, don't
// kick off an additional segment request
if (!this.sourceUpdater_ || this.state !== 'READY' && this.state !== 'INIT') {
return;
}
this.state = 'READY';
this.fillBuffer_();
}
/**
* set a playlist on the segment loader
*
* @param {PlaylistLoader} media the playlist to set on the segment loader
*/
}, {
key: 'playlist',
value: function playlist(media) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (!media) {
return;
}
this.playlist_ = media;
this.xhrOptions_ = options;
// if we were unpaused but waiting for a playlist, start
// buffering now
if (this.mimeType_ && this.state === 'INIT' && !this.paused()) {
return this.init_();
}
}
/**
* Prevent the loader from fetching additional segments. If there
* is a segment request outstanding, it will finish processing
* before the loader halts. A segment loader can be unpaused by
* calling load().
*/
}, {
key: 'pause',
value: function pause() {
if (this.checkBufferTimeout_) {
_globalWindow2['default'].clearTimeout(this.checkBufferTimeout_);
this.checkBufferTimeout_ = null;
}
}
/**
* Returns whether the segment loader is fetching additional
* segments when given the opportunity. This property can be
* modified through calls to pause() and load().
*/
}, {
key: 'paused',
value: function paused() {
return this.checkBufferTimeout_ === null;
}
/**
* setter for expired time on the SegmentLoader
*
* @param {Number} expired the exired time to set
*/
}, {
key: 'expired',
value: function expired(_expired) {
this.expired_ = _expired;
}
/**
* create/set the following mimetype on the SourceBuffer through a
* SourceUpdater
*
* @param {String} mimeType the mime type string to use
*/
}, {
key: 'mimeType',
value: function mimeType(_mimeType) {
if (this.mimeType_) {
return;
}
this.mimeType_ = _mimeType;
// if we were unpaused but waiting for a sourceUpdater, start
// buffering now
if (this.playlist_ && this.state === 'INIT' && !this.paused()) {
this.init_();
}
}
/**
* As long as the SegmentLoader is in the READY state, periodically
* invoke fillBuffer_().
*
* @private
*/
}, {
key: 'monitorBuffer_',
value: function monitorBuffer_() {
if (this.state === 'READY') {
this.fillBuffer_();
}
if (this.checkBufferTimeout_) {
_globalWindow2['default'].clearTimeout(this.checkBufferTimeout_);
}
this.checkBufferTimeout_ = _globalWindow2['default'].setTimeout(this.monitorBuffer_.bind(this), CHECK_BUFFER_DELAY);
}
/**
* Determines what segment request should be made, given current
* playback state.
*
* @param {TimeRanges} buffered - the state of the buffer
* @param {Object} playlist - the playlist object to fetch segments from
* @param {Number} currentTime - the playback position in seconds
* @param {Boolean} hasPlayed - if the player has played before
* @param {Number} expired - the seconds expired off the playlist
* @param {Number} timeCorrection - correction value to add to current time when
* when determining media index to use
* @returns {Object} a segment info object that describes the
* request that should be made or null if no request is necessary
*/
}, {
key: 'checkBuffer_',
value: function checkBuffer_(buffered, playlist, currentTime, hasPlayed, expired, timeCorrection) {
var currentBuffered = _ranges2['default'].findRange(buffered, currentTime);
// There are times when MSE reports the first segment as starting a
// little after 0-time so add a fudge factor to try and fix those cases
// or we end up fetching the same first segment over and over
if (currentBuffered.length === 0 && currentTime === 0) {
currentBuffered = _ranges2['default'].findRange(buffered, currentTime + _ranges2['default'].TIME_FUDGE_FACTOR);
}
var bufferedTime = undefined;
var currentBufferedEnd = undefined;
var mediaIndex = undefined;
if (!playlist.segments.length) {
return null;
}
if (currentBuffered.length === 0) {
// find the segment containing currentTime
mediaIndex = (0, _playlist.getMediaIndexForTime_)(playlist, currentTime + timeCorrection, expired);
} else {
// find the segment adjacent to the end of the current
// buffered region
currentBufferedEnd = currentBuffered.end(0);
bufferedTime = Math.max(0, currentBufferedEnd - currentTime);
// if the video has not yet played only, and we already have
// one segment downloaded do nothing
if (!hasPlayed && bufferedTime >= 1) {
return null;
}
// if there is plenty of content buffered, and the video has
// been played before relax for awhile
if (hasPlayed && bufferedTime >= _config2['default'].GOAL_BUFFER_LENGTH) {
return null;
}
mediaIndex = (0, _playlist.getMediaIndexForTime_)(playlist, currentBufferedEnd + timeCorrection, expired);
}
return mediaIndex;
}
/**
* abort all pending xhr requests and null any pending segements
*
* @private
*/
}, {
key: 'abort_',
value: function abort_() {
if (this.xhr_) {
this.xhr_.abort();
}
// clear out the segment being processed
this.pendingSegment_ = null;
}
/**
* Once all the starting parameters have been specified, begin
* operation. This method should only be invoked from the INIT
* state.
*/
}, {
key: 'init_',
value: function init_() {
this.state = 'READY';
this.sourceUpdater_ = new _sourceUpdater2['default'](this.mediaSource_, this.mimeType_);
this.clearBuffer();
return this.fillBuffer_();
}
/**
* fill the buffer with segements unless the
* sourceBuffers are currently updating
*
* @private
*/
}, {
key: 'fillBuffer_',
value: function fillBuffer_() {
if (this.sourceUpdater_.updating()) {
return;
}
var buffered = this.sourceUpdater_.buffered();
var playlist = this.playlist_;
var currentTime = this.currentTime_();
var hasPlayed = this.hasPlayed_();
var expired = this.expired_;
var timeCorrection = this.timeCorrection_;
// see if we need to begin loading immediately
var requestIndex = this.checkBuffer_(buffered, playlist, currentTime, hasPlayed, expired, timeCorrection);
if (requestIndex === null) {
return;
}
var isEndOfStream = detectEndOfStream(playlist, this.mediaSource_, requestIndex);
if (isEndOfStream) {
this.mediaSource_.endOfStream();
return;
}
if (requestIndex === playlist.segments.length - 1 && this.mediaSource_.readyState === 'ended' && !this.seeking_()) {
return;
}
if (requestIndex < 0 || requestIndex >= playlist.segments.length) {
return;
}
var segment = this.playlist_.segments[requestIndex];
var request = {
// resolve the segment URL relative to the playlist
uri: segment.resolvedUri,
// the segment's mediaIndex at the time it was requested
mediaIndex: requestIndex,
// the segment's playlist
playlist: playlist,
// unencrypted bytes of the segment
bytes: null,
// when a key is defined for this segment, the encrypted bytes
encryptedBytes: null,
// the state of the buffer before a segment is appended will be
// stored here so that the actual segment duration can be
// determined after it has been appended
buffered: null,
// The target timestampOffset for this segment when we append it
// to the source buffer
timestampOffset: NaN,
// The timeline that the segment is in
timeline: segment.timeline,
// The expected duration of the segment in seconds
duration: segment.duration
};
var startOfSegment = (0, _playlist.duration)(playlist, playlist.mediaSequence + request.mediaIndex, expired);
// (we are crossing a discontinuity somehow)
// - The "timestampOffset" for the start of this segment is less than
// the currently set timestampOffset
request.timestampOffset = this.sourceUpdater_.timestampOffset();
if (segment.timeline !== this.currentTimeline_ || startOfSegment < this.sourceUpdater_.timestampOffset()) {
request.timestampOffset = startOfSegment;
}
// Sanity check the segment-index determining logic by calcuating the
// percentage of the chosen segment that is buffered. If more than 90%
// of the segment is buffered then fetching it will likely not help in
// any way
var percentBuffered = _ranges2['default'].getSegmentBufferedPercent(startOfSegment, segment.duration, currentTime, buffered);
if (percentBuffered >= 90) {
// Increment the timeCorrection_ variable to push the fetcher forward
// in time and hopefully skip any gaps or flaws in our understanding
// of the media
var correctionApplied = this.incrementTimeCorrection_(playlist.targetDuration / 2, 1);
if (correctionApplied && !this.paused()) {
this.fillBuffer_();
}
return;
}
this.loadSegment_(request);
}
/**
* trim the back buffer so we only remove content
* on segment boundaries
*
* @private
*
* @param {Object} segmentInfo - the current segment
* @returns {Number} removeToTime - the end point in time, in seconds
* that the the buffer should be trimmed.
*/
}, {
key: 'trimBuffer_',
value: function trimBuffer_(segmentInfo) {
var seekable = this.seekable_();
var currentTime = this.currentTime_();
var removeToTime = undefined;
// Chrome has a hard limit of 150mb of
// buffer and a very conservative "garbage collector"
// We manually clear out the old buffer to ensure
// we don't trigger the QuotaExceeded error
// on the source buffer during subsequent appends
// If we have a seekable range use that as the limit for what can be removed safely
// otherwise remove anything older than 1 minute before the current play head
if (seekable.length && seekable.start(0) > 0 && seekable.start(0) < currentTime) {
return seekable.start(0);
}
removeToTime = currentTime - 60;
if (!this.playlist_.endList) {
return removeToTime;
}
// If we are going to remove time from the front of the buffer, make
// sure we aren't discarding a partial segment to avoid throwing
// PLAYER_ERR_TIMEOUT while trying to read a partially discarded segment
for (var i = 1; i <= segmentInfo.playlist.segments.length; i++) {
// Loop through the segments and calculate the duration to compare
// against the removeToTime
var removeDuration = (0, _playlist.duration)(segmentInfo.playlist, segmentInfo.playlist.mediaSequence + i, this.expired_);
// If we are close to next segment begining, remove to end of previous
// segment instead
var previousDuration = (0, _playlist.duration)(segmentInfo.playlist, segmentInfo.playlist.mediaSequence + (i - 1), this.expired_);
if (removeDuration >= removeToTime) {
removeToTime = previousDuration;
break;
}
}
return removeToTime;
}
/**
* load a specific segment from a request into the buffer
*
* @private
*/
}, {
key: 'loadSegment_',
value: function loadSegment_(segmentInfo) {
var segment = undefined;
var keyXhr = undefined;
var initSegmentXhr = undefined;
var segmentXhr = undefined;
var removeToTime = 0;
removeToTime = this.trimBuffer_(segmentInfo);
if (removeToTime > 0) {
this.sourceUpdater_.remove(0, removeToTime);
}
segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
// optionally, request the decryption key
if (segment.key) {
var keyRequestOptions = _videoJs2['default'].mergeOptions(this.xhrOptions_, {
uri: segment.key.resolvedUri,
responseType: 'arraybuffer'
});
keyXhr = this.hls_.xhr(keyRequestOptions, this.handleResponse_.bind(this));
}
// optionally, request the associated media init segment
if (segment.map && !this.initSegments_[initSegmentId(segment.map)]) {
var initSegmentOptions = _videoJs2['default'].mergeOptions(this.xhrOptions_, {
uri: segment.map.resolvedUri,
responseType: 'arraybuffer',
headers: segmentXhrHeaders(segment.map)
});
initSegmentXhr = this.hls_.xhr(initSegmentOptions, this.handleResponse_.bind(this));
}
this.pendingSegment_ = segmentInfo;
var segmentRequestOptions = _videoJs2['default'].mergeOptions(this.xhrOptions_, {
uri: segmentInfo.uri,
responseType: 'arraybuffer',
headers: segmentXhrHeaders(segment)
});
segmentXhr = this.hls_.xhr(segmentRequestOptions, this.handleResponse_.bind(this));
this.xhr_ = {
keyXhr: keyXhr,
initSegmentXhr: initSegmentXhr,
segmentXhr: segmentXhr,
abort: function abort() {
if (this.segmentXhr) {
// Prevent error handler from running.
this.segmentXhr.onreadystatechange = null;
this.segmentXhr.abort();
this.segmentXhr = null;
}
if (this.initSegmentXhr) {
// Prevent error handler from running.
this.initSegmentXhr.onreadystatechange = null;
this.initSegmentXhr.abort();
this.initSegmentXhr = null;
}
if (this.keyXhr) {
// Prevent error handler from running.
this.keyXhr.onreadystatechange = null;
this.keyXhr.abort();
this.keyXhr = null;
}
}
};
this.state = 'WAITING';
}
/**
* triggered when a segment response is received
*
* @private
*/
}, {
key: 'handleResponse_',
value: function handleResponse_(error, request) {
var segmentInfo = undefined;
var segment = undefined;
var keyXhrRequest = undefined;
var view = undefined;
// timeout of previously aborted request
if (!this.xhr_ || request !== this.xhr_.segmentXhr && request !== this.xhr_.keyXhr && request !== this.xhr_.initSegmentXhr) {
return;
}
segmentInfo = this.pendingSegment_;
segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
// if a request times out, reset bandwidth tracking
if (request.timedout) {
this.abort_();
this.bandwidth = 1;
this.roundTrip = NaN;
this.state = 'READY';
return this.trigger('progress');
}
// trigger an event for other errors
if (!request.aborted && error) {
// abort will clear xhr_
keyXhrRequest = this.xhr_.keyXhr;
this.abort_();
this.error({
status: request.status,
message: request === keyXhrRequest ? 'HLS key request error at URL: ' + segment.key.uri : 'HLS segment request error at URL: ' + segmentInfo.uri,
code: 2,
xhr: request
});
this.state = 'READY';
this.pause();
return this.trigger('error');
}
// stop processing if the request was aborted
if (!request.response) {
this.abort_();
return;
}
if (request === this.xhr_.segmentXhr) {
// the segment request is no longer outstanding
this.xhr_.segmentXhr = null;
segmentInfo.startOfAppend = Date.now();
// calculate the download bandwidth based on segment request
this.roundTrip = request.roundTripTime;
this.bandwidth = request.bandwidth;
this.mediaBytesTransferred += request.bytesReceived || 0;
this.mediaRequests += 1;
this.mediaTransferDuration += request.roundTripTime || 0;
if (segment.key) {
segmentInfo.encryptedBytes = new Uint8Array(request.response);
} else {
segmentInfo.bytes = new Uint8Array(request.response);
}
}
if (request === this.xhr_.keyXhr) {
keyXhrRequest = this.xhr_.segmentXhr;
// the key request is no longer outstanding
this.xhr_.keyXhr = null;
if (request.response.byteLength !== 16) {
this.abort_();
this.error({
status: request.status,
message: 'Invalid HLS key at URL: ' + segment.key.uri,
code: 2,
xhr: request
});
this.state = 'READY';
this.pause();
return this.trigger('error');
}
view = new DataView(request.response);
segment.key.bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
// if the media sequence is greater than 2^32, the IV will be incorrect
// assuming 10s segments, that would be about 1300 years
segment.key.iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
}
if (request === this.xhr_.initSegmentXhr) {
// the init segment request is no longer outstanding
this.xhr_.initSegmentXhr = null;
segment.map.bytes = new Uint8Array(request.response);
this.initSegments_[initSegmentId(segment.map)] = segment.map;
}
if (!this.xhr_.segmentXhr && !this.xhr_.keyXhr && !this.xhr_.initSegmentXhr) {
this.xhr_ = null;
this.processResponse_();
}
}
/**
* clear anything that is currently in the buffer and throw it away
*/
}, {
key: 'clearBuffer',
value: function clearBuffer() {
if (this.sourceUpdater_ && this.sourceUpdater_.buffered().length) {
this.sourceUpdater_.remove(0, Infinity);
}
}
/**
* Decrypt the segment that is being loaded if necessary
*
* @private
*/
}, {
key: 'processResponse_',
value: function processResponse_() {
var segmentInfo = undefined;
var segment = undefined;
this.state = 'DECRYPTING';
segmentInfo = this.pendingSegment_;
segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
// some videos don't start from presentation time zero
// if that is the case, set the timestamp offset on the first
// segment to adjust them so that it is not necessary to seek
// before playback can begin
if (segment.map && isNaN(this.zeroOffset_)) {
var timescales = _muxJsLibMp4Probe2['default'].timescale(segment.map.bytes);
var startTime = _muxJsLibMp4Probe2['default'].startTime(timescales, segmentInfo.bytes);
this.zeroOffset_ = startTime;
segmentInfo.timestampOffset -= startTime;
}
if (segment.key) {
// this is an encrypted segment
// incrementally decrypt the segment
/* eslint-disable no-new, handle-callback-err */
this.decrypter_.postMessage({
action: 'decrypt',
encrypted: {
bytes: segmentInfo.encryptedBytes.buffer,
byteOffset: segmentInfo.encryptedBytes.byteOffset,
byteLength: segmentInfo.encryptedBytes.byteLength
},
key: {
bytes: segment.key.bytes.buffer,
byteOffset: segment.key.bytes.byteOffset,
byteLength: segment.key.bytes.byteLength
},
iv: {
bytes: segment.key.iv.buffer,
byteOffset: segment.key.iv.byteOffset,
byteLength: segment.key.iv.byteLength
}
}, [segmentInfo.encryptedBytes.buffer, segment.key.bytes.buffer]);
/* eslint-enable */
} else {
this.handleSegment_();
}
}
/**
* append a decrypted segement to the SourceBuffer through a SourceUpdater
*
* @private
*/
}, {
key: 'handleSegment_',
value: function handleSegment_() {
var _this2 = this;
var segmentInfo = undefined;
var segment = undefined;
this.state = 'APPENDING';
segmentInfo = this.pendingSegment_;
segmentInfo.buffered = this.sourceUpdater_.buffered();
segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];
this.currentTimeline_ = segmentInfo.timeline;
if (segmentInfo.timestampOffset !== this.sourceUpdater_.timestampOffset()) {
this.sourceUpdater_.timestampOffset(segmentInfo.timestampOffset);
}
// if the media initialization segment is changing, append it
// before the content segment
if (segment.map) {
(function () {
var initId = initSegmentId(segment.map);
if (!_this2.activeInitSegmentId_ || _this2.activeInitSegmentId_ !== initId) {
var initSegment = _this2.initSegments_[initId];
_this2.sourceUpdater_.appendBuffer(initSegment.bytes, function () {
_this2.activeInitSegmentId_ = initId;
});
}
})();
}
segmentInfo.byteLength = segmentInfo.bytes.byteLength;
this.sourceUpdater_.appendBuffer(segmentInfo.bytes, this.handleUpdateEnd_.bind(this));
}
/**
* callback to run when appendBuffer is finished. detects if we are
* in a good state to do things with the data we got, or if we need
* to wait for more
*
* @private
*/
}, {
key: 'handleUpdateEnd_',
value: function handleUpdateEnd_() {
var segmentInfo = this.pendingSegment_;
var currentTime = this.currentTime_();
this.pendingSegment_ = null;
this.recordThroughput_(segmentInfo);
// add segment metadata if it we have gained information during the
// last append
var timelineUpdated = this.updateTimeline_(segmentInfo);
this.trigger('progress');
var currentMediaIndex = segmentInfo.mediaIndex;
currentMediaIndex += segmentInfo.playlist.mediaSequence - this.playlist_.mediaSequence;
var currentBuffered = _ranges2['default'].findRange(this.sourceUpdater_.buffered(), currentTime);
// any time an update finishes and the last segment is in the
// buffer, end the stream. this ensures the "ended" event will
// fire if playback reaches that point.
var isEndOfStream = detectEndOfStream(segmentInfo.playlist, this.mediaSource_, currentMediaIndex + 1);
if (isEndOfStream) {
this.mediaSource_.endOfStream();
}
// when seeking to the beginning of the seekable range, it's
// possible that imprecise timing information may cause the seek to
// end up earlier than the start of the range
// in that case, seek again
var seekable = this.seekable_();
var next = _ranges2['default'].findNextRange(this.sourceUpdater_.buffered(), currentTime);
if (this.seeking_() && currentBuffered.length === 0) {
if (seekable.length && currentTime < seekable.start(0)) {
if (next.length) {
_videoJs2['default'].log('tried seeking to', currentTime, 'but that was too early, retrying at', next.start(0));
this.setCurrentTime_(next.start(0) + _ranges2['default'].TIME_FUDGE_FACTOR);
}
}
}
this.state = 'READY';
if (timelineUpdated) {
this.timeCorrection_ = 0;
if (!this.paused()) {
this.fillBuffer_();
}
return;
}
// the last segment append must have been entirely in the
// already buffered time ranges. adjust the timeCorrection
// offset to fetch forward until we find a segment that adds
// to the buffered time ranges and improves subsequent media
// index calculations.
var correctionApplied = this.incrementTimeCorrection_(segmentInfo.duration, 4);
if (correctionApplied && !this.paused()) {
this.fillBuffer_();
}
}
/**
* annotate the segment with any start and end time information
* added by the media processing
*
* @private
* @param {Object} segmentInfo annotate a segment with time info
*/
}, {
key: 'updateTimeline_',
value: function updateTimeline_(segmentInfo) {
var segment = undefined;
var segmentEnd = undefined;
var timelineUpdated = false;
var playlist = segmentInfo.playlist;
var currentMediaIndex = segmentInfo.mediaIndex;
currentMediaIndex += playlist.mediaSequence - this.playlist_.mediaSequence;
segment = playlist.segments[currentMediaIndex];
// Update segment meta-data (duration and end-point) based on timeline
if (segment && segmentInfo && segmentInfo.playlist.uri === this.playlist_.uri) {
segmentEnd = _ranges2['default'].findSoleUncommonTimeRangesEnd(segmentInfo.buffered, this.sourceUpdater_.buffered());
timelineUpdated = updateSegmentMetadata(playlist, currentMediaIndex, segmentEnd);
}
return timelineUpdated;
}
/**
* Records the current throughput of the decrypt, transmux, and append
* portion of the semgment pipeline. `throughput.rate` is a the cumulative
* moving average of the throughput. `throughput.count` is the number of
* data points in the average.
*
* @private
* @param {Object} segmentInfo the object returned by loadSegment
*/
}, {
key: 'recordThroughput_',
value: function recordThroughput_(segmentInfo) {
var rate = this.throughput.rate;
// Add one to the time to ensure that we don't accidentally attempt to divide
// by zero in the case where the throughput is ridiculously high
var segmentProcessingTime = Date.now() - segmentInfo.startOfAppend + 1;
// Multiply by 8000 to convert from bytes/millisecond to bits/second
var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000);
// This is just a cumulative moving average calculation:
// newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
}
/**
* add a number of seconds to the currentTime when determining which
* segment to fetch in order to force the fetcher to advance in cases
* where it may get stuck on the same segment due to buffer gaps or
* missing segment annotation after a rendition switch (especially
* during a live stream)
*
* @private
* @param {Number} secondsToIncrement number of seconds to add to the
* timeCorrection_ variable
* @param {Number} maxSegmentsToWalk maximum number of times we allow this
* function to walk forward
*/
}, {
key: 'incrementTimeCorrection_',
value: function incrementTimeCorrection_(secondsToIncrement, maxSegmentsToWalk) {
// If we have already incremented timeCorrection_ beyond the limit,
// stop searching for a segment and reset timeCorrection_
if (this.timeCorrection_ >= this.playlist_.targetDuration * maxSegmentsToWalk) {
this.timeCorrection_ = 0;
return false;
}
this.timeCorrection_ += secondsToIncrement;
return true;
}
}]);
return SegmentLoader;
})(_videoJs2['default'].EventTarget);
exports['default'] = SegmentLoader;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./config":30,"./decrypter-worker.js":31,"./playlist":35,"./ranges":36,"./source-updater":41,"global/window":46,"mux.js/lib/mp4/probe":24,"webworkify":89}],41:[function(require,module,exports){
(function (global){
/**
* @file source-updater.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
/**
* A queue of callbacks to be serialized and applied when a
* MediaSource and its associated SourceBuffers are not in the
* updating state. It is used by the segment loader to update the
* underlying SourceBuffers when new data is loaded, for instance.
*
* @class SourceUpdater
* @param {MediaSource} mediaSource the MediaSource to create the
* SourceBuffer from
* @param {String} mimeType the desired MIME type of the underlying
* SourceBuffer
*/
var SourceUpdater = (function () {
function SourceUpdater(mediaSource, mimeType) {
var _this = this;
_classCallCheck(this, SourceUpdater);
var createSourceBuffer = function createSourceBuffer() {
_this.sourceBuffer_ = mediaSource.addSourceBuffer(mimeType);
// run completion handlers and process callbacks as updateend
// events fire
_this.onUpdateendCallback_ = function () {
var pendingCallback = _this.pendingCallback_;
_this.pendingCallback_ = null;
if (pendingCallback) {
pendingCallback();
}
_this.runCallback_();
};
_this.sourceBuffer_.addEventListener('updateend', _this.onUpdateendCallback_);
_this.runCallback_();
};
this.callbacks_ = [];
this.pendingCallback_ = null;
this.timestampOffset_ = 0;
this.mediaSource = mediaSource;
if (mediaSource.readyState === 'closed') {
mediaSource.addEventListener('sourceopen', createSourceBuffer);
} else {
createSourceBuffer();
}
}
/**
* Aborts the current segment and resets the segment parser.
*
* @param {Function} done function to call when done
* @see http://w3c.github.io/media-source/#widl-SourceBuffer-abort-void
*/
_createClass(SourceUpdater, [{
key: 'abort',
value: function abort(done) {
var _this2 = this;
this.queueCallback_(function () {
_this2.sourceBuffer_.abort();
}, done);
}
/**
* Queue an update to append an ArrayBuffer.
*
* @param {ArrayBuffer} bytes
* @param {Function} done the function to call when done
* @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
*/
}, {
key: 'appendBuffer',
value: function appendBuffer(bytes, done) {
var _this3 = this;
this.queueCallback_(function () {
_this3.sourceBuffer_.appendBuffer(bytes);
}, done);
}
/**
* Indicates what TimeRanges are buffered in the managed SourceBuffer.
*
* @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-buffered
*/
}, {
key: 'buffered',
value: function buffered() {
if (!this.sourceBuffer_) {
return _videoJs2['default'].createTimeRanges();
}
return this.sourceBuffer_.buffered;
}
/**
* Queue an update to set the duration.
*
* @param {Double} duration what to set the duration to
* @see http://www.w3.org/TR/media-source/#widl-MediaSource-duration
*/
}, {
key: 'duration',
value: function duration(_duration) {
var _this4 = this;
this.queueCallback_(function () {
_this4.sourceBuffer_.duration = _duration;
});
}
/**
* Queue an update to remove a time range from the buffer.
*
* @param {Number} start where to start the removal
* @param {Number} end where to end the removal
* @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
*/
}, {
key: 'remove',
value: function remove(start, end) {
var _this5 = this;
this.queueCallback_(function () {
_this5.sourceBuffer_.remove(start, end);
});
}
/**
* wether the underlying sourceBuffer is updating or not
*
* @return {Boolean} the updating status of the SourceBuffer
*/
}, {
key: 'updating',
value: function updating() {
return !this.sourceBuffer_ || this.sourceBuffer_.updating;
}
/**
* Set/get the timestampoffset on the SourceBuffer
*
* @return {Number} the timestamp offset
*/
}, {
key: 'timestampOffset',
value: function timestampOffset(offset) {
var _this6 = this;
if (typeof offset !== 'undefined') {
this.queueCallback_(function () {
_this6.sourceBuffer_.timestampOffset = offset;
});
this.timestampOffset_ = offset;
}
return this.timestampOffset_;
}
/**
* que a callback to run
*/
}, {
key: 'queueCallback_',
value: function queueCallback_(callback, done) {
this.callbacks_.push([callback.bind(this), done]);
this.runCallback_();
}
/**
* run a queued callback
*/
}, {
key: 'runCallback_',
value: function runCallback_() {
var callbacks = undefined;
if (this.sourceBuffer_ && !this.sourceBuffer_.updating && this.callbacks_.length) {
callbacks = this.callbacks_.shift();
this.pendingCallback_ = callbacks[1];
callbacks[0]();
}
}
/**
* dispose of the source updater and the underlying sourceBuffer
*/
}, {
key: 'dispose',
value: function dispose() {
this.sourceBuffer_.removeEventListener('updateend', this.onUpdateendCallback_);
if (this.sourceBuffer_ && this.mediaSource.readyState === 'open') {
this.sourceBuffer_.abort();
}
}
}]);
return SourceUpdater;
})();
exports['default'] = SourceUpdater;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],42:[function(require,module,exports){
arguments[4][5][0].apply(exports,arguments)
},{"dup":5}],43:[function(require,module,exports){
(function (global){
/**
* @file xhr.js
*/
/**
* A wrapper for videojs.xhr that tracks bandwidth.
*
* @param {Object} options options for the XHR
* @param {Function} callback the callback to call when done
* @return {Request} the xhr request that is going to be made
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var xhrFactory = function xhrFactory() {
var xhr = function XhrFunction(options, callback) {
// Add a default timeout for all hls requests
options = (0, _videoJs.mergeOptions)({
timeout: 45e3
}, options);
// Allow an optional user-specified function to modify the option
// object before we construct the xhr request
if (XhrFunction.beforeRequest && typeof XhrFunction.beforeRequest === 'function') {
var newOptions = XhrFunction.beforeRequest(options);
if (newOptions) {
options = newOptions;
}
}
var request = (0, _videoJs.xhr)(options, function (error, response) {
if (!error && request.response) {
request.responseTime = Date.now();
request.roundTripTime = request.responseTime - request.requestTime;
request.bytesReceived = request.response.byteLength || request.response.length;
if (!request.bandwidth) {
request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
}
}
// videojs.xhr now uses a specific code
// on the error object to signal that a request has
// timed out errors of setting a boolean on the request object
if (error || request.timedout) {
request.timedout = request.timedout || error.code === 'ETIMEDOUT';
} else {
request.timedout = false;
}
// videojs.xhr no longer considers status codes outside of 200 and 0
// (for file uris) to be errors, but the old XHR did, so emulate that
// behavior. Status 206 may be used in response to byterange requests.
if (!error && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
error = new Error('XHR Failed with a response of: ' + (request && (request.response || request.responseText)));
}
callback(error, request);
});
request.requestTime = Date.now();
return request;
};
return xhr;
};
exports['default'] = xhrFactory;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],44:[function(require,module,exports){
},{}],45:[function(require,module,exports){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = require('min-document');
if (typeof document !== 'undefined') {
module.exports = document;
} else {
var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
module.exports = doccy;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"min-document":44}],46:[function(require,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],47:[function(require,module,exports){
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
},{}],48:[function(require,module,exports){
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = arrayCopy;
},{}],49:[function(require,module,exports){
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
},{}],50:[function(require,module,exports){
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],51:[function(require,module,exports){
var createBaseFor = require('./createBaseFor');
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
},{"./createBaseFor":58}],52:[function(require,module,exports){
var baseFor = require('./baseFor'),
keysIn = require('../object/keysIn');
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
module.exports = baseForIn;
},{"../object/keysIn":79,"./baseFor":51}],53:[function(require,module,exports){
var arrayEach = require('./arrayEach'),
baseMergeDeep = require('./baseMergeDeep'),
isArray = require('../lang/isArray'),
isArrayLike = require('./isArrayLike'),
isObject = require('../lang/isObject'),
isObjectLike = require('./isObjectLike'),
isTypedArray = require('../lang/isTypedArray'),
keys = require('../object/keys');
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns `object`.
*/
function baseMerge(object, source, customizer, stackA, stackB) {
if (!isObject(object)) {
return object;
}
var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
props = isSrcArr ? undefined : keys(source);
arrayEach(props || source, function(srcValue, key) {
if (props) {
key = srcValue;
srcValue = source[key];
}
if (isObjectLike(srcValue)) {
stackA || (stackA = []);
stackB || (stackB = []);
baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
}
else {
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
}
if ((result !== undefined || (isSrcArr && !(key in object))) &&
(isCommon || (result === result ? (result !== value) : (value === value)))) {
object[key] = result;
}
}
});
return object;
}
module.exports = baseMerge;
},{"../lang/isArray":70,"../lang/isObject":73,"../lang/isTypedArray":76,"../object/keys":78,"./arrayEach":49,"./baseMergeDeep":54,"./isArrayLike":61,"./isObjectLike":66}],54:[function(require,module,exports){
var arrayCopy = require('./arrayCopy'),
isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isArrayLike = require('./isArrayLike'),
isPlainObject = require('../lang/isPlainObject'),
isTypedArray = require('../lang/isTypedArray'),
toPlainObject = require('../lang/toPlainObject');
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
var length = stackA.length,
srcValue = source[key];
while (length--) {
if (stackA[length] == srcValue) {
object[key] = stackB[length];
return;
}
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
result = isArray(value)
? value
: (isArrayLike(value) ? arrayCopy(value) : []);
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
result = isArguments(value)
? toPlainObject(value)
: (isPlainObject(value) ? value : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? (result !== value) : (value === value)) {
object[key] = result;
}
}
module.exports = baseMergeDeep;
},{"../lang/isArguments":69,"../lang/isArray":70,"../lang/isPlainObject":74,"../lang/isTypedArray":76,"../lang/toPlainObject":77,"./arrayCopy":48,"./isArrayLike":61}],55:[function(require,module,exports){
var toObject = require('./toObject');
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : toObject(object)[key];
};
}
module.exports = baseProperty;
},{"./toObject":68}],56:[function(require,module,exports){
var identity = require('../utility/identity');
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
},{"../utility/identity":82}],57:[function(require,module,exports){
var bindCallback = require('./bindCallback'),
isIterateeCall = require('./isIterateeCall'),
restParam = require('../function/restParam');
/**
* Creates a `_.assign`, `_.defaults`, or `_.merge` function.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
},{"../function/restParam":47,"./bindCallback":56,"./isIterateeCall":64}],58:[function(require,module,exports){
var toObject = require('./toObject');
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
},{"./toObject":68}],59:[function(require,module,exports){
var baseProperty = require('./baseProperty');
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
module.exports = getLength;
},{"./baseProperty":55}],60:[function(require,module,exports){
var isNative = require('../lang/isNative');
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
module.exports = getNative;
},{"../lang/isNative":72}],61:[function(require,module,exports){
var getLength = require('./getLength'),
isLength = require('./isLength');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
module.exports = isArrayLike;
},{"./getLength":59,"./isLength":65}],62:[function(require,module,exports){
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
var isHostObject = (function() {
try {
Object({ 'toString': 0 } + '');
} catch(e) {
return function() { return false; };
}
return function(value) {
// IE < 9 presents many host objects as `Object` objects that can coerce
// to strings despite having improperly defined `toString` methods.
return typeof value.toString != 'function' && typeof (value + '') == 'string';
};
}());
module.exports = isHostObject;
},{}],63:[function(require,module,exports){
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
},{}],64:[function(require,module,exports){
var isArrayLike = require('./isArrayLike'),
isIndex = require('./isIndex'),
isObject = require('../lang/isObject');
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
},{"../lang/isObject":73,"./isArrayLike":61,"./isIndex":63}],65:[function(require,module,exports){
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
},{}],66:[function(require,module,exports){
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
},{}],67:[function(require,module,exports){
var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('./isIndex'),
isLength = require('./isLength'),
isString = require('../lang/isString'),
keysIn = require('../object/keysIn');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
},{"../lang/isArguments":69,"../lang/isArray":70,"../lang/isString":75,"../object/keysIn":79,"./isIndex":63,"./isLength":65}],68:[function(require,module,exports){
var isObject = require('../lang/isObject'),
isString = require('../lang/isString'),
support = require('../support');
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
if (support.unindexedChars && isString(value)) {
var index = -1,
length = value.length,
result = Object(value);
while (++index < length) {
result[index] = value.charAt(index);
}
return result;
}
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
},{"../lang/isObject":73,"../lang/isString":75,"../support":81}],69:[function(require,module,exports){
var isArrayLike = require('../internal/isArrayLike'),
isObjectLike = require('../internal/isObjectLike');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}
module.exports = isArguments;
},{"../internal/isArrayLike":61,"../internal/isObjectLike":66}],70:[function(require,module,exports){
var getNative = require('../internal/getNative'),
isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var arrayTag = '[object Array]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
module.exports = isArray;
},{"../internal/getNative":60,"../internal/isLength":65,"../internal/isObjectLike":66}],71:[function(require,module,exports){
var isObject = require('./isObject');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 which returns 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
module.exports = isFunction;
},{"./isObject":73}],72:[function(require,module,exports){
var isFunction = require('./isFunction'),
isHostObject = require('../internal/isHostObject'),
isObjectLike = require('../internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value);
}
module.exports = isNative;
},{"../internal/isHostObject":62,"../internal/isObjectLike":66,"./isFunction":71}],73:[function(require,module,exports){
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
},{}],74:[function(require,module,exports){
var baseForIn = require('../internal/baseForIn'),
isArguments = require('./isArguments'),
isHostObject = require('../internal/isHostObject'),
isObjectLike = require('../internal/isObjectLike'),
support = require('../support');
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
var Ctor;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) ||
(!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
if (support.ownLast) {
baseForIn(value, function(subValue, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return result === undefined || hasOwnProperty.call(value, result);
}
module.exports = isPlainObject;
},{"../internal/baseForIn":52,"../internal/isHostObject":62,"../internal/isObjectLike":66,"../support":81,"./isArguments":69}],75:[function(require,module,exports){
var isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
module.exports = isString;
},{"../internal/isObjectLike":66}],76:[function(require,module,exports){
var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
},{"../internal/isLength":65,"../internal/isObjectLike":66}],77:[function(require,module,exports){
var baseCopy = require('../internal/baseCopy'),
keysIn = require('../object/keysIn');
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
module.exports = toPlainObject;
},{"../internal/baseCopy":50,"../object/keysIn":79}],78:[function(require,module,exports){
var getNative = require('../internal/getNative'),
isArrayLike = require('../internal/isArrayLike'),
isObject = require('../lang/isObject'),
shimKeys = require('../internal/shimKeys'),
support = require('../support');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
},{"../internal/getNative":60,"../internal/isArrayLike":61,"../internal/shimKeys":67,"../lang/isObject":73,"../support":81}],79:[function(require,module,exports){
var arrayEach = require('../internal/arrayEach'),
isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isFunction = require('../lang/isFunction'),
isIndex = require('../internal/isIndex'),
isLength = require('../internal/isLength'),
isObject = require('../lang/isObject'),
isString = require('../lang/isString'),
support = require('../support');
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/** Used to fix the JScript `[[DontEnum]]` bug. */
var shadowProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used for native method references. */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to avoid iterating over non-enumerable properties in IE < 9. */
var nonEnumProps = {};
nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true };
nonEnumProps[objectTag] = { 'constructor': true };
arrayEach(shadowProps, function(key) {
for (var tag in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, tag)) {
var props = nonEnumProps[tag];
props[key] = hasOwnProperty.call(props, key);
}
}
});
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
proto = (isFunction(Ctor) && Ctor.prototype) || objectProto,
isProto = proto === object,
result = Array(length),
skipIndexes = length > 0,
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error),
skipProto = support.enumPrototypes && isFunction(object);
while (++index < length) {
result[index] = (index + '');
}
// lodash skips the `constructor` property when it infers it's iterating
// over a `prototype` object because IE < 9 can't set the `[[Enumerable]]`
// attribute of an existing property and the `constructor` property of a
// prototype defaults to non-enumerable.
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name')) &&
!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)),
nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag];
if (tag == objectTag) {
proto = objectProto;
}
length = shadowProps.length;
while (length--) {
key = shadowProps[length];
var nonEnum = nonEnums[key];
if (!(isProto && nonEnum) &&
(nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) {
result.push(key);
}
}
}
return result;
}
module.exports = keysIn;
},{"../internal/arrayEach":49,"../internal/isIndex":63,"../internal/isLength":65,"../lang/isArguments":69,"../lang/isArray":70,"../lang/isFunction":71,"../lang/isObject":73,"../lang/isString":75,"../support":81}],80:[function(require,module,exports){
var baseMerge = require('../internal/baseMerge'),
createAssigner = require('../internal/createAssigner');
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it's invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments: (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* if (_.isArray(a)) {
* return a.concat(b);
* }
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
module.exports = merge;
},{"../internal/baseMerge":53,"../internal/createAssigner":57}],81:[function(require,module,exports){
/** Used for native method references. */
var arrayProto = Array.prototype,
errorProto = Error.prototype,
objectProto = Object.prototype;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = {};
(function(x) {
var Ctor = function() { this.x = x; },
object = { '0': x, 'length': x },
props = [];
Ctor.prototype = { 'valueOf': x, 'y': x };
for (var key in new Ctor) { props.push(key); }
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default (IE < 9, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') ||
propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly set the `[[Enumerable]]` value of a function's `prototype`
* property to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype');
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an object's own properties, shadowing non-enumerable ones,
* are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects
* correctly.
*
* Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array
* `shift()` and `splice()` functions that fail to remove the last element,
* `value[0]`, of array-like objects even though the "length" property is
* set to `0`. The `shift()` method is buggy in compatibility modes of IE 8,
* while `splice()` is buggy regardless of mode in IE < 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index. IE 8 can only access characters
* by index on string literals, not string objects.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
}(1, 0));
module.exports = support;
},{}],82:[function(require,module,exports){
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
},{}],83:[function(require,module,exports){
/**
* @file m3u8/index.js
*
* Utilities for parsing M3U8 files. If the entire manifest is available,
* `Parser` will create an object representation with enough detail for managing
* playback. `ParseStream` and `LineStream` are lower-level parsing primitives
* that do not assume the entirety of the manifest is ready and expose a
* ReadableStream-like interface.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _lineStream = require('./line-stream');
var _lineStream2 = _interopRequireDefault(_lineStream);
var _parseStream = require('./parse-stream');
var _parseStream2 = _interopRequireDefault(_parseStream);
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
exports['default'] = {
LineStream: _lineStream2['default'],
ParseStream: _parseStream2['default'],
Parser: _parser2['default']
};
module.exports = exports['default'];
},{"./line-stream":84,"./parse-stream":85,"./parser":86}],84:[function(require,module,exports){
/**
* @file m3u8/line-stream.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _stream = require('./stream');
var _stream2 = _interopRequireDefault(_stream);
/**
* A stream that buffers string input and generates a `data` event for each
* line.
*
* @class LineStream
* @extends Stream
*/
var LineStream = (function (_Stream) {
_inherits(LineStream, _Stream);
function LineStream() {
_classCallCheck(this, LineStream);
_get(Object.getPrototypeOf(LineStream.prototype), 'constructor', this).call(this);
this.buffer = '';
}
/**
* Add new data to be parsed.
*
* @param {String} data the text to process
*/
_createClass(LineStream, [{
key: 'push',
value: function push(data) {
var nextNewline = undefined;
this.buffer += data;
nextNewline = this.buffer.indexOf('\n');
for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
this.trigger('data', this.buffer.substring(0, nextNewline));
this.buffer = this.buffer.substring(nextNewline + 1);
}
}
}]);
return LineStream;
})(_stream2['default']);
exports['default'] = LineStream;
module.exports = exports['default'];
},{"./stream":87}],85:[function(require,module,exports){
/**
* @file m3u8/parse-stream.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _stream = require('./stream');
var _stream2 = _interopRequireDefault(_stream);
/**
* "forgiving" attribute list psuedo-grammar:
* attributes -> keyvalue (',' keyvalue)*
* keyvalue -> key '=' value
* key -> [^=]*
* value -> '"' [^"]* '"' | [^,]*
*/
var attributeSeparator = function attributeSeparator() {
var key = '[^=]*';
var value = '"[^"]*"|[^,]*';
var keyvalue = '(?:' + key + ')=(?:' + value + ')';
return new RegExp('(?:^|,)(' + keyvalue + ')');
};
/**
* Parse attributes from a line given the seperator
*
* @param {String} attributes the attibute line to parse
*/
var parseAttributes = function parseAttributes(attributes) {
// split the string using attributes as the separator
var attrs = attributes.split(attributeSeparator());
var i = attrs.length;
var result = {};
var attr = undefined;
while (i--) {
// filter out unmatched portions of the string
if (attrs[i] === '') {
continue;
}
// split the key and value
attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1);
// trim whitespace and remove optional quotes around the value
attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
result[attr[0]] = attr[1];
}
return result;
};
/**
* A line-level M3U8 parser event stream. It expects to receive input one
* line at a time and performs a context-free parse of its contents. A stream
* interpretation of a manifest can be useful if the manifest is expected to
* be too large to fit comfortably into memory or the entirety of the input
* is not immediately available. Otherwise, it's probably much easier to work
* with a regular `Parser` object.
*
* Produces `data` events with an object that captures the parser's
* interpretation of the input. That object has a property `tag` that is one
* of `uri`, `comment`, or `tag`. URIs only have a single additional
* property, `line`, which captures the entirety of the input without
* interpretation. Comments similarly have a single additional property
* `text` which is the input without the leading `#`.
*
* Tags always have a property `tagType` which is the lower-cased version of
* the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
* `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
* tags are given the tag type `unknown` and a single additional property
* `data` with the remainder of the input.
*
* @class ParseStream
* @extends Stream
*/
var ParseStream = (function (_Stream) {
_inherits(ParseStream, _Stream);
function ParseStream() {
_classCallCheck(this, ParseStream);
_get(Object.getPrototypeOf(ParseStream.prototype), 'constructor', this).call(this);
}
/**
* Parses an additional line of input.
*
* @param {String} line a single line of an M3U8 file to parse
*/
_createClass(ParseStream, [{
key: 'push',
value: function push(line) {
var match = undefined;
var event = undefined;
// strip whitespace
line = line.replace(/^[\u0000\s]+|[\u0000\s]+$/g, '');
if (line.length === 0) {
// ignore empty lines
return;
}
// URIs
if (line[0] !== '#') {
this.trigger('data', {
type: 'uri',
uri: line
});
return;
}
// Comments
if (line.indexOf('#EXT') !== 0) {
this.trigger('data', {
type: 'comment',
text: line.slice(1)
});
return;
}
// strip off any carriage returns here so the regex matching
// doesn't have to account for them.
line = line.replace('\r', '');
// Tags
match = /^#EXTM3U/.exec(line);
if (match) {
this.trigger('data', {
type: 'tag',
tagType: 'm3u'
});
return;
}
match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'inf'
};
if (match[1]) {
event.duration = parseFloat(match[1]);
}
if (match[2]) {
event.title = match[2];
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'targetduration'
};
if (match[1]) {
event.duration = parseInt(match[1], 10);
}
this.trigger('data', event);
return;
}
match = /^#ZEN-TOTAL-DURATION:?([0-9.]*)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'totalduration'
};
if (match[1]) {
event.duration = parseInt(match[1], 10);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'version'
};
if (match[1]) {
event.version = parseInt(match[1], 10);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'media-sequence'
};
if (match[1]) {
event.number = parseInt(match[1], 10);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'discontinuity-sequence'
};
if (match[1]) {
event.number = parseInt(match[1], 10);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'playlist-type'
};
if (match[1]) {
event.playlistType = match[1];
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'byterange'
};
if (match[1]) {
event.length = parseInt(match[1], 10);
}
if (match[2]) {
event.offset = parseInt(match[2], 10);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'allow-cache'
};
if (match[1]) {
event.allowed = !/NO/.test(match[1]);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-MAP:?(.*)$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'map'
};
if (match[1]) {
var attributes = parseAttributes(match[1]);
if (attributes.URI) {
event.uri = attributes.URI;
}
if (attributes.BYTERANGE) {
var _attributes$BYTERANGE$split = attributes.BYTERANGE.split('@');
var _attributes$BYTERANGE$split2 = _slicedToArray(_attributes$BYTERANGE$split, 2);
var _length = _attributes$BYTERANGE$split2[0];
var offset = _attributes$BYTERANGE$split2[1];
event.byterange = {};
if (_length) {
event.byterange.length = parseInt(_length, 10);
}
if (offset) {
event.byterange.offset = parseInt(offset, 10);
}
}
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'stream-inf'
};
if (match[1]) {
event.attributes = parseAttributes(match[1]);
if (event.attributes.RESOLUTION) {
var split = event.attributes.RESOLUTION.split('x');
var resolution = {};
if (split[0]) {
resolution.width = parseInt(split[0], 10);
}
if (split[1]) {
resolution.height = parseInt(split[1], 10);
}
event.attributes.RESOLUTION = resolution;
}
if (event.attributes.BANDWIDTH) {
event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
}
if (event.attributes['PROGRAM-ID']) {
event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
}
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-MEDIA:?(.*)$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'media'
};
if (match[1]) {
event.attributes = parseAttributes(match[1]);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-ENDLIST/.exec(line);
if (match) {
this.trigger('data', {
type: 'tag',
tagType: 'endlist'
});
return;
}
match = /^#EXT-X-DISCONTINUITY/.exec(line);
if (match) {
this.trigger('data', {
type: 'tag',
tagType: 'discontinuity'
});
return;
}
match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'program-date-time'
};
if (match[1]) {
event.dateTimeString = match[1];
event.dateTimeObject = new Date(match[1]);
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-KEY:?(.*)$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'key'
};
if (match[1]) {
event.attributes = parseAttributes(match[1]);
// parse the IV string into a Uint32Array
if (event.attributes.IV) {
if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
event.attributes.IV = event.attributes.IV.substring(2);
}
event.attributes.IV = event.attributes.IV.match(/.{8}/g);
event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
event.attributes.IV = new Uint32Array(event.attributes.IV);
}
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'cue-out-cont'
};
if (match[1]) {
event.data = match[1];
} else {
event.data = '';
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'cue-out'
};
if (match[1]) {
event.data = match[1];
} else {
event.data = '';
}
this.trigger('data', event);
return;
}
match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(line);
if (match) {
event = {
type: 'tag',
tagType: 'cue-in'
};
if (match[1]) {
event.data = match[1];
} else {
event.data = '';
}
this.trigger('data', event);
return;
}
// unknown tag type
this.trigger('data', {
type: 'tag',
data: line.slice(4)
});
}
}]);
return ParseStream;
})(_stream2['default']);
exports['default'] = ParseStream;
module.exports = exports['default'];
},{"./stream":87}],86:[function(require,module,exports){
/**
* @file m3u8/parser.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _stream = require('./stream');
var _stream2 = _interopRequireDefault(_stream);
var _lineStream = require('./line-stream');
var _lineStream2 = _interopRequireDefault(_lineStream);
var _parseStream = require('./parse-stream');
var _parseStream2 = _interopRequireDefault(_parseStream);
var _lodashCompatObjectMerge = require('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
/**
* A parser for M3U8 files. The current interpretation of the input is
* exposed as a property `manifest` on parser objects. It's just two lines to
* create and parse a manifest once you have the contents available as a string:
*
* ```js
* var parser = new m3u8.Parser();
* parser.push(xhr.responseText);
* ```
*
* New input can later be applied to update the manifest object by calling
* `push` again.
*
* The parser attempts to create a usable manifest object even if the
* underlying input is somewhat nonsensical. It emits `info` and `warning`
* events during the parse if it encounters input that seems invalid or
* requires some property of the manifest object to be defaulted.
*
* @class Parser
* @extends Stream
*/
var Parser = (function (_Stream) {
_inherits(Parser, _Stream);
function Parser() {
_classCallCheck(this, Parser);
_get(Object.getPrototypeOf(Parser.prototype), 'constructor', this).call(this);
this.lineStream = new _lineStream2['default']();
this.parseStream = new _parseStream2['default']();
this.lineStream.pipe(this.parseStream);
/* eslint-disable consistent-this */
var self = this;
/* eslint-enable consistent-this */
var uris = [];
var currentUri = {};
// if specified, the active EXT-X-MAP definition
var currentMap = undefined;
// if specified, the active decryption key
var _key = undefined;
var noop = function noop() {};
var defaultMediaGroups = {
'AUDIO': {},
'VIDEO': {},
'CLOSED-CAPTIONS': {},
'SUBTITLES': {}
};
// group segments into numbered timelines delineated by discontinuities
var currentTimeline = 0;
// the manifest is empty until the parse stream begins delivering data
this.manifest = {
allowCache: true,
discontinuityStarts: []
};
// update the manifest with the m3u8 entry from the parse stream
this.parseStream.on('data', function (entry) {
var mediaGroup = undefined;
var rendition = undefined;
({
tag: function tag() {
// switch based on the tag type
(({
'allow-cache': function allowCache() {
this.manifest.allowCache = entry.allowed;
if (!('allowed' in entry)) {
this.trigger('info', {
message: 'defaulting allowCache to YES'
});
this.manifest.allowCache = true;
}
},
byterange: function byterange() {
var byterange = {};
if ('length' in entry) {
currentUri.byterange = byterange;
byterange.length = entry.length;
if (!('offset' in entry)) {
this.trigger('info', {
message: 'defaulting offset to zero'
});
entry.offset = 0;
}
}
if ('offset' in entry) {
currentUri.byterange = byterange;
byterange.offset = entry.offset;
}
},
endlist: function endlist() {
this.manifest.endList = true;
},
inf: function inf() {
if (!('mediaSequence' in this.manifest)) {
this.manifest.mediaSequence = 0;
this.trigger('info', {
message: 'defaulting media sequence to zero'
});
}
if (!('discontinuitySequence' in this.manifest)) {
this.manifest.discontinuitySequence = 0;
this.trigger('info', {
message: 'defaulting discontinuity sequence to zero'
});
}
if (entry.duration > 0) {
currentUri.duration = entry.duration;
}
if (entry.duration === 0) {
currentUri.duration = 0.01;
this.trigger('info', {
message: 'updating zero segment duration to a small value'
});
}
this.manifest.segments = uris;
},
key: function key() {
if (!entry.attributes) {
this.trigger('warn', {
message: 'ignoring key declaration without attribute list'
});
return;
}
// clear the active encryption key
if (entry.attributes.METHOD === 'NONE') {
_key = null;
return;
}
if (!entry.attributes.URI) {
this.trigger('warn', {
message: 'ignoring key declaration without URI'
});
return;
}
if (!entry.attributes.METHOD) {
this.trigger('warn', {
message: 'defaulting key method to AES-128'
});
}
// setup an encryption key for upcoming segments
_key = {
method: entry.attributes.METHOD || 'AES-128',
uri: entry.attributes.URI
};
if (typeof entry.attributes.IV !== 'undefined') {
_key.iv = entry.attributes.IV;
}
},
'media-sequence': function mediaSequence() {
if (!isFinite(entry.number)) {
this.trigger('warn', {
message: 'ignoring invalid media sequence: ' + entry.number
});
return;
}
this.manifest.mediaSequence = entry.number;
},
'discontinuity-sequence': function discontinuitySequence() {
if (!isFinite(entry.number)) {
this.trigger('warn', {
message: 'ignoring invalid discontinuity sequence: ' + entry.number
});
return;
}
this.manifest.discontinuitySequence = entry.number;
currentTimeline = entry.number;
},
'playlist-type': function playlistType() {
if (!/VOD|EVENT/.test(entry.playlistType)) {
this.trigger('warn', {
message: 'ignoring unknown playlist type: ' + entry.playlist
});
return;
}
this.manifest.playlistType = entry.playlistType;
},
map: function map() {
currentMap = {};
if (entry.uri) {
currentMap.uri = entry.uri;
}
if (entry.byterange) {
currentMap.byterange = entry.byterange;
}
},
'stream-inf': function streamInf() {
this.manifest.playlists = uris;
this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
if (!entry.attributes) {
this.trigger('warn', {
message: 'ignoring empty stream-inf attributes'
});
return;
}
if (!currentUri.attributes) {
currentUri.attributes = {};
}
currentUri.attributes = (0, _lodashCompatObjectMerge2['default'])(currentUri.attributes, entry.attributes);
},
media: function media() {
this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
this.trigger('warn', {
message: 'ignoring incomplete or missing media group'
});
return;
}
// find the media group, creating defaults as necessary
var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']];
// collect the rendition metadata
rendition = {
'default': /yes/i.test(entry.attributes.DEFAULT)
};
if (rendition['default']) {
rendition.autoselect = true;
} else {
rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
}
if (entry.attributes.LANGUAGE) {
rendition.language = entry.attributes.LANGUAGE;
}
if (entry.attributes.URI) {
rendition.uri = entry.attributes.URI;
}
if (entry.attributes['INSTREAM-ID']) {
rendition.instreamId = entry.attributes['INSTREAM-ID'];
}
// insert the new rendition
mediaGroup[entry.attributes.NAME] = rendition;
},
discontinuity: function discontinuity() {
currentTimeline += 1;
currentUri.discontinuity = true;
this.manifest.discontinuityStarts.push(uris.length);
},
'program-date-time': function programDateTime() {
this.manifest.dateTimeString = entry.dateTimeString;
this.manifest.dateTimeObject = entry.dateTimeObject;
},
targetduration: function targetduration() {
if (!isFinite(entry.duration) || entry.duration < 0) {
this.trigger('warn', {
message: 'ignoring invalid target duration: ' + entry.duration
});
return;
}
this.manifest.targetDuration = entry.duration;
},
totalduration: function totalduration() {
if (!isFinite(entry.duration) || entry.duration < 0) {
this.trigger('warn', {
message: 'ignoring invalid total duration: ' + entry.duration
});
return;
}
this.manifest.totalDuration = entry.duration;
},
'cue-out': function cueOut() {
currentUri.cueOut = entry.data;
},
'cue-out-cont': function cueOutCont() {
currentUri.cueOutCont = entry.data;
},
'cue-in': function cueIn() {
currentUri.cueIn = entry.data;
}
})[entry.tagType] || noop).call(self);
},
uri: function uri() {
currentUri.uri = entry.uri;
uris.push(currentUri);
// if no explicit duration was declared, use the target duration
if (this.manifest.targetDuration && !('duration' in currentUri)) {
this.trigger('warn', {
message: 'defaulting segment duration to the target duration'
});
currentUri.duration = this.manifest.targetDuration;
}
// annotate with encryption information, if necessary
if (_key) {
currentUri.key = _key;
}
currentUri.timeline = currentTimeline;
// annotate with initialization segment information, if necessary
if (currentMap) {
currentUri.map = currentMap;
}
// prepare for the next URI
currentUri = {};
},
comment: function comment() {
// comments are not important for playback
}
})[entry.type].call(self);
});
}
/**
* Parse the input string and update the manifest object.
*
* @param {String} chunk a potentially incomplete portion of the manifest
*/
_createClass(Parser, [{
key: 'push',
value: function push(chunk) {
this.lineStream.push(chunk);
}
/**
* Flush any remaining input. This can be handy if the last line of an M3U8
* manifest did not contain a trailing newline but the file has been
* completely received.
*/
}, {
key: 'end',
value: function end() {
// flush any buffered input
this.lineStream.push('\n');
}
}]);
return Parser;
})(_stream2['default']);
exports['default'] = Parser;
module.exports = exports['default'];
},{"./line-stream":84,"./parse-stream":85,"./stream":87,"lodash-compat/object/merge":80}],87:[function(require,module,exports){
arguments[4][5][0].apply(exports,arguments)
},{"dup":5}],88:[function(require,module,exports){
(function() {
var URLToolkit = {
// build an absolute URL from a relative one using the provided baseURL
// if relativeURL is an absolute URL it will be returned as is.
buildAbsoluteURL: function(baseURL, relativeURL) {
// remove any remaining space and CRLF
relativeURL = relativeURL.trim();
if (/^[a-z]+:/i.test(relativeURL)) {
// complete url, not relative
return relativeURL;
}
var relativeURLQuery = null;
var relativeURLHash = null;
var relativeURLHashSplit = /^([^#]*)(.*)$/.exec(relativeURL);
if (relativeURLHashSplit) {
relativeURLHash = relativeURLHashSplit[2];
relativeURL = relativeURLHashSplit[1];
}
var relativeURLQuerySplit = /^([^\?]*)(.*)$/.exec(relativeURL);
if (relativeURLQuerySplit) {
relativeURLQuery = relativeURLQuerySplit[2];
relativeURL = relativeURLQuerySplit[1];
}
var baseURLHashSplit = /^([^#]*)(.*)$/.exec(baseURL);
if (baseURLHashSplit) {
baseURL = baseURLHashSplit[1];
}
var baseURLQuerySplit = /^([^\?]*)(.*)$/.exec(baseURL);
if (baseURLQuerySplit) {
baseURL = baseURLQuerySplit[1];
}
var baseURLDomainSplit = /^(([a-z]+:)?\/\/[a-z0-9\.\-_~]+(:[0-9]+)?)?(\/.*)$/i.exec(baseURL);
if (!baseURLDomainSplit) {
throw new Error('Error trying to parse base URL.');
}
// e.g. 'http:', 'https:', ''
var baseURLProtocol = baseURLDomainSplit[2] || '';
// e.g. 'http://example.com', '//example.com', ''
var baseURLProtocolDomain = baseURLDomainSplit[1] || '';
// e.g. '/a/b/c/playlist.m3u8'
var baseURLPath = baseURLDomainSplit[4];
var builtURL = null;
if (/^\/\//.test(relativeURL)) {
// relative url starts wth '//' so copy protocol (which may be '' if baseUrl didn't provide one)
builtURL = baseURLProtocol+'//'+URLToolkit.buildAbsolutePath('', relativeURL.substring(2));
}
else if (/^\//.test(relativeURL)) {
// relative url starts with '/' so start from root of domain
builtURL = baseURLProtocolDomain+'/'+URLToolkit.buildAbsolutePath('', relativeURL.substring(1));
}
else {
builtURL = URLToolkit.buildAbsolutePath(baseURLProtocolDomain+baseURLPath, relativeURL);
}
// put the query and hash parts back
if (relativeURLQuery) {
builtURL += relativeURLQuery;
}
if (relativeURLHash) {
builtURL += relativeURLHash;
}
return builtURL;
},
// build an absolute path using the provided basePath
// adapted from https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Using_relative_URLs_in_the_path_parameter
// this does not handle the case where relativePath is "/" or "//". These cases should be handled outside this.
buildAbsolutePath: function(basePath, relativePath) {
var sRelPath = relativePath;
var nUpLn, sDir = '', sPath = basePath.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, '$1'));
for (var nEnd, nStart = 0; nEnd = sPath.indexOf('/../', nStart), nEnd > -1; nStart = nEnd + nUpLn) {
nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp('(?:\\\/+[^\\\/]*){0,' + ((nUpLn - 1) / 3) + '}$'), '/');
}
return sDir + sPath.substr(nStart);
}
};
/* jshint ignore:start */
if(typeof exports === 'object' && typeof module === 'object')
module.exports = URLToolkit;
else if(typeof define === 'function' && define.amd)
define([], function() { return URLToolkit; });
else if(typeof exports === 'object')
exports["URLToolkit"] = URLToolkit;
else
root["URLToolkit"] = URLToolkit;
/* jshint ignore:end */
})();
},{}],89:[function(require,module,exports){
var bundleFn = arguments[3];
var sources = arguments[4];
var cache = arguments[5];
var stringify = JSON.stringify;
module.exports = function (fn, options) {
var wkey;
var cacheKeys = Object.keys(cache);
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
var exp = cache[key].exports;
// Using babel as a transpiler to use esmodule, the export will always
// be an object with the default export as a property of it. To ensure
// the existing api and babel esmodule exports are both supported we
// check for both
if (exp === fn || exp && exp.default === fn) {
wkey = key;
break;
}
}
if (!wkey) {
wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var wcache = {};
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
wcache[key] = key;
}
sources[wkey] = [
Function(['require','module','exports'], '(' + fn + ')(self)'),
wcache
];
}
var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var scache = {}; scache[wkey] = wkey;
sources[skey] = [
Function(['require'], (
// try to call default if defined to also support babel esmodule
// exports
'var f = require(' + stringify(wkey) + ');' +
'(f.default ? f.default : f)(self);'
)),
scache
];
var workerSources = {};
resolveSources(skey);
function resolveSources(key) {
workerSources[key] = true;
for (var depPath in sources[key][1]) {
var depKey = sources[key][1][depPath];
if (!workerSources[depKey]) {
resolveSources(depKey);
}
}
}
var src = '(' + bundleFn + ')({'
+ Object.keys(workerSources).map(function (key) {
return stringify(key) + ':['
+ sources[key][0]
+ ',' + stringify(sources[key][1]) + ']'
;
}).join(',')
+ '},{},[' + stringify(skey) + '])'
;
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
var blob = new Blob([src], { type: 'text/javascript' });
if (options && options.bare) { return blob; }
var workerUrl = URL.createObjectURL(blob);
var worker = new Worker(workerUrl);
worker.objectURL = workerUrl;
return worker;
};
},{}],90:[function(require,module,exports){
(function (global){
/**
* @file videojs-contrib-hls.js
*
* The main file for the HLS project.
* License: https://github.com/videojs/videojs-contrib-hls/blob/master/LICENSE
*/
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _globalDocument = require('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _playlistLoader = require('./playlist-loader');
var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
var _playlist = require('./playlist');
var _playlist2 = _interopRequireDefault(_playlist);
var _xhr = require('./xhr');
var _xhr2 = _interopRequireDefault(_xhr);
var _aesDecrypter = require('aes-decrypter');
var _binUtils = require('./bin-utils');
var _binUtils2 = _interopRequireDefault(_binUtils);
var _videojsContribMediaSources = require('videojs-contrib-media-sources');
var _m3u8Parser = require('m3u8-parser');
var _m3u8Parser2 = _interopRequireDefault(_m3u8Parser);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _masterPlaylistController = require('./master-playlist-controller');
var _config = require('./config');
var _config2 = _interopRequireDefault(_config);
var _renditionMixin = require('./rendition-mixin');
var _renditionMixin2 = _interopRequireDefault(_renditionMixin);
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _playbackWatcher = require('./playback-watcher');
var _playbackWatcher2 = _interopRequireDefault(_playbackWatcher);
var _reloadSourceOnError = require('./reload-source-on-error');
var _reloadSourceOnError2 = _interopRequireDefault(_reloadSourceOnError);
var Hls = {
PlaylistLoader: _playlistLoader2['default'],
Playlist: _playlist2['default'],
Decrypter: _aesDecrypter.Decrypter,
AsyncStream: _aesDecrypter.AsyncStream,
decrypt: _aesDecrypter.decrypt,
utils: _binUtils2['default'],
xhr: (0, _xhr2['default'])()
};
Object.defineProperty(Hls, 'GOAL_BUFFER_LENGTH', {
get: function get() {
_videoJs2['default'].log.warn('using Hls.GOAL_BUFFER_LENGTH is UNSAFE be sure ' + 'you know what you are doing');
return _config2['default'].GOAL_BUFFER_LENGTH;
},
set: function set(v) {
_videoJs2['default'].log.warn('using Hls.GOAL_BUFFER_LENGTH is UNSAFE be sure ' + 'you know what you are doing');
if (typeof v !== 'number' || v <= 0) {
_videoJs2['default'].log.warn('value passed to Hls.GOAL_BUFFER_LENGTH ' + 'must be a number and greater than 0');
return;
}
_config2['default'].GOAL_BUFFER_LENGTH = v;
}
});
// A fudge factor to apply to advertised playlist bitrates to account for
// temporary flucations in client bandwidth
var BANDWIDTH_VARIANCE = 1.2;
/**
* Returns the CSS value for the specified property on an element
* using `getComputedStyle`. Firefox has a long-standing issue where
* getComputedStyle() may return null when running in an iframe with
* `display: none`.
*
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
* @param {HTMLElement} el the htmlelement to work on
* @param {string} the proprety to get the style for
*/
var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
var result = undefined;
if (!el) {
return '';
}
result = _globalWindow2['default'].getComputedStyle(el);
if (!result) {
return '';
}
return result[property];
};
/**
* Chooses the appropriate media playlist based on the current
* bandwidth estimate and the player size.
*
* @return {Playlist} the highest bitrate playlist less than the currently detected
* bandwidth, accounting for some amount of bandwidth variance
*/
Hls.STANDARD_PLAYLIST_SELECTOR = function () {
var effectiveBitrate = undefined;
var sortedPlaylists = this.playlists.master.playlists.slice();
var bandwidthPlaylists = [];
var now = +new Date();
var i = undefined;
var variant = undefined;
var bandwidthBestVariant = undefined;
var resolutionPlusOne = undefined;
var resolutionPlusOneAttribute = undefined;
var resolutionBestVariant = undefined;
var width = undefined;
var height = undefined;
sortedPlaylists.sort(Hls.comparePlaylistBandwidth);
// filter out any playlists that have been excluded due to
// incompatible configurations or playback errors
sortedPlaylists = sortedPlaylists.filter(function (localVariant) {
if (typeof localVariant.excludeUntil !== 'undefined') {
return now >= localVariant.excludeUntil;
}
return true;
});
// filter out any variant that has greater effective bitrate
// than the current estimated bandwidth
i = sortedPlaylists.length;
while (i--) {
variant = sortedPlaylists[i];
// ignore playlists without bandwidth information
if (!variant.attributes || !variant.attributes.BANDWIDTH) {
continue;
}
effectiveBitrate = variant.attributes.BANDWIDTH * BANDWIDTH_VARIANCE;
if (effectiveBitrate < this.systemBandwidth) {
bandwidthPlaylists.push(variant);
// since the playlists are sorted in ascending order by
// bandwidth, the first viable variant is the best
if (!bandwidthBestVariant) {
bandwidthBestVariant = variant;
}
}
}
i = bandwidthPlaylists.length;
// sort variants by resolution
bandwidthPlaylists.sort(Hls.comparePlaylistResolution);
// forget our old variant from above,
// or we might choose that in high-bandwidth scenarios
// (this could be the lowest bitrate rendition as we go through all of them above)
variant = null;
width = parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10);
height = parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10);
// iterate through the bandwidth-filtered playlists and find
// best rendition by player dimension
while (i--) {
variant = bandwidthPlaylists[i];
// ignore playlists without resolution information
if (!variant.attributes || !variant.attributes.RESOLUTION || !variant.attributes.RESOLUTION.width || !variant.attributes.RESOLUTION.height) {
continue;
}
// since the playlists are sorted, the first variant that has
// dimensions less than or equal to the player size is the best
var variantResolution = variant.attributes.RESOLUTION;
if (variantResolution.width === width && variantResolution.height === height) {
// if we have the exact resolution as the player use it
resolutionPlusOne = null;
resolutionBestVariant = variant;
break;
} else if (variantResolution.width < width && variantResolution.height < height) {
// if both dimensions are less than the player use the
// previous (next-largest) variant
break;
} else if (!resolutionPlusOne || variantResolution.width < resolutionPlusOneAttribute.width && variantResolution.height < resolutionPlusOneAttribute.height) {
// If we still haven't found a good match keep a
// reference to the previous variant for the next loop
// iteration
// By only saving variants if they are smaller than the
// previously saved variant, we ensure that we also pick
// the highest bandwidth variant that is just-larger-than
// the video player
resolutionPlusOne = variant;
resolutionPlusOneAttribute = resolutionPlusOne.attributes.RESOLUTION;
}
}
// fallback chain of variants
return resolutionPlusOne || resolutionBestVariant || bandwidthBestVariant || sortedPlaylists[0];
};
// HLS is a source handler, not a tech. Make sure attempts to use it
// as one do not cause exceptions.
Hls.canPlaySource = function () {
return _videoJs2['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
};
/**
* Whether the browser has built-in HLS support.
*/
Hls.supportsNativeHls = (function () {
var video = _globalDocument2['default'].createElement('video');
// native HLS is definitely not supported if HTML5 video isn't
if (!_videoJs2['default'].getComponent('Html5').isSupported()) {
return false;
}
// HLS manifests can go by many mime-types
var canPlay = [
// Apple santioned
'application/vnd.apple.mpegurl',
// Apple sanctioned for backwards compatibility
'audio/mpegurl',
// Very common
'audio/x-mpegurl',
// Very common
'application/x-mpegurl',
// Included for completeness
'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
return canPlay.some(function (canItPlay) {
return (/maybe|probably/i.test(video.canPlayType(canItPlay))
);
});
})();
/**
* HLS is a source handler, not a tech. Make sure attempts to use it
* as one do not cause exceptions.
*/
Hls.isSupported = function () {
return _videoJs2['default'].log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
};
var USER_AGENT = _globalWindow2['default'].navigator && _globalWindow2['default'].navigator.userAgent || '';
/**
* Determines whether the browser supports a change in the audio configuration
* during playback. Currently only Firefox 48 and below do not support this.
* window.isSecureContext is a propterty that was added to window in firefox 49,
* so we can use it to detect Firefox 49+.
*
* @return {Boolean} Whether the browser supports audio config change during playback
*/
Hls.supportsAudioInfoChange_ = function () {
if (_videoJs2['default'].browser.IS_FIREFOX) {
var firefoxVersionMap = /Firefox\/([\d.]+)/i.exec(USER_AGENT);
var version = parseInt(firefoxVersionMap[1], 10);
return version >= 49;
}
return true;
};
var Component = _videoJs2['default'].getComponent('Component');
/**
* The Hls Handler object, where we orchestrate all of the parts
* of HLS to interact with video.js
*
* @class HlsHandler
* @extends videojs.Component
* @param {Object} source the soruce object
* @param {Tech} tech the parent tech object
* @param {Object} options optional and required options
*/
var HlsHandler = (function (_Component) {
_inherits(HlsHandler, _Component);
function HlsHandler(source, tech, options) {
var _this = this;
_classCallCheck(this, HlsHandler);
_get(Object.getPrototypeOf(HlsHandler.prototype), 'constructor', this).call(this, tech);
// tech.player() is deprecated but setup a reference to HLS for
// backwards-compatibility
if (tech.options_ && tech.options_.playerId) {
var _player = (0, _videoJs2['default'])(tech.options_.playerId);
if (!_player.hasOwnProperty('hls')) {
Object.defineProperty(_player, 'hls', {
get: function get() {
_videoJs2['default'].log.warn('player.hls is deprecated. Use player.tech_.hls instead.');
return _this;
}
});
}
}
this.tech_ = tech;
this.source_ = source;
this.stats = {};
// handle global & Source Handler level options
this.options_ = _videoJs2['default'].mergeOptions(_videoJs2['default'].options.hls || {}, options.hls);
this.setOptions_();
// listen for fullscreenchange events for this player so that we
// can adjust our quality selection quickly
this.on(_globalDocument2['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
var fullscreenElement = _globalDocument2['default'].fullscreenElement || _globalDocument2['default'].webkitFullscreenElement || _globalDocument2['default'].mozFullScreenElement || _globalDocument2['default'].msFullscreenElement;
if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
_this.masterPlaylistController_.fastQualityChange_();
}
});
this.on(this.tech_, 'seeking', function () {
this.setCurrentTime(this.tech_.currentTime());
});
this.on(this.tech_, 'error', function () {
if (this.masterPlaylistController_) {
this.masterPlaylistController_.pauseLoading();
}
});
this.audioTrackChange_ = function () {
_this.masterPlaylistController_.setupAudio();
};
this.on(this.tech_, 'play', this.play);
}
/**
* The Source Handler object, which informs video.js what additional
* MIME types are supported and sets up playback. It is registered
* automatically to the appropriate tech based on the capabilities of
* the browser it is running in. It is not necessary to use or modify
* this object in normal usage.
*/
_createClass(HlsHandler, [{
key: 'setOptions_',
value: function setOptions_() {
var _this2 = this;
// defaults
this.options_.withCredentials = this.options_.withCredentials || false;
// start playlist selection at a reasonable bandwidth for
// broadband internet
// 0.5 MB/s
if (typeof this.options_.bandwidth !== 'number') {
this.options_.bandwidth = 4194304;
}
// grab options passed to player.src
['withCredentials', 'bandwidth'].forEach(function (option) {
if (typeof _this2.source_[option] !== 'undefined') {
_this2.options_[option] = _this2.source_[option];
}
});
this.bandwidth = this.options_.bandwidth;
}
/**
* called when player.src gets called, handle a new source
*
* @param {Object} src the source object to handle
*/
}, {
key: 'src',
value: function src(_src) {
var _this3 = this;
// do nothing if the src is falsey
if (!_src) {
return;
}
this.setOptions_();
// add master playlist controller options
this.options_.url = this.source_.src;
this.options_.tech = this.tech_;
this.options_.externHls = Hls;
this.masterPlaylistController_ = new _masterPlaylistController.MasterPlaylistController(this.options_);
this.playbackWatcher_ = new _playbackWatcher2['default'](_videoJs2['default'].mergeOptions(this.options_, {
seekable: function seekable() {
return _this3.seekable();
}
}));
// `this` in selectPlaylist should be the HlsHandler for backwards
// compatibility with < v2
this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : Hls.STANDARD_PLAYLIST_SELECTOR.bind(this);
// re-expose some internal objects for backwards compatibility with < v2
this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
this.mediaSource = this.masterPlaylistController_.mediaSource;
// Proxy assignment of some properties to the master playlist
// controller. Using a custom property for backwards compatibility
// with < v2
Object.defineProperties(this, {
selectPlaylist: {
get: function get() {
return this.masterPlaylistController_.selectPlaylist;
},
set: function set(selectPlaylist) {
this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
}
},
throughput: {
get: function get() {
return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
},
set: function set(throughput) {
this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput;
// By setting `count` to 1 the throughput value becomes the starting value
// for the cumulative average
this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
}
},
bandwidth: {
get: function get() {
return this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
},
set: function set(bandwidth) {
this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth;
// setting the bandwidth manually resets the throughput counter
// `count` is set to zero that current value of `rate` isn't included
// in the cumulative average
this.masterPlaylistController_.mainSegmentLoader_.throughput = { rate: 0, count: 0 };
}
},
/**
* `systemBandwidth` is a combination of two serial processes bit-rates. The first
* is the network bitrate provided by `bandwidth` and the second is the bitrate of
* the entire process after that - decryption, transmuxing, and appending - provided
* by `throughput`.
*
* Since the two process are serial, the overall system bandwidth is given by:
* sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
*/
systemBandwidth: {
get: function get() {
var invBandwidth = 1 / (this.bandwidth || 1);
var invThroughput = undefined;
if (this.throughput > 0) {
invThroughput = 1 / this.throughput;
} else {
invThroughput = 0;
}
var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
return systemBitrate;
},
set: function set() {
_videoJs2['default'].log.error('The "systemBandwidth" property is read-only');
}
}
});
Object.defineProperties(this.stats, {
bandwidth: {
get: function get() {
return _this3.bandwidth || 0;
},
enumerable: true
},
mediaRequests: {
get: function get() {
return _this3.masterPlaylistController_.mediaRequests_() || 0;
},
enumerable: true
},
mediaTransferDuration: {
get: function get() {
return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
},
enumerable: true
},
mediaBytesTransferred: {
get: function get() {
return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
},
enumerable: true
}
});
this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
this.masterPlaylistController_.on('sourceopen', function () {
_this3.tech_.audioTracks().addEventListener('change', _this3.audioTrackChange_);
});
this.masterPlaylistController_.on('selectedinitialmedia', function () {
// Add the manual rendition mix-in to HlsHandler
(0, _renditionMixin2['default'])(_this3);
});
this.masterPlaylistController_.on('audioupdate', function () {
// clear current audioTracks
_this3.tech_.clearTracks('audio');
_this3.masterPlaylistController_.activeAudioGroup().forEach(function (audioTrack) {
_this3.tech_.audioTracks().addTrack(audioTrack);
});
});
// the bandwidth of the primary segment loader is our best
// estimate of overall bandwidth
this.on(this.masterPlaylistController_, 'progress', function () {
this.tech_.trigger('progress');
});
// do nothing if the tech has been disposed already
// this can occur if someone sets the src in player.ready(), for instance
if (!this.tech_.el()) {
return;
}
this.tech_.src(_videoJs2['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource));
}
/**
* a helper for grabbing the active audio group from MasterPlaylistController
*
* @private
*/
}, {
key: 'activeAudioGroup_',
value: function activeAudioGroup_() {
return this.masterPlaylistController_.activeAudioGroup();
}
/**
* Begin playing the video.
*/
}, {
key: 'play',
value: function play() {
this.masterPlaylistController_.play();
}
/**
* a wrapper around the function in MasterPlaylistController
*/
}, {
key: 'setCurrentTime',
value: function setCurrentTime(currentTime) {
this.masterPlaylistController_.setCurrentTime(currentTime);
}
/**
* a wrapper around the function in MasterPlaylistController
*/
}, {
key: 'duration',
value: function duration() {
return this.masterPlaylistController_.duration();
}
/**
* a wrapper around the function in MasterPlaylistController
*/
}, {
key: 'seekable',
value: function seekable() {
return this.masterPlaylistController_.seekable();
}
/**
* Abort all outstanding work and cleanup.
*/
}, {
key: 'dispose',
value: function dispose() {
if (this.playbackWatcher_) {
this.playbackWatcher_.dispose();
}
if (this.masterPlaylistController_) {
this.masterPlaylistController_.dispose();
}
this.tech_.audioTracks().removeEventListener('change', this.audioTrackChange_);
_get(Object.getPrototypeOf(HlsHandler.prototype), 'dispose', this).call(this);
}
}]);
return HlsHandler;
})(Component);
var HlsSourceHandler = function HlsSourceHandler(mode) {
return {
canHandleSource: function canHandleSource(srcObj) {
// this forces video.js to skip this tech/mode if its not the one we have been
// overriden to use, by returing that we cannot handle the source.
if (_videoJs2['default'].options.hls && _videoJs2['default'].options.hls.mode && _videoJs2['default'].options.hls.mode !== mode) {
return false;
}
return HlsSourceHandler.canPlayType(srcObj.type);
},
handleSource: function handleSource(source, tech, options) {
if (mode === 'flash') {
// We need to trigger this asynchronously to give others the chance
// to bind to the event when a source is set at player creation
tech.setTimeout(function () {
tech.trigger('loadstart');
}, 1);
}
var settings = _videoJs2['default'].mergeOptions(options, { hls: { mode: mode } });
tech.hls = new HlsHandler(source, tech, settings);
tech.hls.xhr = (0, _xhr2['default'])();
// Use a global `before` function if specified on videojs.Hls.xhr
// but still allow for a per-player override
if (_videoJs2['default'].Hls.xhr.beforeRequest) {
tech.hls.xhr.beforeRequest = _videoJs2['default'].Hls.xhr.beforeRequest;
}
tech.hls.src(source.src);
return tech.hls;
},
canPlayType: function canPlayType(type) {
if (HlsSourceHandler.canPlayType(type)) {
return 'maybe';
}
return '';
}
};
};
/**
* A comparator function to sort two playlist object by bandwidth.
*
* @param {Object} left a media playlist object
* @param {Object} right a media playlist object
* @return {Number} Greater than zero if the bandwidth attribute of
* left is greater than the corresponding attribute of right. Less
* than zero if the bandwidth of right is greater than left and
* exactly zero if the two are equal.
*/
Hls.comparePlaylistBandwidth = function (left, right) {
var leftBandwidth = undefined;
var rightBandwidth = undefined;
if (left.attributes && left.attributes.BANDWIDTH) {
leftBandwidth = left.attributes.BANDWIDTH;
}
leftBandwidth = leftBandwidth || _globalWindow2['default'].Number.MAX_VALUE;
if (right.attributes && right.attributes.BANDWIDTH) {
rightBandwidth = right.attributes.BANDWIDTH;
}
rightBandwidth = rightBandwidth || _globalWindow2['default'].Number.MAX_VALUE;
return leftBandwidth - rightBandwidth;
};
/**
* A comparator function to sort two playlist object by resolution (width).
* @param {Object} left a media playlist object
* @param {Object} right a media playlist object
* @return {Number} Greater than zero if the resolution.width attribute of
* left is greater than the corresponding attribute of right. Less
* than zero if the resolution.width of right is greater than left and
* exactly zero if the two are equal.
*/
Hls.comparePlaylistResolution = function (left, right) {
var leftWidth = undefined;
var rightWidth = undefined;
if (left.attributes && left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
leftWidth = left.attributes.RESOLUTION.width;
}
leftWidth = leftWidth || _globalWindow2['default'].Number.MAX_VALUE;
if (right.attributes && right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
rightWidth = right.attributes.RESOLUTION.width;
}
rightWidth = rightWidth || _globalWindow2['default'].Number.MAX_VALUE;
// NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
// have the same media dimensions/ resolution
if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
}
return leftWidth - rightWidth;
};
HlsSourceHandler.canPlayType = function (type) {
var mpegurlRE = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
// favor native HLS support if it's available
if (Hls.supportsNativeHls) {
return false;
}
return mpegurlRE.test(type);
};
if (typeof _videoJs2['default'].MediaSource === 'undefined' || typeof _videoJs2['default'].URL === 'undefined') {
_videoJs2['default'].MediaSource = _videojsContribMediaSources.MediaSource;
_videoJs2['default'].URL = _videojsContribMediaSources.URL;
}
// register source handlers with the appropriate techs
if (_videojsContribMediaSources.MediaSource.supportsNativeMediaSources()) {
_videoJs2['default'].getComponent('Html5').registerSourceHandler(HlsSourceHandler('html5'));
}
if (_globalWindow2['default'].Uint8Array) {
_videoJs2['default'].getComponent('Flash').registerSourceHandler(HlsSourceHandler('flash'));
}
_videoJs2['default'].HlsHandler = HlsHandler;
_videoJs2['default'].HlsSourceHandler = HlsSourceHandler;
_videoJs2['default'].Hls = Hls;
_videoJs2['default'].m3u8 = _m3u8Parser2['default'];
_videoJs2['default'].registerComponent('Hls', Hls);
_videoJs2['default'].options.hls = _videoJs2['default'].options.hls || {};
_videoJs2['default'].plugin('reloadSourceOnError', _reloadSourceOnError2['default']);
module.exports = {
Hls: Hls,
HlsHandler: HlsHandler,
HlsSourceHandler: HlsSourceHandler
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./bin-utils":29,"./config":30,"./master-playlist-controller":32,"./playback-watcher":33,"./playlist":35,"./playlist-loader":34,"./reload-source-on-error":37,"./rendition-mixin":38,"./xhr":43,"aes-decrypter":4,"global/document":45,"global/window":46,"m3u8-parser":83,"videojs-contrib-media-sources":101}],91:[function(require,module,exports){
(function (global){
/**
* @file add-text-track-data.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
/**
* Define properties on a cue for backwards compatability,
* but warn the user that the way that they are using it
* is depricated and will be removed at a later date.
*
* @param {Cue} cue the cue to add the properties on
* @private
*/
var deprecateOldCue = function deprecateOldCue(cue) {
Object.defineProperties(cue.frame, {
id: {
get: function get() {
_videoJs2['default'].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
return cue.value.key;
}
},
value: {
get: function get() {
_videoJs2['default'].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
return cue.value.data;
}
},
privateData: {
get: function get() {
_videoJs2['default'].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
return cue.value.data;
}
}
});
};
var durationOfVideo = function durationOfVideo(duration) {
var dur = undefined;
if (isNaN(duration) || Math.abs(duration) === Infinity) {
dur = Number.MAX_VALUE;
} else {
dur = duration;
}
return dur;
};
/**
* Add text track data to a source handler given the captions and
* metadata from the buffer.
*
* @param {Object} sourceHandler the flash or virtual source buffer
* @param {Array} captionArray an array of caption data
* @param {Array} cue an array of meta data
* @private
*/
var addTextTrackData = function addTextTrackData(sourceHandler, captionArray, metadataArray) {
var Cue = _globalWindow2['default'].WebKitDataCue || _globalWindow2['default'].VTTCue;
if (captionArray) {
captionArray.forEach(function (caption) {
this.inbandTextTrack_.addCue(new Cue(caption.startTime + this.timestampOffset, caption.endTime + this.timestampOffset, caption.text));
}, sourceHandler);
}
if (metadataArray) {
var videoDuration = durationOfVideo(sourceHandler.mediaSource_.duration);
metadataArray.forEach(function (metadata) {
var time = metadata.cueTime + this.timestampOffset;
metadata.frames.forEach(function (frame) {
var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
cue.frame = frame;
cue.value = frame;
deprecateOldCue(cue);
this.metadataTrack_.addCue(cue);
}, this);
}, sourceHandler);
// Updating the metadeta cues so that
// the endTime of each cue is the startTime of the next cue
// the endTime of last cue is the duration of the video
if (sourceHandler.metadataTrack_ && sourceHandler.metadataTrack_.cues && sourceHandler.metadataTrack_.cues.length) {
var cues = sourceHandler.metadataTrack_.cues;
var cuesArray = [];
for (var j = 0; j < cues.length; j++) {
cuesArray.push(cues[j]);
}
cuesArray.sort(function (first, second) {
return first.startTime - second.startTime;
});
for (var i = 0; i < cuesArray.length - 1; i++) {
if (cuesArray[i].endTime !== cuesArray[i + 1].startTime) {
cuesArray[i].endTime = cuesArray[i + 1].startTime;
}
}
cuesArray[cuesArray.length - 1].endTime = videoDuration;
}
}
};
exports['default'] = {
addTextTrackData: addTextTrackData,
durationOfVideo: durationOfVideo
};
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"global/window":104}],92:[function(require,module,exports){
/**
* @file codec-utils.js
*/
/**
* Check if a codec string refers to an audio codec.
*
* @param {String} codec codec string to check
* @return {Boolean} if this is an audio codec
* @private
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var isAudioCodec = function isAudioCodec(codec) {
return (/mp4a\.\d+.\d+/i.test(codec)
);
};
/**
* Check if a codec string refers to a video codec.
*
* @param {String} codec codec string to check
* @return {Boolean} if this is a video codec
* @private
*/
var isVideoCodec = function isVideoCodec(codec) {
return (/avc1\.[\da-f]+/i.test(codec)
);
};
/**
* Parse a content type header into a type and parameters
* object
*
* @param {String} type the content type header
* @return {Object} the parsed content-type
* @private
*/
var parseContentType = function parseContentType(type) {
var object = { type: '', parameters: {} };
var parameters = type.trim().split(';');
// first parameter should always be content-type
object.type = parameters.shift().trim();
parameters.forEach(function (parameter) {
var pair = parameter.trim().split('=');
if (pair.length > 1) {
var _name = pair[0].replace(/"/g, '').trim();
var value = pair[1].replace(/"/g, '').trim();
object.parameters[_name] = value;
}
});
return object;
};
exports['default'] = {
isAudioCodec: isAudioCodec,
parseContentType: parseContentType,
isVideoCodec: isVideoCodec
};
module.exports = exports['default'];
},{}],93:[function(require,module,exports){
/**
* @file create-text-tracks-if-necessary.js
*/
/**
* Create text tracks on video.js if they exist on a segment.
*
* @param {Object} sourceBuffer the VSB or FSB
* @param {Object} mediaSource the HTML or Flash media source
* @param {Object} segment the segment that may contain the text track
* @private
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var createTextTracksIfNecessary = function createTextTracksIfNecessary(sourceBuffer, mediaSource, segment) {
// create an in-band caption track if one is present in the segment
if (segment.captions && segment.captions.length && !sourceBuffer.inbandTextTrack_) {
sourceBuffer.inbandTextTrack_ = mediaSource.player_.addTextTrack('captions', 'cc1');
}
if (segment.metadata && segment.metadata.length && !sourceBuffer.metadataTrack_) {
sourceBuffer.metadataTrack_ = mediaSource.player_.addTextTrack('metadata', 'Timed Metadata');
sourceBuffer.metadataTrack_.inBandMetadataTrackDispatchType = segment.metadata.dispatchType;
}
};
exports['default'] = createTextTracksIfNecessary;
module.exports = exports['default'];
},{}],94:[function(require,module,exports){
/**
* @file flash-constants.js
*/
/**
* The maximum size in bytes for append operations to the video.js
* SWF. Calling through to Flash blocks and can be expensive so
* we chunk data and pass through 4KB at a time, yielding to the
* browser between chunks. This gives a theoretical maximum rate of
* 1MB/s into Flash. Any higher and we begin to drop frames and UI
* responsiveness suffers.
*
* @private
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var flashConstants = {
// times in milliseconds
TIME_BETWEEN_CHUNKS: 0,
BYTES_PER_CHUNK: 0x10000
};
exports["default"] = flashConstants;
module.exports = exports["default"];
},{}],95:[function(require,module,exports){
(function (global){
/**
* @file flash-media-source.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _globalDocument = require('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _flashSourceBuffer = require('./flash-source-buffer');
var _flashSourceBuffer2 = _interopRequireDefault(_flashSourceBuffer);
var _flashConstants = require('./flash-constants');
var _flashConstants2 = _interopRequireDefault(_flashConstants);
var _codecUtils = require('./codec-utils');
/**
* A flash implmentation of HTML MediaSources and a polyfill
* for browsers that don't support native or HTML MediaSources..
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
* @class FlashMediaSource
* @extends videojs.EventTarget
*/
var FlashMediaSource = (function (_videojs$EventTarget) {
_inherits(FlashMediaSource, _videojs$EventTarget);
function FlashMediaSource() {
var _this = this;
_classCallCheck(this, FlashMediaSource);
_get(Object.getPrototypeOf(FlashMediaSource.prototype), 'constructor', this).call(this);
this.sourceBuffers = [];
this.readyState = 'closed';
this.on(['sourceopen', 'webkitsourceopen'], function (event) {
// find the swf where we will push media data
_this.swfObj = _globalDocument2['default'].getElementById(event.swfId);
_this.player_ = (0, _videoJs2['default'])(_this.swfObj.parentNode);
_this.tech_ = _this.swfObj.tech;
_this.readyState = 'open';
_this.tech_.on('seeking', function () {
var i = _this.sourceBuffers.length;
while (i--) {
_this.sourceBuffers[i].abort();
}
});
// trigger load events
if (_this.swfObj) {
_this.swfObj.vjs_load();
}
});
}
/**
* Set or return the presentation duration.
*
* @param {Double} value the duration of the media in seconds
* @param {Double} the current presentation duration
* @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
*/
/**
* We have this function so that the html and flash interfaces
* are the same.
*
* @private
*/
_createClass(FlashMediaSource, [{
key: 'addSeekableRange_',
value: function addSeekableRange_() {}
// intentional no-op
/**
* Create a new flash source buffer and add it to our flash media source.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
* @param {String} type the content-type of the source
* @return {Object} the flash source buffer
*/
}, {
key: 'addSourceBuffer',
value: function addSourceBuffer(type) {
var parsedType = (0, _codecUtils.parseContentType)(type);
var sourceBuffer = undefined;
// if this is an FLV type, we'll push data to flash
if (parsedType.type === 'video/mp2t') {
// Flash source buffers
sourceBuffer = new _flashSourceBuffer2['default'](this);
} else {
throw new Error('NotSupportedError (Video.js)');
}
this.sourceBuffers.push(sourceBuffer);
return sourceBuffer;
}
/**
* Signals the end of the stream.
*
* @link https://w3c.github.io/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error
* @param {String=} error Signals that a playback error
* has occurred. If specified, it must be either "network" or
* "decode".
*/
}, {
key: 'endOfStream',
value: function endOfStream(error) {
if (error === 'network') {
// MEDIA_ERR_NETWORK
this.tech_.error(2);
} else if (error === 'decode') {
// MEDIA_ERR_DECODE
this.tech_.error(3);
}
if (this.readyState !== 'ended') {
this.readyState = 'ended';
this.swfObj.vjs_endOfStream();
}
}
}]);
return FlashMediaSource;
})(_videoJs2['default'].EventTarget);
exports['default'] = FlashMediaSource;
try {
Object.defineProperty(FlashMediaSource.prototype, 'duration', {
/**
* Return the presentation duration.
*
* @return {Double} the duration of the media in seconds
* @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
*/
get: function get() {
if (!this.swfObj) {
return NaN;
}
// get the current duration from the SWF
return this.swfObj.vjs_getProperty('duration');
},
/**
* Set the presentation duration.
*
* @param {Double} value the duration of the media in seconds
* @return {Double} the duration of the media in seconds
* @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration
*/
set: function set(value) {
var i = undefined;
var oldDuration = this.swfObj.vjs_getProperty('duration');
this.swfObj.vjs_setProperty('duration', value);
if (value < oldDuration) {
// In MSE, this triggers the range removal algorithm which causes
// an update to occur
for (i = 0; i < this.sourceBuffers.length; i++) {
this.sourceBuffers[i].remove(value, oldDuration);
}
}
return value;
}
});
} catch (e) {
// IE8 throws if defineProperty is called on a non-DOM node. We
// don't support IE8 but we shouldn't throw an error if loaded
// there.
FlashMediaSource.prototype.duration = NaN;
}
for (var property in _flashConstants2['default']) {
FlashMediaSource[property] = _flashConstants2['default'][property];
}
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./codec-utils":92,"./flash-constants":94,"./flash-source-buffer":96,"global/document":103}],96:[function(require,module,exports){
(function (global){
/**
* @file flash-source-buffer.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _muxJsLibFlv = require('mux.js/lib/flv');
var _muxJsLibFlv2 = _interopRequireDefault(_muxJsLibFlv);
var _removeCuesFromTrack = require('./remove-cues-from-track');
var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack);
var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary');
var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary);
var _addTextTrackData = require('./add-text-track-data');
var _flashTransmuxerWorker = require('./flash-transmuxer-worker');
var _flashTransmuxerWorker2 = _interopRequireDefault(_flashTransmuxerWorker);
var _webworkify = require('webworkify');
var _webworkify2 = _interopRequireDefault(_webworkify);
var _flashConstants = require('./flash-constants');
var _flashConstants2 = _interopRequireDefault(_flashConstants);
/**
* A wrapper around the setTimeout function that uses
* the flash constant time between ticks value.
*
* @param {Function} func the function callback to run
* @private
*/
var scheduleTick = function scheduleTick(func) {
// Chrome doesn't invoke requestAnimationFrame callbacks
// in background tabs, so use setTimeout.
_globalWindow2['default'].setTimeout(func, _flashConstants2['default'].TIME_BETWEEN_CHUNKS);
};
/**
* Round a number to a specified number of places much like
* toFixed but return a number instead of a string representation.
*
* @param {Number} num A number
* @param {Number} places The number of decimal places which to
* round
* @private
*/
var toDecimalPlaces = function toDecimalPlaces(num, places) {
if (typeof places !== 'number' || places < 0) {
places = 0;
}
var scale = Math.pow(10, places);
return Math.round(num * scale) / scale;
};
/**
* A SourceBuffer implementation for Flash rather than HTML.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
* @param {Object} mediaSource the flash media source
* @class FlashSourceBuffer
* @extends videojs.EventTarget
*/
var FlashSourceBuffer = (function (_videojs$EventTarget) {
_inherits(FlashSourceBuffer, _videojs$EventTarget);
function FlashSourceBuffer(mediaSource) {
var _this = this;
_classCallCheck(this, FlashSourceBuffer);
_get(Object.getPrototypeOf(FlashSourceBuffer.prototype), 'constructor', this).call(this);
var encodedHeader = undefined;
// Start off using the globally defined value but refine
// as we append data into flash
this.chunkSize_ = _flashConstants2['default'].BYTES_PER_CHUNK;
// byte arrays queued to be appended
this.buffer_ = [];
// the total number of queued bytes
this.bufferSize_ = 0;
// to be able to determine the correct position to seek to, we
// need to retain information about the mapping between the
// media timeline and PTS values
this.basePtsOffset_ = NaN;
this.mediaSource_ = mediaSource;
// indicates whether the asynchronous continuation of an operation
// is still being processed
// see https://w3c.github.io/media-source/#widl-SourceBuffer-updating
this.updating = false;
this.timestampOffset_ = 0;
encodedHeader = _globalWindow2['default'].btoa(String.fromCharCode.apply(null, Array.prototype.slice.call(_muxJsLibFlv2['default'].getFlvHeader())));
_globalWindow2['default'].encodedHeaderSuperSecret = function () {
delete _globalWindow2['default'].encodedHeaderSuperSecret;
throw encodedHeader;
};
this.mediaSource_.swfObj.vjs_appendChunkReady('encodedHeaderSuperSecret');
// TS to FLV transmuxer
this.transmuxer_ = (0, _webworkify2['default'])(_flashTransmuxerWorker2['default']);
this.transmuxer_.postMessage({ action: 'init', options: {} });
this.transmuxer_.onmessage = function (event) {
if (event.data.action === 'metadata') {
_this.receiveBuffer_(event.data.segment);
}
if (event.data.action === 'data') {
_this.buffer_ = _this.buffer_.concat(event.data.b64);
scheduleTick(_this.processBuffer_.bind(_this));
}
};
this.one('updateend', function () {
_this.mediaSource_.tech_.trigger('loadedmetadata');
});
Object.defineProperty(this, 'timestampOffset', {
get: function get() {
return this.timestampOffset_;
},
set: function set(val) {
if (typeof val === 'number' && val >= 0) {
this.timestampOffset_ = val;
// We have to tell flash to expect a discontinuity
this.mediaSource_.swfObj.vjs_discontinuity();
// the media <-> PTS mapping must be re-established after
// the discontinuity
this.basePtsOffset_ = NaN;
this.transmuxer_.postMessage({ action: 'reset' });
}
}
});
Object.defineProperty(this, 'buffered', {
get: function get() {
if (!this.mediaSource_ || !this.mediaSource_.swfObj || !('vjs_getProperty' in this.mediaSource_.swfObj)) {
return _videoJs2['default'].createTimeRange();
}
var buffered = this.mediaSource_.swfObj.vjs_getProperty('buffered');
if (buffered && buffered.length) {
buffered[0][0] = toDecimalPlaces(buffered[0][0], 3);
buffered[0][1] = toDecimalPlaces(buffered[0][1], 3);
}
return _videoJs2['default'].createTimeRanges(buffered);
}
});
// On a seek we remove all text track data since flash has no concept
// of a buffered-range and everything else is reset on seek
this.mediaSource_.player_.on('seeked', function () {
(0, _removeCuesFromTrack2['default'])(0, Infinity, _this.metadataTrack_);
(0, _removeCuesFromTrack2['default'])(0, Infinity, _this.inbandTextTrack_);
});
}
/**
* Append bytes to the sourcebuffers buffer, in this case we
* have to append it to swf object.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
* @param {Array} bytes
*/
_createClass(FlashSourceBuffer, [{
key: 'appendBuffer',
value: function appendBuffer(bytes) {
var error = undefined;
if (this.updating) {
error = new Error('SourceBuffer.append() cannot be called ' + 'while an update is in progress');
error.name = 'InvalidStateError';
error.code = 11;
throw error;
}
this.updating = true;
this.mediaSource_.readyState = 'open';
this.trigger({ type: 'update' });
this.transmuxer_.postMessage({
action: 'push',
data: bytes.buffer,
byteOffset: bytes.byteOffset,
byteLength: bytes.byteLength
}, [bytes.buffer]);
this.transmuxer_.postMessage({ action: 'flush' });
}
/**
* Reset the parser and remove any data queued to be sent to the SWF.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
*/
}, {
key: 'abort',
value: function abort() {
this.buffer_ = [];
this.bufferSize_ = 0;
this.mediaSource_.swfObj.vjs_abort();
// report any outstanding updates have ended
if (this.updating) {
this.updating = false;
this.trigger({ type: 'updateend' });
}
}
/**
* Flash cannot remove ranges already buffered in the NetStream
* but seeking clears the buffer entirely. For most purposes,
* having this operation act as a no-op is acceptable.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
* @param {Double} start start of the section to remove
* @param {Double} end end of the section to remove
*/
}, {
key: 'remove',
value: function remove(start, end) {
(0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_);
(0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_);
this.trigger({ type: 'update' });
this.trigger({ type: 'updateend' });
}
/**
* Receive a buffer from the flv.
*
* @param {Object} segment
* @private
*/
}, {
key: 'receiveBuffer_',
value: function receiveBuffer_(segment) {
// create an in-band caption track if one is present in the segment
(0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource_, segment);
(0, _addTextTrackData.addTextTrackData)(this, segment.captions, segment.metadata);
var targetPts = this.calculateTargetPts_(segment.basePts, segment.length);
this.transmuxer_.postMessage({ action: 'convertTagsToData', targetPts: targetPts });
}
/**
* Append a portion of the current buffer to the SWF.
*
* @private
*/
}, {
key: 'processBuffer_',
value: function processBuffer_() {
if (!this.buffer_.length) {
if (this.updating !== false) {
this.updating = false;
this.trigger({ type: 'updateend' });
}
// do nothing if the buffer is empty
return;
}
var b64str = this.buffer_.shift();
_globalWindow2['default'].throwDataSuperSecret = (function () {
if (this.buffer_.length !== 0) {
scheduleTick(this.processBuffer_.bind(this));
} else {
delete _globalWindow2['default'].throwDataSuperSecret;
this.updating = false;
this.trigger({ type: 'updateend' });
}
throw b64str;
}).bind(this);
this.mediaSource_.swfObj.vjs_appendChunkReady('throwDataSuperSecret');
}
}, {
key: 'calculateTargetPts_',
value: function calculateTargetPts_(basePts, length) {
if (isNaN(this.basePtsOffset_) && length) {
this.basePtsOffset_ = basePts;
}
var tech = this.mediaSource_.tech_;
var targetPts = 0;
// Trim to currentTime if it's ahead of buffered or buffered doesn't exist
if (tech.seeking()) {
targetPts = Math.max(targetPts, tech.currentTime() - this.timestampOffset);
}
// PTS values are represented in milliseconds
targetPts *= 1e3;
targetPts += this.basePtsOffset_;
return targetPts;
}
}]);
return FlashSourceBuffer;
})(_videoJs2['default'].EventTarget);
exports['default'] = FlashSourceBuffer;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./add-text-track-data":91,"./create-text-tracks-if-necessary":93,"./flash-constants":94,"./flash-transmuxer-worker":97,"./remove-cues-from-track":99,"global/window":104,"mux.js/lib/flv":14,"webworkify":105}],97:[function(require,module,exports){
/**
* @file flash-worker.js
*/
/**
* videojs-contrib-media-sources
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* Handles communication between the browser-world and the mux.js
* transmuxer running inside of a WebWorker by exposing a simple
* message-based interface to a Transmuxer object.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _muxJsLibFlv = require('mux.js/lib/flv');
var _muxJsLibFlv2 = _interopRequireDefault(_muxJsLibFlv);
var _flashConstants = require('./flash-constants');
var _flashConstants2 = _interopRequireDefault(_flashConstants);
/**
* Assemble the FLV tags in decoder order
*
* @function orderTags
* @param {Object} tags object containing video and audio tags
* @return {Object} object containing the filtered array of tags and total bytelength
*/
var orderTags = function orderTags(tags) {
var videoTags = tags.videoTags;
var audioTags = tags.audioTags;
var ordered = [];
var tag = undefined;
while (videoTags.length || audioTags.length) {
if (!videoTags.length) {
// only audio tags remain
tag = audioTags.shift();
} else if (!audioTags.length) {
// only video tags remain
tag = videoTags.shift();
} else if (audioTags[0].dts < videoTags[0].dts) {
// audio should be decoded next
tag = audioTags.shift();
} else {
// video should be decoded next
tag = videoTags.shift();
}
ordered.push(tag);
}
return ordered;
};
/**
* Turns an array of flv tags into a Uint8Array representing the
* flv data.
*
* @function convertTagsToData
* @param {Array} list of flv tags
*/
var convertTagsToData_ = function convertTagsToData_(tags, targetPts) {
var filtered = [];
var len = 0;
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].pts >= targetPts) {
filtered.push(tags[i]);
len += tags[i].bytes.length;
}
}
if (filtered.length === 0) {
return [];
}
var segment = new Uint8Array(len);
for (var i = 0, j = 0, l = filtered.length; i < l; i++) {
segment.set(filtered[i].bytes, j);
j += filtered[i].bytes.byteLength;
}
var b64Chunks = [];
for (var chunkStart = 0, l = segment.byteLength; chunkStart < l; chunkStart += _flashConstants2['default'].BYTES_PER_CHUNK) {
var chunkEnd = Math.min(chunkStart + _flashConstants2['default'].BYTES_PER_CHUNK, l);
var chunk = segment.subarray(chunkStart, chunkEnd);
var binary = [];
for (var chunkByte = 0; chunkByte < chunk.byteLength; chunkByte++) {
binary.push(String.fromCharCode(chunk[chunkByte]));
}
b64Chunks.push(_globalWindow2['default'].btoa(binary.join('')));
}
return b64Chunks;
};
/**
* Re-emits tranmsuxer events by converting them into messages to the
* world outside the worker.
*
* @param {Object} transmuxer the transmuxer to wire events on
* @private
*/
var wireTransmuxerEvents = function wireTransmuxerEvents(transmuxer) {
var _this = this;
transmuxer.on('data', function (segment) {
_this.tags = orderTags(segment.tags);
delete segment.tags;
segment.basePts = _this.tags[0].pts;
segment.length = _this.tags.length;
_globalWindow2['default'].postMessage({
action: 'metadata',
segment: segment
});
});
transmuxer.on('done', function (data) {
_globalWindow2['default'].postMessage({ action: 'done' });
});
};
/**
* All incoming messages route through this hash. If no function exists
* to handle an incoming message, then we ignore the message.
*
* @class MessageHandlers
* @param {Object} options the options to initialize with
*/
var MessageHandlers = (function () {
function MessageHandlers(options) {
_classCallCheck(this, MessageHandlers);
this.options = options || {};
this.init();
this.tags = [];
this.targetPts_ = 0;
}
/**
* Our web wroker interface so that things can talk to mux.js
* that will be running in a web worker. the scope is passed to this by
* webworkify.
*
* @param {Object} self the scope for the web worker
*/
/**
* initialize our web worker and wire all the events.
*/
_createClass(MessageHandlers, [{
key: 'init',
value: function init() {
if (this.transmuxer) {
this.transmuxer.dispose();
}
this.transmuxer = new _muxJsLibFlv2['default'].Transmuxer(this.options);
wireTransmuxerEvents.call(this, this.transmuxer);
}
}, {
key: 'convertTagsToData',
value: function convertTagsToData(data) {
this.targetPts_ = data.targetPts;
var b64 = convertTagsToData_(this.tags, this.targetPts_);
_globalWindow2['default'].postMessage({
action: 'data',
b64: b64
});
}
/**
* Adds data (a ts segment) to the start of the transmuxer pipeline for
* processing.
*
* @param {ArrayBuffer} data data to push into the muxer
*/
}, {
key: 'push',
value: function push(data) {
// Cast array buffer to correct type for transmuxer
var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
this.transmuxer.push(segment);
}
/**
* Recreate the transmuxer so that the next segment added via `push`
* start with a fresh transmuxer.
*/
}, {
key: 'reset',
value: function reset() {
this.init();
}
/**
* Forces the pipeline to finish processing the last segment and emit it's
* results.
*
* @param {Object} data event data, not really used
*/
}, {
key: 'flush',
value: function flush(data) {
this.transmuxer.flush();
}
}]);
return MessageHandlers;
})();
var Worker = function Worker(self) {
self.onmessage = function (event) {
if (event.data.action === 'init' && event.data.options) {
this.messageHandlers = new MessageHandlers(event.data.options);
return;
}
if (!this.messageHandlers) {
this.messageHandlers = new MessageHandlers();
}
if (event.data && event.data.action && event.data.action !== 'init') {
if (this.messageHandlers[event.data.action]) {
this.messageHandlers[event.data.action](event.data);
}
}
};
};
exports['default'] = function (self) {
return new Worker(self);
};
module.exports = exports['default'];
},{"./flash-constants":94,"global/window":104,"mux.js/lib/flv":14}],98:[function(require,module,exports){
(function (global){
/**
* @file html-media-source.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = require('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _virtualSourceBuffer = require('./virtual-source-buffer');
var _virtualSourceBuffer2 = _interopRequireDefault(_virtualSourceBuffer);
var _addTextTrackData = require('./add-text-track-data');
var _codecUtils = require('./codec-utils');
/**
* Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
* `avc1.<hhhhhh>`
*
* @param {Array} codecs an array of codec strings to fix
* @return {Array} the translated codec array
* @private
*/
var translateLegacyCodecs = function translateLegacyCodecs(codecs) {
return codecs.map(function (codec) {
return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
return 'avc1.' + profileHex + '00' + avcLevelHex;
});
});
};
/**
* Our MediaSource implementation in HTML, mimics native
* MediaSource where/if possible.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource
* @class HtmlMediaSource
* @extends videojs.EventTarget
*/
var HtmlMediaSource = (function (_videojs$EventTarget) {
_inherits(HtmlMediaSource, _videojs$EventTarget);
function HtmlMediaSource() {
var _this = this;
_classCallCheck(this, HtmlMediaSource);
_get(Object.getPrototypeOf(HtmlMediaSource.prototype), 'constructor', this).call(this);
var property = undefined;
this.nativeMediaSource_ = new _globalWindow2['default'].MediaSource();
// delegate to the native MediaSource's methods by default
for (property in this.nativeMediaSource_) {
if (!(property in HtmlMediaSource.prototype) && typeof this.nativeMediaSource_[property] === 'function') {
this[property] = this.nativeMediaSource_[property].bind(this.nativeMediaSource_);
}
}
// emulate `duration` and `seekable` until seeking can be
// handled uniformly for live streams
// see https://github.com/w3c/media-source/issues/5
this.duration_ = NaN;
Object.defineProperty(this, 'duration', {
get: function get() {
if (this.duration_ === Infinity) {
return this.duration_;
}
return this.nativeMediaSource_.duration;
},
set: function set(duration) {
this.duration_ = duration;
if (duration !== Infinity) {
this.nativeMediaSource_.duration = duration;
return;
}
}
});
Object.defineProperty(this, 'seekable', {
get: function get() {
if (this.duration_ === Infinity) {
return _videoJs2['default'].createTimeRanges([[0, this.nativeMediaSource_.duration]]);
}
return this.nativeMediaSource_.seekable;
}
});
Object.defineProperty(this, 'readyState', {
get: function get() {
return this.nativeMediaSource_.readyState;
}
});
Object.defineProperty(this, 'activeSourceBuffers', {
get: function get() {
return this.activeSourceBuffers_;
}
});
// the list of virtual and native SourceBuffers created by this
// MediaSource
this.sourceBuffers = [];
this.activeSourceBuffers_ = [];
/**
* update the list of active source buffers based upon various
* imformation from HLS and video.js
*
* @private
*/
this.updateActiveSourceBuffers_ = function () {
// Retain the reference but empty the array
_this.activeSourceBuffers_.length = 0;
// By default, the audio in the combined virtual source buffer is enabled
// and the audio-only source buffer (if it exists) is disabled.
var combined = false;
var audioOnly = true;
// TODO: maybe we can store the sourcebuffers on the track objects?
// safari may do something like this
for (var i = 0; i < _this.player_.audioTracks().length; i++) {
var track = _this.player_.audioTracks()[i];
if (track.enabled && track.kind !== 'main') {
// The enabled track is an alternate audio track so disable the audio in
// the combined source buffer and enable the audio-only source buffer.
combined = true;
audioOnly = false;
break;
}
}
// Since we currently support a max of two source buffers, add all of the source
// buffers (in order).
_this.sourceBuffers.forEach(function (sourceBuffer) {
/* eslinst-disable */
// TODO once codecs are required, we can switch to using the codecs to determine
// what stream is the video stream, rather than relying on videoTracks
/* eslinst-enable */
sourceBuffer.appendAudioInitSegment_ = true;
if (sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
// combined
sourceBuffer.audioDisabled_ = combined;
} else if (sourceBuffer.videoCodec_ && !sourceBuffer.audioCodec_) {
// If the "combined" source buffer is video only, then we do not want
// disable the audio-only source buffer (this is mostly for demuxed
// audio and video hls)
sourceBuffer.audioDisabled_ = true;
audioOnly = false;
} else if (!sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
// audio only
sourceBuffer.audioDisabled_ = audioOnly;
if (audioOnly) {
return;
}
}
_this.activeSourceBuffers_.push(sourceBuffer);
});
};
this.onPlayerMediachange_ = function () {
_this.sourceBuffers.forEach(function (sourceBuffer) {
sourceBuffer.appendAudioInitSegment_ = true;
});
};
// Re-emit MediaSource events on the polyfill
['sourceopen', 'sourceclose', 'sourceended'].forEach(function (eventName) {
this.nativeMediaSource_.addEventListener(eventName, this.trigger.bind(this));
}, this);
// capture the associated player when the MediaSource is
// successfully attached
this.on('sourceopen', function (event) {
// Get the player this MediaSource is attached to
var video = _globalDocument2['default'].querySelector('[src="' + _this.url_ + '"]');
if (!video) {
return;
}
_this.player_ = (0, _videoJs2['default'])(video.parentNode);
if (_this.player_.audioTracks && _this.player_.audioTracks()) {
_this.player_.audioTracks().on('change', _this.updateActiveSourceBuffers_);
_this.player_.audioTracks().on('addtrack', _this.updateActiveSourceBuffers_);
_this.player_.audioTracks().on('removetrack', _this.updateActiveSourceBuffers_);
}
_this.player_.on('mediachange', _this.onPlayerMediachange_);
});
this.on('sourceended', function (event) {
var duration = (0, _addTextTrackData.durationOfVideo)(_this.duration);
for (var i = 0; i < _this.sourceBuffers.length; i++) {
var sourcebuffer = _this.sourceBuffers[i];
var cues = sourcebuffer.metadataTrack_ && sourcebuffer.metadataTrack_.cues;
if (cues && cues.length) {
cues[cues.length - 1].endTime = duration;
}
}
});
// explicitly terminate any WebWorkers that were created
// by SourceHandlers
this.on('sourceclose', function (event) {
this.sourceBuffers.forEach(function (sourceBuffer) {
if (sourceBuffer.transmuxer_) {
sourceBuffer.transmuxer_.terminate();
}
});
this.sourceBuffers.length = 0;
if (!this.player_) {
return;
}
if (this.player_.audioTracks && this.player_.audioTracks()) {
this.player_.audioTracks().off('change', this.updateActiveSourceBuffers_);
this.player_.audioTracks().off('addtrack', this.updateActiveSourceBuffers_);
this.player_.audioTracks().off('removetrack', this.updateActiveSourceBuffers_);
}
this.player_.off('mediachange', this.onPlayerMediachange_);
});
}
/**
* Add a range that that can now be seeked to.
*
* @param {Double} start where to start the addition
* @param {Double} end where to end the addition
* @private
*/
_createClass(HtmlMediaSource, [{
key: 'addSeekableRange_',
value: function addSeekableRange_(start, end) {
var error = undefined;
if (this.duration !== Infinity) {
error = new Error('MediaSource.addSeekableRange() can only be invoked ' + 'when the duration is Infinity');
error.name = 'InvalidStateError';
error.code = 11;
throw error;
}
if (end > this.nativeMediaSource_.duration || isNaN(this.nativeMediaSource_.duration)) {
this.nativeMediaSource_.duration = end;
}
}
/**
* Add a source buffer to the media source.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
* @param {String} type the content-type of the content
* @return {Object} the created source buffer
*/
}, {
key: 'addSourceBuffer',
value: function addSourceBuffer(type) {
var buffer = undefined;
var parsedType = (0, _codecUtils.parseContentType)(type);
// Create a VirtualSourceBuffer to transmux MPEG-2 transport
// stream segments into fragmented MP4s
if (/^(video|audio)\/mp2t$/i.test(parsedType.type)) {
var codecs = [];
if (parsedType.parameters && parsedType.parameters.codecs) {
codecs = parsedType.parameters.codecs.split(',');
codecs = translateLegacyCodecs(codecs);
codecs = codecs.filter(function (codec) {
return (0, _codecUtils.isAudioCodec)(codec) || (0, _codecUtils.isVideoCodec)(codec);
});
}
if (codecs.length === 0) {
codecs = ['avc1.4d400d', 'mp4a.40.2'];
}
buffer = new _virtualSourceBuffer2['default'](this, codecs);
if (this.sourceBuffers.length !== 0) {
// If another VirtualSourceBuffer already exists, then we are creating a
// SourceBuffer for an alternate audio track and therefore we know that
// the source has both an audio and video track.
// That means we should trigger the manual creation of the real
// SourceBuffers instead of waiting for the transmuxer to return data
this.sourceBuffers[0].createRealSourceBuffers_();
buffer.createRealSourceBuffers_();
// Automatically disable the audio on the first source buffer if
// a second source buffer is ever created
this.sourceBuffers[0].audioDisabled_ = true;
}
} else {
// delegate to the native implementation
buffer = this.nativeMediaSource_.addSourceBuffer(type);
}
this.sourceBuffers.push(buffer);
return buffer;
}
}]);
return HtmlMediaSource;
})(_videoJs2['default'].EventTarget);
exports['default'] = HtmlMediaSource;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./add-text-track-data":91,"./codec-utils":92,"./virtual-source-buffer":102,"global/document":103,"global/window":104}],99:[function(require,module,exports){
/**
* @file remove-cues-from-track.js
*/
/**
* Remove cues from a track on video.js.
*
* @param {Double} start start of where we should remove the cue
* @param {Double} end end of where the we should remove the cue
* @param {Object} track the text track to remove the cues from
* @private
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
var i = undefined;
var cue = undefined;
if (!track) {
return;
}
i = track.cues.length;
while (i--) {
cue = track.cues[i];
// Remove any overlapping cue
if (cue.startTime <= end && cue.endTime >= start) {
track.removeCue(cue);
}
}
};
exports["default"] = removeCuesFromTrack;
module.exports = exports["default"];
},{}],100:[function(require,module,exports){
/**
* @file transmuxer-worker.js
*/
/**
* videojs-contrib-media-sources
*
* Copyright (c) 2015 Brightcove
* All rights reserved.
*
* Handles communication between the browser-world and the mux.js
* transmuxer running inside of a WebWorker by exposing a simple
* message-based interface to a Transmuxer object.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _muxJsLibMp4 = require('mux.js/lib/mp4');
var _muxJsLibMp42 = _interopRequireDefault(_muxJsLibMp4);
/**
* Re-emits tranmsuxer events by converting them into messages to the
* world outside the worker.
*
* @param {Object} transmuxer the transmuxer to wire events on
* @private
*/
var wireTransmuxerEvents = function wireTransmuxerEvents(transmuxer) {
transmuxer.on('data', function (segment) {
// transfer ownership of the underlying ArrayBuffer
// instead of doing a copy to save memory
// ArrayBuffers are transferable but generic TypedArrays are not
// @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
var initArray = segment.initSegment;
segment.initSegment = {
data: initArray.buffer,
byteOffset: initArray.byteOffset,
byteLength: initArray.byteLength
};
var typedArray = segment.data;
segment.data = typedArray.buffer;
_globalWindow2['default'].postMessage({
action: 'data',
segment: segment,
byteOffset: typedArray.byteOffset,
byteLength: typedArray.byteLength
}, [segment.data]);
});
if (transmuxer.captionStream) {
transmuxer.captionStream.on('data', function (caption) {
_globalWindow2['default'].postMessage({
action: 'caption',
data: caption
});
});
}
transmuxer.on('done', function (data) {
_globalWindow2['default'].postMessage({ action: 'done' });
});
};
/**
* All incoming messages route through this hash. If no function exists
* to handle an incoming message, then we ignore the message.
*
* @class MessageHandlers
* @param {Object} options the options to initialize with
*/
var MessageHandlers = (function () {
function MessageHandlers(options) {
_classCallCheck(this, MessageHandlers);
this.options = options || {};
this.init();
}
/**
* Our web wroker interface so that things can talk to mux.js
* that will be running in a web worker. the scope is passed to this by
* webworkify.
*
* @param {Object} self the scope for the web worker
*/
/**
* initialize our web worker and wire all the events.
*/
_createClass(MessageHandlers, [{
key: 'init',
value: function init() {
if (this.transmuxer) {
this.transmuxer.dispose();
}
this.transmuxer = new _muxJsLibMp42['default'].Transmuxer(this.options);
wireTransmuxerEvents(this.transmuxer);
}
/**
* Adds data (a ts segment) to the start of the transmuxer pipeline for
* processing.
*
* @param {ArrayBuffer} data data to push into the muxer
*/
}, {
key: 'push',
value: function push(data) {
// Cast array buffer to correct type for transmuxer
var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
this.transmuxer.push(segment);
}
/**
* Recreate the transmuxer so that the next segment added via `push`
* start with a fresh transmuxer.
*/
}, {
key: 'reset',
value: function reset() {
this.init();
}
/**
* Set the value that will be used as the `baseMediaDecodeTime` time for the
* next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
* set relative to the first based on the PTS values.
*
* @param {Object} data used to set the timestamp offset in the muxer
*/
}, {
key: 'setTimestampOffset',
value: function setTimestampOffset(data) {
var timestampOffset = data.timestampOffset || 0;
this.transmuxer.setBaseMediaDecodeTime(Math.round(timestampOffset * 90000));
}
/**
* Forces the pipeline to finish processing the last segment and emit it's
* results.
*
* @param {Object} data event data, not really used
*/
}, {
key: 'flush',
value: function flush(data) {
this.transmuxer.flush();
}
}]);
return MessageHandlers;
})();
var Worker = function Worker(self) {
self.onmessage = function (event) {
if (event.data.action === 'init' && event.data.options) {
this.messageHandlers = new MessageHandlers(event.data.options);
return;
}
if (!this.messageHandlers) {
this.messageHandlers = new MessageHandlers();
}
if (event.data && event.data.action && event.data.action !== 'init') {
if (this.messageHandlers[event.data.action]) {
this.messageHandlers[event.data.action](event.data);
}
}
};
};
exports['default'] = function (self) {
return new Worker(self);
};
module.exports = exports['default'];
},{"global/window":104,"mux.js/lib/mp4":22}],101:[function(require,module,exports){
(function (global){
/**
* @file videojs-contrib-media-sources.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = require('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _flashMediaSource = require('./flash-media-source');
var _flashMediaSource2 = _interopRequireDefault(_flashMediaSource);
var _htmlMediaSource = require('./html-media-source');
var _htmlMediaSource2 = _interopRequireDefault(_htmlMediaSource);
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var urlCount = 0;
// ------------
// Media Source
// ------------
var defaults = {
// how to determine the MediaSource implementation to use. There
// are three available modes:
// - auto: use native MediaSources where available and Flash
// everywhere else
// - html5: always use native MediaSources
// - flash: always use the Flash MediaSource polyfill
mode: 'auto'
};
// store references to the media sources so they can be connected
// to a video element (a swf object)
// TODO: can we store this somewhere local to this module?
_videoJs2['default'].mediaSources = {};
/**
* Provide a method for a swf object to notify JS that a
* media source is now open.
*
* @param {String} msObjectURL string referencing the MSE Object URL
* @param {String} swfId the swf id
*/
var open = function open(msObjectURL, swfId) {
var mediaSource = _videoJs2['default'].mediaSources[msObjectURL];
if (mediaSource) {
mediaSource.trigger({ type: 'sourceopen', swfId: swfId });
} else {
throw new Error('Media Source not found (Video.js)');
}
};
/**
* Check to see if the native MediaSource object exists and supports
* an MP4 container with both H.264 video and AAC-LC audio.
*
* @return {Boolean} if native media sources are supported
*/
var supportsNativeMediaSources = function supportsNativeMediaSources() {
return !!_globalWindow2['default'].MediaSource && !!_globalWindow2['default'].MediaSource.isTypeSupported && _globalWindow2['default'].MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"');
};
/**
* An emulation of the MediaSource API so that we can support
* native and non-native functionality such as flash and
* video/mp2t videos. returns an instance of HtmlMediaSource or
* FlashMediaSource depending on what is supported and what options
* are passed in.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/MediaSource
* @param {Object} options options to use during setup.
*/
var MediaSource = function MediaSource(options) {
var settings = _videoJs2['default'].mergeOptions(defaults, options);
this.MediaSource = {
open: open,
supportsNativeMediaSources: supportsNativeMediaSources
};
// determine whether HTML MediaSources should be used
if (settings.mode === 'html5' || settings.mode === 'auto' && supportsNativeMediaSources()) {
return new _htmlMediaSource2['default']();
}
// otherwise, emulate them through the SWF
return new _flashMediaSource2['default']();
};
exports.MediaSource = MediaSource;
MediaSource.open = open;
MediaSource.supportsNativeMediaSources = supportsNativeMediaSources;
/**
* A wrapper around the native URL for our MSE object
* implementation, this object is exposed under videojs.URL
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
*/
var URL = {
/**
* A wrapper around the native createObjectURL for our objects.
* This function maps a native or emulated mediaSource to a blob
* url so that it can be loaded into video.js
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
* @param {MediaSource} object the object to create a blob url to
*/
createObjectURL: function createObjectURL(object) {
var objectUrlPrefix = 'blob:vjs-media-source/';
var url = undefined;
// use the native MediaSource to generate an object URL
if (object instanceof _htmlMediaSource2['default']) {
url = _globalWindow2['default'].URL.createObjectURL(object.nativeMediaSource_);
object.url_ = url;
return url;
}
// if the object isn't an emulated MediaSource, delegate to the
// native implementation
if (!(object instanceof _flashMediaSource2['default'])) {
url = _globalWindow2['default'].URL.createObjectURL(object);
object.url_ = url;
return url;
}
// build a URL that can be used to map back to the emulated
// MediaSource
url = objectUrlPrefix + urlCount;
urlCount++;
// setup the mapping back to object
_videoJs2['default'].mediaSources[url] = object;
return url;
}
};
exports.URL = URL;
_videoJs2['default'].MediaSource = MediaSource;
_videoJs2['default'].URL = URL;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./flash-media-source":95,"./html-media-source":98,"global/window":104}],102:[function(require,module,exports){
(function (global){
/**
* @file virtual-source-buffer.js
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _videoJs = (typeof window !== "undefined" ? window['videojs'] : typeof global !== "undefined" ? global['videojs'] : null);
var _videoJs2 = _interopRequireDefault(_videoJs);
var _createTextTracksIfNecessary = require('./create-text-tracks-if-necessary');
var _createTextTracksIfNecessary2 = _interopRequireDefault(_createTextTracksIfNecessary);
var _removeCuesFromTrack = require('./remove-cues-from-track');
var _removeCuesFromTrack2 = _interopRequireDefault(_removeCuesFromTrack);
var _addTextTrackData = require('./add-text-track-data');
var _webworkify = require('webworkify');
var _webworkify2 = _interopRequireDefault(_webworkify);
var _transmuxerWorker = require('./transmuxer-worker');
var _transmuxerWorker2 = _interopRequireDefault(_transmuxerWorker);
var _codecUtils = require('./codec-utils');
/**
* VirtualSourceBuffers exist so that we can transmux non native formats
* into a native format, but keep the same api as a native source buffer.
* It creates a transmuxer, that works in its own thread (a web worker) and
* that transmuxer muxes the data into a native format. VirtualSourceBuffer will
* then send all of that data to the naive sourcebuffer so that it is
* indestinguishable from a natively supported format.
*
* @param {HtmlMediaSource} mediaSource the parent mediaSource
* @param {Array} codecs array of codecs that we will be dealing with
* @class VirtualSourceBuffer
* @extends video.js.EventTarget
*/
var VirtualSourceBuffer = (function (_videojs$EventTarget) {
_inherits(VirtualSourceBuffer, _videojs$EventTarget);
function VirtualSourceBuffer(mediaSource, codecs) {
var _this = this;
_classCallCheck(this, VirtualSourceBuffer);
_get(Object.getPrototypeOf(VirtualSourceBuffer.prototype), 'constructor', this).call(this, _videoJs2['default'].EventTarget);
this.timestampOffset_ = 0;
this.pendingBuffers_ = [];
this.bufferUpdating_ = false;
this.mediaSource_ = mediaSource;
this.codecs_ = codecs;
this.audioCodec_ = null;
this.videoCodec_ = null;
this.audioDisabled_ = false;
this.appendAudioInitSegment_ = true;
var options = {
remux: false
};
this.codecs_.forEach(function (codec) {
if ((0, _codecUtils.isAudioCodec)(codec)) {
_this.audioCodec_ = codec;
} else if ((0, _codecUtils.isVideoCodec)(codec)) {
_this.videoCodec_ = codec;
}
});
// append muxed segments to their respective native buffers as
// soon as they are available
this.transmuxer_ = (0, _webworkify2['default'])(_transmuxerWorker2['default']);
this.transmuxer_.postMessage({ action: 'init', options: options });
this.transmuxer_.onmessage = function (event) {
if (event.data.action === 'data') {
return _this.data_(event);
}
if (event.data.action === 'done') {
return _this.done_(event);
}
};
// this timestampOffset is a property with the side-effect of resetting
// baseMediaDecodeTime in the transmuxer on the setter
Object.defineProperty(this, 'timestampOffset', {
get: function get() {
return this.timestampOffset_;
},
set: function set(val) {
if (typeof val === 'number' && val >= 0) {
this.timestampOffset_ = val;
this.appendAudioInitSegment_ = true;
// We have to tell the transmuxer to set the baseMediaDecodeTime to
// the desired timestampOffset for the next segment
this.transmuxer_.postMessage({
action: 'setTimestampOffset',
timestampOffset: val
});
}
}
});
// setting the append window affects both source buffers
Object.defineProperty(this, 'appendWindowStart', {
get: function get() {
return (this.videoBuffer_ || this.audioBuffer_).appendWindowStart;
},
set: function set(start) {
if (this.videoBuffer_) {
this.videoBuffer_.appendWindowStart = start;
}
if (this.audioBuffer_) {
this.audioBuffer_.appendWindowStart = start;
}
}
});
// this buffer is "updating" if either of its native buffers are
Object.defineProperty(this, 'updating', {
get: function get() {
return !!(this.bufferUpdating_ || !this.audioDisabled_ && this.audioBuffer_ && this.audioBuffer_.updating || this.videoBuffer_ && this.videoBuffer_.updating);
}
});
// the buffered property is the intersection of the buffered
// ranges of the native source buffers
Object.defineProperty(this, 'buffered', {
get: function get() {
var start = null;
var end = null;
var arity = 0;
var extents = [];
var ranges = [];
// neither buffer has been created yet
if (!this.videoBuffer_ && !this.audioBuffer_) {
return _videoJs2['default'].createTimeRange();
}
// only one buffer is configured
if (!this.videoBuffer_) {
return this.audioBuffer_.buffered;
}
if (!this.audioBuffer_) {
return this.videoBuffer_.buffered;
}
// both buffers are configured
if (this.audioDisabled_) {
return this.videoBuffer_.buffered;
}
// both buffers are empty
if (this.videoBuffer_.buffered.length === 0 && this.audioBuffer_.buffered.length === 0) {
return _videoJs2['default'].createTimeRange();
}
// Handle the case where we have both buffers and create an
// intersection of the two
var videoBuffered = this.videoBuffer_.buffered;
var audioBuffered = this.audioBuffer_.buffered;
var count = videoBuffered.length;
// A) Gather up all start and end times
while (count--) {
extents.push({ time: videoBuffered.start(count), type: 'start' });
extents.push({ time: videoBuffered.end(count), type: 'end' });
}
count = audioBuffered.length;
while (count--) {
extents.push({ time: audioBuffered.start(count), type: 'start' });
extents.push({ time: audioBuffered.end(count), type: 'end' });
}
// B) Sort them by time
extents.sort(function (a, b) {
return a.time - b.time;
});
// C) Go along one by one incrementing arity for start and decrementing
// arity for ends
for (count = 0; count < extents.length; count++) {
if (extents[count].type === 'start') {
arity++;
// D) If arity is ever incremented to 2 we are entering an
// overlapping range
if (arity === 2) {
start = extents[count].time;
}
} else if (extents[count].type === 'end') {
arity--;
// E) If arity is ever decremented to 1 we leaving an
// overlapping range
if (arity === 1) {
end = extents[count].time;
}
}
// F) Record overlapping ranges
if (start !== null && end !== null) {
ranges.push([start, end]);
start = null;
end = null;
}
}
return _videoJs2['default'].createTimeRanges(ranges);
}
});
}
/**
* When we get a data event from the transmuxer
* we call this function and handle the data that
* was sent to us
*
* @private
* @param {Event} event the data event from the transmuxer
*/
_createClass(VirtualSourceBuffer, [{
key: 'data_',
value: function data_(event) {
var segment = event.data.segment;
// Cast ArrayBuffer to TypedArray
segment.data = new Uint8Array(segment.data, event.data.byteOffset, event.data.byteLength);
segment.initSegment = new Uint8Array(segment.initSegment.data, segment.initSegment.byteOffset, segment.initSegment.byteLength);
(0, _createTextTracksIfNecessary2['default'])(this, this.mediaSource_, segment);
// Add the segments to the pendingBuffers array
this.pendingBuffers_.push(segment);
return;
}
/**
* When we get a done event from the transmuxer
* we call this function and we process all
* of the pending data that we have been saving in the
* data_ function
*
* @private
* @param {Event} event the done event from the transmuxer
*/
}, {
key: 'done_',
value: function done_(event) {
// All buffers should have been flushed from the muxer
// start processing anything we have received
this.processPendingSegments_();
return;
}
/**
* Create our internal native audio/video source buffers and add
* event handlers to them with the following conditions:
* 1. they do not already exist on the mediaSource
* 2. this VSB has a codec for them
*
* @private
*/
}, {
key: 'createRealSourceBuffers_',
value: function createRealSourceBuffers_() {
var _this2 = this;
var types = ['audio', 'video'];
types.forEach(function (type) {
// Don't create a SourceBuffer of this type if we don't have a
// codec for it
if (!_this2[type + 'Codec_']) {
return;
}
// Do nothing if a SourceBuffer of this type already exists
if (_this2[type + 'Buffer_']) {
return;
}
var buffer = null;
// If the mediasource already has a SourceBuffer for the codec
// use that
if (_this2.mediaSource_[type + 'Buffer_']) {
buffer = _this2.mediaSource_[type + 'Buffer_'];
} else {
buffer = _this2.mediaSource_.nativeMediaSource_.addSourceBuffer(type + '/mp4;codecs="' + _this2[type + 'Codec_'] + '"');
_this2.mediaSource_[type + 'Buffer_'] = buffer;
}
_this2[type + 'Buffer_'] = buffer;
// Wire up the events to the SourceBuffer
['update', 'updatestart', 'updateend'].forEach(function (event) {
buffer.addEventListener(event, function () {
// if audio is disabled
if (type === 'audio' && _this2.audioDisabled_) {
return;
}
var shouldTrigger = types.every(function (t) {
// skip checking audio's updating status if audio
// is not enabled
if (t === 'audio' && _this2.audioDisabled_) {
return true;
}
// if the other type if updating we don't trigger
if (type !== t && _this2[t + 'Buffer_'] && _this2[t + 'Buffer_'].updating) {
return false;
}
return true;
});
if (shouldTrigger) {
return _this2.trigger(event);
}
});
});
});
}
/**
* Emulate the native mediasource function, but our function will
* send all of the proposed segments to the transmuxer so that we
* can transmux them before we append them to our internal
* native source buffers in the correct format.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/appendBuffer
* @param {Uint8Array} segment the segment to append to the buffer
*/
}, {
key: 'appendBuffer',
value: function appendBuffer(segment) {
// Start the internal "updating" state
this.bufferUpdating_ = true;
this.transmuxer_.postMessage({
action: 'push',
// Send the typed-array of data as an ArrayBuffer so that
// it can be sent as a "Transferable" and avoid the costly
// memory copy
data: segment.buffer,
// To recreate the original typed-array, we need information
// about what portion of the ArrayBuffer it was a view into
byteOffset: segment.byteOffset,
byteLength: segment.byteLength
}, [segment.buffer]);
this.transmuxer_.postMessage({ action: 'flush' });
}
/**
* Emulate the native mediasource function and remove parts
* of the buffer from any of our internal buffers that exist
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/remove
* @param {Double} start position to start the remove at
* @param {Double} end position to end the remove at
*/
}, {
key: 'remove',
value: function remove(start, end) {
if (this.videoBuffer_) {
this.videoBuffer_.remove(start, end);
}
if (this.audioBuffer_) {
this.audioBuffer_.remove(start, end);
}
// Remove Metadata Cues (id3)
(0, _removeCuesFromTrack2['default'])(start, end, this.metadataTrack_);
// Remove Any Captions
(0, _removeCuesFromTrack2['default'])(start, end, this.inbandTextTrack_);
}
/**
* Process any segments that the muxer has output
* Concatenate segments together based on type and append them into
* their respective sourceBuffers
*
* @private
*/
}, {
key: 'processPendingSegments_',
value: function processPendingSegments_() {
var sortedSegments = {
video: {
segments: [],
bytes: 0
},
audio: {
segments: [],
bytes: 0
},
captions: [],
metadata: []
};
// Sort segments into separate video/audio arrays and
// keep track of their total byte lengths
sortedSegments = this.pendingBuffers_.reduce(function (segmentObj, segment) {
var type = segment.type;
var data = segment.data;
var initSegment = segment.initSegment;
segmentObj[type].segments.push(data);
segmentObj[type].bytes += data.byteLength;
segmentObj[type].initSegment = initSegment;
// Gather any captions into a single array
if (segment.captions) {
segmentObj.captions = segmentObj.captions.concat(segment.captions);
}
if (segment.info) {
segmentObj[type].info = segment.info;
}
// Gather any metadata into a single array
if (segment.metadata) {
segmentObj.metadata = segmentObj.metadata.concat(segment.metadata);
}
return segmentObj;
}, sortedSegments);
// Create the real source buffers if they don't exist by now since we
// finally are sure what tracks are contained in the source
if (!this.videoBuffer_ && !this.audioBuffer_) {
// Remove any codecs that may have been specified by default but
// are no longer applicable now
if (sortedSegments.video.bytes === 0) {
this.videoCodec_ = null;
}
if (sortedSegments.audio.bytes === 0) {
this.audioCodec_ = null;
}
this.createRealSourceBuffers_();
}
if (sortedSegments.audio.info) {
this.mediaSource_.trigger({ type: 'audioinfo', info: sortedSegments.audio.info });
}
if (sortedSegments.video.info) {
this.mediaSource_.trigger({ type: 'videoinfo', info: sortedSegments.video.info });
}
if (this.appendAudioInitSegment_) {
if (!this.audioDisabled_ && this.audioBuffer_) {
sortedSegments.audio.segments.unshift(sortedSegments.audio.initSegment);
sortedSegments.audio.bytes += sortedSegments.audio.initSegment.byteLength;
}
this.appendAudioInitSegment_ = false;
}
// Merge multiple video and audio segments into one and append
if (this.videoBuffer_) {
sortedSegments.video.segments.unshift(sortedSegments.video.initSegment);
sortedSegments.video.bytes += sortedSegments.video.initSegment.byteLength;
this.concatAndAppendSegments_(sortedSegments.video, this.videoBuffer_);
// TODO: are video tracks the only ones with text tracks?
(0, _addTextTrackData.addTextTrackData)(this, sortedSegments.captions, sortedSegments.metadata);
}
if (!this.audioDisabled_ && this.audioBuffer_) {
this.concatAndAppendSegments_(sortedSegments.audio, this.audioBuffer_);
}
this.pendingBuffers_.length = 0;
// We are no longer in the internal "updating" state
this.bufferUpdating_ = false;
}
/**
* Combine all segments into a single Uint8Array and then append them
* to the destination buffer
*
* @param {Object} segmentObj
* @param {SourceBuffer} destinationBuffer native source buffer to append data to
* @private
*/
}, {
key: 'concatAndAppendSegments_',
value: function concatAndAppendSegments_(segmentObj, destinationBuffer) {
var offset = 0;
var tempBuffer = undefined;
if (segmentObj.bytes) {
tempBuffer = new Uint8Array(segmentObj.bytes);
// Combine the individual segments into one large typed-array
segmentObj.segments.forEach(function (segment) {
tempBuffer.set(segment, offset);
offset += segment.byteLength;
});
try {
destinationBuffer.appendBuffer(tempBuffer);
} catch (error) {
if (this.mediaSource_.player_) {
this.mediaSource_.player_.error({
code: -3,
type: 'APPEND_BUFFER_ERR'
});
}
}
}
}
/**
* Emulate the native mediasource function. abort any soureBuffer
* actions and throw out any un-appended data.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer/abort
*/
}, {
key: 'abort',
value: function abort() {
if (this.videoBuffer_) {
this.videoBuffer_.abort();
}
if (this.audioBuffer_) {
this.audioBuffer_.abort();
}
if (this.transmuxer_) {
this.transmuxer_.postMessage({ action: 'reset' });
}
this.pendingBuffers_.length = 0;
this.bufferUpdating_ = false;
}
}]);
return VirtualSourceBuffer;
})(_videoJs2['default'].EventTarget);
exports['default'] = VirtualSourceBuffer;
module.exports = exports['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./add-text-track-data":91,"./codec-utils":92,"./create-text-tracks-if-necessary":93,"./remove-cues-from-track":99,"./transmuxer-worker":100,"webworkify":105}],103:[function(require,module,exports){
arguments[4][45][0].apply(exports,arguments)
},{"dup":45,"min-document":44}],104:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"dup":46}],105:[function(require,module,exports){
var bundleFn = arguments[3];
var sources = arguments[4];
var cache = arguments[5];
var stringify = JSON.stringify;
module.exports = function (fn) {
var keys = [];
var wkey;
var cacheKeys = Object.keys(cache);
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
if (cache[key].exports === fn) {
wkey = key;
break;
}
}
if (!wkey) {
wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var wcache = {};
for (var i = 0, l = cacheKeys.length; i < l; i++) {
var key = cacheKeys[i];
wcache[key] = key;
}
sources[wkey] = [
Function(['require','module','exports'], '(' + fn + ')(self)'),
wcache
];
}
var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
var scache = {}; scache[wkey] = wkey;
sources[skey] = [
Function(['require'],'require(' + stringify(wkey) + ')(self)'),
scache
];
var src = '(' + bundleFn + ')({'
+ Object.keys(sources).map(function (key) {
return stringify(key) + ':['
+ sources[key][0]
+ ',' + stringify(sources[key][1]) + ']'
;
}).join(',')
+ '},{},[' + stringify(skey) + '])'
;
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
return new Worker(URL.createObjectURL(
new Blob([src], { type: 'text/javascript' })
));
};
},{}]},{},[90])(90)
});
|
var binding;
var fs = require('fs');
var path = require('path');
var v8 = 'v8-' + /[0-9]+\.[0-9]+/.exec(process.versions.v8)[0];
var modPath = path.join(__dirname, 'bin', process.platform + '-' + process.arch + '-' + v8, 'binding');
try {
if (fs.realpathSync(__dirname + '/build')) {
// use the build version if it exists
binding = require(__dirname + '/build/Release/binding');
}
} catch (e) {
try {
fs.realpathSync(modPath + '.node');
binding = require(modPath);
} catch (ex) {
// No binary!
throw new Error('`'+ modPath + '.node` is missing. Try reinstalling `node-sass`?');
}
}
var SASS_OUTPUT_STYLE = {
nested: 0,
expanded: 1,
compact: 2,
compressed: 3
};
var SASS_SOURCE_COMMENTS = {
none: 0,
// This is called default in libsass, but is a reserved keyword here
normal: 1,
map: 2
};
var prepareOptions = function(options) {
var paths, style, comments;
options = typeof options !== 'object' ? {} : options;
paths = options.include_paths || options.includePaths || [];
style = SASS_OUTPUT_STYLE[options.output_style || options.outputStyle] || 0;
comments = SASS_SOURCE_COMMENTS[options.source_comments || options.sourceComments] || 0;
return {
paths: paths,
style: style,
comments: comments
};
};
var deprecatedRender = function(css, callback, options) {
options = prepareOptions(options);
var errCallback = function(err) {
callback(err);
};
var oldCallback = function(css) {
callback(null, css);
};
return binding.render(css, oldCallback, errCallback, options.paths.join(':'), options.style, options.comments);
};
var deprecatedRenderSync = function(css, options) {
options = prepareOptions(options);
return binding.renderSync(css, options.paths.join(':'), options.style, options.comments);
};
exports.render = function(options) {
var newOptions;
if (typeof arguments[0] === 'string') {
return deprecatedRender.apply(this, arguments);
}
newOptions = prepareOptions(options);
options.error = options.error || function(){};
if (options.file !== undefined && options.file !== null) {
return binding.renderFile(options.file, options.success, options.error, newOptions.paths.join(path.delimiter), newOptions.style, newOptions.comments, options.sourceMap);
}
//Assume data is present if file is not. binding/libsass will tell the user otherwise!
return binding.render(options.data, options.success, options.error, newOptions.paths.join(path.delimiter), newOptions.style);
};
exports.renderSync = function(options) {
var newOptions;
if (typeof arguments[0] === 'string') {
return deprecatedRenderSync.apply(this, arguments);
}
newOptions = prepareOptions(options);
if (options.file !== undefined && options.file !== null) {
return binding.renderFileSync(options.file, newOptions.paths.join(path.delimiter), newOptions.style, newOptions.comments);
}
//Assume data is present if file is not. binding/libsass will tell the user otherwise!
return binding.renderSync(options.data, newOptions.paths.join(path.delimiter), newOptions.style);
};
exports.middleware = require('./lib/middleware');
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const { Buffer } = require('sdk/io/buffer');
exports.testWriteDouble = helper('writeDoubleBE/writeDoubleLE', function (assert) {
var buffer = new Buffer(16);
buffer.writeDoubleBE(2.225073858507201e-308, 0);
buffer.writeDoubleLE(2.225073858507201e-308, 8);
assert.equal(0x00, buffer[0]);
assert.equal(0x0f, buffer[1]);
assert.equal(0xff, buffer[2]);
assert.equal(0xff, buffer[3]);
assert.equal(0xff, buffer[4]);
assert.equal(0xff, buffer[5]);
assert.equal(0xff, buffer[6]);
assert.equal(0xff, buffer[7]);
assert.equal(0xff, buffer[8]);
assert.equal(0xff, buffer[9]);
assert.equal(0xff, buffer[10]);
assert.equal(0xff, buffer[11]);
assert.equal(0xff, buffer[12]);
assert.equal(0xff, buffer[13]);
assert.equal(0x0f, buffer[14]);
assert.equal(0x00, buffer[15]);
buffer.writeDoubleBE(1.0000000000000004, 0);
buffer.writeDoubleLE(1.0000000000000004, 8);
assert.equal(0x3f, buffer[0]);
assert.equal(0xf0, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x02, buffer[7]);
assert.equal(0x02, buffer[8]);
assert.equal(0x00, buffer[9]);
assert.equal(0x00, buffer[10]);
assert.equal(0x00, buffer[11]);
assert.equal(0x00, buffer[12]);
assert.equal(0x00, buffer[13]);
assert.equal(0xf0, buffer[14]);
assert.equal(0x3f, buffer[15]);
buffer.writeDoubleBE(-2, 0);
buffer.writeDoubleLE(-2, 8);
assert.equal(0xc0, buffer[0]);
assert.equal(0x00, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
assert.equal(0x00, buffer[8]);
assert.equal(0x00, buffer[9]);
assert.equal(0x00, buffer[10]);
assert.equal(0x00, buffer[11]);
assert.equal(0x00, buffer[12]);
assert.equal(0x00, buffer[13]);
assert.equal(0x00, buffer[14]);
assert.equal(0xc0, buffer[15]);
buffer.writeDoubleBE(1.7976931348623157e+308, 0);
buffer.writeDoubleLE(1.7976931348623157e+308, 8);
assert.equal(0x7f, buffer[0]);
assert.equal(0xef, buffer[1]);
assert.equal(0xff, buffer[2]);
assert.equal(0xff, buffer[3]);
assert.equal(0xff, buffer[4]);
assert.equal(0xff, buffer[5]);
assert.equal(0xff, buffer[6]);
assert.equal(0xff, buffer[7]);
assert.equal(0xff, buffer[8]);
assert.equal(0xff, buffer[9]);
assert.equal(0xff, buffer[10]);
assert.equal(0xff, buffer[11]);
assert.equal(0xff, buffer[12]);
assert.equal(0xff, buffer[13]);
assert.equal(0xef, buffer[14]);
assert.equal(0x7f, buffer[15]);
buffer.writeDoubleBE(0 * -1, 0);
buffer.writeDoubleLE(0 * -1, 8);
assert.equal(0x80, buffer[0]);
assert.equal(0x00, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
assert.equal(0x00, buffer[8]);
assert.equal(0x00, buffer[9]);
assert.equal(0x00, buffer[10]);
assert.equal(0x00, buffer[11]);
assert.equal(0x00, buffer[12]);
assert.equal(0x00, buffer[13]);
assert.equal(0x00, buffer[14]);
assert.equal(0x80, buffer[15]);
buffer.writeDoubleBE(Infinity, 0);
buffer.writeDoubleLE(Infinity, 8);
assert.equal(0x7F, buffer[0]);
assert.equal(0xF0, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
assert.equal(0x00, buffer[8]);
assert.equal(0x00, buffer[9]);
assert.equal(0x00, buffer[10]);
assert.equal(0x00, buffer[11]);
assert.equal(0x00, buffer[12]);
assert.equal(0x00, buffer[13]);
assert.equal(0xF0, buffer[14]);
assert.equal(0x7F, buffer[15]);
assert.equal(Infinity, buffer.readDoubleBE(0));
assert.equal(Infinity, buffer.readDoubleLE(8));
buffer.writeDoubleBE(-Infinity, 0);
buffer.writeDoubleLE(-Infinity, 8);
assert.equal(0xFF, buffer[0]);
assert.equal(0xF0, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
assert.equal(0x00, buffer[8]);
assert.equal(0x00, buffer[9]);
assert.equal(0x00, buffer[10]);
assert.equal(0x00, buffer[11]);
assert.equal(0x00, buffer[12]);
assert.equal(0x00, buffer[13]);
assert.equal(0xF0, buffer[14]);
assert.equal(0xFF, buffer[15]);
assert.equal(-Infinity, buffer.readDoubleBE(0));
assert.equal(-Infinity, buffer.readDoubleLE(8));
buffer.writeDoubleBE(NaN, 0);
buffer.writeDoubleLE(NaN, 8);
// Darwin ia32 does the other kind of NaN.
// Compiler bug. No one really cares.
assert.ok(0x7F === buffer[0] || 0xFF === buffer[0]);
assert.equal(0xF8, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
assert.equal(0x00, buffer[8]);
assert.equal(0x00, buffer[9]);
assert.equal(0x00, buffer[10]);
assert.equal(0x00, buffer[11]);
assert.equal(0x00, buffer[12]);
assert.equal(0x00, buffer[13]);
assert.equal(0xF8, buffer[14]);
// Darwin ia32 does the other kind of NaN.
// Compiler bug. No one really cares.
assert.ok(0x7F === buffer[15] || 0xFF === buffer[15]);
assert.ok(isNaN(buffer.readDoubleBE(0)));
assert.ok(isNaN(buffer.readDoubleLE(8)));
});
exports.testWriteFloat = helper('writeFloatBE/writeFloatLE', function (assert) {
var buffer = new Buffer(8);
buffer.writeFloatBE(1, 0);
buffer.writeFloatLE(1, 4);
assert.equal(0x3f, buffer[0]);
assert.equal(0x80, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x80, buffer[6]);
assert.equal(0x3f, buffer[7]);
buffer.writeFloatBE(1 / 3, 0);
buffer.writeFloatLE(1 / 3, 4);
assert.equal(0x3e, buffer[0]);
assert.equal(0xaa, buffer[1]);
assert.equal(0xaa, buffer[2]);
assert.equal(0xab, buffer[3]);
assert.equal(0xab, buffer[4]);
assert.equal(0xaa, buffer[5]);
assert.equal(0xaa, buffer[6]);
assert.equal(0x3e, buffer[7]);
buffer.writeFloatBE(3.4028234663852886e+38, 0);
buffer.writeFloatLE(3.4028234663852886e+38, 4);
assert.equal(0x7f, buffer[0]);
assert.equal(0x7f, buffer[1]);
assert.equal(0xff, buffer[2]);
assert.equal(0xff, buffer[3]);
assert.equal(0xff, buffer[4]);
assert.equal(0xff, buffer[5]);
assert.equal(0x7f, buffer[6]);
assert.equal(0x7f, buffer[7]);
buffer.writeFloatLE(1.1754943508222875e-38, 0);
buffer.writeFloatBE(1.1754943508222875e-38, 4);
assert.equal(0x00, buffer[0]);
assert.equal(0x00, buffer[1]);
assert.equal(0x80, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x80, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
buffer.writeFloatBE(0 * -1, 0);
buffer.writeFloatLE(0 * -1, 4);
assert.equal(0x80, buffer[0]);
assert.equal(0x00, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x80, buffer[7]);
buffer.writeFloatBE(Infinity, 0);
buffer.writeFloatLE(Infinity, 4);
assert.equal(0x7F, buffer[0]);
assert.equal(0x80, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x80, buffer[6]);
assert.equal(0x7F, buffer[7]);
assert.equal(Infinity, buffer.readFloatBE(0));
assert.equal(Infinity, buffer.readFloatLE(4));
buffer.writeFloatBE(-Infinity, 0);
buffer.writeFloatLE(-Infinity, 4);
// Darwin ia32 does the other kind of NaN.
// Compiler bug. No one really cares.
assert.ok(0xFF === buffer[0] || 0x7F === buffer[0]);
assert.equal(0x80, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x80, buffer[6]);
assert.equal(0xFF, buffer[7]);
assert.equal(-Infinity, buffer.readFloatBE(0));
assert.equal(-Infinity, buffer.readFloatLE(4));
buffer.writeFloatBE(NaN, 0);
buffer.writeFloatLE(NaN, 4);
// Darwin ia32 does the other kind of NaN.
// Compiler bug. No one really cares.
assert.ok(0x7F === buffer[0] || 0xFF === buffer[0]);
assert.equal(0xc0, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0xc0, buffer[6]);
// Darwin ia32 does the other kind of NaN.
// Compiler bug. No one really cares.
assert.ok(0x7F === buffer[7] || 0xFF === buffer[7]);
assert.ok(isNaN(buffer.readFloatBE(0)));
assert.ok(isNaN(buffer.readFloatLE(4)));
});
exports.testWriteInt8 = helper('writeInt8', function (assert) {
var buffer = new Buffer(2);
buffer.writeInt8(0x23, 0);
buffer.writeInt8(-5, 1);
assert.equal(0x23, buffer[0]);
assert.equal(0xfb, buffer[1]);
/* Make sure we handle truncation correctly */
assert.throws(function() {
buffer.writeInt8(0xabc, 0);
});
assert.throws(function() {
buffer.writeInt8(0xabc, 0);
});
/* Make sure we handle min/max correctly */
buffer.writeInt8(0x7f, 0);
buffer.writeInt8(-0x80, 1);
assert.equal(0x7f, buffer[0]);
assert.equal(0x80, buffer[1]);
assert.throws(function() {
buffer.writeInt8(0x7f + 1, 0);
});
assert.throws(function() {
buffer.writeInt8(-0x80 - 1, 0);
});
});
exports.testWriteInt16 = helper('writeInt16LE/writeInt16BE', function (assert) {
var buffer = new Buffer(6);
buffer.writeInt16BE(0x0023, 0);
buffer.writeInt16LE(0x0023, 2);
assert.equal(0x00, buffer[0]);
assert.equal(0x23, buffer[1]);
assert.equal(0x23, buffer[2]);
assert.equal(0x00, buffer[3]);
buffer.writeInt16BE(-5, 0);
buffer.writeInt16LE(-5, 2);
assert.equal(0xff, buffer[0]);
assert.equal(0xfb, buffer[1]);
assert.equal(0xfb, buffer[2]);
assert.equal(0xff, buffer[3]);
buffer.writeInt16BE(-1679, 1);
buffer.writeInt16LE(-1679, 3);
assert.equal(0xf9, buffer[1]);
assert.equal(0x71, buffer[2]);
assert.equal(0x71, buffer[3]);
assert.equal(0xf9, buffer[4]);
/* Make sure we handle min/max correctly */
buffer.writeInt16BE(0x7fff, 0);
buffer.writeInt16BE(-0x8000, 2);
assert.equal(0x7f, buffer[0]);
assert.equal(0xff, buffer[1]);
assert.equal(0x80, buffer[2]);
assert.equal(0x00, buffer[3]);
assert.throws(function() {
buffer.writeInt16BE(0x7fff + 1, 0);
});
assert.throws(function() {
buffer.writeInt16BE(-0x8000 - 1, 0);
});
buffer.writeInt16LE(0x7fff, 0);
buffer.writeInt16LE(-0x8000, 2);
assert.equal(0xff, buffer[0]);
assert.equal(0x7f, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x80, buffer[3]);
assert.throws(function() {
buffer.writeInt16LE(0x7fff + 1, 0);
});
assert.throws(function() {
buffer.writeInt16LE(-0x8000 - 1, 0);
});
});
exports.testWriteInt32 = helper('writeInt32BE/writeInt32LE', function (assert) {
var buffer = new Buffer(8);
buffer.writeInt32BE(0x23, 0);
buffer.writeInt32LE(0x23, 4);
assert.equal(0x00, buffer[0]);
assert.equal(0x00, buffer[1]);
assert.equal(0x00, buffer[2]);
assert.equal(0x23, buffer[3]);
assert.equal(0x23, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
buffer.writeInt32BE(-5, 0);
buffer.writeInt32LE(-5, 4);
assert.equal(0xff, buffer[0]);
assert.equal(0xff, buffer[1]);
assert.equal(0xff, buffer[2]);
assert.equal(0xfb, buffer[3]);
assert.equal(0xfb, buffer[4]);
assert.equal(0xff, buffer[5]);
assert.equal(0xff, buffer[6]);
assert.equal(0xff, buffer[7]);
buffer.writeInt32BE(-805306713, 0);
buffer.writeInt32LE(-805306713, 4);
assert.equal(0xcf, buffer[0]);
assert.equal(0xff, buffer[1]);
assert.equal(0xfe, buffer[2]);
assert.equal(0xa7, buffer[3]);
assert.equal(0xa7, buffer[4]);
assert.equal(0xfe, buffer[5]);
assert.equal(0xff, buffer[6]);
assert.equal(0xcf, buffer[7]);
/* Make sure we handle min/max correctly */
buffer.writeInt32BE(0x7fffffff, 0);
buffer.writeInt32BE(-0x80000000, 4);
assert.equal(0x7f, buffer[0]);
assert.equal(0xff, buffer[1]);
assert.equal(0xff, buffer[2]);
assert.equal(0xff, buffer[3]);
assert.equal(0x80, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x00, buffer[7]);
assert.throws(function() {
buffer.writeInt32BE(0x7fffffff + 1, 0);
});
assert.throws(function() {
buffer.writeInt32BE(-0x80000000 - 1, 0);
});
buffer.writeInt32LE(0x7fffffff, 0);
buffer.writeInt32LE(-0x80000000, 4);
assert.equal(0xff, buffer[0]);
assert.equal(0xff, buffer[1]);
assert.equal(0xff, buffer[2]);
assert.equal(0x7f, buffer[3]);
assert.equal(0x00, buffer[4]);
assert.equal(0x00, buffer[5]);
assert.equal(0x00, buffer[6]);
assert.equal(0x80, buffer[7]);
assert.throws(function() {
buffer.writeInt32LE(0x7fffffff + 1, 0);
});
assert.throws(function() {
buffer.writeInt32LE(-0x80000000 - 1, 0);
});
});
/*
* We need to check the following things:
* - We are correctly resolving big endian (doesn't mean anything for 8 bit)
* - Correctly resolving little endian (doesn't mean anything for 8 bit)
* - Correctly using the offsets
* - Correctly interpreting values that are beyond the signed range as unsigned
*/
exports.testWriteUInt8 = helper('writeUInt8', function (assert) {
var data = new Buffer(4);
data.writeUInt8(23, 0);
data.writeUInt8(23, 1);
data.writeUInt8(23, 2);
data.writeUInt8(23, 3);
assert.equal(23, data[0]);
assert.equal(23, data[1]);
assert.equal(23, data[2]);
assert.equal(23, data[3]);
data.writeUInt8(23, 0);
data.writeUInt8(23, 1);
data.writeUInt8(23, 2);
data.writeUInt8(23, 3);
assert.equal(23, data[0]);
assert.equal(23, data[1]);
assert.equal(23, data[2]);
assert.equal(23, data[3]);
data.writeUInt8(255, 0);
assert.equal(255, data[0]);
data.writeUInt8(255, 0);
assert.equal(255, data[0]);
});
exports.testWriteUInt16 = helper('writeUInt16BE/writeUInt16LE', function (assert) {
var value = 0x2343;
var data = new Buffer(4);
data.writeUInt16BE(value, 0);
assert.equal(0x23, data[0]);
assert.equal(0x43, data[1]);
data.writeUInt16BE(value, 1);
assert.equal(0x23, data[1]);
assert.equal(0x43, data[2]);
data.writeUInt16BE(value, 2);
assert.equal(0x23, data[2]);
assert.equal(0x43, data[3]);
data.writeUInt16LE(value, 0);
assert.equal(0x23, data[1]);
assert.equal(0x43, data[0]);
data.writeUInt16LE(value, 1);
assert.equal(0x23, data[2]);
assert.equal(0x43, data[1]);
data.writeUInt16LE(value, 2);
assert.equal(0x23, data[3]);
assert.equal(0x43, data[2]);
value = 0xff80;
data.writeUInt16LE(value, 0);
assert.equal(0xff, data[1]);
assert.equal(0x80, data[0]);
data.writeUInt16BE(value, 0);
assert.equal(0xff, data[0]);
assert.equal(0x80, data[1]);
});
exports.testWriteUInt32 = helper('writeUInt32BE/writeUInt32LE', function (assert) {
var data = new Buffer(6);
var value = 0xe7f90a6d;
data.writeUInt32BE(value, 0);
assert.equal(0xe7, data[0]);
assert.equal(0xf9, data[1]);
assert.equal(0x0a, data[2]);
assert.equal(0x6d, data[3]);
data.writeUInt32BE(value, 1);
assert.equal(0xe7, data[1]);
assert.equal(0xf9, data[2]);
assert.equal(0x0a, data[3]);
assert.equal(0x6d, data[4]);
data.writeUInt32BE(value, 2);
assert.equal(0xe7, data[2]);
assert.equal(0xf9, data[3]);
assert.equal(0x0a, data[4]);
assert.equal(0x6d, data[5]);
data.writeUInt32LE(value, 0);
assert.equal(0xe7, data[3]);
assert.equal(0xf9, data[2]);
assert.equal(0x0a, data[1]);
assert.equal(0x6d, data[0]);
data.writeUInt32LE(value, 1);
assert.equal(0xe7, data[4]);
assert.equal(0xf9, data[3]);
assert.equal(0x0a, data[2]);
assert.equal(0x6d, data[1]);
data.writeUInt32LE(value, 2);
assert.equal(0xe7, data[5]);
assert.equal(0xf9, data[4]);
assert.equal(0x0a, data[3]);
assert.equal(0x6d, data[2]);
});
function helper (description, fn) {
return function (assert) {
let bulkAssert = {
equal: function (a, b) {
if (a !== b) throw new Error('Error found in ' + description);
},
ok: function (value) {
if (!value) throw new Error('Error found in ' + description);
},
/*
* TODO
* There should be errors when setting outside of the value range
* of the data type (like writeInt8 with value of 1000), but DataView
* does not throw; seems to just grab the appropriate max bits.
* So ignoring this test for now
*/
throws: function (shouldThrow) {
assert.pass(description + ': Need to implement error handling for setting buffer values ' +
'outside of the data types\' range.');
/*
let didItThrow = false;
try {
shouldThrow();
} catch (e) {
didItThrow = e;
}
if (!didItThrow)
throw new Error('Error found in ' + description + ': ' + shouldThrow + ' should have thrown');
*/
}
};
fn(bulkAssert);
// If we get here, no errors thrown
assert.pass('All tests passed for ' + description);
};
}
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom"));
else
root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_5__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _BootstrapTable = __webpack_require__(1);
var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable);
var _TableHeaderColumn = __webpack_require__(41);
var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn);
if (typeof window !== 'undefined') {
window.BootstrapTable = _BootstrapTable2['default'];
window.TableHeaderColumn = _TableHeaderColumn2['default'];
}
exports.BootstrapTable = _BootstrapTable2['default'];
exports.TableHeaderColumn = _TableHeaderColumn2['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/* eslint no-alert: 0 */
/* eslint max-len: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _TableHeader = __webpack_require__(4);
var _TableHeader2 = _interopRequireDefault(_TableHeader);
var _TableBody = __webpack_require__(8);
var _TableBody2 = _interopRequireDefault(_TableBody);
var _paginationPaginationList = __webpack_require__(29);
var _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList);
var _toolbarToolBar = __webpack_require__(31);
var _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar);
var _TableFilter = __webpack_require__(32);
var _TableFilter2 = _interopRequireDefault(_TableFilter);
var _storeTableDataStore = __webpack_require__(33);
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
var _csv_export_util = __webpack_require__(35);
var _csv_export_util2 = _interopRequireDefault(_csv_export_util);
var _Filter = __webpack_require__(39);
var BootstrapTable = (function (_Component) {
_inherits(BootstrapTable, _Component);
function BootstrapTable(props) {
var _this = this;
_classCallCheck(this, BootstrapTable);
_get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props);
this.handleSort = function (order, sortField) {
if (_this.props.options.onSortChange) {
_this.props.options.onSortChange(sortField, order, _this.props);
}
var result = _this.store.sort(order, sortField).get();
_this.setState({
data: result
});
};
this.handlePaginationData = function (page, sizePerPage) {
var onPageChange = _this.props.options.onPageChange;
if (onPageChange) {
onPageChange(page, sizePerPage);
}
if (_this.isRemoteDataSource()) {
return;
}
var result = _this.store.page(page, sizePerPage).get();
_this.setState({
data: result,
currPage: page,
sizePerPage: sizePerPage
});
};
this.handleMouseLeave = function () {
if (_this.props.options.onMouseLeave) {
_this.props.options.onMouseLeave();
}
};
this.handleMouseEnter = function () {
if (_this.props.options.onMouseEnter) {
_this.props.options.onMouseEnter();
}
};
this.handleRowMouseOut = function (row, event) {
if (_this.props.options.onRowMouseOut) {
_this.props.options.onRowMouseOut(row, event);
}
};
this.handleRowMouseOver = function (row, event) {
if (_this.props.options.onRowMouseOver) {
_this.props.options.onRowMouseOver(row, event);
}
};
this.handleRowClick = function (row) {
if (_this.props.options.onRowClick) {
_this.props.options.onRowClick(row);
}
};
this.handleSelectAllRow = function (e) {
var isSelected = e.currentTarget.checked;
var selectedRowKeys = [];
var result = true;
if (_this.props.selectRow.onSelectAll) {
result = _this.props.selectRow.onSelectAll(isSelected, isSelected ? _this.store.get() : []);
}
if (typeof result === 'undefined' || result !== false) {
if (isSelected) {
selectedRowKeys = _this.store.getAllRowkey();
}
_this.store.setSelectedRowKey(selectedRowKeys);
_this.setState({ selectedRowKeys: selectedRowKeys });
}
};
this.handleShowOnlySelected = function () {
_this.store.ignoreNonSelected();
var result = undefined;
if (_this.props.pagination) {
result = _this.store.page(1, _this.state.sizePerPage).get();
} else {
result = _this.store.get();
}
_this.setState({
data: result,
currPage: 1
});
};
this.handleSelectRow = function (row, isSelected) {
var result = true;
var currSelected = _this.store.getSelectedRowKeys();
var rowKey = row[_this.store.getKeyField()];
var selectRow = _this.props.selectRow;
if (selectRow.onSelect) {
result = selectRow.onSelect(row, isSelected);
}
if (typeof result === 'undefined' || result !== false) {
if (selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) {
currSelected = isSelected ? [rowKey] : [];
} else {
if (isSelected) {
currSelected.push(rowKey);
} else {
currSelected = currSelected.filter(function (key) {
return rowKey !== key;
});
}
}
_this.store.setSelectedRowKey(currSelected);
_this.setState({
selectedRowKeys: currSelected
});
}
};
this.handleAddRow = function (newObj) {
try {
_this.store.add(newObj);
} catch (e) {
return e;
}
_this._handleAfterAddingRow(newObj);
};
this.getPageByRowKey = function (rowKey) {
var sizePerPage = _this.state.sizePerPage;
var currentData = _this.store.getCurrentDisplayData();
var keyField = _this.store.getKeyField();
var result = currentData.findIndex(function (x) {
return x[keyField] === rowKey;
});
if (result > -1) {
return parseInt(result / sizePerPage, 10) + 1;
} else {
return result;
}
};
this.handleDropRow = function (rowKeys) {
var dropRowKeys = rowKeys ? rowKeys : _this.store.getSelectedRowKeys();
// add confirm before the delete action if that option is set.
if (dropRowKeys && dropRowKeys.length > 0) {
if (_this.props.options.handleConfirmDeleteRow) {
_this.props.options.handleConfirmDeleteRow(function () {
_this.deleteRow(dropRowKeys);
}, dropRowKeys);
} else if (confirm('Are you sure want delete?')) {
_this.deleteRow(dropRowKeys);
}
}
};
this.handleFilterData = function (filterObj) {
_this.store.filter(filterObj);
var result = undefined;
if (_this.props.pagination) {
var sizePerPage = _this.state.sizePerPage;
result = _this.store.page(1, sizePerPage).get();
} else {
result = _this.store.get();
}
if (_this.props.options.afterColumnFilter) {
_this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination());
}
_this.setState({
data: result,
currPage: 1
});
};
this.handleExportCSV = function () {
var result = _this.store.getDataIgnoringPagination();
var keys = [];
_this.props.children.map(function (column) {
if (column.props.hidden === false) {
keys.push(column.props.dataField);
}
});
(0, _csv_export_util2['default'])(result, keys, _this.props.csvFileName);
};
this.handleSearch = function (searchText) {
_this.store.search(searchText);
var result = undefined;
if (_this.props.pagination) {
var sizePerPage = _this.state.sizePerPage;
result = _this.store.page(1, sizePerPage).get();
} else {
result = _this.store.get();
}
if (_this.props.options.afterSearch) {
_this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination());
}
_this.setState({
data: result,
currPage: 1
});
};
this._scrollHeader = function (e) {
_this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft;
};
this._adjustTable = function () {
_this._adjustHeaderWidth();
_this._adjustHeight();
};
this._adjustHeaderWidth = function () {
var header = _this.refs.header.refs.header;
var headerContainer = _this.refs.header.refs.container;
var tbody = _this.refs.body.refs.tbody;
var firstRow = tbody.childNodes[0];
var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth;
var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0;
if (firstRow && _this.store.getDataNum()) {
var cells = firstRow.childNodes;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var computedStyle = getComputedStyle(cell);
var width = parseFloat(computedStyle.width.replace('px', ''));
if (_this.isIE) {
var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', ''));
var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', ''));
var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', ''));
var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', ''));
width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth;
}
var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0;
if (width <= 0) {
width = 120;
cell.width = width + lastPadding + 'px';
}
var result = width + lastPadding + 'px';
header.childNodes[i].style.width = result;
header.childNodes[i].style.minWidth = result;
}
}
};
this._adjustHeight = function () {
if (_this.props.height.indexOf('%') === -1) {
_this.refs.body.refs.container.style.height = parseFloat(_this.props.height, 10) - _this.refs.header.refs.container.offsetHeight + 'px';
}
};
this.isIE = false;
this._attachCellEditFunc();
if (_util2['default'].canUseDOM()) {
this.isIE = document.documentMode;
}
this.store = new _storeTableDataStore.TableDataStore(this.props.data.slice());
this.initTable(this.props);
if (this.filter) {
this.filter.on('onFilterChange', function (currentFilter) {
_this.handleFilterData(currentFilter);
});
}
if (this.props.selectRow && this.props.selectRow.selected) {
var copy = this.props.selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
}
this.state = {
data: this.getTableData(),
currPage: this.props.options.page || 1,
sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0],
selectedRowKeys: this.store.getSelectedRowKeys()
};
}
_createClass(BootstrapTable, [{
key: 'initTable',
value: function initTable(props) {
var _this2 = this;
var keyField = props.keyField;
var isKeyFieldDefined = typeof keyField === 'string' && keyField.length;
_react2['default'].Children.forEach(props.children, function (column) {
if (column.props.isKey) {
if (keyField) {
throw 'Error. Multiple key column be detected in TableHeaderColumn.';
}
keyField = column.props.dataField;
}
if (column.props.filter) {
// a column contains a filter
if (!_this2.filter) {
// first time create the filter on the BootstrapTable
_this2.filter = new _Filter.Filter();
}
// pass the filter to column with filter
column.props.filter.emitter = _this2.filter;
}
});
var colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) {
prev[curr.name] = curr;
return prev;
}, {});
if (!isKeyFieldDefined && !keyField) {
throw 'Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.';
}
this.store.setProps({
isPagination: props.pagination,
keyField: keyField,
colInfos: colInfos,
multiColumnSearch: props.multiColumnSearch,
remote: this.isRemoteDataSource()
});
}
}, {
key: 'getTableData',
value: function getTableData() {
var _props = this.props;
var options = _props.options;
var pagination = _props.pagination;
var result = [];
if (options.sortName && options.sortOrder) {
this.store.sort(options.sortOrder, options.sortName);
}
if (pagination) {
var page = undefined;
var sizePerPage = undefined;
if (this.store.isChangedPage()) {
sizePerPage = this.state.sizePerPage;
page = this.state.currPage;
} else {
sizePerPage = options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0];
page = options.page || 1;
}
result = this.store.page(page, sizePerPage).get();
} else {
result = this.store.get();
}
return result;
}
}, {
key: 'getColumnsDescription',
value: function getColumnsDescription(_ref) {
var children = _ref.children;
return _react2['default'].Children.map(children, function (column, i) {
return {
name: column.props.dataField,
align: column.props.dataAlign,
sort: column.props.dataSort,
format: column.props.dataFormat,
formatExtraData: column.props.formatExtraData,
filterFormatted: column.props.filterFormatted,
editable: column.props.editable,
hidden: column.props.hidden,
searchable: column.props.searchable,
className: column.props.columnClassName,
width: column.props.width,
text: column.props.children,
sortFunc: column.props.sortFunc,
sortFuncExtraData: column.props.sortFuncExtraData,
index: i
};
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.initTable(nextProps);
var options = nextProps.options;
var selectRow = nextProps.selectRow;
this.store.setData(nextProps.data.slice());
var page = options.page || this.state.currPage;
var sizePerPage = options.sizePerPage || this.state.sizePerPage;
// #125
if (!options.page && page >= Math.ceil(nextProps.data.length / sizePerPage)) {
page = 1;
}
var sortInfo = this.store.getSortInfo();
var sortField = options.sortName || (sortInfo ? sortInfo.sortField : undefined);
var sortOrder = options.sortOrder || (sortInfo ? sortInfo.order : undefined);
if (sortField && sortOrder) this.store.sort(sortOrder, sortField);
var data = this.store.page(page, sizePerPage).get();
this.setState({
data: data,
currPage: page,
sizePerPage: sizePerPage
});
if (selectRow && selectRow.selected) {
// set default select rows to store.
var copy = selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
this.setState({
selectedRowKeys: copy
});
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this._adjustTable();
window.addEventListener('resize', this._adjustTable);
this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
window.removeEventListener('resize', this._adjustTable);
this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader);
if (this.filter) {
this.filter.removeAllListeners('onFilterChange');
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this._adjustTable();
this._attachCellEditFunc();
if (this.props.options.afterTableComplete) {
this.props.options.afterTableComplete();
}
}
}, {
key: '_attachCellEditFunc',
value: function _attachCellEditFunc() {
var cellEdit = this.props.cellEdit;
if (cellEdit) {
this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this);
if (cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) {
this.props.selectRow.clickToSelect = false;
}
}
}
/**
* Returns true if in the current configuration,
* the datagrid should load its data remotely.
*
* @param {Object} [props] Optional. If not given, this.props will be used
* @return {Boolean}
*/
}, {
key: 'isRemoteDataSource',
value: function isRemoteDataSource(props) {
return (props || this.props).remote;
}
}, {
key: 'render',
value: function render() {
var style = {
height: this.props.height,
maxHeight: this.props.maxHeight
};
var columns = this.getColumnsDescription(this.props);
var sortInfo = this.store.getSortInfo();
var pagination = this.renderPagination();
var toolBar = this.renderToolBar();
var tableFilter = this.renderTableFilter(columns);
var isSelectAll = this.isSelectAll();
var sortIndicator = this.props.options.sortIndicator;
if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true;
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-container' },
toolBar,
_react2['default'].createElement(
'div',
{ className: 'react-bs-table', ref: 'table', style: style,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave },
_react2['default'].createElement(
_TableHeader2['default'],
{
ref: 'header',
rowSelectType: this.props.selectRow.mode,
hideSelectColumn: this.props.selectRow.hideSelectColumn,
sortName: sortInfo ? sortInfo.sortField : undefined,
sortOrder: sortInfo ? sortInfo.order : undefined,
sortIndicator: sortIndicator,
onSort: this.handleSort,
onSelectAllRow: this.handleSelectAllRow,
bordered: this.props.bordered,
condensed: this.props.condensed,
isFiltered: this.filter ? true : false,
isSelectAll: isSelectAll },
this.props.children
),
_react2['default'].createElement(_TableBody2['default'], { ref: 'body',
style: style,
data: this.state.data,
columns: columns,
trClassName: this.props.trClassName,
striped: this.props.striped,
bordered: this.props.bordered,
hover: this.props.hover,
keyField: this.store.getKeyField(),
condensed: this.props.condensed,
selectRow: this.props.selectRow,
cellEdit: this.props.cellEdit,
selectedRowKeys: this.state.selectedRowKeys,
onRowClick: this.handleRowClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow,
noDataText: this.props.options.noDataText })
),
tableFilter,
pagination
);
}
}, {
key: 'isSelectAll',
value: function isSelectAll() {
var defaultSelectRowKeys = this.store.getSelectedRowKeys();
var allRowKeys = this.store.getAllRowkey();
if (defaultSelectRowKeys.length !== allRowKeys.length) {
return defaultSelectRowKeys.length === 0 ? false : 'indeterminate';
} else {
if (this.store.isEmpty()) {
return false;
}
return true;
}
}
}, {
key: 'cleanSelected',
value: function cleanSelected() {
this.store.setSelectedRowKey([]);
this.setState({
selectedRowKeys: []
});
}
}, {
key: 'handleEditCell',
value: function handleEditCell(newVal, rowIndex, colIndex) {
var _props$cellEdit = this.props.cellEdit;
var beforeSaveCell = _props$cellEdit.beforeSaveCell;
var afterSaveCell = _props$cellEdit.afterSaveCell;
var fieldName = undefined;
_react2['default'].Children.forEach(this.props.children, function (column, i) {
if (i === colIndex) {
fieldName = column.props.dataField;
return false;
}
});
if (beforeSaveCell) {
var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal);
if (!isValid && typeof isValid !== 'undefined') {
this.setState({
data: this.store.get()
});
return;
}
}
var result = this.store.edit(newVal, rowIndex, fieldName).get();
this.setState({
data: result
});
if (afterSaveCell) {
afterSaveCell(this.state.data[rowIndex], fieldName, newVal);
}
}
}, {
key: 'handleAddRowAtBegin',
value: function handleAddRowAtBegin(newObj) {
try {
this.store.addAtBegin(newObj);
} catch (e) {
return e;
}
this._handleAfterAddingRow(newObj);
}
}, {
key: 'getSizePerPage',
value: function getSizePerPage() {
return this.state.sizePerPage;
}
}, {
key: 'getCurrentPage',
value: function getCurrentPage() {
return this.state.currPage;
}
}, {
key: 'deleteRow',
value: function deleteRow(dropRowKeys) {
var result = undefined;
this.store.remove(dropRowKeys); // remove selected Row
this.store.setSelectedRowKey([]); // clear selected row key
if (this.props.pagination) {
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
var currPage = this.state.currPage;
if (currPage > currLastPage) currPage = currLastPage;
result = this.store.page(currPage, sizePerPage).get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys(),
currPage: currPage
});
} else {
result = this.store.get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys()
});
}
if (this.props.options.afterDeleteRow) {
this.props.options.afterDeleteRow(dropRowKeys);
}
}
}, {
key: 'renderPagination',
value: function renderPagination() {
if (this.props.pagination) {
var dataSize = undefined;
if (this.isRemoteDataSource()) {
dataSize = this.props.fetchInfo.dataTotalSize;
} else {
dataSize = this.store.getDataNum();
}
var options = this.props.options;
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-pagination' },
_react2['default'].createElement(_paginationPaginationList2['default'], {
ref: 'pagination',
currPage: this.state.currPage,
changePage: this.handlePaginationData,
sizePerPage: this.state.sizePerPage,
sizePerPageList: options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST,
paginationSize: options.paginationSize || _Const2['default'].PAGINATION_SIZE,
remote: this.isRemoteDataSource(),
dataSize: dataSize,
onSizePerPageList: options.onSizePerPageList,
prePage: options.prePage || _Const2['default'].PRE_PAGE,
nextPage: options.nextPage || _Const2['default'].NEXT_PAGE,
firstPage: options.firstPage || _Const2['default'].FIRST_PAGE,
lastPage: options.lastPage || _Const2['default'].LAST_PAGE })
);
}
return null;
}
}, {
key: 'renderToolBar',
value: function renderToolBar() {
var _props2 = this.props;
var selectRow = _props2.selectRow;
var insertRow = _props2.insertRow;
var deleteRow = _props2.deleteRow;
var search = _props2.search;
var children = _props2.children;
var enableShowOnlySelected = selectRow && selectRow.showOnlySelected;
if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) {
var columns = undefined;
if (Array.isArray(children)) {
columns = children.map(function (column) {
var props = column.props;
return {
name: props.children,
field: props.dataField,
// when you want same auto generate value and not allow edit, example ID field
autoValue: props.autoValue || false,
// for create editor, no params for column.editable() indicate that editor for new row
editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable,
format: props.dataFormat ? function (value) {
return props.dataFormat(value, null, props.formatExtraData).replace(/<.*?>/g, '');
} : false
};
});
} else {
columns = [{
name: children.props.children,
field: children.props.dataField,
editable: children.props.editable
}];
}
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-tool-bar' },
_react2['default'].createElement(_toolbarToolBar2['default'], {
clearSearch: this.props.options.clearSearch,
searchDelayTime: this.props.options.searchDelayTime,
enableInsert: insertRow,
enableDelete: deleteRow,
enableSearch: search,
enableExportCSV: this.props.exportCSV,
enableShowOnlySelected: enableShowOnlySelected,
columns: columns,
searchPlaceholder: this.props.searchPlaceholder,
exportCSVText: this.props.options.exportCSVText,
ignoreEditable: this.props.options.ignoreEditable,
onAddRow: this.handleAddRow,
onDropRow: this.handleDropRow,
onSearch: this.handleSearch,
onExportCSV: this.handleExportCSV,
onShowOnlySelected: this.handleShowOnlySelected })
);
} else {
return null;
}
}
}, {
key: 'renderTableFilter',
value: function renderTableFilter(columns) {
if (this.props.columnFilter) {
return _react2['default'].createElement(_TableFilter2['default'], { columns: columns,
rowSelectType: this.props.selectRow.mode,
onFilter: this.handleFilterData });
} else {
return null;
}
}
}, {
key: '_handleAfterAddingRow',
value: function _handleAfterAddingRow(newObj) {
var result = undefined;
if (this.props.pagination) {
// if pagination is enabled and insert row be trigger, change to last page
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
result = this.store.page(currLastPage, sizePerPage).get();
this.setState({
data: result,
currPage: currLastPage
});
} else {
result = this.store.get();
this.setState({
data: result
});
}
if (this.props.options.afterInsertRow) {
this.props.options.afterInsertRow(newObj);
}
}
}]);
return BootstrapTable;
})(_react.Component);
BootstrapTable.propTypes = {
keyField: _react.PropTypes.string,
height: _react.PropTypes.string,
maxHeight: _react.PropTypes.string,
data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]),
remote: _react.PropTypes.bool, // remote data, default is false
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
pagination: _react.PropTypes.bool,
searchPlaceholder: _react.PropTypes.string,
selectRow: _react.PropTypes.shape({
mode: _react.PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]),
bgColor: _react.PropTypes.string,
selected: _react.PropTypes.array,
onSelect: _react.PropTypes.func,
onSelectAll: _react.PropTypes.func,
clickToSelect: _react.PropTypes.bool,
hideSelectColumn: _react.PropTypes.bool,
clickToSelectAndEditCell: _react.PropTypes.bool,
showOnlySelected: _react.PropTypes.bool
}),
cellEdit: _react.PropTypes.shape({
mode: _react.PropTypes.string,
blurToSave: _react.PropTypes.bool,
beforeSaveCell: _react.PropTypes.func,
afterSaveCell: _react.PropTypes.func
}),
insertRow: _react.PropTypes.bool,
deleteRow: _react.PropTypes.bool,
search: _react.PropTypes.bool,
columnFilter: _react.PropTypes.bool,
trClassName: _react.PropTypes.any,
options: _react.PropTypes.shape({
clearSearch: _react.PropTypes.bool,
sortName: _react.PropTypes.string,
sortOrder: _react.PropTypes.string,
sortIndicator: _react.PropTypes.bool,
afterTableComplete: _react.PropTypes.func,
afterDeleteRow: _react.PropTypes.func,
afterInsertRow: _react.PropTypes.func,
afterSearch: _react.PropTypes.func,
afterColumnFilter: _react.PropTypes.func,
onRowClick: _react.PropTypes.func,
page: _react.PropTypes.number,
sizePerPageList: _react.PropTypes.array,
sizePerPage: _react.PropTypes.number,
paginationSize: _react.PropTypes.number,
onSortChange: _react.PropTypes.func,
onPageChange: _react.PropTypes.func,
onSizePerPageList: _react.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
handleConfirmDeleteRow: _react.PropTypes.func,
prePage: _react.PropTypes.string,
nextPage: _react.PropTypes.string,
firstPage: _react.PropTypes.string,
lastPage: _react.PropTypes.string,
searchDelayTime: _react.PropTypes.number,
exportCSVText: _react.PropTypes.text,
ignoreEditable: _react.PropTypes.bool
}),
fetchInfo: _react.PropTypes.shape({
dataTotalSize: _react.PropTypes.number
}),
exportCSV: _react.PropTypes.bool,
csvFileName: _react.PropTypes.string
};
BootstrapTable.defaultProps = {
height: '100%',
maxHeight: undefined,
striped: false,
bordered: true,
hover: false,
condensed: false,
pagination: false,
searchPlaceholder: undefined,
selectRow: {
mode: _Const2['default'].ROW_SELECT_NONE,
bgColor: _Const2['default'].ROW_SELECT_BG_COLOR,
selected: [],
onSelect: undefined,
onSelectAll: undefined,
clickToSelect: false,
hideSelectColumn: false,
clickToSelectAndEditCell: false,
showOnlySelected: false
},
cellEdit: {
mode: _Const2['default'].CELL_EDIT_NONE,
blurToSave: false,
beforeSaveCell: undefined,
afterSaveCell: undefined
},
insertRow: false,
deleteRow: false,
search: false,
multiColumnSearch: false,
columnFilter: false,
trClassName: '',
options: {
clearSearch: false,
sortName: undefined,
sortOrder: undefined,
sortIndicator: true,
afterTableComplete: undefined,
afterDeleteRow: undefined,
afterInsertRow: undefined,
afterSearch: undefined,
afterColumnFilter: undefined,
onRowClick: undefined,
onMouseLeave: undefined,
onMouseEnter: undefined,
onRowMouseOut: undefined,
onRowMouseOver: undefined,
page: undefined,
sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST,
sizePerPage: undefined,
paginationSize: _Const2['default'].PAGINATION_SIZE,
onSizePerPageList: undefined,
noDataText: undefined,
handleConfirmDeleteRow: undefined,
prePage: _Const2['default'].PRE_PAGE,
nextPage: _Const2['default'].NEXT_PAGE,
firstPage: _Const2['default'].FIRST_PAGE,
lastPage: _Const2['default'].LAST_PAGE,
searchDelayTime: undefined,
exportCSVText: _Const2['default'].EXPORT_CSV_TEXT,
ignoreEditable: false
},
fetchInfo: {
dataTotalSize: 0
},
exportCSV: false,
csvFileName: undefined
};
exports['default'] = BootstrapTable;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = {
SORT_DESC: 'desc',
SORT_ASC: 'asc',
SIZE_PER_PAGE: 10,
NEXT_PAGE: '>',
LAST_PAGE: '>>',
PRE_PAGE: '<',
FIRST_PAGE: '<<',
ROW_SELECT_BG_COLOR: '',
ROW_SELECT_NONE: 'none',
ROW_SELECT_SINGLE: 'radio',
ROW_SELECT_MULTI: 'checkbox',
CELL_EDIT_NONE: 'none',
CELL_EDIT_CLICK: 'click',
CELL_EDIT_DBCLICK: 'dbclick',
SIZE_PER_PAGE_LIST: [10, 25, 30, 50],
PAGINATION_SIZE: 5,
NO_DATA_TEXT: 'There is no data to display',
SHOW_ONLY_SELECT: 'Show Selected Only',
SHOW_ALL: 'Show All',
EXPORT_CSV_TEXT: 'Export to CSV',
FILTER_DELAY: 500,
FILTER_TYPE: {
TEXT: 'TextFilter',
REGEX: 'RegexFilter',
SELECT: 'SelectFilter',
NUMBER: 'NumberFilter',
DATE: 'DateFilter',
CUSTOM: 'CustomFilter'
}
};
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _SelectRowHeaderColumn = __webpack_require__(7);
var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn);
var Checkbox = (function (_Component) {
_inherits(Checkbox, _Component);
function Checkbox() {
_classCallCheck(this, Checkbox);
_get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Checkbox, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.update(this.props.checked);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
this.update(props.checked);
}
}, {
key: 'update',
value: function update(checked) {
_reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate';
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('input', { className: 'react-bs-select-all',
type: 'checkbox',
checked: this.props.checked,
onChange: this.props.onChange });
}
}]);
return Checkbox;
})(_react.Component);
var TableHeader = (function (_Component2) {
_inherits(TableHeader, _Component2);
function TableHeader() {
_classCallCheck(this, TableHeader);
_get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(TableHeader, [{
key: 'render',
value: function render() {
var containerClasses = (0, _classnames2['default'])('react-bs-container-header', 'table-header-wrapper');
var tableClasses = (0, _classnames2['default'])('table', 'table-hover', {
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed
});
var selectRowHeaderCol = null;
if (!this.props.hideSelectColumn) selectRowHeaderCol = this.renderSelectRowHeader();
this._attachClearSortCaretFunc();
return _react2['default'].createElement(
'div',
{ ref: 'container', className: containerClasses },
_react2['default'].createElement(
'table',
{ className: tableClasses },
_react2['default'].createElement(
'thead',
null,
_react2['default'].createElement(
'tr',
{ ref: 'header' },
selectRowHeaderCol,
this.props.children
)
)
)
);
}
}, {
key: 'renderSelectRowHeader',
value: function renderSelectRowHeader() {
if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_SINGLE) {
return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null);
} else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_MULTI) {
return _react2['default'].createElement(
_SelectRowHeaderColumn2['default'],
null,
_react2['default'].createElement(Checkbox, {
onChange: this.props.onSelectAllRow,
checked: this.props.isSelectAll })
);
} else {
return null;
}
}
}, {
key: '_attachClearSortCaretFunc',
value: function _attachClearSortCaretFunc() {
var _props = this.props;
var sortIndicator = _props.sortIndicator;
var children = _props.children;
var sortName = _props.sortName;
var sortOrder = _props.sortOrder;
var onSort = _props.onSort;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var _children$i$props = children[i].props;
var dataField = _children$i$props.dataField;
var dataSort = _children$i$props.dataSort;
var sort = dataSort && dataField === sortName ? sortOrder : undefined;
this.props.children[i] = _react2['default'].cloneElement(children[i], { key: i, onSort: onSort, sort: sort, sortIndicator: sortIndicator });
}
} else {
var _children$props = children.props;
var dataField = _children$props.dataField;
var dataSort = _children$props.dataSort;
var sort = dataSort && dataField === sortName ? sortOrder : undefined;
this.props.children = _react2['default'].cloneElement(children, { key: 0, onSort: onSort, sort: sort, sortIndicator: sortIndicator });
}
}
}]);
return TableHeader;
})(_react.Component);
TableHeader.propTypes = {
rowSelectType: _react.PropTypes.string,
onSort: _react.PropTypes.func,
onSelectAllRow: _react.PropTypes.func,
sortName: _react.PropTypes.string,
sortOrder: _react.PropTypes.string,
hideSelectColumn: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
isFiltered: _react.PropTypes.bool,
isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]),
sortIndicator: _react.PropTypes.bool
};
exports['default'] = TableHeader;
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_5__;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var SelectRowHeaderColumn = (function (_Component) {
_inherits(SelectRowHeaderColumn, _Component);
function SelectRowHeaderColumn() {
_classCallCheck(this, SelectRowHeaderColumn);
_get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(SelectRowHeaderColumn, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(
'th',
{ style: { textAlign: 'center' } },
this.props.children
);
}
}]);
return SelectRowHeaderColumn;
})(_react.Component);
SelectRowHeaderColumn.propTypes = {
children: _react.PropTypes.node
};
exports['default'] = SelectRowHeaderColumn;
module.exports = exports['default'];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _TableRow = __webpack_require__(9);
var _TableRow2 = _interopRequireDefault(_TableRow);
var _TableColumn = __webpack_require__(10);
var _TableColumn2 = _interopRequireDefault(_TableColumn);
var _TableEditColumn = __webpack_require__(11);
var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var isFun = function isFun(obj) {
return obj && typeof obj === 'function';
};
var TableBody = (function (_Component) {
_inherits(TableBody, _Component);
function TableBody(props) {
var _this = this;
_classCallCheck(this, TableBody);
_get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props);
this.handleRowMouseOut = function (rowIndex, event) {
var targetRow = _this.props.data[rowIndex];
_this.props.onRowMouseOut(targetRow, event);
};
this.handleRowMouseOver = function (rowIndex, event) {
var targetRow = _this.props.data[rowIndex];
_this.props.onRowMouseOver(targetRow, event);
};
this.handleRowClick = function (rowIndex) {
var selectedRow = undefined;
var _props = _this.props;
var data = _props.data;
var onRowClick = _props.onRowClick;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
}
});
onRowClick(selectedRow);
};
this.handleSelectRow = function (rowIndex, isSelected) {
var selectedRow = undefined;
var _props2 = _this.props;
var data = _props2.data;
var onSelectRow = _props2.onSelectRow;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
return false;
}
});
onSelectRow(selectedRow, isSelected);
};
this.handleSelectRowColumChange = function (e) {
if (!_this.props.selectRow.clickToSelect || !_this.props.selectRow.clickToSelectAndEditCell) {
_this.handleSelectRow(e.currentTarget.parentElement.parentElement.rowIndex + 1, e.currentTarget.checked);
}
};
this.handleEditCell = function (rowIndex, columnIndex) {
_this.editing = true;
if (_this._isSelectRowDefined()) {
columnIndex--;
if (_this.props.selectRow.hideSelectColumn) columnIndex++;
}
rowIndex--;
var stateObj = {
currEditCell: {
rid: rowIndex,
cid: columnIndex
}
};
if (_this.props.selectRow.clickToSelectAndEditCell && _this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_DBCLICK) {
var selected = _this.props.selectedRowKeys.indexOf(_this.props.data[rowIndex][_this.props.keyField]) !== -1;
_this.handleSelectRow(rowIndex + 1, !selected);
}
_this.setState(stateObj);
};
this.handleCompleteEditCell = function (newVal, rowIndex, columnIndex) {
_this.setState({ currEditCell: null });
if (newVal !== null) {
_this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex);
}
};
this.state = {
currEditCell: null
};
this.editing = false;
}
_createClass(TableBody, [{
key: 'render',
value: function render() {
var tableClasses = (0, _classnames2['default'])('table', {
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-hover': this.props.hover,
'table-condensed': this.props.condensed
});
var isSelectRowDefined = this._isSelectRowDefined();
var tableHeader = this.renderTableHeader(isSelectRowDefined);
var tableRows = this.props.data.map(function (data, r) {
var tableColumns = this.props.columns.map(function (column, i) {
var fieldValue = data[column.name];
if (this.editing && column.name !== this.props.keyField && // Key field can't be edit
column.editable && // column is editable? default is true, user can set it false
this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i) {
var editable = column.editable;
var format = column.format ? function (value) {
return column.format(value, data, column.formatExtraData).replace(/<.*?>/g, '');
} : false;
if (isFun(column.editable)) {
editable = column.editable(fieldValue, data, r, i);
}
return _react2['default'].createElement(
_TableEditColumn2['default'],
{
completeEdit: this.handleCompleteEditCell,
// add by bluespring for column editor customize
editable: editable,
format: column.format ? format : false,
key: i,
blurToSave: this.props.cellEdit.blurToSave,
rowIndex: r,
colIndex: i },
fieldValue
);
} else {
// add by bluespring for className customize
var columnChild = fieldValue;
var tdClassName = column.className;
if (isFun(column.className)) {
tdClassName = column.className(fieldValue, data, r, i);
}
if (typeof column.format !== 'undefined') {
var formattedValue = column.format(fieldValue, data, column.formatExtraData);
if (!_react2['default'].isValidElement(formattedValue)) {
columnChild = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } });
} else {
columnChild = formattedValue;
}
}
return _react2['default'].createElement(
_TableColumn2['default'],
{ key: i,
dataAlign: column.align,
className: tdClassName,
cellEdit: this.props.cellEdit,
hidden: column.hidden,
onEdit: this.handleEditCell,
width: column.width },
columnChild
);
}
}, this);
var selected = this.props.selectedRowKeys.indexOf(data[this.props.keyField]) !== -1;
var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected) : null;
// add by bluespring for className customize
var trClassName = this.props.trClassName;
if (isFun(this.props.trClassName)) {
trClassName = this.props.trClassName(data, r);
}
return _react2['default'].createElement(
_TableRow2['default'],
{ isSelected: selected, key: r, className: trClassName,
selectRow: isSelectRowDefined ? this.props.selectRow : undefined,
enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE,
onRowClick: this.handleRowClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow },
selectRowColumn,
tableColumns
);
}, this);
if (tableRows.length === 0) {
tableRows.push(_react2['default'].createElement(
_TableRow2['default'],
{ key: '##table-empty##' },
_react2['default'].createElement(
'td',
{ colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0),
className: 'react-bs-table-no-data' },
this.props.noDataText || _Const2['default'].NO_DATA_TEXT
)
));
}
this.editing = false;
return _react2['default'].createElement(
'div',
{ ref: 'container', className: 'react-bs-container-body', style: this.props.style },
_react2['default'].createElement(
'table',
{ className: tableClasses },
tableHeader,
_react2['default'].createElement(
'tbody',
{ ref: 'tbody' },
tableRows
)
)
);
}
}, {
key: 'renderTableHeader',
value: function renderTableHeader(isSelectRowDefined) {
var selectRowHeader = null;
if (isSelectRowDefined) {
var style = {
width: 30,
minWidth: 30
};
if (!this.props.selectRow.hideSelectColumn) {
selectRowHeader = _react2['default'].createElement('col', { style: style, key: -1 });
}
}
var theader = this.props.columns.map(function (column, i) {
var width = column.width === null ? column.width : parseInt(column.width, 10);
var style = {
display: column.hidden ? 'none' : null,
width: width,
minWidth: width
/** add min-wdth to fix user assign column width
not eq offsetWidth in large column table **/
};
return _react2['default'].createElement('col', { style: style, key: i, className: column.className });
});
return _react2['default'].createElement(
'colgroup',
{ ref: 'header' },
selectRowHeader,
theader
);
}
}, {
key: 'renderSelectRowColumn',
value: function renderSelectRowColumn(selected) {
if (this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) {
return _react2['default'].createElement(
_TableColumn2['default'],
{ dataAlign: 'center' },
_react2['default'].createElement('input', { type: 'radio', checked: selected,
onChange: this.handleSelectRowColumChange })
);
} else {
return _react2['default'].createElement(
_TableColumn2['default'],
{ dataAlign: 'center' },
_react2['default'].createElement('input', { type: 'checkbox', checked: selected,
onChange: this.handleSelectRowColumChange })
);
}
}
}, {
key: '_isSelectRowDefined',
value: function _isSelectRowDefined() {
return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI;
}
}]);
return TableBody;
})(_react.Component);
TableBody.propTypes = {
data: _react.PropTypes.array,
columns: _react.PropTypes.array,
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
keyField: _react.PropTypes.string,
selectedRowKeys: _react.PropTypes.array,
onRowClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
style: _react.PropTypes.object
};
exports['default'] = TableBody;
module.exports = exports['default'];
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var TableRow = (function (_Component) {
_inherits(TableRow, _Component);
function TableRow(props) {
var _this = this;
_classCallCheck(this, TableRow);
_get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props);
this.rowClick = function (e) {
if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') {
(function () {
var rowIndex = e.currentTarget.rowIndex + 1;
if (_this.props.selectRow) {
if (_this.props.selectRow.clickToSelect) {
_this.props.onSelectRow(rowIndex, !_this.props.isSelected);
} else if (_this.props.selectRow.clickToSelectAndEditCell) {
_this.clickNum++;
/** if clickToSelectAndEditCell is enabled,
* there should be a delay to prevent a selection changed when
* user dblick to edit cell on same row but different cell
**/
setTimeout(function () {
if (_this.clickNum === 1) {
_this.props.onSelectRow(rowIndex, !_this.props.isSelected);
}
_this.clickNum = 0;
}, 200);
}
}
if (_this.props.onRowClick) _this.props.onRowClick(rowIndex);
})();
}
};
this.rowMouseOut = function (e) {
if (_this.props.onRowMouseOut) {
_this.props.onRowMouseOut(e.currentTarget.rowIndex, e);
}
};
this.rowMouseOver = function (e) {
if (_this.props.onRowMouseOver) {
_this.props.onRowMouseOver(e.currentTarget.rowIndex, e);
}
};
this.clickNum = 0;
}
_createClass(TableRow, [{
key: 'render',
value: function render() {
this.clickNum = 0;
var trCss = {
style: {
backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null
},
className: (this.props.isSelected && this.props.selectRow.className ? this.props.selectRow.className : '') + (this.props.className || '')
};
if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) {
return _react2['default'].createElement(
'tr',
_extends({}, trCss, {
onMouseOver: this.rowMouseOver,
onMouseOut: this.rowMouseOut,
onClick: this.rowClick }),
this.props.children
);
} else {
return _react2['default'].createElement(
'tr',
trCss,
this.props.children
);
}
}
}]);
return TableRow;
})(_react.Component);
TableRow.propTypes = {
isSelected: _react.PropTypes.bool,
enableCellEdit: _react.PropTypes.bool,
onRowClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
onRowMouseOut: _react.PropTypes.func,
onRowMouseOver: _react.PropTypes.func
};
TableRow.defaultProps = {
onRowClick: undefined
};
exports['default'] = TableRow;
module.exports = exports['default'];
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var TableColumn = (function (_Component) {
_inherits(TableColumn, _Component);
function TableColumn(props) {
var _this = this;
_classCallCheck(this, TableColumn);
_get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props);
this.handleCellEdit = function (e) {
if (_this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) {
if (document.selection && document.selection.empty) {
document.selection.empty();
} else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
_this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex);
};
}
/* eslint no-unused-vars: [0, { "args": "after-used" }] */
_createClass(TableColumn, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var children = this.props.children;
var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString();
if (shouldUpdated) {
return shouldUpdated;
}
if (typeof children === 'object' && children !== null && children.props !== null) {
if (children.props.type === 'checkbox' || children.props.type === 'radio') {
shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked;
} else {
shouldUpdated = true;
}
} else {
shouldUpdated = shouldUpdated || children !== nextProps.children;
}
if (shouldUpdated) {
return shouldUpdated;
}
if (!(this.props.cellEdit && nextProps.cellEdit)) {
return false;
} else {
return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode;
}
}
}, {
key: 'render',
value: function render() {
var tdStyle = {
textAlign: this.props.dataAlign,
display: this.props.hidden ? 'none' : null
};
var opts = {};
if (this.props.cellEdit) {
if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_CLICK) {
opts.onClick = this.handleCellEdit;
} else if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) {
opts.onDoubleClick = this.handleCellEdit;
}
}
return _react2['default'].createElement(
'td',
_extends({ style: tdStyle, className: this.props.className }, opts),
this.props.children
);
}
}]);
return TableColumn;
})(_react.Component);
TableColumn.propTypes = {
dataAlign: _react.PropTypes.string,
hidden: _react.PropTypes.bool,
className: _react.PropTypes.string,
children: _react.PropTypes.node
};
TableColumn.defaultProps = {
dataAlign: 'left',
hidden: false,
className: ''
};
exports['default'] = TableColumn;
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Editor = __webpack_require__(12);
var _Editor2 = _interopRequireDefault(_Editor);
var _NotificationJs = __webpack_require__(13);
var _NotificationJs2 = _interopRequireDefault(_NotificationJs);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var TableEditColumn = (function (_Component) {
_inherits(TableEditColumn, _Component);
function TableEditColumn(props) {
var _this = this;
_classCallCheck(this, TableEditColumn);
_get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props);
this.handleKeyPress = function (e) {
if (e.keyCode === 13) {
// Pressed ENTER
var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
} else if (e.keyCode === 27) {
_this.props.completeEdit(null, _this.props.rowIndex, _this.props.colIndex);
}
};
this.handleBlur = function (e) {
if (_this.props.blurToSave) {
var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
}
};
this.timeouteClear = 0;
this.state = {
shakeEditor: false
};
}
_createClass(TableEditColumn, [{
key: 'validator',
value: function validator(value) {
var ts = this;
if (ts.props.editable.validator) {
var valid = ts.props.editable.validator(value);
if (!valid) {
ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel');
var input = ts.refs.inputRef;
// animate input
ts.clearTimeout();
ts.setState({ shakeEditor: true });
ts.timeouteClear = setTimeout(function () {
ts.setState({ shakeEditor: false });
}, 300);
input.focus();
return false;
}
}
return true;
}
}, {
key: 'clearTimeout',
value: (function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
})(function () {
if (this.timeouteClear !== 0) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs.inputRef.focus();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var editable = _props.editable;
var format = _props.format;
var children = _props.children;
var shakeEditor = this.state.shakeEditor;
var attr = {
ref: 'inputRef',
onKeyDown: this.handleKeyPress,
onBlur: this.handleBlur
};
// put placeholder if exist
editable.placeholder && (attr.placeholder = editable.placeholder);
var editorClass = (0, _classnames2['default'])({ 'animated': shakeEditor, 'shake': shakeEditor });
return _react2['default'].createElement(
'td',
{ ref: 'td', style: { position: 'relative' } },
(0, _Editor2['default'])(editable, attr, format, editorClass, children || ''),
_react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' })
);
}
}, {
key: '_getCheckBoxValue',
value: function _getCheckBoxValue(e) {
var value = '';
var values = e.currentTarget.value.split(':');
value = e.currentTarget.checked ? values[0] : values[1];
return value;
}
}]);
return TableEditColumn;
})(_react.Component);
TableEditColumn.propTypes = {
completeEdit: _react.PropTypes.func,
rowIndex: _react.PropTypes.number,
colIndex: _react.PropTypes.number,
blurToSave: _react.PropTypes.bool,
editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
children: _react.PropTypes.node
};
exports['default'] = TableEditColumn;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) {
if (editable === true || ignoreEditable || typeof editable === 'string') {
// simple declare
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (!editable) {
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
disabled: 'disabled',
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (editable.type) {
// standard declare
// put style if exist
editable.style && (attr.style = editable.style);
// put class if exist
attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : '');
if (editable.type === 'select') {
// process select input
var options = [];
var values = editable.options.values;
if (Array.isArray(values)) {
(function () {
// only can use arrray data for options
var rowValue = undefined;
options = values.map(function (d, i) {
rowValue = format ? format(d) : d;
return _react2['default'].createElement(
'option',
{ key: 'option' + i, value: d },
rowValue
);
});
})();
}
return _react2['default'].createElement(
'select',
_extends({}, attr, { defaultValue: defaultValue }),
options
);
} else if (editable.type === 'textarea') {
var _ret2 = (function () {
// process textarea input
// put other if exist
editable.cols && (attr.cols = editable.cols);
editable.rows && (attr.rows = editable.rows);
var saveBtn = undefined;
var keyUpHandler = attr.onKeyDown;
if (keyUpHandler) {
attr.onKeyDown = function (e) {
if (e.keyCode !== 13) {
// not Pressed ENTER
keyUpHandler(e);
}
};
saveBtn = _react2['default'].createElement(
'button',
{
className: 'btn btn-info btn-xs textarea-save-btn',
onClick: keyUpHandler },
'save'
);
}
return {
v: _react2['default'].createElement(
'div',
null,
_react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })),
saveBtn
)
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
} else if (editable.type === 'checkbox') {
var values = 'true:false';
if (editable.options && editable.options.values) {
// values = editable.options.values.split(':');
values = editable.options.values;
}
attr.className = attr.className.replace('form-control', '');
attr.className += ' checkbox pull-right';
var checked = defaultValue && defaultValue.toString() === values.split(':')[0] ? true : false;
return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox',
value: values, defaultChecked: checked }));
} else {
// process other input type. as password,url,email...
return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue }));
}
}
// default return for other case of editable
return _react2['default'].createElement('input', _extends({}, attr, { type: 'text',
className: (editorClass || '') + ' form-control editor edit-text' }));
};
exports['default'] = editor;
module.exports = exports['default'];
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactToastr = __webpack_require__(14);
var ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation);
var Notification = (function (_Component) {
_inherits(Notification, _Component);
function Notification() {
_classCallCheck(this, Notification);
_get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Notification, [{
key: 'notice',
// allow type is success,info,warning,error
value: function notice(type, msg, title) {
this.refs.toastr[type](msg, title, {
mode: 'single',
timeOut: 5000,
extendedTimeOut: 1000,
showAnimation: 'animated bounceIn',
hideAnimation: 'animated bounceOut'
});
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr',
toastMessageFactory: ToastrMessageFactory,
id: 'toast-container',
className: 'toast-top-right' });
}
}]);
return Notification;
})(_react.Component);
exports['default'] = Notification;
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToastMessage = exports.ToastContainer = undefined;
var _ToastContainer = __webpack_require__(15);
var _ToastContainer2 = _interopRequireDefault(_ToastContainer);
var _ToastMessage = __webpack_require__(22);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.ToastContainer = _ToastContainer2.default;
exports.ToastMessage = _ToastMessage2.default;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _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; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(16);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _ToastMessage = __webpack_require__(22);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ToastContainer = function (_Component) {
_inherits(ToastContainer, _Component);
function ToastContainer() {
var _Object$getPrototypeO;
var _temp, _this, _ret;
_classCallCheck(this, ToastContainer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
toasts: [],
toastId: 0,
previousMessage: null
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(ToastContainer, [{
key: "error",
value: function error(message, title, optionsOverride) {
this._notify(this.props.toastType.error, message, title, optionsOverride);
}
}, {
key: "info",
value: function info(message, title, optionsOverride) {
this._notify(this.props.toastType.info, message, title, optionsOverride);
}
}, {
key: "success",
value: function success(message, title, optionsOverride) {
this._notify(this.props.toastType.success, message, title, optionsOverride);
}
}, {
key: "warning",
value: function warning(message, title, optionsOverride) {
this._notify(this.props.toastType.warning, message, title, optionsOverride);
}
}, {
key: "clear",
value: function clear() {
var _this2 = this;
Object.keys(this.refs).forEach(function (key) {
_this2.refs[key].hideToast(false);
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return _react2.default.createElement(
"div",
_extends({}, this.props, { "aria-live": "polite", role: "alert" }),
this.state.toasts.map(function (toast) {
return _this3.props.toastMessageFactory(toast);
})
);
}
}, {
key: "_notify",
value: function _notify(type, message, title) {
var _this4 = this;
var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
if (this.props.preventDuplicates) {
if (this.state.previousMessage === message) {
return;
}
}
var key = this.state.toastId++;
var toastId = key;
var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {
$merge: {
type: type,
title: title,
message: message,
toastId: toastId,
key: key,
ref: "toasts__" + key,
handleOnClick: function handleOnClick(e) {
if ("function" === typeof optionsOverride.handleOnClick) {
optionsOverride.handleOnClick();
}
return _this4._handle_toast_on_click(e);
},
handleRemove: this._handle_toast_remove.bind(this)
}
});
var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);
var nextState = (0, _reactAddonsUpdate2.default)(this.state, {
toasts: toastOperation,
previousMessage: { $set: message }
});
this.setState(nextState);
}
}, {
key: "_handle_toast_on_click",
value: function _handle_toast_on_click(event) {
this.props.onClick(event);
if (event.defaultPrevented) {
return;
}
event.preventDefault();
event.stopPropagation();
}
}, {
key: "_handle_toast_remove",
value: function _handle_toast_remove(toastId) {
var _this5 = this;
var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");
this.state.toasts[operationName](function (found, toast, index) {
if (found || toast.toastId !== toastId) {
return false;
}
_this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, {
toasts: { $splice: [[index, 1]] }
}));
return true;
}, false);
}
}]);
return ToastContainer;
}(_react.Component);
ToastContainer.defaultProps = {
toastType: {
error: "error",
info: "info",
success: "success",
warning: "warning"
},
id: "toast-container",
toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default),
preventDuplicates: false,
newestOnTop: true,
onClick: function onClick() {}
};
exports.default = ToastContainer;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(17);
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var assign = __webpack_require__(19);
var keyOf = __webpack_require__(20);
var invariant = __webpack_require__(21);
var hasOwnProperty = ({}).hasOwnProperty;
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({ $push: null });
var COMMAND_UNSHIFT = keyOf({ $unshift: null });
var COMMAND_SPLICE = keyOf({ $splice: null });
var COMMAND_SET = keyOf({ $set: null });
var COMMAND_MERGE = keyOf({ $merge: null });
var COMMAND_APPLY = keyOf({ $apply: null });
var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function (command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined;
var specValue = spec[command];
!Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined;
}
function update(value, spec) {
!(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined;
if (hasOwnProperty.call(spec, COMMAND_SET)) {
!(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined;
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
!(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined;
!(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined;
assign(nextValue, spec[COMMAND_MERGE]);
}
if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function (item) {
nextValue.push(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function (item) {
nextValue.unshift(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined;
!Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
spec[COMMAND_SPLICE].forEach(function (args) {
!Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
nextValue.splice.apply(nextValue, args);
});
}
if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
!(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined;
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 18 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 19 */
/***/ function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
"use strict";
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.jQuery = exports.animation = undefined;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(16);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _animationMixin = __webpack_require__(23);
var _animationMixin2 = _interopRequireDefault(_animationMixin);
var _jQueryMixin = __webpack_require__(28);
var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function noop() {}
var ToastMessageSpec = {
displayName: "ToastMessage",
getDefaultProps: function getDefaultProps() {
var iconClassNames = {
error: "toast-error",
info: "toast-info",
success: "toast-success",
warning: "toast-warning"
};
return {
className: "toast",
iconClassNames: iconClassNames,
titleClassName: "toast-title",
messageClassName: "toast-message",
tapToDismiss: true,
closeButton: false
};
},
handleOnClick: function handleOnClick(event) {
this.props.handleOnClick(event);
if (this.props.tapToDismiss) {
this.hideToast(true);
}
},
_handle_close_button_click: function _handle_close_button_click(event) {
event.stopPropagation();
this.hideToast(true);
},
_handle_remove: function _handle_remove() {
this.props.handleRemove(this.props.toastId);
},
_render_close_button: function _render_close_button() {
return this.props.closeButton ? _react2.default.createElement("button", {
className: "toast-close-button", role: "button",
onClick: this._handle_close_button_click,
dangerouslySetInnerHTML: { __html: "×" }
}) : false;
},
_render_title_element: function _render_title_element() {
return this.props.title ? _react2.default.createElement(
"div",
{ className: this.props.titleClassName },
this.props.title
) : false;
},
_render_message_element: function _render_message_element() {
return this.props.message ? _react2.default.createElement(
"div",
{ className: this.props.messageClassName },
this.props.message
) : false;
},
render: function render() {
var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type];
return _react2.default.createElement(
"div",
{
className: (0, _classnames2.default)(this.props.className, iconClassName),
style: this.props.style,
onClick: this.handleOnClick,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave
},
this._render_close_button(),
this._render_title_element(),
this._render_message_element()
);
}
};
var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.animation" },
mixins: { $set: [_animationMixin2.default] }
}));
var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.jQuery" },
mixins: { $set: [_jQueryMixin2.default] }
}));
/*
* assign default noop functions
*/
ToastMessageSpec.handleMouseEnter = noop;
ToastMessageSpec.handleMouseLeave = noop;
ToastMessageSpec.hideToast = noop;
var ToastMessage = _react2.default.createClass(ToastMessageSpec);
ToastMessage.animation = animation;
ToastMessage.jQuery = jQuery;
exports.default = ToastMessage;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CSSCore = __webpack_require__(24);
var _CSSCore2 = _interopRequireDefault(_CSSCore);
var _ReactTransitionEvents = __webpack_require__(26);
var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents);
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TICK = 17;
var toString = Object.prototype.toString;
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate)
showAnimation: "animated bounceIn", // or other animations from animate.css
hideAnimation: "animated bounceOut",
timeOut: 5000,
extendedTimeOut: 1000
};
},
componentWillMount: function componentWillMount() {
this.classNameQueue = [];
this.isHiding = false;
this.intervalId = null;
},
componentDidMount: function componentDidMount() {
var _this = this;
this._is_mounted = true;
this._show();
var node = _reactDom2.default.findDOMNode(this);
var onHideComplete = function onHideComplete() {
if (_this.isHiding) {
_this._set_is_hiding(false);
_ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete);
_this._handle_remove();
}
};
_ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
componentWillUnmount: function componentWillUnmount() {
this._is_mounted = false;
if (this.intervalId) {
clearTimeout(this.intervalId);
}
},
_set_transition: function _set_transition(hide) {
var animationType = hide ? "leave" : "enter";
var node = _reactDom2.default.findDOMNode(this);
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
_CSSCore2.default.removeClass(node, className);
_CSSCore2.default.removeClass(node, activeClassName);
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
_CSSCore2.default.addClass(node, className);
// Need to do this to actually trigger a transition.
this._queue_class(activeClassName);
},
_clear_transition: function _clear_transition(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animationType = hide ? "leave" : "enter";
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
_CSSCore2.default.removeClass(node, className);
_CSSCore2.default.removeClass(node, activeClassName);
},
_set_animation: function _set_animation(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animations = this._get_animation_classes(hide);
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
animations.forEach(function (anim) {
_CSSCore2.default.removeClass(node, anim);
});
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
animations.forEach(function (anim) {
_CSSCore2.default.addClass(node, anim);
});
},
_get_animation_classes: function _get_animation_classes(hide) {
var animations = hide ? this.props.hideAnimation : this.props.showAnimation;
if ("[object Array]" === toString.call(animations)) {
return animations;
} else if ("string" === typeof animations) {
return animations.split(" ");
}
},
_clear_animation: function _clear_animation(hide) {
var _this2 = this;
var animations = this._get_animation_classes(hide);
animations.forEach(function (animation) {
_CSSCore2.default.removeClass(_reactDom2.default.findDOMNode(_this2), animation);
});
},
_queue_class: function _queue_class(className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this._flush_class_name_queue, TICK);
}
},
_flush_class_name_queue: function _flush_class_name_queue() {
if (this._is_mounted) {
this.classNameQueue.forEach(_CSSCore2.default.addClass.bind(_CSSCore2.default, _reactDom2.default.findDOMNode(this)));
}
this.classNameQueue.length = 0;
this.timeout = null;
},
_show: function _show() {
if (this.props.transition) {
this._set_transition();
} else if (this.props.showAnimation) {
this._set_animation();
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.intervalId);
this._set_interval_id(null);
if (this.isHiding) {
this._set_is_hiding(false);
if (this.props.hideAnimation) {
this._clear_animation(true);
} else if (this.props.transition) {
this._clear_transition(true);
}
}
},
handleMouseLeave: function handleMouseLeave() {
if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.isHiding || this.intervalId === null && !override) {
return;
}
this._set_is_hiding(true);
if (this.props.transition) {
this._set_transition(true);
} else if (this.props.hideAnimation) {
this._set_animation(true);
} else {
this._handle_remove();
}
},
_set_interval_id: function _set_interval_id(intervalId) {
this.intervalId = intervalId;
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.isHiding = isHiding;
}
};
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSCore
* @typechecks
*/
'use strict';
var invariant = __webpack_require__(25);
/**
* The CSSCore module specifies the API (and implements most of the methods)
* that should be used when dealing with the display of elements (via their
* CSS classes and visibility on screen. It is an API focused on mutating the
* display and not reading it as no logical state should be encoded in the
* display of elements.
*/
var CSSCore = {
/**
* Adds the class passed in to the element if it doesn't already have it.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
addClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
},
/**
* Removes the class passed in from the element
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
removeClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
},
/**
* Helper to add or remove a class from an element based on a condition.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @param {*} bool condition to whether to add or remove the class
* @return {DOMElement} the element passed in
*/
conditionClass: function (element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
},
/**
* Tests whether the element has the class specified.
*
* @param {DOMNode|DOMWindow} element the element to set the class on
* @param {string} className the CSS className
* @return {boolean} true if the element has the class, false if not
*/
hasClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined;
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}
};
module.exports = CSSCore;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(27);
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
/***/ },
/* 27 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function call_show_method($node, props) {
$node[props.showMethod]({
duration: props.showDuration,
easing: props.showEasing
});
}
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
style: {
display: "none" },
// effective $.hide()
showMethod: "fadeIn", // slideDown, and show are built into jQuery
showDuration: 300,
showEasing: "swing", // and linear are built into jQuery
hideMethod: "fadeOut",
hideDuration: 1000,
hideEasing: "swing",
//
timeOut: 5000,
extendedTimeOut: 1000
};
},
getInitialState: function getInitialState() {
return {
intervalId: null,
isHiding: false
};
},
componentDidMount: function componentDidMount() {
call_show_method(this._get_$_node(), this.props);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.state.intervalId);
this._set_interval_id(null);
this._set_is_hiding(false);
call_show_method(this._get_$_node().stop(true, true), this.props);
},
handleMouseLeave: function handleMouseLeave() {
if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.state.isHiding || this.state.intervalId === null && !override) {
return;
}
this.setState({ isHiding: true });
this._get_$_node()[this.props.hideMethod]({
duration: this.props.hideDuration,
easing: this.props.hideEasing,
complete: this._handle_remove
});
},
_get_$_node: function _get_$_node() {
/* eslint-disable no-undef */
return jQuery(_reactDom2.default.findDOMNode(this));
/* eslint-enable no-undef */
},
_set_interval_id: function _set_interval_id(intervalId) {
this.setState({
intervalId: intervalId
});
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.setState({
isHiding: isHiding
});
}
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _PageButtonJs = __webpack_require__(30);
var _PageButtonJs2 = _interopRequireDefault(_PageButtonJs);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var PaginationList = (function (_Component) {
_inherits(PaginationList, _Component);
function PaginationList() {
var _this = this;
_classCallCheck(this, PaginationList);
_get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments);
this.changePage = function (page) {
var _props = _this.props;
var prePage = _props.prePage;
var currPage = _props.currPage;
var nextPage = _props.nextPage;
var lastPage = _props.lastPage;
var firstPage = _props.firstPage;
var sizePerPage = _props.sizePerPage;
if (page === prePage) {
page = currPage - 1 < 1 ? 1 : currPage - 1;
} else if (page === nextPage) {
page = currPage + 1 > _this.totalPages ? _this.totalPages : currPage + 1;
} else if (page === lastPage) {
page = _this.totalPages;
} else if (page === firstPage) {
page = 1;
} else {
page = parseInt(page, 10);
}
if (page !== currPage) {
_this.props.changePage(page, sizePerPage);
}
};
this.changeSizePerPage = function (e) {
e.preventDefault();
var selectSize = parseInt(e.currentTarget.text, 10);
var currPage = _this.props.currPage;
if (selectSize !== _this.props.sizePerPage) {
_this.totalPages = Math.ceil(_this.props.dataSize / selectSize);
if (currPage > _this.totalPages) currPage = _this.totalPages;
_this.props.changePage(currPage, selectSize);
if (_this.props.onSizePerPageList) {
_this.props.onSizePerPageList(selectSize);
}
}
};
}
_createClass(PaginationList, [{
key: 'render',
value: function render() {
var _this2 = this;
var _props2 = this.props;
var dataSize = _props2.dataSize;
var sizePerPage = _props2.sizePerPage;
var sizePerPageList = _props2.sizePerPageList;
this.totalPages = Math.ceil(dataSize / sizePerPage);
var pageBtns = this.makePage();
var pageListStyle = {
float: 'right',
// override the margin-top defined in .pagination class in bootstrap.
marginTop: '0px'
};
var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) {
return _react2['default'].createElement(
'li',
{ key: _sizePerPage, role: 'presentation' },
_react2['default'].createElement(
'a',
{ role: 'menuitem',
tabIndex: '-1', href: '#',
onClick: _this2.changeSizePerPage },
_sizePerPage
)
);
});
return _react2['default'].createElement(
'div',
{ className: 'row', style: { marginTop: 15 } },
sizePerPageList.length > 1 ? _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
_react2['default'].createElement(
'div',
{ className: 'dropdown' },
_react2['default'].createElement(
'button',
{ className: 'btn btn-default dropdown-toggle',
type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown',
'aria-expanded': 'true' },
sizePerPage,
_react2['default'].createElement(
'span',
null,
' ',
_react2['default'].createElement('span', { className: 'caret' })
)
),
_react2['default'].createElement(
'ul',
{ className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' },
sizePerPageOptions
)
)
),
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
_react2['default'].createElement(
'ul',
{ className: 'pagination', style: pageListStyle },
pageBtns
)
)
) : _react2['default'].createElement(
'div',
{ className: 'col-md-12' },
_react2['default'].createElement(
'ul',
{ className: 'pagination', style: pageListStyle },
pageBtns
)
)
);
}
}, {
key: 'makePage',
value: function makePage() {
var pages = this.getPages();
return pages.map(function (page) {
var isActive = page === this.props.currPage;
var disabled = false;
var hidden = false;
if (this.props.currPage === 1 && (page === this.props.firstPage || page === this.props.prePage)) {
disabled = true;
hidden = true;
}
if (this.props.currPage === this.totalPages && (page === this.props.nextPage || page === this.props.lastPage)) {
disabled = true;
hidden = true;
}
return _react2['default'].createElement(
_PageButtonJs2['default'],
{ key: page,
changePage: this.changePage,
active: isActive,
disable: disabled,
hidden: hidden },
page
);
}, this);
}
}, {
key: 'getPages',
value: function getPages() {
var pages = undefined;
var startPage = 1;
var endPage = this.totalPages;
startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), 1);
endPage = startPage + this.props.paginationSize - 1;
if (endPage > this.totalPages) {
endPage = this.totalPages;
startPage = endPage - this.props.paginationSize + 1;
}
if (startPage !== 1 && this.totalPages > this.props.paginationSize) {
pages = [this.props.firstPage, this.props.prePage];
} else if (this.totalPages > 1) {
pages = [this.props.prePage];
} else {
pages = [];
}
for (var i = startPage; i <= endPage; i++) {
if (i > 0) pages.push(i);
}
if (endPage !== this.totalPages) {
pages.push(this.props.nextPage);
pages.push(this.props.lastPage);
} else if (this.totalPages > 1) {
pages.push(this.props.nextPage);
}
return pages;
}
}]);
return PaginationList;
})(_react.Component);
PaginationList.propTypes = {
currPage: _react.PropTypes.number,
sizePerPage: _react.PropTypes.number,
dataSize: _react.PropTypes.number,
changePage: _react.PropTypes.func,
sizePerPageList: _react.PropTypes.array,
paginationSize: _react.PropTypes.number,
remote: _react.PropTypes.bool,
onSizePerPageList: _react.PropTypes.func,
prePage: _react.PropTypes.string
};
PaginationList.defaultProps = {
sizePerPage: _Const2['default'].SIZE_PER_PAGE
};
exports['default'] = PaginationList;
module.exports = exports['default'];
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var PageButton = (function (_Component) {
_inherits(PageButton, _Component);
function PageButton(props) {
var _this = this;
_classCallCheck(this, PageButton);
_get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props);
this.pageBtnClick = function (e) {
e.preventDefault();
_this.props.changePage(e.currentTarget.textContent);
};
}
_createClass(PageButton, [{
key: 'render',
value: function render() {
var classes = (0, _classnames2['default'])({
'active': this.props.active,
'disabled': this.props.disable,
'hidden': this.props.hidden
});
return _react2['default'].createElement(
'li',
{ className: classes },
_react2['default'].createElement(
'a',
{ href: '#', onClick: this.pageBtnClick },
this.props.children
)
);
}
}]);
return PageButton;
})(_react.Component);
PageButton.propTypes = {
changePage: _react.PropTypes.func,
active: _react.PropTypes.bool,
disable: _react.PropTypes.bool,
hidden: _react.PropTypes.bool,
children: _react.PropTypes.node
};
exports['default'] = PageButton;
module.exports = exports['default'];
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _Editor = __webpack_require__(12);
var _Editor2 = _interopRequireDefault(_Editor);
var _NotificationJs = __webpack_require__(13);
var _NotificationJs2 = _interopRequireDefault(_NotificationJs);
var ToolBar = (function (_Component) {
_inherits(ToolBar, _Component);
_createClass(ToolBar, null, [{
key: 'modalSeq',
value: 0,
enumerable: true
}]);
function ToolBar(props) {
var _this = this,
_arguments2 = arguments;
_classCallCheck(this, ToolBar);
_get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props);
this.handleSaveBtnClick = function () {
var newObj = _this.checkAndParseForm();
if (!newObj) {
// validate errors
return;
}
var msg = _this.props.onAddRow(newObj);
if (msg) {
_this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel');
_this.clearTimeout();
// shake form and hack prevent modal hide
_this.setState({
shakeEditor: true,
validateState: 'this is hack for prevent bootstrap modal hide'
});
// clear animate class
_this.timeouteClear = setTimeout(function () {
_this.setState({ shakeEditor: false });
}, 300);
} else {
// reset state and hide modal hide
_this.setState({
validateState: null,
shakeEditor: false
}, function () {
document.querySelector('.modal-backdrop').click();
document.querySelector('.' + _this.modalClassName).click();
});
// reset form
_this.refs.form.reset();
}
};
this.handleShowOnlyToggle = function () {
_this.setState({
showSelected: !_this.state.showSelected
});
_this.props.onShowOnlySelected();
};
this.handleDropRowBtnClick = function () {
_this.props.onDropRow();
};
this.handleDebounce = function (func, wait, immediate) {
var timeout = undefined;
return function () {
var later = function later() {
timeout = null;
if (!immediate) {
func.apply(_this, _arguments2);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait || 0);
if (callNow) {
func.appy(_this, _arguments2);
}
};
};
this.handleKeyUp = function (event) {
event.persist();
_this.debounceCallback(event);
};
this.handleExportCSV = function () {
_this.props.onExportCSV();
};
this.handleClearBtnClick = function () {
_this.refs.seachInput.value = '';
_this.props.onSearch('');
};
this.timeouteClear = 0;
this.modalClassName;
this.state = {
isInsertRowTrigger: true,
validateState: null,
shakeEditor: false,
showSelected: false
};
}
_createClass(ToolBar, [{
key: 'componentWillMount',
value: function componentWillMount() {
var _this2 = this;
var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0;
this.debounceCallback = this.handleDebounce(function () {
_this2.props.onSearch(_this2.refs.seachInput.value);
}, delay);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'clearTimeout',
value: (function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
})(function () {
if (this.timeouteClear) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'checkAndParseForm',
value: function checkAndParseForm() {
var _this3 = this;
var newObj = {};
var validateState = {};
var isValid = true;
var tempValue = undefined;
var tempMsg = undefined;
this.props.columns.forEach(function (column, i) {
if (column.autoValue) {
// when you want same auto generate value and not allow edit, example ID field
var time = new Date().getTime();
tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time;
} else {
var dom = this.refs[column.field + i];
tempValue = dom.value;
if (column.editable && column.editable.type === 'checkbox') {
var values = tempValue.split(':');
tempValue = dom.checked ? values[0] : values[1];
}
if (column.editable && column.editable.validator) {
// process validate
tempMsg = column.editable.validator(tempValue);
if (tempMsg !== true) {
isValid = false;
validateState[column.field] = tempMsg;
}
}
}
newObj[column.field] = tempValue;
}, this);
if (isValid) {
return newObj;
} else {
this.clearTimeout();
// show error in form and shake it
this.setState({ validateState: validateState, shakeEditor: true });
// notifier error
this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel');
// clear animate class
this.timeouteClear = setTimeout(function () {
_this3.setState({ shakeEditor: false });
}, 300);
return null;
}
}
}, {
key: 'handleCloseBtn',
value: function handleCloseBtn() {
this.refs.warning.style.display = 'none';
}
}, {
key: 'render',
value: function render() {
this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++;
var insertBtn = null;
var deleteBtn = null;
var exportCSV = null;
var showSelectedOnlyBtn = null;
if (this.props.enableInsert) {
insertBtn = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-info react-bs-table-add-btn',
'data-toggle': 'modal',
'data-target': '.' + this.modalClassName },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }),
' New'
);
}
if (this.props.enableDelete) {
deleteBtn = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-warning react-bs-table-del-btn',
'data-toggle': 'tooltip',
'data-placement': 'right',
title: 'Drop selected row',
onClick: this.handleDropRowBtnClick },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }),
' Delete'
);
}
if (this.props.enableShowOnlySelected) {
showSelectedOnlyBtn = _react2['default'].createElement(
'button',
{ type: 'button',
onClick: this.handleShowOnlyToggle,
className: 'btn btn-primary',
'data-toggle': 'button',
'aria-pressed': 'false' },
this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT
);
}
if (this.props.enableExportCSV) {
exportCSV = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-success',
onClick: this.handleExportCSV },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }),
this.props.exportCSVText
);
}
var searchTextInput = this.renderSearchPanel();
var modal = this.props.enableInsert ? this.renderInsertRowModal() : null;
return _react2['default'].createElement(
'div',
{ className: 'row' },
_react2['default'].createElement(
'div',
{ className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' },
_react2['default'].createElement(
'div',
{ className: 'btn-group btn-group-sm', role: 'group' },
exportCSV,
insertBtn,
deleteBtn,
showSelectedOnlyBtn
)
),
_react2['default'].createElement(
'div',
{ className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' },
searchTextInput
),
_react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }),
modal
);
}
}, {
key: 'renderSearchPanel',
value: function renderSearchPanel() {
if (this.props.enableSearch) {
var classNames = 'form-group form-group-sm react-bs-table-search-form';
var clearBtn = null;
if (this.props.clearSearch) {
clearBtn = _react2['default'].createElement(
'span',
{ className: 'input-group-btn' },
_react2['default'].createElement(
'button',
{
className: 'btn btn-default',
type: 'button',
onClick: this.handleClearBtnClick },
'Clear'
)
);
classNames += ' input-group input-group-sm';
}
return _react2['default'].createElement(
'div',
{ className: classNames },
_react2['default'].createElement('input', { ref: 'seachInput',
className: 'form-control',
type: 'text',
placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search',
onKeyUp: this.handleKeyUp }),
clearBtn
);
} else {
return null;
}
}
}, {
key: 'renderInsertRowModal',
value: function renderInsertRowModal() {
var _this4 = this;
var validateState = this.state.validateState || {};
var shakeEditor = this.state.shakeEditor;
var inputField = this.props.columns.map(function (column, i) {
var editable = column.editable;
var format = column.format;
var field = column.field;
var name = column.name;
var autoValue = column.autoValue;
var attr = {
ref: field + i,
placeholder: editable.placeholder ? editable.placeholder : name
};
if (autoValue) {
// when you want same auto generate value
// and not allow edit, for example ID field
return null;
}
var error = validateState[field] ? _react2['default'].createElement(
'span',
{ className: 'help-block bg-danger' },
validateState[field]
) : null;
// let editor = Editor(editable,attr,format);
// if(editor.props.type && editor.props.type == 'checkbox'){
return _react2['default'].createElement(
'div',
{ className: 'form-group', key: field },
_react2['default'].createElement(
'label',
null,
name
),
(0, _Editor2['default'])(editable, attr, format, '', undefined, _this4.props.ignoreEditable),
error
);
});
var modalClass = (0, _classnames2['default'])('modal', 'fade', this.modalClassName, {
// hack prevent bootstrap modal hide by reRender
'in': shakeEditor || this.state.validateState
});
var dialogClass = (0, _classnames2['default'])('modal-dialog', 'modal-sm', {
'animated': shakeEditor,
'shake': shakeEditor
});
return _react2['default'].createElement(
'div',
{ ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' },
_react2['default'].createElement(
'div',
{ className: dialogClass },
_react2['default'].createElement(
'div',
{ className: 'modal-content' },
_react2['default'].createElement(
'div',
{ className: 'modal-header' },
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'close',
'data-dismiss': 'modal',
'aria-label': 'Close' },
_react2['default'].createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
),
_react2['default'].createElement(
'h4',
{ className: 'modal-title' },
'New Record'
)
),
_react2['default'].createElement(
'div',
{ className: 'modal-body' },
_react2['default'].createElement(
'form',
{ ref: 'form' },
inputField
)
),
_react2['default'].createElement(
'div',
{ className: 'modal-footer' },
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-default',
'data-dismiss': 'modal' },
'Close'
),
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-info',
onClick: this.handleSaveBtnClick },
'Save'
)
)
)
)
);
}
}]);
return ToolBar;
})(_react.Component);
ToolBar.propTypes = {
onAddRow: _react.PropTypes.func,
onDropRow: _react.PropTypes.func,
onShowOnlySelected: _react.PropTypes.func,
enableInsert: _react.PropTypes.bool,
enableDelete: _react.PropTypes.bool,
enableSearch: _react.PropTypes.bool,
enableShowOnlySelected: _react.PropTypes.bool,
columns: _react.PropTypes.array,
searchPlaceholder: _react.PropTypes.string,
exportCSVText: _react.PropTypes.string,
clearSearch: _react.PropTypes.bool,
ignoreEditable: _react.PropTypes.bool
};
ToolBar.defaultProps = {
enableInsert: false,
enableDelete: false,
enableSearch: false,
enableShowOnlySelected: false,
clearSearch: false,
ignoreEditable: false
};
exports['default'] = ToolBar;
module.exports = exports['default'];
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var TableFilter = (function (_Component) {
_inherits(TableFilter, _Component);
function TableFilter(props) {
var _this = this;
_classCallCheck(this, TableFilter);
_get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props);
this.handleKeyUp = function (e) {
var _e$currentTarget = e.currentTarget;
var value = _e$currentTarget.value;
var name = _e$currentTarget.name;
if (value.trim() === '') {
delete _this.filterObj[name];
} else {
_this.filterObj[name] = value;
}
_this.props.onFilter(_this.filterObj);
};
this.filterObj = {};
}
_createClass(TableFilter, [{
key: 'render',
value: function render() {
var _props = this.props;
var striped = _props.striped;
var condensed = _props.condensed;
var rowSelectType = _props.rowSelectType;
var columns = _props.columns;
var tableClasses = (0, _classnames2['default'])('table', {
'table-striped': striped,
'table-condensed': condensed
});
var selectRowHeader = null;
if (rowSelectType === _Const2['default'].ROW_SELECT_SINGLE || rowSelectType === _Const2['default'].ROW_SELECT_MULTI) {
var style = {
width: 35,
paddingLeft: 0,
paddingRight: 0
};
selectRowHeader = _react2['default'].createElement(
'th',
{ style: style, key: -1 },
'Filter'
);
}
var filterField = columns.map(function (column) {
var hidden = column.hidden;
var width = column.width;
var name = column.name;
var thStyle = {
display: hidden ? 'none' : null,
width: width
};
return _react2['default'].createElement(
'th',
{ key: name, style: thStyle },
_react2['default'].createElement(
'div',
{ className: 'th-inner table-header-column' },
_react2['default'].createElement('input', { size: '10', type: 'text',
placeholder: name, name: name, onKeyUp: this.handleKeyUp })
)
);
}, this);
return _react2['default'].createElement(
'table',
{ className: tableClasses, style: { marginTop: 5 } },
_react2['default'].createElement(
'thead',
null,
_react2['default'].createElement(
'tr',
{ style: { borderBottomStyle: 'hidden' } },
selectRowHeader,
filterField
)
)
);
}
}]);
return TableFilter;
})(_react.Component);
TableFilter.propTypes = {
columns: _react.PropTypes.array,
rowSelectType: _react.PropTypes.string,
onFilter: _react.PropTypes.func
};
exports['default'] = TableFilter;
module.exports = exports['default'];
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/* eslint no-nested-ternary: 0 */
/* eslint guard-for-in: 0 */
/* eslint no-console: 0 */
/* eslint eqeqeq: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
function _sort(arr, sortField, order, sortFunc, sortFuncExtraData) {
order = order.toLowerCase();
var isDesc = order === _Const2['default'].SORT_DESC;
arr.sort(function (a, b) {
if (sortFunc) {
return sortFunc(a, b, order, sortField, sortFuncExtraData);
} else {
if (isDesc) {
if (b[sortField] === null) return false;
if (a[sortField] === null) return true;
if (typeof b[sortField] === 'string') {
return b[sortField].localeCompare(a[sortField]);
} else {
return a[sortField] > b[sortField] ? -1 : a[sortField] < b[sortField] ? 1 : 0;
}
} else {
if (b[sortField] === null) return true;
if (a[sortField] === null) return false;
if (typeof a[sortField] === 'string') {
return a[sortField].localeCompare(b[sortField]);
} else {
return a[sortField] < b[sortField] ? -1 : a[sortField] > b[sortField] ? 1 : 0;
}
}
}
});
return arr;
}
var TableDataStore = (function () {
function TableDataStore(data) {
_classCallCheck(this, TableDataStore);
this.data = data;
this.colInfos = null;
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
this.searchText = null;
this.sortObj = null;
this.pageObj = {};
this.selected = [];
this.multiColumnSearch = false;
this.showOnlySelected = false;
this.remote = false; // remote data
}
_createClass(TableDataStore, [{
key: 'setProps',
value: function setProps(props) {
this.keyField = props.keyField;
this.enablePagination = props.isPagination;
this.colInfos = props.colInfos;
this.remote = props.remote;
this.multiColumnSearch = props.multiColumnSearch;
}
}, {
key: 'setData',
value: function setData(data) {
this.data = data;
this._refresh();
}
}, {
key: 'getSortInfo',
value: function getSortInfo() {
return this.sortObj;
}
}, {
key: 'setSelectedRowKey',
value: function setSelectedRowKey(selectedRowKeys) {
this.selected = selectedRowKeys;
}
}, {
key: 'getSelectedRowKeys',
value: function getSelectedRowKeys() {
return this.selected;
}
}, {
key: 'getCurrentDisplayData',
value: function getCurrentDisplayData() {
if (this.isOnFilter) return this.filteredData;else return this.data;
}
}, {
key: '_refresh',
value: function _refresh() {
if (this.isOnFilter) {
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
if (this.sortObj) {
this.sort(this.sortObj.order, this.sortObj.sortField);
}
}
}, {
key: 'ignoreNonSelected',
value: function ignoreNonSelected() {
var _this = this;
this.showOnlySelected = !this.showOnlySelected;
if (this.showOnlySelected) {
this.isOnFilter = true;
this.filteredData = this.data.filter(function (row) {
var result = _this.selected.find(function (x) {
return row[_this.keyField] === x;
});
return typeof result !== 'undefined' ? true : false;
});
} else {
this.isOnFilter = false;
}
}
}, {
key: 'sort',
value: function sort(order, sortField) {
this.sortObj = { order: order, sortField: sortField };
var currentDisplayData = this.getCurrentDisplayData();
if (!this.colInfos[sortField]) return this;
var _colInfos$sortField = this.colInfos[sortField];
var sortFunc = _colInfos$sortField.sortFunc;
var sortFuncExtraData = _colInfos$sortField.sortFuncExtraData;
currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc, sortFuncExtraData);
return this;
}
}, {
key: 'page',
value: function page(_page, sizePerPage) {
this.pageObj.end = _page * sizePerPage - 1;
this.pageObj.start = this.pageObj.end - (sizePerPage - 1);
return this;
}
}, {
key: 'edit',
value: function edit(newVal, rowIndex, fieldName) {
var currentDisplayData = this.getCurrentDisplayData();
var rowKeyCache = undefined;
if (!this.enablePagination) {
currentDisplayData[rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[rowIndex][this.keyField];
} else {
currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField];
}
if (this.isOnFilter) {
this.data.forEach(function (row) {
if (row[this.keyField] === rowKeyCache) {
row[fieldName] = newVal;
}
}, this);
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
return this;
}
}, {
key: 'addAtBegin',
value: function addAtBegin(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw this.keyField + ' can\'t be empty value.';
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw this.keyField + ' ' + newObj[this.keyField] + ' already exists';
}
}, this);
currentDisplayData.unshift(newObj);
if (this.isOnFilter) {
this.data.unshift(newObj);
}
this._refresh();
}
}, {
key: 'add',
value: function add(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw this.keyField + ' can\'t be empty value.';
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw this.keyField + ' ' + newObj[this.keyField] + ' already exists';
}
}, this);
currentDisplayData.push(newObj);
if (this.isOnFilter) {
this.data.push(newObj);
}
this._refresh();
}
}, {
key: 'remove',
value: function remove(rowKey) {
var _this2 = this;
var currentDisplayData = this.getCurrentDisplayData();
var result = currentDisplayData.filter(function (row) {
return rowKey.indexOf(row[_this2.keyField]) === -1;
});
if (this.isOnFilter) {
this.data = this.data.filter(function (row) {
return rowKey.indexOf(row[_this2.keyField]) === -1;
});
this.filteredData = result;
} else {
this.data = result;
}
}
}, {
key: 'filter',
value: function filter(filterObj) {
var _this3 = this;
if (Object.keys(filterObj).length === 0) {
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
if (this.searchText !== null) this.search(this.searchText);
} else {
this.filterObj = filterObj;
this.filteredData = this.data.filter(function (row) {
var valid = true;
var filterVal = undefined;
for (var key in filterObj) {
var targetVal = row[key];
switch (filterObj[key].type) {
case _Const2['default'].FILTER_TYPE.NUMBER:
{
filterVal = filterObj[key].value.number;
break;
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
filterVal = typeof filterObj[key].value === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
break;
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
filterVal = filterObj[key].value;
break;
}
default:
{
filterVal = typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
if (filterVal === undefined) {
// Support old filter
filterVal = filterObj[key].toLowerCase();
}
break;
}
}
if (_this3.colInfos[key]) {
var _colInfos$key = _this3.colInfos[key];
var format = _colInfos$key.format;
var filterFormatted = _colInfos$key.filterFormatted;
var formatExtraData = _colInfos$key.formatExtraData;
if (filterFormatted && format) {
targetVal = format(row[key], row, formatExtraData);
}
}
switch (filterObj[key].type) {
case _Const2['default'].FILTER_TYPE.NUMBER:
{
valid = _this3.filterNumber(targetVal, filterVal, filterObj[key].value.comparator);
break;
}
case _Const2['default'].FILTER_TYPE.DATE:
{
valid = _this3.filterDate(targetVal, filterVal);
break;
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
valid = _this3.filterRegex(targetVal, filterVal);
break;
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
valid = _this3.filterCustom(targetVal, filterVal, filterObj[key].value);
break;
}
default:
{
valid = _this3.filterText(targetVal, filterVal);
break;
}
}
if (!valid) {
break;
}
}
return valid;
});
this.isOnFilter = true;
}
}
}, {
key: 'filterNumber',
value: function filterNumber(targetVal, filterVal, comparator) {
var valid = true;
switch (comparator) {
case '=':
{
if (targetVal != filterVal) {
valid = false;
}
break;
}
case '>':
{
if (targetVal <= filterVal) {
valid = false;
}
break;
}
case '>=':
{
if (targetVal < filterVal) {
valid = false;
}
break;
}
case '<':
{
if (targetVal >= filterVal) {
valid = false;
}
break;
}
case '<=':
{
if (targetVal > filterVal) {
valid = false;
}
break;
}
case '!=':
{
if (targetVal == filterVal) {
valid = false;
}
break;
}
default:
{
console.error('Number comparator provided is not supported');
break;
}
}
return valid;
}
}, {
key: 'filterDate',
value: function filterDate(targetVal, filterVal) {
if (!targetVal) {
return false;
}
return targetVal.getDate() === filterVal.getDate() && targetVal.getMonth() === filterVal.getMonth() && targetVal.getFullYear() === filterVal.getFullYear();
}
}, {
key: 'filterRegex',
value: function filterRegex(targetVal, filterVal) {
try {
return new RegExp(filterVal, 'i').test(targetVal);
} catch (e) {
console.error('Invalid regular expression');
return true;
}
}
}, {
key: 'filterCustom',
value: function filterCustom(targetVal, filterVal, callbackInfo) {
if (callbackInfo !== null && typeof callbackInfo === 'object') {
return callbackInfo.callback(targetVal, callbackInfo.callbackParameters);
}
return this.filterText(targetVal, filterVal);
}
}, {
key: 'filterText',
value: function filterText(targetVal, filterVal) {
if (targetVal.toString().toLowerCase().indexOf(filterVal) === -1) {
return false;
}
return true;
}
/* General search function
* It will search for the text if the input includes that text;
*/
}, {
key: 'search',
value: function search(searchText) {
var _this4 = this;
if (searchText.trim() === '') {
this.filteredData = null;
this.isOnFilter = false;
this.searchText = null;
if (this.filterObj !== null) this.filter(this.filterObj);
} else {
(function () {
_this4.searchText = searchText;
var searchTextArray = [];
if (_this4.multiColumnSearch) {
searchTextArray = searchText.split(' ');
} else {
searchTextArray.push(searchText);
}
// Mark following code for fixing #363
// To avoid to search on a data which be searched or filtered
// But this solution have a poor performance, because I do a filter again
// const source = this.isOnFilter ? this.filteredData : this.data;
var source = _this4.filterObj !== null ? _this4.filter(_this4.filterObj) : _this4.data;
_this4.filteredData = source.filter(function (row) {
var keys = Object.keys(row);
var valid = false;
// for loops are ugly, but performance matters here.
// And you cant break from a forEach.
// http://jsperf.com/for-vs-foreach/66
for (var i = 0, keysLength = keys.length; i < keysLength; i++) {
var key = keys[i];
if (_this4.colInfos[key] && row[key]) {
var _colInfos$key2 = _this4.colInfos[key];
var format = _colInfos$key2.format;
var filterFormatted = _colInfos$key2.filterFormatted;
var formatExtraData = _colInfos$key2.formatExtraData;
var searchable = _colInfos$key2.searchable;
var targetVal = row[key];
if (searchable) {
if (filterFormatted && format) {
targetVal = format(targetVal, row, formatExtraData);
}
for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) {
var filterVal = searchTextArray[j].toLowerCase();
if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) {
valid = true;
break;
}
}
}
}
}
return valid;
});
_this4.isOnFilter = true;
})();
}
}
}, {
key: 'getDataIgnoringPagination',
value: function getDataIgnoringPagination() {
return this.getCurrentDisplayData();
}
}, {
key: 'get',
value: function get() {
var _data = this.getCurrentDisplayData();
if (_data.length === 0) return _data;
if (this.remote || !this.enablePagination) {
return _data;
} else {
var result = [];
for (var i = this.pageObj.start; i <= this.pageObj.end; i++) {
result.push(_data[i]);
if (i + 1 === _data.length) break;
}
return result;
}
}
}, {
key: 'getKeyField',
value: function getKeyField() {
return this.keyField;
}
}, {
key: 'getDataNum',
value: function getDataNum() {
return this.getCurrentDisplayData().length;
}
}, {
key: 'isChangedPage',
value: function isChangedPage() {
return this.pageObj.start && this.pageObj.end ? true : false;
}
}, {
key: 'isEmpty',
value: function isEmpty() {
return this.data.length === 0 || this.data === null || this.data === undefined;
}
}, {
key: 'getAllRowkey',
value: function getAllRowkey() {
var _this5 = this;
return this.data.map(function (row) {
return row[_this5.keyField];
});
}
}]);
return TableDataStore;
})();
exports.TableDataStore = TableDataStore;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
exports['default'] = {
renderReactSortCaret: function renderReactSortCaret(order) {
var orderClass = (0, _classnames2['default'])('order', {
'dropup': order === _Const2['default'].SORT_ASC
});
return _react2['default'].createElement(
'span',
{ className: orderClass },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '0px 5px' } })
);
},
getScrollBarWidth: function getScrollBarWidth() {
var inner = document.createElement('p');
inner.style.width = '100%';
inner.style.height = '200px';
var outer = document.createElement('div');
outer.style.position = 'absolute';
outer.style.top = '0px';
outer.style.left = '0px';
outer.style.visibility = 'hidden';
outer.style.width = '200px';
outer.style.height = '150px';
outer.style.overflow = 'hidden';
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 === w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return w1 - w2;
},
canUseDOM: function canUseDOM() {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
}
};
module.exports = exports['default'];
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* eslint block-scoped-var: 0 */
/* eslint vars-on-top: 0 */
/* eslint no-var: 0 */
/* eslint no-unused-vars: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
if (_util2['default'].canUseDOM()) {
var filesaver = __webpack_require__(36);
var saveAs = filesaver.saveAs;
}
function toString(data, keys) {
var dataString = '';
if (data.length === 0) return dataString;
dataString += keys.join(',') + '\n';
data.map(function (row) {
keys.map(function (col, i) {
var cell = typeof row[col] !== 'undefined' ? '"' + row[col] + '"' : '';
dataString += cell;
if (i + 1 < keys.length) dataString += ',';
});
dataString += '\n';
});
return dataString;
}
var exportCSV = function exportCSV(data, keys, filename) {
var dataString = toString(data, keys);
if (typeof window !== 'undefined') {
saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename || 'spreadsheet.csv');
}
};
exports['default'] = exportCSV;
module.exports = exports['default'];
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20151003
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
"use strict";
var saveAs = saveAs || (function (view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var doc = view.document,
// only get URL when necessary in case Blob.js hasn't overridden it yet
get_URL = function get_URL() {
return view.URL || view.webkitURL || view;
},
save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
can_use_save_link = ("download" in save_link),
click = function click(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
},
is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent),
webkit_req_fs = view.webkitRequestFileSystem,
req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem,
throw_outside = function throw_outside(ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
},
force_saveable_type = "application/octet-stream",
fs_min_size = 0,
// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
// for the reasoning behind the timeout and revocation flow
arbitrary_revoke_timeout = 500,
// in ms
revoke = function revoke(file) {
var revoker = function revoker() {
if (typeof file === "string") {
// file is an object URL
get_URL().revokeObjectURL(file);
} else {
// file is a File
file.remove();
}
};
if (view.chrome) {
revoker();
} else {
setTimeout(revoker, arbitrary_revoke_timeout);
}
},
dispatch = function dispatch(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
},
auto_bom = function auto_bom(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob(["", blob], { type: blob.type });
}
return blob;
},
FileSaver = function FileSaver(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var filesaver = this,
type = blob.type,
blob_changed = false,
object_url,
target_view,
dispatch_all = function dispatch_all() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
},
// on any filesys errors revert to saving with object URLs
fs_error = function fs_error() {
if (target_view && is_safari && typeof FileReader !== "undefined") {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function () {
var base64Data = reader.result;
target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && is_safari) {
//Apple do not allow window.open, see http://bit.ly/1kZffRI
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
},
abortable = function abortable(func) {
return function () {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
},
create_if_not_found = { create: true, exclusive: false },
slice;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
save_link.href = object_url;
save_link.download = name;
setTimeout(function () {
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
// Update: Google errantly closed 91158, I submitted it again:
// https://code.google.com/p/chromium/issues/detail?id=389642
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
if (webkit_req_fs && name !== "download") {
name += ".download";
}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) {
var save = function save() {
dir.getFile(name, create_if_not_found, abortable(function (file) {
file.createWriter(abortable(function (writer) {
writer.onwriteend = function (event) {
target_view.location.href = file.toURL();
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
revoke(file);
};
writer.onerror = function () {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function (event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function () {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, { create: false }, abortable(function (file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function (ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
},
FS_proto = FileSaver.prototype,
saveAs = function saveAs(blob, name, no_auto_bom) {
return new FileSaver(blob, name, no_auto_bom);
};
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function (blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name || "download");
};
}
FS_proto.abort = function () {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
return saveAs;
})(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content);
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ("function" !== "undefined" && __webpack_require__(37) !== null && __webpack_require__(38) != null) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return saveAs;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 37 */
/***/ function(module, exports) {
module.exports = function() { throw new Error("define cannot be used indirect"); };
/***/ },
/* 38 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _events = __webpack_require__(40);
var Filter = (function (_EventEmitter) {
_inherits(Filter, _EventEmitter);
function Filter(data) {
_classCallCheck(this, Filter);
_get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data);
this.currentFilter = {};
}
_createClass(Filter, [{
key: 'handleFilter',
value: function handleFilter(dataField, value, type) {
var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM;
if (value !== null && typeof value === 'object') {
// value of the filter is an object
var hasValue = true;
for (var prop in value) {
if (!value[prop] || value[prop] === '') {
hasValue = false;
break;
}
}
// if one of the object properties is undefined or empty, we remove the filter
if (hasValue) {
this.currentFilter[dataField] = { value: value, type: filterType };
} else {
delete this.currentFilter[dataField];
}
} else if (!value || value.trim() === '') {
delete this.currentFilter[dataField];
} else {
this.currentFilter[dataField] = { value: value.trim(), type: filterType };
}
this.emit('onFilterChange', this.currentFilter);
}
}]);
return Filter;
})(_events.EventEmitter);
exports.Filter = Filter;
/***/ },
/* 40 */
/***/ function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
/* eslint default-case: 0 */
/* eslint guard-for-in: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
var _filtersDate = __webpack_require__(42);
var _filtersDate2 = _interopRequireDefault(_filtersDate);
var _filtersText = __webpack_require__(43);
var _filtersText2 = _interopRequireDefault(_filtersText);
var _filtersRegex = __webpack_require__(44);
var _filtersRegex2 = _interopRequireDefault(_filtersRegex);
var _filtersSelect = __webpack_require__(45);
var _filtersSelect2 = _interopRequireDefault(_filtersSelect);
var _filtersNumber = __webpack_require__(46);
var _filtersNumber2 = _interopRequireDefault(_filtersNumber);
var TableHeaderColumn = (function (_Component) {
_inherits(TableHeaderColumn, _Component);
function TableHeaderColumn(props) {
var _this = this;
_classCallCheck(this, TableHeaderColumn);
_get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props);
this.handleColumnClick = function () {
if (!_this.props.dataSort) return;
var order = _this.props.sort === _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC;
_this.props.onSort(order, _this.props.dataField);
};
this.handleFilter = this.handleFilter.bind(this);
}
_createClass(TableHeaderColumn, [{
key: 'handleFilter',
value: function handleFilter(value, type) {
this.props.filter.emitter.handleFilter(this.props.dataField, value, type);
}
}, {
key: 'getFilters',
value: function getFilters() {
switch (this.props.filter.type) {
case _Const2['default'].FILTER_TYPE.TEXT:
{
return _react2['default'].createElement(_filtersText2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
return _react2['default'].createElement(_filtersRegex2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.SELECT:
{
return _react2['default'].createElement(_filtersSelect2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.NUMBER:
{
return _react2['default'].createElement(_filtersNumber2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.DATE:
{
return _react2['default'].createElement(_filtersDate2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters);
}
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs['header-col'].setAttribute('data-field', this.props.dataField);
}
}, {
key: 'render',
value: function render() {
var defaultCaret = undefined;
var thStyle = {
textAlign: this.props.dataAlign,
display: this.props.hidden ? 'none' : null
};
if (this.props.sortIndicator) {
defaultCaret = !this.props.dataSort ? null : _react2['default'].createElement(
'span',
{ className: 'order' },
_react2['default'].createElement(
'span',
{ className: 'dropdown' },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } })
),
_react2['default'].createElement(
'span',
{ className: 'dropup' },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } })
)
);
}
var sortCaret = this.props.sort ? _util2['default'].renderReactSortCaret(this.props.sort) : defaultCaret;
var classes = this.props.className + ' ' + (this.props.dataSort ? 'sort-column' : '');
var title = typeof this.props.children === 'string' ? { title: this.props.children } : null;
return _react2['default'].createElement(
'th',
_extends({ ref: 'header-col',
className: classes,
style: thStyle,
onClick: this.handleColumnClick
}, title),
this.props.children,
sortCaret,
_react2['default'].createElement(
'div',
{ onClick: function (e) {
return e.stopPropagation();
} },
this.props.filter ? this.getFilters() : null
)
);
}
}]);
return TableHeaderColumn;
})(_react.Component);
var filterTypeArray = [];
for (var key in _Const2['default'].FILTER_TYPE) {
filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]);
}
TableHeaderColumn.propTypes = {
dataField: _react.PropTypes.string,
dataAlign: _react.PropTypes.string,
dataSort: _react.PropTypes.bool,
onSort: _react.PropTypes.func,
dataFormat: _react.PropTypes.func,
isKey: _react.PropTypes.bool,
editable: _react.PropTypes.any,
hidden: _react.PropTypes.bool,
searchable: _react.PropTypes.bool,
className: _react.PropTypes.string,
width: _react.PropTypes.string,
sortFunc: _react.PropTypes.func,
sortFuncExtraData: _react.PropTypes.any,
columnClassName: _react.PropTypes.any,
filterFormatted: _react.PropTypes.bool,
sort: _react.PropTypes.string,
formatExtraData: _react.PropTypes.any,
filter: _react.PropTypes.shape({
type: _react.PropTypes.oneOf(filterTypeArray),
delay: _react.PropTypes.number,
options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter
_react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter
]),
numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string),
emitter: _react.PropTypes.object,
placeholder: _react.PropTypes.string,
getElement: _react.PropTypes.func,
customFilterParameters: _react.PropTypes.object
}),
sortIndicator: _react.PropTypes.bool
};
TableHeaderColumn.defaultProps = {
dataAlign: 'left',
dataSort: false,
dataFormat: undefined,
isKey: false,
editable: true,
onSort: undefined,
hidden: false,
searchable: true,
className: '',
width: null,
sortFunc: undefined,
columnClassName: '',
filterFormatted: false,
sort: undefined,
formatExtraData: undefined,
sortFuncExtraData: undefined,
filter: undefined,
sortIndicator: true
};
exports['default'] = TableHeaderColumn;
module.exports = exports['default'];
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/* eslint quotes: 0 */
/* eslint max-len: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var DateFilter = (function (_Component) {
_inherits(DateFilter, _Component);
function DateFilter(props) {
_classCallCheck(this, DateFilter);
_get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
}
_createClass(DateFilter, [{
key: 'setDefaultDate',
value: function setDefaultDate() {
var defaultDate = '';
if (this.props.defaultValue) {
// Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
var defaultValue = new Date(this.props.defaultValue);
defaultDate = defaultValue.getFullYear() + '-' + ("0" + (defaultValue.getMonth() + 1)).slice(-2) + '-' + ("0" + defaultValue.getDate()).slice(-2);
}
return defaultDate;
}
}, {
key: 'filter',
value: function filter(event) {
var dateValue = event.target.value;
if (dateValue) {
this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE);
} else {
this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE);
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var dateValue = this.refs.inputDate.defaultValue;
if (dateValue) {
this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE);
}
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('input', { ref: 'inputDate',
className: 'filter date-filter form-control',
type: 'date',
onChange: this.filter,
defaultValue: this.setDefaultDate() });
}
}]);
return DateFilter;
})(_react.Component);
DateFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.object,
columnName: _react.PropTypes.string
};
exports['default'] = DateFilter;
module.exports = exports['default'];
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var TextFilter = (function (_Component) {
_inherits(TextFilter, _Component);
function TextFilter(props) {
_classCallCheck(this, TextFilter);
_get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.timeout = null;
}
_createClass(TextFilter, [{
key: 'filter',
value: function filter(event) {
var _this = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT);
}, this.props.delay);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var defaultValue = this.refs.inputText.defaultValue;
if (defaultValue) {
this.props.filterHandler(defaultValue, _Const2['default'].FILTER_TYPE.TEXT);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
var defaultValue = _props.defaultValue;
return _react2['default'].createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return TextFilter;
})(_react.Component);
TextFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
TextFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = TextFilter;
module.exports = exports['default'];
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var RegexFilter = (function (_Component) {
_inherits(RegexFilter, _Component);
function RegexFilter(props) {
_classCallCheck(this, RegexFilter);
_get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.timeout = null;
}
_createClass(RegexFilter, [{
key: 'filter',
value: function filter(event) {
var _this = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX);
}, this.props.delay);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.inputText.defaultValue;
if (value) {
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.REGEX);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var defaultValue = _props.defaultValue;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
return _react2['default'].createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter Regex for ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return RegexFilter;
})(_react.Component);
RegexFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
RegexFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = RegexFilter;
module.exports = exports['default'];
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var SelectFilter = (function (_Component) {
_inherits(SelectFilter, _Component);
function SelectFilter(props) {
_classCallCheck(this, SelectFilter);
_get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.state = {
isPlaceholderSelected: this.props.defaultValue === undefined || !this.props.options.hasOwnProperty(this.props.defaultValue)
};
}
_createClass(SelectFilter, [{
key: 'filter',
value: function filter(event) {
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT);
}
}, {
key: 'getOptions',
value: function getOptions() {
var optionTags = [];
var _props = this.props;
var options = _props.options;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
optionTags.push(_react2['default'].createElement(
'option',
{ key: '-1', value: '' },
placeholder || 'Select ' + columnName + '...'
));
Object.keys(options).map(function (key) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: key, value: key },
options[key]
));
});
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.selectInput.value;
if (value) {
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT);
}
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2['default'])('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2['default'].createElement(
'select',
{ ref: 'selectInput',
className: selectClass,
onChange: this.filter,
defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' },
this.getOptions()
);
}
}]);
return SelectFilter;
})(_react.Component);
SelectFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.object.isRequired,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
exports['default'] = SelectFilter;
module.exports = exports['default'];
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _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 { _x = parent; _x2 = property; _x3 = 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); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var legalComparators = ['=', '>', '>=', '<', '<=', '!='];
var NumberFilter = (function (_Component) {
_inherits(NumberFilter, _Component);
function NumberFilter(props) {
_classCallCheck(this, NumberFilter);
_get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props);
this.numberComparators = this.props.numberComparators || legalComparators;
this.timeout = null;
this.state = {
isPlaceholderSelected: this.props.defaultValue === undefined || this.props.defaultValue.number === undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) === -1
};
this.onChangeNumber = this.onChangeNumber.bind(this);
this.onChangeNumberSet = this.onChangeNumberSet.bind(this);
this.onChangeComparator = this.onChangeComparator.bind(this);
}
_createClass(NumberFilter, [{
key: 'onChangeNumber',
value: function onChangeNumber(event) {
var _this = this;
var comparator = this.refs.numberFilterComparator.value;
if (comparator === '') {
return;
}
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}, this.props.delay);
}
}, {
key: 'onChangeNumberSet',
value: function onChangeNumberSet(event) {
var comparator = this.refs.numberFilterComparator.value;
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
if (comparator === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}, {
key: 'onChangeComparator',
value: function onChangeComparator(event) {
var value = this.refs.numberFilter.value;
var comparator = event.target.value;
if (value === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}, {
key: 'getComparatorOptions',
value: function getComparatorOptions() {
var optionTags = [];
optionTags.push(_react2['default'].createElement('option', { key: '-1' }));
for (var i = 0; i < this.numberComparators.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: this.numberComparators[i] },
this.numberComparators[i]
));
}
return optionTags;
}
}, {
key: 'getNumberOptions',
value: function getNumberOptions() {
var optionTags = [];
var options = this.props.options;
optionTags.push(_react2['default'].createElement(
'option',
{ key: '-1', value: '' },
this.props.placeholder || 'Select ' + this.props.columnName + '...'
));
for (var i = 0; i < options.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: options[i] },
options[i]
));
}
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var comparator = this.refs.numberFilterComparator.value;
var number = this.refs.numberFilter.value;
if (comparator && number) {
this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2['default'])('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2['default'].createElement(
'div',
{ className: 'filter number-filter' },
_react2['default'].createElement(
'select',
{ ref: 'numberFilterComparator',
className: 'number-filter-comparator form-control',
onChange: this.onChangeComparator,
defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' },
this.getComparatorOptions()
),
this.props.options ? _react2['default'].createElement(
'select',
{ ref: 'numberFilter',
className: selectClass,
onChange: this.onChangeNumberSet,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' },
this.getNumberOptions()
) : _react2['default'].createElement('input', { ref: 'numberFilter',
type: 'number',
className: 'number-filter-input form-control',
placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...',
onChange: this.onChangeNumber,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' })
);
}
}]);
return NumberFilter;
})(_react.Component);
NumberFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.arrayOf(_react.PropTypes.number),
defaultValue: _react.PropTypes.shape({
number: _react.PropTypes.number,
comparator: _react.PropTypes.oneOf(legalComparators)
}),
delay: _react.PropTypes.number,
/* eslint consistent-return: 0 */
numberComparators: function numberComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators);
}
}
},
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
NumberFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = NumberFilter;
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
//# sourceMappingURL=react-bootstrap-table.js.map
|
(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.vl = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
(function (Buffer){
var u = module.exports;
// utility functions
var FNAME = '__name__';
u.namedfunc = function(name, f) { return (f[FNAME] = name, f); };
u.name = function(f) { return f==null ? null : f[FNAME]; };
u.identity = function(x) { return x; };
u.true = u.namedfunc('true', function() { return true; });
u.false = u.namedfunc('false', function() { return false; });
u.duplicate = function(obj) {
return JSON.parse(JSON.stringify(obj));
};
u.equal = function(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
};
u.extend = function(obj) {
for (var x, name, i=1, len=arguments.length; i<len; ++i) {
x = arguments[i];
for (name in x) { obj[name] = x[name]; }
}
return obj;
};
u.length = function(x) {
return x != null && x.length != null ? x.length : null;
};
u.keys = function(x) {
var keys = [], k;
for (k in x) keys.push(k);
return keys;
};
u.vals = function(x) {
var vals = [], k;
for (k in x) vals.push(x[k]);
return vals;
};
u.toMap = function(list, f) {
return (f = u.$(f)) ?
list.reduce(function(obj, x) { return (obj[f(x)] = 1, obj); }, {}) :
list.reduce(function(obj, x) { return (obj[x] = 1, obj); }, {});
};
u.keystr = function(values) {
// use to ensure consistent key generation across modules
var n = values.length;
if (!n) return '';
for (var s=String(values[0]), i=1; i<n; ++i) {
s += '|' + String(values[i]);
}
return s;
};
// type checking functions
var toString = Object.prototype.toString;
u.isObject = function(obj) {
return obj === Object(obj);
};
u.isFunction = function(obj) {
return toString.call(obj) === '[object Function]';
};
u.isString = function(obj) {
return typeof value === 'string' || toString.call(obj) === '[object String]';
};
u.isArray = Array.isArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
u.isNumber = function(obj) {
return typeof obj === 'number' || toString.call(obj) === '[object Number]';
};
u.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
u.isDate = function(obj) {
return toString.call(obj) === '[object Date]';
};
u.isValid = function(obj) {
return obj != null && obj === obj;
};
u.isBuffer = (typeof Buffer === 'function' && Buffer.isBuffer) || u.false;
// type coercion functions
u.number = function(s) {
return s == null || s === '' ? null : +s;
};
u.boolean = function(s) {
return s == null || s === '' ? null : s==='false' ? false : !!s;
};
// parse a date with optional d3.time-format format
u.date = function(s, format) {
var d = format ? format : Date;
return s == null || s === '' ? null : d.parse(s);
};
u.array = function(x) {
return x != null ? (u.isArray(x) ? x : [x]) : [];
};
u.str = function(x) {
return u.isArray(x) ? '[' + x.map(u.str) + ']'
: u.isObject(x) || u.isString(x) ?
// Output valid JSON and JS source strings.
// See http://timelessrepo.com/json-isnt-a-javascript-subset
JSON.stringify(x).replace('\u2028','\\u2028').replace('\u2029', '\\u2029')
: x;
};
// data access functions
var field_re = /\[(.*?)\]|[^.\[]+/g;
u.field = function(f) {
return String(f).match(field_re).map(function(d) {
return d[0] !== '[' ? d :
d[1] !== "'" && d[1] !== '"' ? d.slice(1, -1) :
d.slice(2, -2).replace(/\\(["'])/g, '$1');
});
};
u.accessor = function(f) {
/* jshint evil: true */
return f==null || u.isFunction(f) ? f :
u.namedfunc(f, Function('x', 'return x[' + u.field(f).map(u.str).join('][') + '];'));
};
// short-cut for accessor
u.$ = u.accessor;
u.mutator = function(f) {
var s;
return u.isString(f) && (s=u.field(f)).length > 1 ?
function(x, v) {
for (var i=0; i<s.length-1; ++i) x = x[s[i]];
x[s[i]] = v;
} :
function(x, v) { x[f] = v; };
};
u.$func = function(name, op) {
return function(f) {
f = u.$(f) || u.identity;
var n = name + (u.name(f) ? '_'+u.name(f) : '');
return u.namedfunc(n, function(d) { return op(f(d)); });
};
};
u.$valid = u.$func('valid', u.isValid);
u.$length = u.$func('length', u.length);
u.$in = function(f, values) {
f = u.$(f);
var map = u.isArray(values) ? u.toMap(values) : values;
return function(d) { return !!map[f(d)]; };
};
// comparison / sorting functions
u.comparator = function(sort) {
var sign = [];
if (sort === undefined) sort = [];
sort = u.array(sort).map(function(f) {
var s = 1;
if (f[0] === '-') { s = -1; f = f.slice(1); }
else if (f[0] === '+') { s = +1; f = f.slice(1); }
sign.push(s);
return u.accessor(f);
});
return function(a, b) {
var i, n, f, c;
for (i=0, n=sort.length; i<n; ++i) {
f = sort[i];
c = u.cmp(f(a), f(b));
if (c) return c * sign[i];
}
return 0;
};
};
u.cmp = function(a, b) {
return (a < b || a == null) && b != null ? -1 :
(a > b || b == null) && a != null ? 1 :
((b = b instanceof Date ? +b : b),
(a = a instanceof Date ? +a : a)) !== a && b === b ? -1 :
b !== b && a === a ? 1 : 0;
};
u.numcmp = function(a, b) { return a - b; };
u.stablesort = function(array, sortBy, keyFn) {
var indices = array.reduce(function(idx, v, i) {
return (idx[keyFn(v)] = i, idx);
}, {});
array.sort(function(a, b) {
var sa = sortBy(a),
sb = sortBy(b);
return sa < sb ? -1 : sa > sb ? 1
: (indices[keyFn(a)] - indices[keyFn(b)]);
});
return array;
};
// permutes an array using a Knuth shuffle
u.permute = function(a) {
var m = a.length,
swap,
i;
while (m) {
i = Math.floor(Math.random() * m--);
swap = a[m];
a[m] = a[i];
a[i] = swap;
}
};
// string functions
u.pad = function(s, length, pos, padchar) {
padchar = padchar || " ";
var d = length - s.length;
if (d <= 0) return s;
switch (pos) {
case 'left':
return strrep(d, padchar) + s;
case 'middle':
case 'center':
return strrep(Math.floor(d/2), padchar) +
s + strrep(Math.ceil(d/2), padchar);
default:
return s + strrep(d, padchar);
}
};
function strrep(n, str) {
var s = "", i;
for (i=0; i<n; ++i) s += str;
return s;
}
u.truncate = function(s, length, pos, word, ellipsis) {
var len = s.length;
if (len <= length) return s;
ellipsis = ellipsis !== undefined ? String(ellipsis) : '\u2026';
var l = Math.max(0, length - ellipsis.length);
switch (pos) {
case 'left':
return ellipsis + (word ? truncateOnWord(s,l,1) : s.slice(len-l));
case 'middle':
case 'center':
var l1 = Math.ceil(l/2), l2 = Math.floor(l/2);
return (word ? truncateOnWord(s,l1) : s.slice(0,l1)) +
ellipsis + (word ? truncateOnWord(s,l2,1) : s.slice(len-l2));
default:
return (word ? truncateOnWord(s,l) : s.slice(0,l)) + ellipsis;
}
};
function truncateOnWord(s, len, rev) {
var cnt = 0, tok = s.split(truncate_word_re);
if (rev) {
s = (tok = tok.reverse())
.filter(function(w) { cnt += w.length; return cnt <= len; })
.reverse();
} else {
s = tok.filter(function(w) { cnt += w.length; return cnt <= len; });
}
return s.length ? s.join('').trim() : tok[0].slice(0, len);
}
var truncate_word_re = /([\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF])/;
}).call(this,require("buffer").Buffer)
},{"buffer":1}],3:[function(require,module,exports){
var json = typeof JSON !== 'undefined' ? JSON : require('jsonify');
module.exports = function (obj, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var space = opts.space || '';
if (typeof space === 'number') space = Array(space+1).join(' ');
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var replacer = opts.replacer || function(key, value) { return value; };
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (parent, key, node, level) {
var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
var colonSeparator = space ? ': ' : ':';
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
node = replacer.call(parent, key, node);
if (node === undefined) {
return;
}
if (typeof node !== 'object' || node === null) {
return json.stringify(node);
}
if (isArray(node)) {
var out = [];
for (var i = 0; i < node.length; i++) {
var item = stringify(node, i, node[i], level+1) || json.stringify(null);
out.push(indent + space + item);
}
return '[' + out.join(',') + indent + ']';
}
else {
if (seen.indexOf(node) !== -1) {
if (cycles) return json.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
else seen.push(node);
var keys = objectKeys(node).sort(cmp && cmp(node));
var out = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node, key, node[key], level+1);
if(!value) continue;
var keyValue = json.stringify(key)
+ colonSeparator
+ value;
;
out.push(indent + space + keyValue);
}
seen.splice(seen.indexOf(node), 1);
return '{' + out.join(',') + indent + '}';
}
})({ '': obj }, '', obj, 0);
};
var isArray = Array.isArray || function (x) {
return {}.toString.call(x) === '[object Array]';
};
var objectKeys = Object.keys || function (obj) {
var has = Object.prototype.hasOwnProperty || function () { return true };
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) keys.push(key);
}
return keys;
};
},{"jsonify":4}],4:[function(require,module,exports){
exports.parse = require('./lib/parse');
exports.stringify = require('./lib/stringify');
},{"./lib/parse":5,"./lib/stringify":6}],5:[function(require,module,exports){
var at, // The index of the current character
ch, // The current character
escapee = {
'"': '"',
'\\': '\\',
'/': '/',
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t'
},
text,
error = function (m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
next = function (c) {
// If a c parameter is provided, verify that it matches the current character.
if (c && c !== ch) {
error("Expected '" + c + "' instead of '" + ch + "'");
}
// Get the next character. When there are no more characters,
// return the empty string.
ch = text.charAt(at);
at += 1;
return ch;
},
number = function () {
// Parse a number value.
var number,
string = '';
if (ch === '-') {
string = '-';
next('-');
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
if (ch === '.') {
string += '.';
while (next() && ch >= '0' && ch <= '9') {
string += ch;
}
}
if (ch === 'e' || ch === 'E') {
string += ch;
next();
if (ch === '-' || ch === '+') {
string += ch;
next();
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
}
number = +string;
if (!isFinite(number)) {
error("Bad number");
} else {
return number;
}
},
string = function () {
// Parse a string value.
var hex,
i,
string = '',
uffff;
// When parsing for string values, we must look for " and \ characters.
if (ch === '"') {
while (next()) {
if (ch === '"') {
next();
return string;
} else if (ch === '\\') {
next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break;
}
} else {
string += ch;
}
}
}
error("Bad string");
},
white = function () {
// Skip whitespace.
while (ch && ch <= ' ') {
next();
}
},
word = function () {
// true, false, or null.
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return true;
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return false;
case 'n':
next('n');
next('u');
next('l');
next('l');
return null;
}
error("Unexpected '" + ch + "'");
},
value, // Place holder for the value function.
array = function () {
// Parse an array value.
var array = [];
if (ch === '[') {
next('[');
white();
if (ch === ']') {
next(']');
return array; // empty array
}
while (ch) {
array.push(value());
white();
if (ch === ']') {
next(']');
return array;
}
next(',');
white();
}
}
error("Bad array");
},
object = function () {
// Parse an object value.
var key,
object = {};
if (ch === '{') {
next('{');
white();
if (ch === '}') {
next('}');
return object; // empty object
}
while (ch) {
key = string();
white();
next(':');
if (Object.hasOwnProperty.call(object, key)) {
error('Duplicate key "' + key + '"');
}
object[key] = value();
white();
if (ch === '}') {
next('}');
return object;
}
next(',');
white();
}
}
error("Bad object");
};
value = function () {
// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.
white();
switch (ch) {
case '{':
return object();
case '[':
return array();
case '"':
return string();
case '-':
return number();
default:
return ch >= '0' && ch <= '9' ? number() : word();
}
};
// Return the json_parse function. It will have access to all of the above
// functions and variables.
module.exports = function (source, reviver) {
var result;
text = source;
at = 0;
ch = ' ';
result = value();
white();
if (ch) {
error("Syntax error");
}
// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.
return typeof reviver === 'function' ? (function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}({'': result}, '')) : result;
};
},{}],6:[function(require,module,exports){
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
case 'object':
if (!value) return 'null';
gap += indent;
partial = [];
// Array.isArray
if (Object.prototype.toString.apply(value) === '[object Array]') {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and
// wrap them in brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be
// stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
module.exports = function (value, replacer, space) {
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
}
// If the space parameter is a string, it will be used as the indent string.
else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function'
&& (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
},{}],7:[function(require,module,exports){
"use strict";
(function (AggregateOp) {
AggregateOp[AggregateOp["VALUES"] = 'values'] = "VALUES";
AggregateOp[AggregateOp["COUNT"] = 'count'] = "COUNT";
AggregateOp[AggregateOp["VALID"] = 'valid'] = "VALID";
AggregateOp[AggregateOp["MISSING"] = 'missing'] = "MISSING";
AggregateOp[AggregateOp["DISTINCT"] = 'distinct'] = "DISTINCT";
AggregateOp[AggregateOp["SUM"] = 'sum'] = "SUM";
AggregateOp[AggregateOp["MEAN"] = 'mean'] = "MEAN";
AggregateOp[AggregateOp["AVERAGE"] = 'average'] = "AVERAGE";
AggregateOp[AggregateOp["VARIANCE"] = 'variance'] = "VARIANCE";
AggregateOp[AggregateOp["VARIANCEP"] = 'variancep'] = "VARIANCEP";
AggregateOp[AggregateOp["STDEV"] = 'stdev'] = "STDEV";
AggregateOp[AggregateOp["STDEVP"] = 'stdevp'] = "STDEVP";
AggregateOp[AggregateOp["MEDIAN"] = 'median'] = "MEDIAN";
AggregateOp[AggregateOp["Q1"] = 'q1'] = "Q1";
AggregateOp[AggregateOp["Q3"] = 'q3'] = "Q3";
AggregateOp[AggregateOp["MODESKEW"] = 'modeskew'] = "MODESKEW";
AggregateOp[AggregateOp["MIN"] = 'min'] = "MIN";
AggregateOp[AggregateOp["MAX"] = 'max'] = "MAX";
AggregateOp[AggregateOp["ARGMIN"] = 'argmin'] = "ARGMIN";
AggregateOp[AggregateOp["ARGMAX"] = 'argmax'] = "ARGMAX";
})(exports.AggregateOp || (exports.AggregateOp = {}));
var AggregateOp = exports.AggregateOp;
exports.AGGREGATE_OPS = [
AggregateOp.VALUES,
AggregateOp.COUNT,
AggregateOp.VALID,
AggregateOp.MISSING,
AggregateOp.DISTINCT,
AggregateOp.SUM,
AggregateOp.MEAN,
AggregateOp.AVERAGE,
AggregateOp.VARIANCE,
AggregateOp.VARIANCEP,
AggregateOp.STDEV,
AggregateOp.STDEVP,
AggregateOp.MEDIAN,
AggregateOp.Q1,
AggregateOp.Q3,
AggregateOp.MODESKEW,
AggregateOp.MIN,
AggregateOp.MAX,
AggregateOp.ARGMIN,
AggregateOp.ARGMAX,
];
exports.SUM_OPS = [
AggregateOp.COUNT,
AggregateOp.SUM,
AggregateOp.DISTINCT
];
exports.SHARED_DOMAIN_OPS = [
AggregateOp.MEAN,
AggregateOp.AVERAGE,
AggregateOp.STDEV,
AggregateOp.STDEVP,
AggregateOp.MEDIAN,
AggregateOp.Q1,
AggregateOp.Q3,
AggregateOp.MIN,
AggregateOp.MAX,
];
},{}],8:[function(require,module,exports){
"use strict";
(function (AxisOrient) {
AxisOrient[AxisOrient["TOP"] = 'top'] = "TOP";
AxisOrient[AxisOrient["RIGHT"] = 'right'] = "RIGHT";
AxisOrient[AxisOrient["LEFT"] = 'left'] = "LEFT";
AxisOrient[AxisOrient["BOTTOM"] = 'bottom'] = "BOTTOM";
})(exports.AxisOrient || (exports.AxisOrient = {}));
var AxisOrient = exports.AxisOrient;
exports.defaultAxisConfig = {
offset: undefined,
grid: undefined,
labels: true,
labelMaxLength: 25,
tickSize: undefined,
characterWidth: 6
};
exports.defaultFacetAxisConfig = {
axisWidth: 0,
labels: true,
grid: false,
tickSize: 0
};
},{}],9:[function(require,module,exports){
"use strict";
var channel_1 = require('./channel');
function autoMaxBins(channel) {
switch (channel) {
case channel_1.ROW:
case channel_1.COLUMN:
case channel_1.SIZE:
case channel_1.SHAPE:
return 6;
default:
return 10;
}
}
exports.autoMaxBins = autoMaxBins;
},{"./channel":10}],10:[function(require,module,exports){
"use strict";
var util_1 = require('./util');
(function (Channel) {
Channel[Channel["X"] = 'x'] = "X";
Channel[Channel["Y"] = 'y'] = "Y";
Channel[Channel["X2"] = 'x2'] = "X2";
Channel[Channel["Y2"] = 'y2'] = "Y2";
Channel[Channel["ROW"] = 'row'] = "ROW";
Channel[Channel["COLUMN"] = 'column'] = "COLUMN";
Channel[Channel["SHAPE"] = 'shape'] = "SHAPE";
Channel[Channel["SIZE"] = 'size'] = "SIZE";
Channel[Channel["COLOR"] = 'color'] = "COLOR";
Channel[Channel["TEXT"] = 'text'] = "TEXT";
Channel[Channel["DETAIL"] = 'detail'] = "DETAIL";
Channel[Channel["LABEL"] = 'label'] = "LABEL";
Channel[Channel["PATH"] = 'path'] = "PATH";
Channel[Channel["ORDER"] = 'order'] = "ORDER";
Channel[Channel["OPACITY"] = 'opacity'] = "OPACITY";
})(exports.Channel || (exports.Channel = {}));
var Channel = exports.Channel;
exports.X = Channel.X;
exports.Y = Channel.Y;
exports.X2 = Channel.X2;
exports.Y2 = Channel.Y2;
exports.ROW = Channel.ROW;
exports.COLUMN = Channel.COLUMN;
exports.SHAPE = Channel.SHAPE;
exports.SIZE = Channel.SIZE;
exports.COLOR = Channel.COLOR;
exports.TEXT = Channel.TEXT;
exports.DETAIL = Channel.DETAIL;
exports.LABEL = Channel.LABEL;
exports.PATH = Channel.PATH;
exports.ORDER = Channel.ORDER;
exports.OPACITY = Channel.OPACITY;
exports.CHANNELS = [exports.X, exports.Y, exports.X2, exports.Y2, exports.ROW, exports.COLUMN, exports.SIZE, exports.SHAPE, exports.COLOR, exports.PATH, exports.ORDER, exports.OPACITY, exports.TEXT, exports.DETAIL, exports.LABEL];
exports.UNIT_CHANNELS = util_1.without(exports.CHANNELS, [exports.ROW, exports.COLUMN]);
exports.UNIT_SCALE_CHANNELS = util_1.without(exports.UNIT_CHANNELS, [exports.PATH, exports.ORDER, exports.DETAIL, exports.TEXT, exports.LABEL, exports.X2, exports.Y2]);
exports.NONSPATIAL_CHANNELS = util_1.without(exports.UNIT_CHANNELS, [exports.X, exports.Y, exports.X2, exports.Y2]);
exports.NONSPATIAL_SCALE_CHANNELS = util_1.without(exports.UNIT_SCALE_CHANNELS, [exports.X, exports.Y, exports.X2, exports.Y2]);
exports.STACK_GROUP_CHANNELS = [exports.COLOR, exports.DETAIL, exports.ORDER, exports.OPACITY, exports.SIZE];
;
function supportMark(channel, mark) {
return !!getSupportedMark(channel)[mark];
}
exports.supportMark = supportMark;
function getSupportedMark(channel) {
switch (channel) {
case exports.X:
case exports.Y:
case exports.COLOR:
case exports.DETAIL:
case exports.ORDER:
case exports.OPACITY:
case exports.ROW:
case exports.COLUMN:
return {
point: true, tick: true, rule: true, circle: true, square: true,
bar: true, line: true, area: true, text: true
};
case exports.X2:
case exports.Y2:
return {
rule: true, bar: true, area: true
};
case exports.SIZE:
return {
point: true, tick: true, rule: true, circle: true, square: true,
bar: true, text: true
};
case exports.SHAPE:
return { point: true };
case exports.TEXT:
return { text: true };
case exports.PATH:
return { line: true };
}
return {};
}
exports.getSupportedMark = getSupportedMark;
;
function getSupportedRole(channel) {
switch (channel) {
case exports.X:
case exports.Y:
case exports.COLOR:
case exports.OPACITY:
case exports.LABEL:
case exports.DETAIL:
return {
measure: true,
dimension: true
};
case exports.ROW:
case exports.COLUMN:
case exports.SHAPE:
return {
measure: false,
dimension: true
};
case exports.X2:
case exports.Y2:
case exports.SIZE:
case exports.TEXT:
return {
measure: true,
dimension: false
};
case exports.PATH:
return {
measure: false,
dimension: true
};
}
throw new Error('Invalid encoding channel' + channel);
}
exports.getSupportedRole = getSupportedRole;
function hasScale(channel) {
return !util_1.contains([exports.DETAIL, exports.PATH, exports.TEXT, exports.LABEL, exports.ORDER], channel);
}
exports.hasScale = hasScale;
},{"./util":60}],11:[function(require,module,exports){
"use strict";
var axis_1 = require('../axis');
var channel_1 = require('../channel');
var fielddef_1 = require('../fielddef');
var type_1 = require('../type');
var util_1 = require('../util');
var common_1 = require('./common');
function parseAxisComponent(model, axisChannels) {
return axisChannels.reduce(function (axis, channel) {
if (model.axis(channel)) {
axis[channel] = parseAxis(channel, model);
}
return axis;
}, {});
}
exports.parseAxisComponent = parseAxisComponent;
function parseInnerAxis(channel, model) {
var isCol = channel === channel_1.COLUMN, isRow = channel === channel_1.ROW, type = isCol ? 'x' : isRow ? 'y' : channel;
var def = {
type: type,
scale: model.scaleName(channel),
grid: true,
tickSize: 0,
properties: {
labels: {
text: { value: '' }
},
axis: {
stroke: { value: 'transparent' }
}
}
};
var axis = model.axis(channel);
['layer', 'ticks', 'values', 'subdivide'].forEach(function (property) {
var method;
var value = (method = exports[property]) ?
method(model, channel, def) :
axis[property];
if (value !== undefined) {
def[property] = value;
}
});
var props = model.axis(channel).properties || {};
['grid'].forEach(function (group) {
var value = properties[group] ?
properties[group](model, channel, props[group] || {}, def) :
props[group];
if (value !== undefined && util_1.keys(value).length > 0) {
def.properties = def.properties || {};
def.properties[group] = value;
}
});
return def;
}
exports.parseInnerAxis = parseInnerAxis;
function parseAxis(channel, model) {
var isCol = channel === channel_1.COLUMN, isRow = channel === channel_1.ROW, type = isCol ? 'x' : isRow ? 'y' : channel;
var axis = model.axis(channel);
var def = {
type: type,
scale: model.scaleName(channel)
};
[
'format', 'grid', 'layer', 'offset', 'orient', 'tickSize', 'ticks', 'tickSizeEnd', 'title', 'titleOffset',
'tickPadding', 'tickSize', 'tickSizeMajor', 'tickSizeMinor', 'values', 'subdivide'
].forEach(function (property) {
var method;
var value = (method = exports[property]) ?
method(model, channel, def) :
axis[property];
if (value !== undefined) {
def[property] = value;
}
});
var props = model.axis(channel).properties || {};
[
'axis', 'labels',
'grid', 'title', 'ticks', 'majorTicks', 'minorTicks'
].forEach(function (group) {
var value = properties[group] ?
properties[group](model, channel, props[group] || {}, def) :
props[group];
if (value !== undefined && util_1.keys(value).length > 0) {
def.properties = def.properties || {};
def.properties[group] = value;
}
});
return def;
}
exports.parseAxis = parseAxis;
function format(model, channel) {
return common_1.numberFormat(model.fieldDef(channel), model.axis(channel).format, model.config());
}
exports.format = format;
function offset(model, channel) {
return model.axis(channel).offset;
}
exports.offset = offset;
function gridShow(model, channel) {
var grid = model.axis(channel).grid;
if (grid !== undefined) {
return grid;
}
return !model.isOrdinalScale(channel) && !model.fieldDef(channel).bin;
}
exports.gridShow = gridShow;
function grid(model, channel) {
if (channel === channel_1.ROW || channel === channel_1.COLUMN) {
return undefined;
}
return gridShow(model, channel) && ((channel === channel_1.Y || channel === channel_1.X) && !(model.parent() && model.parent().isFacet()));
}
exports.grid = grid;
function layer(model, channel, def) {
var layer = model.axis(channel).layer;
if (layer !== undefined) {
return layer;
}
if (def.grid) {
return 'back';
}
return undefined;
}
exports.layer = layer;
;
function orient(model, channel) {
var orient = model.axis(channel).orient;
if (orient) {
return orient;
}
else if (channel === channel_1.COLUMN) {
return axis_1.AxisOrient.TOP;
}
return undefined;
}
exports.orient = orient;
function ticks(model, channel) {
var ticks = model.axis(channel).ticks;
if (ticks !== undefined) {
return ticks;
}
if (channel === channel_1.X && !model.fieldDef(channel).bin) {
return 5;
}
return undefined;
}
exports.ticks = ticks;
function tickSize(model, channel) {
var tickSize = model.axis(channel).tickSize;
if (tickSize !== undefined) {
return tickSize;
}
return undefined;
}
exports.tickSize = tickSize;
function tickSizeEnd(model, channel) {
var tickSizeEnd = model.axis(channel).tickSizeEnd;
if (tickSizeEnd !== undefined) {
return tickSizeEnd;
}
return undefined;
}
exports.tickSizeEnd = tickSizeEnd;
function title(model, channel) {
var axis = model.axis(channel);
if (axis.title !== undefined) {
return axis.title;
}
var fieldTitle = fielddef_1.title(model.fieldDef(channel), model.config());
var maxLength;
if (axis.titleMaxLength) {
maxLength = axis.titleMaxLength;
}
else if (channel === channel_1.X && !model.isOrdinalScale(channel_1.X)) {
var unitModel = model;
maxLength = unitModel.width / model.axis(channel_1.X).characterWidth;
}
else if (channel === channel_1.Y && !model.isOrdinalScale(channel_1.Y)) {
var unitModel = model;
maxLength = unitModel.height / model.axis(channel_1.Y).characterWidth;
}
return maxLength ? util_1.truncate(fieldTitle, maxLength) : fieldTitle;
}
exports.title = title;
function titleOffset(model, channel) {
var titleOffset = model.axis(channel).titleOffset;
if (titleOffset !== undefined) {
return titleOffset;
}
return undefined;
}
exports.titleOffset = titleOffset;
var properties;
(function (properties) {
function axis(model, channel, axisPropsSpec) {
var axis = model.axis(channel);
return util_1.extend(axis.axisColor !== undefined ?
{ stroke: { value: axis.axisColor } } :
{}, axis.axisWidth !== undefined ?
{ strokeWidth: { value: axis.axisWidth } } :
{}, axisPropsSpec || {});
}
properties.axis = axis;
function grid(model, channel, gridPropsSpec) {
var axis = model.axis(channel);
return util_1.extend(axis.gridColor !== undefined ? { stroke: { value: axis.gridColor } } : {}, axis.gridOpacity !== undefined ? { strokeOpacity: { value: axis.gridOpacity } } : {}, axis.gridWidth !== undefined ? { strokeWidth: { value: axis.gridWidth } } : {}, axis.gridDash !== undefined ? { strokeDashOffset: { value: axis.gridDash } } : {}, gridPropsSpec || {});
}
properties.grid = grid;
function labels(model, channel, labelsSpec, def) {
var fieldDef = model.fieldDef(channel);
var axis = model.axis(channel);
var config = model.config();
if (!axis.labels) {
return util_1.extend({
text: ''
}, labelsSpec);
}
if (util_1.contains([type_1.NOMINAL, type_1.ORDINAL], fieldDef.type) && axis.labelMaxLength) {
labelsSpec = util_1.extend({
text: {
template: '{{ datum["data"] | truncate:' + axis.labelMaxLength + ' }}'
}
}, labelsSpec || {});
}
else if (fieldDef.type === type_1.TEMPORAL) {
labelsSpec = util_1.extend({
text: {
template: common_1.timeTemplate('datum["data"]', fieldDef.timeUnit, axis.format, axis.shortTimeLabels, config)
}
}, labelsSpec);
}
if (axis.labelAngle !== undefined) {
labelsSpec.angle = { value: axis.labelAngle };
}
else {
if (channel === channel_1.X && (util_1.contains([type_1.NOMINAL, type_1.ORDINAL], fieldDef.type) || !!fieldDef.bin || fieldDef.type === type_1.TEMPORAL)) {
labelsSpec.angle = { value: 270 };
}
}
if (axis.labelAlign !== undefined) {
labelsSpec.align = { value: axis.labelAlign };
}
else {
if (labelsSpec.angle) {
if (labelsSpec.angle.value === 270) {
labelsSpec.align = {
value: def.orient === 'top' ? 'left' :
def.type === 'x' ? 'right' :
'center'
};
}
else if (labelsSpec.angle.value === 90) {
labelsSpec.align = { value: 'center' };
}
}
}
if (axis.labelBaseline !== undefined) {
labelsSpec.baseline = { value: axis.labelBaseline };
}
else {
if (labelsSpec.angle) {
if (labelsSpec.angle.value === 270) {
labelsSpec.baseline = { value: def.type === 'x' ? 'middle' : 'bottom' };
}
else if (labelsSpec.angle.value === 90) {
labelsSpec.baseline = { value: 'bottom' };
}
}
}
if (axis.tickLabelColor !== undefined) {
labelsSpec.stroke = { value: axis.tickLabelColor };
}
if (axis.tickLabelFont !== undefined) {
labelsSpec.font = { value: axis.tickLabelFont };
}
if (axis.tickLabelFontSize !== undefined) {
labelsSpec.fontSize = { value: axis.tickLabelFontSize };
}
return util_1.keys(labelsSpec).length === 0 ? undefined : labelsSpec;
}
properties.labels = labels;
function ticks(model, channel, ticksPropsSpec) {
var axis = model.axis(channel);
return util_1.extend(axis.tickColor !== undefined ? { stroke: { value: axis.tickColor } } : {}, axis.tickWidth !== undefined ? { strokeWidth: { value: axis.tickWidth } } : {}, ticksPropsSpec || {});
}
properties.ticks = ticks;
function title(model, channel, titlePropsSpec) {
var axis = model.axis(channel);
return util_1.extend(axis.titleColor !== undefined ? { stroke: { value: axis.titleColor } } : {}, axis.titleFont !== undefined ? { font: { value: axis.titleFont } } : {}, axis.titleFontSize !== undefined ? { fontSize: { value: axis.titleFontSize } } : {}, axis.titleFontWeight !== undefined ? { fontWeight: { value: axis.titleFontWeight } } : {}, titlePropsSpec || {});
}
properties.title = title;
})(properties = exports.properties || (exports.properties = {}));
},{"../axis":8,"../channel":10,"../fielddef":48,"../type":59,"../util":60,"./common":12}],12:[function(require,module,exports){
"use strict";
var mark_1 = require('../mark');
var aggregate_1 = require('../aggregate');
var channel_1 = require('../channel');
var fielddef_1 = require('../fielddef');
var sort_1 = require('../sort');
var type_1 = require('../type');
var util_1 = require('../util');
var facet_1 = require('./facet');
var layer_1 = require('./layer');
var timeunit_1 = require('../timeunit');
var unit_1 = require('./unit');
var spec_1 = require('../spec');
function buildModel(spec, parent, parentGivenName) {
if (spec_1.isFacetSpec(spec)) {
return new facet_1.FacetModel(spec, parent, parentGivenName);
}
if (spec_1.isLayerSpec(spec)) {
return new layer_1.LayerModel(spec, parent, parentGivenName);
}
if (spec_1.isUnitSpec(spec)) {
return new unit_1.UnitModel(spec, parent, parentGivenName);
}
console.error('Invalid spec.');
return null;
}
exports.buildModel = buildModel;
exports.STROKE_CONFIG = ['stroke', 'strokeWidth',
'strokeDash', 'strokeDashOffset', 'strokeOpacity', 'opacity'];
exports.FILL_CONFIG = ['fill', 'fillOpacity',
'opacity'];
exports.FILL_STROKE_CONFIG = util_1.union(exports.STROKE_CONFIG, exports.FILL_CONFIG);
function applyColorAndOpacity(p, model) {
var filled = model.config().mark.filled;
var colorFieldDef = model.encoding().color;
var opacityFieldDef = model.encoding().opacity;
if (filled) {
applyMarkConfig(p, model, exports.FILL_CONFIG);
}
else {
applyMarkConfig(p, model, exports.STROKE_CONFIG);
}
var colorValue;
var opacityValue;
if (model.has(channel_1.COLOR)) {
colorValue = {
scale: model.scaleName(channel_1.COLOR),
field: model.field(channel_1.COLOR, colorFieldDef.type === type_1.ORDINAL ? { prefix: 'rank' } : {})
};
}
else if (colorFieldDef && colorFieldDef.value) {
colorValue = { value: colorFieldDef.value };
}
if (model.has(channel_1.OPACITY)) {
opacityValue = {
scale: model.scaleName(channel_1.OPACITY),
field: model.field(channel_1.OPACITY, opacityFieldDef.type === type_1.ORDINAL ? { prefix: 'rank' } : {})
};
}
else if (opacityFieldDef && opacityFieldDef.value) {
opacityValue = { value: opacityFieldDef.value };
}
if (colorValue !== undefined) {
if (filled) {
p.fill = colorValue;
}
else {
p.stroke = colorValue;
}
}
else {
p[filled ? 'fill' : 'stroke'] = p[filled ? 'fill' : 'stroke'] ||
{ value: model.config().mark.color };
}
if (!p.fill && util_1.contains([mark_1.BAR, mark_1.POINT, mark_1.CIRCLE, mark_1.SQUARE], model.mark())) {
p.fill = { value: 'transparent' };
}
if (opacityValue !== undefined) {
p.opacity = opacityValue;
}
}
exports.applyColorAndOpacity = applyColorAndOpacity;
function applyConfig(properties, config, propsList) {
propsList.forEach(function (property) {
var value = config[property];
if (value !== undefined) {
properties[property] = { value: value };
}
});
return properties;
}
exports.applyConfig = applyConfig;
function applyMarkConfig(marksProperties, model, propsList) {
return applyConfig(marksProperties, model.config().mark, propsList);
}
exports.applyMarkConfig = applyMarkConfig;
function numberFormat(fieldDef, format, config) {
if (fieldDef.type === type_1.QUANTITATIVE && !fieldDef.bin) {
if (format) {
return format;
}
else if (fieldDef.aggregate === aggregate_1.AggregateOp.COUNT) {
return 'd';
}
return config.numberFormat;
}
return undefined;
}
exports.numberFormat = numberFormat;
function sortField(orderChannelDef) {
return (orderChannelDef.sort === sort_1.SortOrder.DESCENDING ? '-' : '') +
fielddef_1.field(orderChannelDef, { binSuffix: 'mid' });
}
exports.sortField = sortField;
function timeTemplate(templateField, timeUnit, format, shortTimeLabels, config) {
if (!timeUnit || format) {
var _format = format || config.timeFormat;
return '{{' + templateField + ' | time:\'' + _format + '\'}}';
}
else {
return timeunit_1.template(timeUnit, templateField, shortTimeLabels);
}
}
exports.timeTemplate = timeTemplate;
},{"../aggregate":7,"../channel":10,"../fielddef":48,"../mark":51,"../sort":54,"../spec":55,"../timeunit":57,"../type":59,"../util":60,"./facet":28,"./layer":29,"./unit":42}],13:[function(require,module,exports){
"use strict";
var data_1 = require('../data');
var spec_1 = require('../spec');
var util_1 = require('../util');
var common_1 = require('./common');
function compile(inputSpec) {
var spec = spec_1.normalize(inputSpec);
var model = common_1.buildModel(spec, null, '');
model.parse();
return assemble(model);
}
exports.compile = compile;
function assemble(model) {
var config = model.config();
var output = util_1.extend({
width: 1,
height: 1,
padding: 'auto'
}, config.viewport ? { viewport: config.viewport } : {}, config.background ? { background: config.background } : {}, {
data: [].concat(model.assembleData([]), model.assembleLayout([])),
marks: [assembleRootGroup(model)]
});
return {
spec: output
};
}
function assembleRootGroup(model) {
var rootGroup = util_1.extend({
name: model.name('root'),
type: 'group',
}, model.description() ? { description: model.description() } : {}, {
from: { data: data_1.LAYOUT },
properties: {
update: util_1.extend({
width: { field: 'width' },
height: { field: 'height' }
}, model.assembleParentGroupProperties(model.config().cell))
}
});
return util_1.extend(rootGroup, model.assembleGroup());
}
exports.assembleRootGroup = assembleRootGroup;
},{"../data":44,"../spec":55,"../util":60,"./common":12}],14:[function(require,module,exports){
"use strict";
var channel_1 = require('../channel');
var config_1 = require('../config');
var encoding_1 = require('../encoding');
var fielddef_1 = require('../fielddef');
var mark_1 = require('../mark');
var scale_1 = require('../scale');
var util_1 = require('../util');
var scale_2 = require('../compile/scale');
function initMarkConfig(mark, encoding, config) {
return util_1.extend(['filled', 'opacity', 'orient', 'align'].reduce(function (cfg, property) {
var value = config.mark[property];
switch (property) {
case 'filled':
if (value === undefined) {
cfg[property] = mark !== mark_1.POINT && mark !== mark_1.LINE && mark !== mark_1.RULE;
}
break;
case 'opacity':
if (value === undefined) {
if (util_1.contains([mark_1.POINT, mark_1.TICK, mark_1.CIRCLE, mark_1.SQUARE], mark)) {
if (!encoding_1.isAggregate(encoding) || encoding_1.has(encoding, channel_1.DETAIL)) {
cfg[property] = 0.7;
}
}
if (mark === mark_1.AREA) {
cfg[property] = 0.7;
}
}
break;
case 'orient':
cfg[property] = orient(mark, encoding, config.mark);
break;
case 'align':
if (value === undefined) {
cfg[property] = encoding_1.has(encoding, channel_1.X) ? 'center' : 'right';
}
}
return cfg;
}, {}), config.mark);
}
exports.initMarkConfig = initMarkConfig;
function orient(mark, encoding, markConfig) {
if (markConfig === void 0) { markConfig = {}; }
switch (mark) {
case mark_1.POINT:
case mark_1.CIRCLE:
case mark_1.SQUARE:
case mark_1.TEXT:
return undefined;
}
var yIsRange = encoding.y && encoding.y2;
var xIsRange = encoding.x && encoding.x2;
switch (mark) {
case mark_1.TICK:
var xScaleType = encoding.x ? scale_2.scaleType(encoding.x.scale || {}, encoding.x, channel_1.X, mark) : null;
var yScaleType = encoding.y ? scale_2.scaleType(encoding.y.scale || {}, encoding.y, channel_1.Y, mark) : null;
if (xScaleType !== scale_1.ScaleType.ORDINAL && (!encoding.y || yScaleType === scale_1.ScaleType.ORDINAL)) {
return config_1.Orient.VERTICAL;
}
return config_1.Orient.HORIZONTAL;
case mark_1.RULE:
if (xIsRange) {
return config_1.Orient.HORIZONTAL;
}
if (yIsRange) {
return config_1.Orient.VERTICAL;
}
if (encoding.y) {
return config_1.Orient.HORIZONTAL;
}
if (encoding.x) {
return config_1.Orient.VERTICAL;
}
return undefined;
case mark_1.BAR:
case mark_1.AREA:
if (yIsRange) {
return config_1.Orient.VERTICAL;
}
if (xIsRange) {
return config_1.Orient.HORIZONTAL;
}
case mark_1.LINE:
var xIsMeasure = fielddef_1.isMeasure(encoding.x) || fielddef_1.isMeasure(encoding.x2);
var yIsMeasure = fielddef_1.isMeasure(encoding.y) || fielddef_1.isMeasure(encoding.y2);
if (xIsMeasure && !yIsMeasure) {
return config_1.Orient.HORIZONTAL;
}
return config_1.Orient.VERTICAL;
}
console.warn('orient unimplemented for mark', mark);
return config_1.Orient.VERTICAL;
}
exports.orient = orient;
},{"../channel":10,"../compile/scale":41,"../config":43,"../encoding":46,"../fielddef":48,"../mark":51,"../scale":52,"../util":60}],15:[function(require,module,exports){
"use strict";
var bin_1 = require('../../bin');
var channel_1 = require('../../channel');
var fielddef_1 = require('../../fielddef');
var util_1 = require('../../util');
var bin;
(function (bin_2) {
function parse(model) {
return model.reduce(function (binComponent, fieldDef, channel) {
var bin = model.fieldDef(channel).bin;
if (bin) {
var binTrans = util_1.extend({
type: 'bin',
field: fieldDef.field,
output: {
start: fielddef_1.field(fieldDef, { binSuffix: 'start' }),
mid: fielddef_1.field(fieldDef, { binSuffix: 'mid' }),
end: fielddef_1.field(fieldDef, { binSuffix: 'end' })
}
}, typeof bin === 'boolean' ? {} : bin);
if (!binTrans.maxbins && !binTrans.step) {
binTrans.maxbins = bin_1.autoMaxBins(channel);
}
var transform = [binTrans];
var isOrdinalColor = model.isOrdinalScale(channel) || channel === channel_1.COLOR;
if (isOrdinalColor) {
transform.push({
type: 'formula',
field: fielddef_1.field(fieldDef, { binSuffix: 'range' }),
expr: fielddef_1.field(fieldDef, { datum: true, binSuffix: 'start' }) +
' + \'-\' + ' +
fielddef_1.field(fieldDef, { datum: true, binSuffix: 'end' })
});
}
var key = util_1.hash(bin) + '_' + fieldDef.field + 'oc:' + isOrdinalColor;
binComponent[key] = transform;
}
return binComponent;
}, {});
}
bin_2.parseUnit = parse;
function parseFacet(model) {
var binComponent = parse(model);
var childDataComponent = model.child().component.data;
if (!childDataComponent.source) {
util_1.extend(binComponent, childDataComponent.bin);
delete childDataComponent.bin;
}
return binComponent;
}
bin_2.parseFacet = parseFacet;
function parseLayer(model) {
var binComponent = parse(model);
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (!childDataComponent.source) {
util_1.extend(binComponent, childDataComponent.bin);
delete childDataComponent.bin;
}
});
return binComponent;
}
bin_2.parseLayer = parseLayer;
function assemble(component) {
return util_1.flatten(util_1.vals(component.bin));
}
bin_2.assemble = assemble;
})(bin = exports.bin || (exports.bin = {}));
},{"../../bin":9,"../../channel":10,"../../fielddef":48,"../../util":60}],16:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var type_1 = require('../../type');
var util_1 = require('../../util');
var colorRank;
(function (colorRank) {
function parseUnit(model) {
var colorRankComponent = {};
if (model.has(channel_1.COLOR) && model.encoding().color.type === type_1.ORDINAL) {
colorRankComponent[model.field(channel_1.COLOR)] = [{
type: 'sort',
by: model.field(channel_1.COLOR)
}, {
type: 'rank',
field: model.field(channel_1.COLOR),
output: {
rank: model.field(channel_1.COLOR, { prefix: 'rank' })
}
}];
}
return colorRankComponent;
}
colorRank.parseUnit = parseUnit;
function parseFacet(model) {
var childDataComponent = model.child().component.data;
if (!childDataComponent.source) {
var colorRankComponent = childDataComponent.colorRank;
delete childDataComponent.colorRank;
return colorRankComponent;
}
return {};
}
colorRank.parseFacet = parseFacet;
function parseLayer(model) {
var colorRankComponent = {};
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (!childDataComponent.source) {
util_1.extend(colorRankComponent, childDataComponent.colorRank);
delete childDataComponent.colorRank;
}
});
return colorRankComponent;
}
colorRank.parseLayer = parseLayer;
function assemble(component) {
return util_1.flatten(util_1.vals(component.colorRank));
}
colorRank.assemble = assemble;
})(colorRank = exports.colorRank || (exports.colorRank = {}));
},{"../../channel":10,"../../type":59,"../../util":60}],17:[function(require,module,exports){
"use strict";
var util_1 = require('../../util');
var source_1 = require('./source');
var formatparse_1 = require('./formatparse');
var nullfilter_1 = require('./nullfilter');
var filter_1 = require('./filter');
var bin_1 = require('./bin');
var formula_1 = require('./formula');
var nonpositivenullfilter_1 = require('./nonpositivenullfilter');
var summary_1 = require('./summary');
var stackscale_1 = require('./stackscale');
var timeunit_1 = require('./timeunit');
var timeunitdomain_1 = require('./timeunitdomain');
var colorrank_1 = require('./colorrank');
function parseUnitData(model) {
return {
formatParse: formatparse_1.formatParse.parseUnit(model),
nullFilter: nullfilter_1.nullFilter.parseUnit(model),
filter: filter_1.filter.parseUnit(model),
nonPositiveFilter: nonpositivenullfilter_1.nonPositiveFilter.parseUnit(model),
source: source_1.source.parseUnit(model),
bin: bin_1.bin.parseUnit(model),
calculate: formula_1.formula.parseUnit(model),
timeUnit: timeunit_1.timeUnit.parseUnit(model),
timeUnitDomain: timeunitdomain_1.timeUnitDomain.parseUnit(model),
summary: summary_1.summary.parseUnit(model),
stackScale: stackscale_1.stackScale.parseUnit(model),
colorRank: colorrank_1.colorRank.parseUnit(model)
};
}
exports.parseUnitData = parseUnitData;
function parseFacetData(model) {
return {
formatParse: formatparse_1.formatParse.parseFacet(model),
nullFilter: nullfilter_1.nullFilter.parseFacet(model),
filter: filter_1.filter.parseFacet(model),
nonPositiveFilter: nonpositivenullfilter_1.nonPositiveFilter.parseFacet(model),
source: source_1.source.parseFacet(model),
bin: bin_1.bin.parseFacet(model),
calculate: formula_1.formula.parseFacet(model),
timeUnit: timeunit_1.timeUnit.parseFacet(model),
timeUnitDomain: timeunitdomain_1.timeUnitDomain.parseFacet(model),
summary: summary_1.summary.parseFacet(model),
stackScale: stackscale_1.stackScale.parseFacet(model),
colorRank: colorrank_1.colorRank.parseFacet(model)
};
}
exports.parseFacetData = parseFacetData;
function parseLayerData(model) {
return {
filter: filter_1.filter.parseLayer(model),
formatParse: formatparse_1.formatParse.parseLayer(model),
nullFilter: nullfilter_1.nullFilter.parseLayer(model),
nonPositiveFilter: nonpositivenullfilter_1.nonPositiveFilter.parseLayer(model),
source: source_1.source.parseLayer(model),
bin: bin_1.bin.parseLayer(model),
calculate: formula_1.formula.parseLayer(model),
timeUnit: timeunit_1.timeUnit.parseLayer(model),
timeUnitDomain: timeunitdomain_1.timeUnitDomain.parseLayer(model),
summary: summary_1.summary.parseLayer(model),
stackScale: stackscale_1.stackScale.parseLayer(model),
colorRank: colorrank_1.colorRank.parseLayer(model)
};
}
exports.parseLayerData = parseLayerData;
function assembleData(model, data) {
var component = model.component.data;
var sourceData = source_1.source.assemble(model, component);
if (sourceData) {
data.push(sourceData);
}
summary_1.summary.assemble(component, model).forEach(function (summaryData) {
data.push(summaryData);
});
if (data.length > 0) {
var dataTable = data[data.length - 1];
var colorRankTransform = colorrank_1.colorRank.assemble(component);
if (colorRankTransform.length > 0) {
dataTable.transform = (dataTable.transform || []).concat(colorRankTransform);
}
var nonPositiveFilterTransform = nonpositivenullfilter_1.nonPositiveFilter.assemble(component);
if (nonPositiveFilterTransform.length > 0) {
dataTable.transform = (dataTable.transform || []).concat(nonPositiveFilterTransform);
}
}
else {
if (util_1.keys(component.colorRank).length > 0) {
throw new Error('Invalid colorRank not merged');
}
else if (util_1.keys(component.nonPositiveFilter).length > 0) {
throw new Error('Invalid nonPositiveFilter not merged');
}
}
var stackData = stackscale_1.stackScale.assemble(component);
if (stackData) {
data.push(stackData);
}
timeunitdomain_1.timeUnitDomain.assemble(component).forEach(function (timeUnitDomainData) {
data.push(timeUnitDomainData);
});
return data;
}
exports.assembleData = assembleData;
},{"../../util":60,"./bin":15,"./colorrank":16,"./filter":18,"./formatparse":19,"./formula":20,"./nonpositivenullfilter":21,"./nullfilter":22,"./source":23,"./stackscale":24,"./summary":25,"./timeunit":26,"./timeunitdomain":27}],18:[function(require,module,exports){
"use strict";
var filter_1 = require('../../filter');
var util_1 = require('../../util');
var filter;
(function (filter_2) {
function parse(model) {
var filter = model.transform().filter;
if (util_1.isArray(filter)) {
return '(' +
filter.map(function (f) { return filter_1.expression(f); })
.filter(function (f) { return f !== undefined; })
.join(') && (') +
')';
}
else if (filter) {
return filter_1.expression(filter);
}
return undefined;
}
filter_2.parse = parse;
filter_2.parseUnit = parse;
function parseFacet(model) {
var filterComponent = parse(model);
var childDataComponent = model.child().component.data;
if (!childDataComponent.source && childDataComponent.filter) {
filterComponent =
(filterComponent ? filterComponent + ' && ' : '') +
childDataComponent.filter;
delete childDataComponent.filter;
}
return filterComponent;
}
filter_2.parseFacet = parseFacet;
function parseLayer(model) {
var filterComponent = parse(model);
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (model.compatibleSource(child) && childDataComponent.filter && childDataComponent.filter === filterComponent) {
delete childDataComponent.filter;
}
});
return filterComponent;
}
filter_2.parseLayer = parseLayer;
function assemble(component) {
var filter = component.filter;
return filter ? [{
type: 'filter',
test: filter
}] : [];
}
filter_2.assemble = assemble;
})(filter = exports.filter || (exports.filter = {}));
},{"../../filter":49,"../../util":60}],19:[function(require,module,exports){
"use strict";
var fielddef_1 = require('../../fielddef');
var type_1 = require('../../type');
var util_1 = require('../../util');
var formatParse;
(function (formatParse) {
function parse(model) {
var calcFieldMap = (model.transform().calculate || []).reduce(function (fieldMap, formula) {
fieldMap[formula.field] = true;
return fieldMap;
}, {});
var parseComponent = {};
model.forEach(function (fieldDef) {
if (fieldDef.type === type_1.TEMPORAL) {
parseComponent[fieldDef.field] = 'date';
}
else if (fieldDef.type === type_1.QUANTITATIVE) {
if (fielddef_1.isCount(fieldDef) || calcFieldMap[fieldDef.field]) {
return;
}
parseComponent[fieldDef.field] = 'number';
}
});
return parseComponent;
}
formatParse.parseUnit = parse;
function parseFacet(model) {
var parseComponent = parse(model);
var childDataComponent = model.child().component.data;
if (!childDataComponent.source && childDataComponent.formatParse) {
util_1.extend(parseComponent, childDataComponent.formatParse);
delete childDataComponent.formatParse;
}
return parseComponent;
}
formatParse.parseFacet = parseFacet;
function parseLayer(model) {
var parseComponent = parse(model);
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (model.compatibleSource(child) && !util_1.differ(childDataComponent.formatParse, parseComponent)) {
util_1.extend(parseComponent, childDataComponent.formatParse);
delete childDataComponent.formatParse;
}
});
return parseComponent;
}
formatParse.parseLayer = parseLayer;
})(formatParse = exports.formatParse || (exports.formatParse = {}));
},{"../../fielddef":48,"../../type":59,"../../util":60}],20:[function(require,module,exports){
"use strict";
var util_1 = require('../../util');
var formula;
(function (formula_1) {
function parse(model) {
return (model.transform().calculate || []).reduce(function (formulaComponent, formula) {
formulaComponent[util_1.hash(formula)] = formula;
return formulaComponent;
}, {});
}
formula_1.parseUnit = parse;
function parseFacet(model) {
var formulaComponent = parse(model);
var childDataComponent = model.child().component.data;
if (!childDataComponent.source) {
util_1.extend(formulaComponent, childDataComponent.calculate);
delete childDataComponent.calculate;
}
return formulaComponent;
}
formula_1.parseFacet = parseFacet;
function parseLayer(model) {
var formulaComponent = parse(model);
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (!childDataComponent.source && childDataComponent.calculate) {
util_1.extend(formulaComponent || {}, childDataComponent.calculate);
delete childDataComponent.calculate;
}
});
return formulaComponent;
}
formula_1.parseLayer = parseLayer;
function assemble(component) {
return util_1.vals(component.calculate).reduce(function (transform, formula) {
transform.push(util_1.extend({ type: 'formula' }, formula));
return transform;
}, []);
}
formula_1.assemble = assemble;
})(formula = exports.formula || (exports.formula = {}));
},{"../../util":60}],21:[function(require,module,exports){
"use strict";
var scale_1 = require('../../scale');
var util_1 = require('../../util');
var nonPositiveFilter;
(function (nonPositiveFilter_1) {
function parseUnit(model) {
return model.channels().reduce(function (nonPositiveComponent, channel) {
var scale = model.scale(channel);
if (!model.field(channel) || !scale) {
return nonPositiveComponent;
}
nonPositiveComponent[model.field(channel)] = scale.type === scale_1.ScaleType.LOG;
return nonPositiveComponent;
}, {});
}
nonPositiveFilter_1.parseUnit = parseUnit;
function parseFacet(model) {
var childDataComponent = model.child().component.data;
if (!childDataComponent.source) {
var nonPositiveFilterComponent = childDataComponent.nonPositiveFilter;
delete childDataComponent.nonPositiveFilter;
return nonPositiveFilterComponent;
}
return {};
}
nonPositiveFilter_1.parseFacet = parseFacet;
function parseLayer(model) {
var nonPositiveFilter = {};
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (model.compatibleSource(child) && !util_1.differ(childDataComponent.nonPositiveFilter, nonPositiveFilter)) {
util_1.extend(nonPositiveFilter, childDataComponent.nonPositiveFilter);
delete childDataComponent.nonPositiveFilter;
}
});
return nonPositiveFilter;
}
nonPositiveFilter_1.parseLayer = parseLayer;
function assemble(component) {
return util_1.keys(component.nonPositiveFilter).filter(function (field) {
return component.nonPositiveFilter[field];
}).map(function (field) {
return {
type: 'filter',
test: 'datum["' + field + '"] > 0'
};
});
}
nonPositiveFilter_1.assemble = assemble;
})(nonPositiveFilter = exports.nonPositiveFilter || (exports.nonPositiveFilter = {}));
},{"../../scale":52,"../../util":60}],22:[function(require,module,exports){
"use strict";
var type_1 = require('../../type');
var util_1 = require('../../util');
var DEFAULT_NULL_FILTERS = {
nominal: false,
ordinal: false,
quantitative: true,
temporal: true
};
var nullFilter;
(function (nullFilter) {
function parse(model) {
var transform = model.transform();
var filterInvalid = transform.filterInvalid;
if (filterInvalid === undefined && transform['filterNull'] !== undefined) {
filterInvalid = transform['filterNull'];
console.warn('filterNull is deprecated. Please use filterInvalid instead.');
}
return model.reduce(function (aggregator, fieldDef) {
if (fieldDef.field !== '*') {
if (filterInvalid ||
(filterInvalid === undefined && fieldDef.field && DEFAULT_NULL_FILTERS[fieldDef.type])) {
aggregator[fieldDef.field] = fieldDef;
}
else {
aggregator[fieldDef.field] = null;
}
}
return aggregator;
}, {});
}
nullFilter.parseUnit = parse;
function parseFacet(model) {
var nullFilterComponent = parse(model);
var childDataComponent = model.child().component.data;
if (!childDataComponent.source) {
util_1.extend(nullFilterComponent, childDataComponent.nullFilter);
delete childDataComponent.nullFilter;
}
return nullFilterComponent;
}
nullFilter.parseFacet = parseFacet;
function parseLayer(model) {
var nullFilterComponent = parse(model);
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (model.compatibleSource(child) && !util_1.differ(childDataComponent.nullFilter, nullFilterComponent)) {
util_1.extend(nullFilterComponent, childDataComponent.nullFilter);
delete childDataComponent.nullFilter;
}
});
return nullFilterComponent;
}
nullFilter.parseLayer = parseLayer;
function assemble(component) {
var filters = util_1.keys(component.nullFilter).reduce(function (_filters, field) {
var fieldDef = component.nullFilter[field];
if (fieldDef !== null) {
_filters.push('datum["' + fieldDef.field + '"] !== null');
if (util_1.contains([type_1.QUANTITATIVE, type_1.TEMPORAL], fieldDef.type)) {
_filters.push('!isNaN(datum["' + fieldDef.field + '"])');
}
}
return _filters;
}, []);
return filters.length > 0 ?
[{
type: 'filter',
test: filters.join(' && ')
}] : [];
}
nullFilter.assemble = assemble;
})(nullFilter = exports.nullFilter || (exports.nullFilter = {}));
},{"../../type":59,"../../util":60}],23:[function(require,module,exports){
"use strict";
var data_1 = require('../../data');
var util_1 = require('../../util');
var nullfilter_1 = require('./nullfilter');
var filter_1 = require('./filter');
var bin_1 = require('./bin');
var formula_1 = require('./formula');
var timeunit_1 = require('./timeunit');
var source;
(function (source) {
function parse(model) {
var data = model.data();
if (data) {
var sourceData = { name: model.dataName(data_1.SOURCE) };
if (data.values && data.values.length > 0) {
sourceData.values = data.values;
sourceData.format = { type: 'json' };
}
else if (data.url) {
sourceData.url = data.url;
var defaultExtension = /(?:\.([^.]+))?$/.exec(sourceData.url)[1];
if (!util_1.contains(['json', 'csv', 'tsv', 'topojson'], defaultExtension)) {
defaultExtension = 'json';
}
var dataFormat = data.format || {};
var formatType = dataFormat.type || data['formatType'];
sourceData.format =
util_1.extend({ type: formatType ? formatType : defaultExtension }, dataFormat.property ? { property: dataFormat.property } : {}, dataFormat.feature ?
{ feature: dataFormat.feature } :
dataFormat.mesh ?
{ mesh: dataFormat.mesh } :
{});
}
return sourceData;
}
else if (!model.parent()) {
return { name: model.dataName(data_1.SOURCE) };
}
return undefined;
}
source.parseUnit = parse;
function parseFacet(model) {
var sourceData = parse(model);
if (!model.child().component.data.source) {
model.child().renameData(model.child().dataName(data_1.SOURCE), model.dataName(data_1.SOURCE));
}
return sourceData;
}
source.parseFacet = parseFacet;
function parseLayer(model) {
var sourceData = parse(model);
model.children().forEach(function (child) {
var childData = child.component.data;
if (model.compatibleSource(child)) {
var canMerge = !childData.filter && !childData.formatParse && !childData.nullFilter;
if (canMerge) {
child.renameData(child.dataName(data_1.SOURCE), model.dataName(data_1.SOURCE));
delete childData.source;
}
else {
childData.source = {
name: child.dataName(data_1.SOURCE),
source: model.dataName(data_1.SOURCE)
};
}
}
});
return sourceData;
}
source.parseLayer = parseLayer;
function assemble(model, component) {
if (component.source) {
var sourceData = component.source;
if (component.formatParse) {
component.source.format = component.source.format || {};
component.source.format.parse = component.formatParse;
}
sourceData.transform = [].concat(formula_1.formula.assemble(component), nullfilter_1.nullFilter.assemble(component), filter_1.filter.assemble(component), bin_1.bin.assemble(component), timeunit_1.timeUnit.assemble(component));
return sourceData;
}
return null;
}
source.assemble = assemble;
})(source = exports.source || (exports.source = {}));
},{"../../data":44,"../../util":60,"./bin":15,"./filter":18,"./formula":20,"./nullfilter":22,"./timeunit":26}],24:[function(require,module,exports){
"use strict";
var data_1 = require('../../data');
var fielddef_1 = require('../../fielddef');
var util_1 = require('../../util');
var stackScale;
(function (stackScale) {
function parseUnit(model) {
var stackProps = model.stack();
if (stackProps) {
var groupbyChannel = stackProps.groupbyChannel;
var fieldChannel = stackProps.fieldChannel;
var fields = [];
var field_1 = model.field(groupbyChannel);
if (field_1) {
fields.push(field_1);
}
return {
name: model.dataName(data_1.STACKED_SCALE),
source: model.dataName(data_1.SUMMARY),
transform: [util_1.extend({
type: 'aggregate',
summarize: [{ ops: ['sum'], field: model.field(fieldChannel) }]
}, fields.length > 0 ? {
groupby: fields
} : {})]
};
}
return null;
}
stackScale.parseUnit = parseUnit;
;
function parseFacet(model) {
var child = model.child();
var childDataComponent = child.component.data;
if (!childDataComponent.source && childDataComponent.stackScale) {
var stackComponent = childDataComponent.stackScale;
var newName = model.dataName(data_1.STACKED_SCALE);
child.renameData(stackComponent.name, newName);
stackComponent.name = newName;
stackComponent.source = model.dataName(data_1.SUMMARY);
stackComponent.transform[0].groupby = model.reduce(function (groupby, fieldDef) {
groupby.push(fielddef_1.field(fieldDef));
return groupby;
}, stackComponent.transform[0].groupby);
delete childDataComponent.stackScale;
return stackComponent;
}
return null;
}
stackScale.parseFacet = parseFacet;
function parseLayer(model) {
return null;
}
stackScale.parseLayer = parseLayer;
function assemble(component) {
return component.stackScale;
}
stackScale.assemble = assemble;
})(stackScale = exports.stackScale || (exports.stackScale = {}));
},{"../../data":44,"../../fielddef":48,"../../util":60}],25:[function(require,module,exports){
"use strict";
var aggregate_1 = require('../../aggregate');
var data_1 = require('../../data');
var fielddef_1 = require('../../fielddef');
var util_1 = require('../../util');
var summary;
(function (summary) {
function addDimension(dims, fieldDef) {
if (fieldDef.bin) {
dims[fielddef_1.field(fieldDef, { binSuffix: 'start' })] = true;
dims[fielddef_1.field(fieldDef, { binSuffix: 'mid' })] = true;
dims[fielddef_1.field(fieldDef, { binSuffix: 'end' })] = true;
dims[fielddef_1.field(fieldDef, { binSuffix: 'range' })] = true;
}
else {
dims[fielddef_1.field(fieldDef)] = true;
}
return dims;
}
function parseUnit(model) {
var dims = {};
var meas = {};
model.forEach(function (fieldDef, channel) {
if (fieldDef.aggregate) {
if (fieldDef.aggregate === aggregate_1.AggregateOp.COUNT) {
meas['*'] = meas['*'] || {};
meas['*']['count'] = true;
}
else {
meas[fieldDef.field] = meas[fieldDef.field] || {};
meas[fieldDef.field][fieldDef.aggregate] = true;
}
}
else {
addDimension(dims, fieldDef);
}
});
return [{
name: model.dataName(data_1.SUMMARY),
dimensions: dims,
measures: meas
}];
}
summary.parseUnit = parseUnit;
function parseFacet(model) {
var childDataComponent = model.child().component.data;
if (!childDataComponent.source && childDataComponent.summary) {
var summaryComponents = childDataComponent.summary.map(function (summaryComponent) {
summaryComponent.dimensions = model.reduce(addDimension, summaryComponent.dimensions);
var summaryNameWithoutPrefix = summaryComponent.name.substr(model.child().name('').length);
model.child().renameData(summaryComponent.name, summaryNameWithoutPrefix);
summaryComponent.name = summaryNameWithoutPrefix;
return summaryComponent;
});
delete childDataComponent.summary;
return summaryComponents;
}
return [];
}
summary.parseFacet = parseFacet;
function mergeMeasures(parentMeasures, childMeasures) {
for (var field_1 in childMeasures) {
if (childMeasures.hasOwnProperty(field_1)) {
var ops = childMeasures[field_1];
for (var op in ops) {
if (ops.hasOwnProperty(op)) {
if (field_1 in parentMeasures) {
parentMeasures[field_1][op] = true;
}
else {
parentMeasures[field_1] = { op: true };
}
}
}
}
}
}
function parseLayer(model) {
var summaries = {};
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (!childDataComponent.source && childDataComponent.summary) {
childDataComponent.summary.forEach(function (childSummary) {
var key = util_1.hash(childSummary.dimensions);
if (key in summaries) {
mergeMeasures(summaries[key].measures, childSummary.measures);
}
else {
childSummary.name = model.dataName(data_1.SUMMARY) + '_' + util_1.keys(summaries).length;
summaries[key] = childSummary;
}
child.renameData(child.dataName(data_1.SUMMARY), summaries[key].name);
delete childDataComponent.summary;
});
}
});
return util_1.vals(summaries);
}
summary.parseLayer = parseLayer;
function assemble(component, model) {
if (!component.summary) {
return [];
}
return component.summary.reduce(function (summaryData, summaryComponent) {
var dims = summaryComponent.dimensions;
var meas = summaryComponent.measures;
var groupby = util_1.keys(dims);
var summarize = util_1.reduce(meas, function (aggregator, fnDictSet, field) {
aggregator[field] = util_1.keys(fnDictSet);
return aggregator;
}, {});
if (util_1.keys(meas).length > 0) {
summaryData.push({
name: summaryComponent.name,
source: model.dataName(data_1.SOURCE),
transform: [{
type: 'aggregate',
groupby: groupby,
summarize: summarize
}]
});
}
return summaryData;
}, []);
}
summary.assemble = assemble;
})(summary = exports.summary || (exports.summary = {}));
},{"../../aggregate":7,"../../data":44,"../../fielddef":48,"../../util":60}],26:[function(require,module,exports){
"use strict";
var fielddef_1 = require('../../fielddef');
var timeunit_1 = require('../../timeunit');
var type_1 = require('../../type');
var util_1 = require('../../util');
var timeUnit;
(function (timeUnit) {
function parse(model) {
return model.reduce(function (timeUnitComponent, fieldDef, channel) {
if (fieldDef.type === type_1.TEMPORAL && fieldDef.timeUnit) {
var hash = fielddef_1.field(fieldDef);
timeUnitComponent[hash] = {
type: 'formula',
field: fielddef_1.field(fieldDef),
expr: timeunit_1.fieldExpr(fieldDef.timeUnit, fieldDef.field)
};
}
return timeUnitComponent;
}, {});
}
timeUnit.parseUnit = parse;
function parseFacet(model) {
var timeUnitComponent = parse(model);
var childDataComponent = model.child().component.data;
if (!childDataComponent.source) {
util_1.extend(timeUnitComponent, childDataComponent.timeUnit);
delete childDataComponent.timeUnit;
}
return timeUnitComponent;
}
timeUnit.parseFacet = parseFacet;
function parseLayer(model) {
var timeUnitComponent = parse(model);
model.children().forEach(function (child) {
var childDataComponent = child.component.data;
if (!childDataComponent.source) {
util_1.extend(timeUnitComponent, childDataComponent.timeUnit);
delete childDataComponent.timeUnit;
}
});
return timeUnitComponent;
}
timeUnit.parseLayer = parseLayer;
function assemble(component) {
return util_1.vals(component.timeUnit);
}
timeUnit.assemble = assemble;
})(timeUnit = exports.timeUnit || (exports.timeUnit = {}));
},{"../../fielddef":48,"../../timeunit":57,"../../type":59,"../../util":60}],27:[function(require,module,exports){
"use strict";
var datetime_1 = require('../../datetime');
var timeunit_1 = require('../../timeunit');
var util_1 = require('../../util');
var timeUnitDomain;
(function (timeUnitDomain) {
function parse(model) {
return model.reduce(function (timeUnitDomainMap, fieldDef, channel) {
if (fieldDef.timeUnit) {
var domain = timeunit_1.rawDomain(fieldDef.timeUnit, channel);
if (domain) {
timeUnitDomainMap[fieldDef.timeUnit] = true;
}
}
return timeUnitDomainMap;
}, {});
}
timeUnitDomain.parseUnit = parse;
function parseFacet(model) {
return util_1.extend(parse(model), model.child().component.data.timeUnitDomain);
}
timeUnitDomain.parseFacet = parseFacet;
function parseLayer(model) {
return util_1.extend(parse(model), model.children().forEach(function (child) {
return child.component.data.timeUnitDomain;
}));
}
timeUnitDomain.parseLayer = parseLayer;
function assemble(component) {
return util_1.keys(component.timeUnitDomain).reduce(function (timeUnitData, tu) {
var timeUnit = tu;
var domain = timeunit_1.rawDomain(timeUnit, null);
if (domain) {
var datetime = {};
datetime[timeUnit] = 'datum["data"]';
timeUnitData.push({
name: timeUnit,
values: domain,
transform: [{
type: 'formula',
field: 'date',
expr: datetime_1.dateTimeExpr(datetime)
}]
});
}
return timeUnitData;
}, []);
}
timeUnitDomain.assemble = assemble;
})(timeUnitDomain = exports.timeUnitDomain || (exports.timeUnitDomain = {}));
},{"../../datetime":45,"../../timeunit":57,"../../util":60}],28:[function(require,module,exports){
"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 axis_1 = require('../axis');
var channel_1 = require('../channel');
var config_1 = require('../config');
var data_1 = require('../data');
var encoding_1 = require('../encoding');
var fielddef_1 = require('../fielddef');
var scale_1 = require('../scale');
var type_1 = require('../type');
var util_1 = require('../util');
var axis_2 = require('./axis');
var common_1 = require('./common');
var data_2 = require('./data/data');
var layout_1 = require('./layout');
var model_1 = require('./model');
var scale_2 = require('./scale');
var FacetModel = (function (_super) {
__extends(FacetModel, _super);
function FacetModel(spec, parent, parentGivenName) {
_super.call(this, spec, parent, parentGivenName);
var config = this._config = this._initConfig(spec.config, parent);
var child = this._child = common_1.buildModel(spec.spec, this, this.name('child'));
var facet = this._facet = this._initFacet(spec.facet);
this._scale = this._initScale(facet, config, child);
this._axis = this._initAxis(facet, config, child);
}
FacetModel.prototype._initConfig = function (specConfig, parent) {
return util_1.mergeDeep(util_1.duplicate(config_1.defaultConfig), specConfig, parent ? parent.config() : {});
};
FacetModel.prototype._initFacet = function (facet) {
facet = util_1.duplicate(facet);
var model = this;
encoding_1.channelMappingForEach(this.channels(), facet, function (fieldDef, channel) {
if (!fielddef_1.isDimension(fieldDef)) {
model.addWarning(channel + ' encoding should be ordinal.');
}
if (fieldDef.type) {
fieldDef.type = type_1.getFullName(fieldDef.type);
}
});
return facet;
};
FacetModel.prototype._initScale = function (facet, config, child) {
return [channel_1.ROW, channel_1.COLUMN].reduce(function (_scale, channel) {
if (facet[channel]) {
var scaleSpec = facet[channel].scale || {};
_scale[channel] = util_1.extend({
type: scale_1.ScaleType.ORDINAL,
round: config.facet.scale.round,
padding: (channel === channel_1.ROW && child.has(channel_1.Y)) || (channel === channel_1.COLUMN && child.has(channel_1.X)) ?
config.facet.scale.padding : 0
}, scaleSpec);
}
return _scale;
}, {});
};
FacetModel.prototype._initAxis = function (facet, config, child) {
return [channel_1.ROW, channel_1.COLUMN].reduce(function (_axis, channel) {
if (facet[channel]) {
var axisSpec = facet[channel].axis;
if (axisSpec !== false) {
var modelAxis = _axis[channel] = util_1.extend({}, config.facet.axis, axisSpec === true ? {} : axisSpec || {});
if (channel === channel_1.ROW) {
var yAxis = child.axis(channel_1.Y);
if (yAxis && yAxis.orient !== axis_1.AxisOrient.RIGHT && !modelAxis.orient) {
modelAxis.orient = axis_1.AxisOrient.RIGHT;
}
if (child.has(channel_1.X) && !modelAxis.labelAngle) {
modelAxis.labelAngle = modelAxis.orient === axis_1.AxisOrient.RIGHT ? 90 : 270;
}
}
}
}
return _axis;
}, {});
};
FacetModel.prototype.facet = function () {
return this._facet;
};
FacetModel.prototype.has = function (channel) {
return !!this._facet[channel];
};
FacetModel.prototype.child = function () {
return this._child;
};
FacetModel.prototype.hasSummary = function () {
var summary = this.component.data.summary;
for (var i = 0; i < summary.length; i++) {
if (util_1.keys(summary[i].measures).length > 0) {
return true;
}
}
return false;
};
FacetModel.prototype.dataTable = function () {
return (this.hasSummary() ? data_1.SUMMARY : data_1.SOURCE) + '';
};
FacetModel.prototype.fieldDef = function (channel) {
return this.facet()[channel];
};
FacetModel.prototype.stack = function () {
return null;
};
FacetModel.prototype.parseData = function () {
this.child().parseData();
this.component.data = data_2.parseFacetData(this);
};
FacetModel.prototype.parseSelectionData = function () {
};
FacetModel.prototype.parseLayoutData = function () {
this.child().parseLayoutData();
this.component.layout = layout_1.parseFacetLayout(this);
};
FacetModel.prototype.parseScale = function () {
var child = this.child();
var model = this;
child.parseScale();
var scaleComponent = this.component.scale = scale_2.parseScaleComponent(this);
util_1.keys(child.component.scale).forEach(function (channel) {
if (true) {
scaleComponent[channel] = child.component.scale[channel];
util_1.vals(scaleComponent[channel]).forEach(function (scale) {
var scaleNameWithoutPrefix = scale.name.substr(child.name('').length);
var newName = model.scaleName(scaleNameWithoutPrefix);
child.renameScale(scale.name, newName);
scale.name = newName;
});
delete child.component.scale[channel];
}
});
};
FacetModel.prototype.parseMark = function () {
this.child().parseMark();
this.component.mark = util_1.extend({
name: this.name('cell'),
type: 'group',
from: util_1.extend(this.dataTable() ? { data: this.dataTable() } : {}, {
transform: [{
type: 'facet',
groupby: [].concat(this.has(channel_1.ROW) ? [this.field(channel_1.ROW)] : [], this.has(channel_1.COLUMN) ? [this.field(channel_1.COLUMN)] : [])
}]
}),
properties: {
update: getFacetGroupProperties(this)
}
}, this.child().assembleGroup());
};
FacetModel.prototype.parseAxis = function () {
this.child().parseAxis();
this.component.axis = axis_2.parseAxisComponent(this, [channel_1.ROW, channel_1.COLUMN]);
};
FacetModel.prototype.parseAxisGroup = function () {
var xAxisGroup = parseAxisGroup(this, channel_1.X);
var yAxisGroup = parseAxisGroup(this, channel_1.Y);
this.component.axisGroup = util_1.extend(xAxisGroup ? { x: xAxisGroup } : {}, yAxisGroup ? { y: yAxisGroup } : {});
};
FacetModel.prototype.parseGridGroup = function () {
var child = this.child();
this.component.gridGroup = util_1.extend(!child.has(channel_1.X) && this.has(channel_1.COLUMN) ? { column: getColumnGridGroups(this) } : {}, !child.has(channel_1.Y) && this.has(channel_1.ROW) ? { row: getRowGridGroups(this) } : {});
};
FacetModel.prototype.parseLegend = function () {
this.child().parseLegend();
this.component.legend = this._child.component.legend;
this._child.component.legend = {};
};
FacetModel.prototype.assembleParentGroupProperties = function () {
return null;
};
FacetModel.prototype.assembleData = function (data) {
data_2.assembleData(this, data);
return this._child.assembleData(data);
};
FacetModel.prototype.assembleLayout = function (layoutData) {
this._child.assembleLayout(layoutData);
return layout_1.assembleLayout(this, layoutData);
};
FacetModel.prototype.assembleMarks = function () {
return [].concat(util_1.vals(this.component.axisGroup), util_1.flatten(util_1.vals(this.component.gridGroup)), this.component.mark);
};
FacetModel.prototype.channels = function () {
return [channel_1.ROW, channel_1.COLUMN];
};
FacetModel.prototype.mapping = function () {
return this.facet();
};
FacetModel.prototype.isFacet = function () {
return true;
};
return FacetModel;
}(model_1.Model));
exports.FacetModel = FacetModel;
function getFacetGroupProperties(model) {
var child = model.child();
var mergedCellConfig = util_1.extend({}, child.config().cell, child.config().facet.cell);
return util_1.extend({
x: model.has(channel_1.COLUMN) ? {
scale: model.scaleName(channel_1.COLUMN),
field: model.field(channel_1.COLUMN),
offset: model.scale(channel_1.COLUMN).padding / 2
} : { value: model.config().facet.scale.padding / 2 },
y: model.has(channel_1.ROW) ? {
scale: model.scaleName(channel_1.ROW),
field: model.field(channel_1.ROW),
offset: model.scale(channel_1.ROW).padding / 2
} : { value: model.config().facet.scale.padding / 2 },
width: { field: { parent: model.child().sizeName('width') } },
height: { field: { parent: model.child().sizeName('height') } }
}, child.assembleParentGroupProperties(mergedCellConfig));
}
function parseAxisGroup(model, channel) {
var axisGroup = null;
var child = model.child();
if (child.has(channel)) {
if (child.axis(channel)) {
if (true) {
axisGroup = channel === channel_1.X ? getXAxesGroup(model) : getYAxesGroup(model);
if (child.axis(channel) && axis_2.gridShow(child, channel)) {
child.component.axis[channel] = axis_2.parseInnerAxis(channel, child);
}
else {
delete child.component.axis[channel];
}
}
else {
}
}
}
return axisGroup;
}
function getXAxesGroup(model) {
var hasCol = model.has(channel_1.COLUMN);
return util_1.extend({
name: model.name('x-axes'),
type: 'group'
}, hasCol ? {
from: {
data: model.dataTable(),
transform: [{
type: 'aggregate',
groupby: [model.field(channel_1.COLUMN)],
summarize: { '*': ['count'] }
}]
}
} : {}, {
properties: {
update: {
width: { field: { parent: model.child().sizeName('width') } },
height: {
field: { group: 'height' }
},
x: hasCol ? {
scale: model.scaleName(channel_1.COLUMN),
field: model.field(channel_1.COLUMN),
offset: model.scale(channel_1.COLUMN).padding / 2
} : {
value: model.config().facet.scale.padding / 2
}
}
},
axes: [axis_2.parseAxis(channel_1.X, model.child())]
});
}
function getYAxesGroup(model) {
var hasRow = model.has(channel_1.ROW);
return util_1.extend({
name: model.name('y-axes'),
type: 'group'
}, hasRow ? {
from: {
data: model.dataTable(),
transform: [{
type: 'aggregate',
groupby: [model.field(channel_1.ROW)],
summarize: { '*': ['count'] }
}]
}
} : {}, {
properties: {
update: {
width: {
field: { group: 'width' }
},
height: { field: { parent: model.child().sizeName('height') } },
y: hasRow ? {
scale: model.scaleName(channel_1.ROW),
field: model.field(channel_1.ROW),
offset: model.scale(channel_1.ROW).padding / 2
} : {
value: model.config().facet.scale.padding / 2
}
}
},
axes: [axis_2.parseAxis(channel_1.Y, model.child())]
});
}
function getRowGridGroups(model) {
var facetGridConfig = model.config().facet.grid;
var rowGrid = {
name: model.name('row-grid'),
type: 'rule',
from: {
data: model.dataTable(),
transform: [{ type: 'facet', groupby: [model.field(channel_1.ROW)] }]
},
properties: {
update: {
y: {
scale: model.scaleName(channel_1.ROW),
field: model.field(channel_1.ROW)
},
x: { value: 0, offset: -facetGridConfig.offset },
x2: { field: { group: 'width' }, offset: facetGridConfig.offset },
stroke: { value: facetGridConfig.color },
strokeOpacity: { value: facetGridConfig.opacity },
strokeWidth: { value: 0.5 }
}
}
};
return [rowGrid, {
name: model.name('row-grid-end'),
type: 'rule',
properties: {
update: {
y: { field: { group: 'height' } },
x: { value: 0, offset: -facetGridConfig.offset },
x2: { field: { group: 'width' }, offset: facetGridConfig.offset },
stroke: { value: facetGridConfig.color },
strokeOpacity: { value: facetGridConfig.opacity },
strokeWidth: { value: 0.5 }
}
}
}];
}
function getColumnGridGroups(model) {
var facetGridConfig = model.config().facet.grid;
var columnGrid = {
name: model.name('column-grid'),
type: 'rule',
from: {
data: model.dataTable(),
transform: [{ type: 'facet', groupby: [model.field(channel_1.COLUMN)] }]
},
properties: {
update: {
x: {
scale: model.scaleName(channel_1.COLUMN),
field: model.field(channel_1.COLUMN)
},
y: { value: 0, offset: -facetGridConfig.offset },
y2: { field: { group: 'height' }, offset: facetGridConfig.offset },
stroke: { value: facetGridConfig.color },
strokeOpacity: { value: facetGridConfig.opacity },
strokeWidth: { value: 0.5 }
}
}
};
return [columnGrid, {
name: model.name('column-grid-end'),
type: 'rule',
properties: {
update: {
x: { field: { group: 'width' } },
y: { value: 0, offset: -facetGridConfig.offset },
y2: { field: { group: 'height' }, offset: facetGridConfig.offset },
stroke: { value: facetGridConfig.color },
strokeOpacity: { value: facetGridConfig.opacity },
strokeWidth: { value: 0.5 }
}
}
}];
}
},{"../axis":8,"../channel":10,"../config":43,"../data":44,"../encoding":46,"../fielddef":48,"../scale":52,"../type":59,"../util":60,"./axis":11,"./common":12,"./data/data":17,"./layout":30,"./model":40,"./scale":41}],29:[function(require,module,exports){
"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 util_1 = require('../util');
var config_1 = require('../config');
var data_1 = require('./data/data');
var layout_1 = require('./layout');
var model_1 = require('./model');
var common_1 = require('./common');
var vega_schema_1 = require('../vega.schema');
var LayerModel = (function (_super) {
__extends(LayerModel, _super);
function LayerModel(spec, parent, parentGivenName) {
var _this = this;
_super.call(this, spec, parent, parentGivenName);
this._width = spec.width;
this._height = spec.height;
this._config = this._initConfig(spec.config, parent);
this._children = spec.layers.map(function (layer, i) {
return common_1.buildModel(layer, _this, _this.name('layer_' + i));
});
}
LayerModel.prototype._initConfig = function (specConfig, parent) {
return util_1.mergeDeep(util_1.duplicate(config_1.defaultConfig), specConfig, parent ? parent.config() : {});
};
Object.defineProperty(LayerModel.prototype, "width", {
get: function () {
return this._width;
},
enumerable: true,
configurable: true
});
Object.defineProperty(LayerModel.prototype, "height", {
get: function () {
return this._height;
},
enumerable: true,
configurable: true
});
LayerModel.prototype.has = function (channel) {
return false;
};
LayerModel.prototype.children = function () {
return this._children;
};
LayerModel.prototype.isOrdinalScale = function (channel) {
return this._children[0].isOrdinalScale(channel);
};
LayerModel.prototype.dataTable = function () {
return this._children[0].dataTable();
};
LayerModel.prototype.fieldDef = function (channel) {
return null;
};
LayerModel.prototype.stack = function () {
return null;
};
LayerModel.prototype.parseData = function () {
this._children.forEach(function (child) {
child.parseData();
});
this.component.data = data_1.parseLayerData(this);
};
LayerModel.prototype.parseSelectionData = function () {
};
LayerModel.prototype.parseLayoutData = function () {
this._children.forEach(function (child, i) {
child.parseLayoutData();
});
this.component.layout = layout_1.parseLayerLayout(this);
};
LayerModel.prototype.parseScale = function () {
var model = this;
var scaleComponent = this.component.scale = {};
this._children.forEach(function (child) {
child.parseScale();
if (true) {
util_1.keys(child.component.scale).forEach(function (channel) {
var childScales = child.component.scale[channel];
if (!childScales) {
return;
}
var modelScales = scaleComponent[channel];
if (modelScales && modelScales.main) {
var modelDomain = modelScales.main.domain;
var childDomain = childScales.main.domain;
if (util_1.isArray(modelDomain)) {
if (util_1.isArray(childScales.main.domain)) {
modelScales.main.domain = modelDomain.concat(childDomain);
}
else {
model.addWarning('custom domain scale cannot be unioned with default field-based domain');
}
}
else {
var unionedFields = vega_schema_1.isUnionedDomain(modelDomain) ? modelDomain.fields : [modelDomain];
if (util_1.isArray(childDomain)) {
model.addWarning('custom domain scale cannot be unioned with default field-based domain');
}
var fields = vega_schema_1.isDataRefDomain(childDomain) ? unionedFields.concat([childDomain]) :
vega_schema_1.isUnionedDomain(childDomain) ? unionedFields.concat(childDomain.fields) :
unionedFields;
fields = util_1.unique(fields, util_1.hash);
if (fields.length > 1) {
modelScales.main.domain = { fields: fields };
}
else {
modelScales.main.domain = fields[0];
}
}
modelScales.colorLegend = modelScales.colorLegend ? modelScales.colorLegend : childScales.colorLegend;
modelScales.binColorLegend = modelScales.binColorLegend ? modelScales.binColorLegend : childScales.binColorLegend;
}
else {
scaleComponent[channel] = childScales;
}
util_1.vals(childScales).forEach(function (scale) {
var scaleNameWithoutPrefix = scale.name.substr(child.name('').length);
var newName = model.scaleName(scaleNameWithoutPrefix);
child.renameScale(scale.name, newName);
scale.name = newName;
});
delete childScales[channel];
});
}
});
};
LayerModel.prototype.parseMark = function () {
this._children.forEach(function (child) {
child.parseMark();
});
};
LayerModel.prototype.parseAxis = function () {
var axisComponent = this.component.axis = {};
this._children.forEach(function (child) {
child.parseAxis();
if (true) {
util_1.keys(child.component.axis).forEach(function (channel) {
if (!axisComponent[channel]) {
axisComponent[channel] = child.component.axis[channel];
}
});
}
});
};
LayerModel.prototype.parseAxisGroup = function () {
return null;
};
LayerModel.prototype.parseGridGroup = function () {
return null;
};
LayerModel.prototype.parseLegend = function () {
var legendComponent = this.component.legend = {};
this._children.forEach(function (child) {
child.parseLegend();
if (true) {
util_1.keys(child.component.legend).forEach(function (channel) {
if (!legendComponent[channel]) {
legendComponent[channel] = child.component.legend[channel];
}
});
}
});
};
LayerModel.prototype.assembleParentGroupProperties = function () {
return null;
};
LayerModel.prototype.assembleData = function (data) {
data_1.assembleData(this, data);
this._children.forEach(function (child) {
child.assembleData(data);
});
return data;
};
LayerModel.prototype.assembleLayout = function (layoutData) {
this._children.forEach(function (child) {
child.assembleLayout(layoutData);
});
return layout_1.assembleLayout(this, layoutData);
};
LayerModel.prototype.assembleMarks = function () {
return util_1.flatten(this._children.map(function (child) {
return child.assembleMarks();
}));
};
LayerModel.prototype.channels = function () {
return [];
};
LayerModel.prototype.mapping = function () {
return null;
};
LayerModel.prototype.isLayer = function () {
return true;
};
LayerModel.prototype.compatibleSource = function (child) {
var data = this.data();
var childData = child.component.data;
var compatible = !childData.source || (data && data.url === childData.source.url);
return compatible;
};
return LayerModel;
}(model_1.Model));
exports.LayerModel = LayerModel;
},{"../config":43,"../util":60,"../vega.schema":62,"./common":12,"./data/data":17,"./layout":30,"./model":40}],30:[function(require,module,exports){
"use strict";
var channel_1 = require('../channel');
var data_1 = require('../data');
var scale_1 = require('../scale');
var util_1 = require('../util');
var timeunit_1 = require('../timeunit');
function assembleLayout(model, layoutData) {
var layoutComponent = model.component.layout;
if (!layoutComponent.width && !layoutComponent.height) {
return layoutData;
}
if (true) {
var distinctFields = util_1.keys(util_1.extend(layoutComponent.width.distinct, layoutComponent.height.distinct));
var formula = layoutComponent.width.formula.concat(layoutComponent.height.formula)
.map(function (formula) {
return util_1.extend({ type: 'formula' }, formula);
});
return [
distinctFields.length > 0 ? {
name: model.dataName(data_1.LAYOUT),
source: model.dataTable(),
transform: [{
type: 'aggregate',
summarize: distinctFields.map(function (field) {
return { field: field, ops: ['distinct'] };
})
}].concat(formula)
} : {
name: model.dataName(data_1.LAYOUT),
values: [{}],
transform: formula
}
];
}
}
exports.assembleLayout = assembleLayout;
function parseUnitLayout(model) {
return {
width: parseUnitSizeLayout(model, channel_1.X),
height: parseUnitSizeLayout(model, channel_1.Y)
};
}
exports.parseUnitLayout = parseUnitLayout;
function parseUnitSizeLayout(model, channel) {
return {
distinct: getDistinct(model, channel),
formula: [{
field: model.channelSizeName(channel),
expr: unitSizeExpr(model, channel)
}]
};
}
function unitSizeExpr(model, channel) {
var scale = model.scale(channel);
if (scale) {
if (scale.type === scale_1.ScaleType.ORDINAL && scale.bandSize !== scale_1.BANDSIZE_FIT) {
return '(' + cardinalityExpr(model, channel) +
' + ' + 1 +
') * ' + scale.bandSize;
}
}
return (channel === channel_1.X ? model.width : model.height) + '';
}
exports.unitSizeExpr = unitSizeExpr;
function parseFacetLayout(model) {
return {
width: parseFacetSizeLayout(model, channel_1.COLUMN),
height: parseFacetSizeLayout(model, channel_1.ROW)
};
}
exports.parseFacetLayout = parseFacetLayout;
function parseFacetSizeLayout(model, channel) {
var childLayoutComponent = model.child().component.layout;
var sizeType = channel === channel_1.ROW ? 'height' : 'width';
var childSizeComponent = childLayoutComponent[sizeType];
if (true) {
var distinct = util_1.extend(getDistinct(model, channel), childSizeComponent.distinct);
var formula = childSizeComponent.formula.concat([{
field: model.channelSizeName(channel),
expr: facetSizeFormula(model, channel, model.child().channelSizeName(channel))
}]);
delete childLayoutComponent[sizeType];
return {
distinct: distinct,
formula: formula
};
}
}
function facetSizeFormula(model, channel, innerSize) {
var scale = model.scale(channel);
if (model.has(channel)) {
return '(datum["' + innerSize + '"] + ' + scale.padding + ')' + ' * ' + cardinalityExpr(model, channel);
}
else {
return 'datum["' + innerSize + '"] + ' + model.config().facet.scale.padding;
}
}
function parseLayerLayout(model) {
return {
width: parseLayerSizeLayout(model, channel_1.X),
height: parseLayerSizeLayout(model, channel_1.Y)
};
}
exports.parseLayerLayout = parseLayerLayout;
function parseLayerSizeLayout(model, channel) {
if (true) {
var childLayoutComponent = model.children()[0].component.layout;
var sizeType_1 = channel === channel_1.Y ? 'height' : 'width';
var childSizeComponent = childLayoutComponent[sizeType_1];
var distinct = childSizeComponent.distinct;
var formula = [{
field: model.channelSizeName(channel),
expr: childSizeComponent.formula[0].expr
}];
model.children().forEach(function (child) {
delete child.component.layout[sizeType_1];
});
return {
distinct: distinct,
formula: formula
};
}
}
function getDistinct(model, channel) {
if (model.has(channel) && model.isOrdinalScale(channel)) {
var scale = model.scale(channel);
if (scale.type === scale_1.ScaleType.ORDINAL && !(scale.domain instanceof Array)) {
var distinctField = model.field(channel);
var distinct = {};
distinct[distinctField] = true;
return distinct;
}
}
return {};
}
function cardinalityExpr(model, channel) {
var scale = model.scale(channel);
if (scale.domain instanceof Array) {
return scale.domain.length;
}
var timeUnit = model.fieldDef(channel).timeUnit;
var timeUnitDomain = timeUnit ? timeunit_1.rawDomain(timeUnit, channel) : null;
return timeUnitDomain !== null ? timeUnitDomain.length :
model.field(channel, { datum: true, prefix: 'distinct' });
}
exports.cardinalityExpr = cardinalityExpr;
},{"../channel":10,"../data":44,"../scale":52,"../timeunit":57,"../util":60}],31:[function(require,module,exports){
"use strict";
var channel_1 = require('../channel');
var fielddef_1 = require('../fielddef');
var mark_1 = require('../mark');
var type_1 = require('../type');
var util_1 = require('../util');
var common_1 = require('./common');
var scale_1 = require('./scale');
function parseLegendComponent(model) {
return [channel_1.COLOR, channel_1.SIZE, channel_1.SHAPE, channel_1.OPACITY].reduce(function (legendComponent, channel) {
if (model.legend(channel)) {
legendComponent[channel] = parseLegend(model, channel);
}
return legendComponent;
}, {});
}
exports.parseLegendComponent = parseLegendComponent;
function getLegendDefWithScale(model, channel) {
switch (channel) {
case channel_1.COLOR:
var fieldDef = model.encoding().color;
var scale = model.scaleName(useColorLegendScale(fieldDef) ?
scale_1.COLOR_LEGEND :
channel_1.COLOR);
return model.config().mark.filled ? { fill: scale } : { stroke: scale };
case channel_1.SIZE:
return { size: model.scaleName(channel_1.SIZE) };
case channel_1.SHAPE:
return { shape: model.scaleName(channel_1.SHAPE) };
case channel_1.OPACITY:
return { opacity: model.scaleName(channel_1.OPACITY) };
}
return null;
}
function parseLegend(model, channel) {
var fieldDef = model.fieldDef(channel);
var legend = model.legend(channel);
var config = model.config();
var def = getLegendDefWithScale(model, channel);
def.title = title(legend, fieldDef, config);
var format = common_1.numberFormat(fieldDef, legend.format, config);
if (format) {
def.format = format;
}
['offset', 'orient', 'values'].forEach(function (property) {
var value = legend[property];
if (value !== undefined) {
def[property] = value;
}
});
var props = (typeof legend !== 'boolean' && legend.properties) || {};
['title', 'symbols', 'legend', 'labels'].forEach(function (group) {
var value = properties[group] ?
properties[group](fieldDef, props[group], model, channel) :
props[group];
if (value !== undefined && util_1.keys(value).length > 0) {
def.properties = def.properties || {};
def.properties[group] = value;
}
});
return def;
}
exports.parseLegend = parseLegend;
function title(legend, fieldDef, config) {
if (typeof legend !== 'boolean' && legend.title) {
return legend.title;
}
return fielddef_1.title(fieldDef, config);
}
exports.title = title;
function useColorLegendScale(fieldDef) {
return fieldDef.type === type_1.ORDINAL || fieldDef.bin || fieldDef.timeUnit;
}
exports.useColorLegendScale = useColorLegendScale;
var properties;
(function (properties) {
function symbols(fieldDef, symbolsSpec, model, channel) {
var symbols = {};
var mark = model.mark();
var legend = model.legend(channel);
switch (mark) {
case mark_1.BAR:
case mark_1.TICK:
case mark_1.TEXT:
symbols.shape = { value: 'square' };
break;
case mark_1.CIRCLE:
case mark_1.SQUARE:
symbols.shape = { value: mark };
break;
case mark_1.POINT:
case mark_1.LINE:
case mark_1.AREA:
break;
}
var cfg = model.config();
var filled = cfg.mark.filled;
var config = channel === channel_1.COLOR ?
util_1.without(common_1.FILL_STROKE_CONFIG, [filled ? 'fill' : 'stroke', 'strokeDash', 'strokeDashOffset']) :
util_1.without(common_1.FILL_STROKE_CONFIG, ['strokeDash', 'strokeDashOffset']);
config = util_1.without(config, ['strokeDash', 'strokeDashOffset']);
common_1.applyMarkConfig(symbols, model, config);
if (filled) {
symbols.strokeWidth = { value: 0 };
}
if (channel === channel_1.OPACITY) {
delete symbols.opacity;
}
var value;
if (model.has(channel_1.COLOR) && channel === channel_1.COLOR) {
if (useColorLegendScale(fieldDef)) {
value = { scale: model.scaleName(channel_1.COLOR), field: 'data' };
}
}
else if (model.encoding().color && model.encoding().color.value) {
value = { value: model.encoding().color.value };
}
if (value !== undefined) {
if (filled) {
symbols.fill = value;
}
else {
symbols.stroke = value;
}
}
else if (channel !== channel_1.COLOR) {
symbols[filled ? 'fill' : 'stroke'] = symbols[filled ? 'fill' : 'stroke'] ||
{ value: cfg.mark.color };
}
if (legend.symbolColor !== undefined) {
symbols.fill = { value: legend.symbolColor };
}
else if (symbols.fill === undefined) {
if (cfg.mark.fill !== undefined) {
symbols.fill = { value: cfg.mark.fill };
}
else if (cfg.mark.stroke !== undefined) {
symbols.stroke = { value: cfg.mark.stroke };
}
}
if (channel !== channel_1.SHAPE) {
if (legend.symbolShape !== undefined) {
symbols.shape = { value: legend.symbolShape };
}
else if (cfg.mark.shape !== undefined) {
symbols.shape = { value: cfg.mark.shape };
}
}
if (channel !== channel_1.SIZE) {
if (legend.symbolSize !== undefined) {
symbols.size = { value: legend.symbolSize };
}
}
if (legend.symbolStrokeWidth !== undefined) {
symbols.strokeWidth = { value: legend.symbolStrokeWidth };
}
symbols = util_1.extend(symbols, symbolsSpec || {});
return util_1.keys(symbols).length > 0 ? symbols : undefined;
}
properties.symbols = symbols;
function labels(fieldDef, labelsSpec, model, channel) {
var legend = model.legend(channel);
var config = model.config();
var labels = {};
if (channel === channel_1.COLOR) {
if (fieldDef.type === type_1.ORDINAL) {
labelsSpec = util_1.extend({
text: {
scale: model.scaleName(scale_1.COLOR_LEGEND),
field: 'data'
}
}, labelsSpec || {});
}
else if (fieldDef.bin) {
labelsSpec = util_1.extend({
text: {
scale: model.scaleName(scale_1.COLOR_LEGEND_LABEL),
field: 'data'
}
}, labelsSpec || {});
}
else if (fieldDef.type === type_1.TEMPORAL) {
labelsSpec = util_1.extend({
text: {
template: common_1.timeTemplate('datum["data"]', fieldDef.timeUnit, legend.format, legend.shortTimeLabels, config)
}
}, labelsSpec || {});
}
}
if (legend.labelAlign !== undefined) {
labels.align = { value: legend.labelAlign };
}
if (legend.labelColor !== undefined) {
labels.stroke = { value: legend.labelColor };
}
if (legend.labelFont !== undefined) {
labels.font = { value: legend.labelFont };
}
if (legend.labelFontSize !== undefined) {
labels.fontSize = { value: legend.labelFontSize };
}
if (legend.labelBaseline !== undefined) {
labels.baseline = { value: legend.labelBaseline };
}
labels = util_1.extend(labels, labelsSpec || {});
return util_1.keys(labels).length > 0 ? labels : undefined;
}
properties.labels = labels;
function title(fieldDef, titleSpec, model, channel) {
var legend = model.legend(channel);
var titles = {};
if (legend.titleColor !== undefined) {
titles.stroke = { value: legend.titleColor };
}
if (legend.titleFont !== undefined) {
titles.font = { value: legend.titleFont };
}
if (legend.titleFontSize !== undefined) {
titles.fontSize = { value: legend.titleFontSize };
}
if (legend.titleFontWeight !== undefined) {
titles.fontWeight = { value: legend.titleFontWeight };
}
titles = util_1.extend(titles, titleSpec || {});
return util_1.keys(titles).length > 0 ? titles : undefined;
}
properties.title = title;
})(properties = exports.properties || (exports.properties = {}));
},{"../channel":10,"../fielddef":48,"../mark":51,"../type":59,"../util":60,"./common":12,"./scale":41}],32:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var config_1 = require('../../config');
var fielddef_1 = require('../../fielddef');
var scale_1 = require('../../scale');
var common_1 = require('../common');
var area;
(function (area) {
function markType() {
return 'area';
}
area.markType = markType;
function properties(model) {
var p = {};
var config = model.config();
var orient = config.mark.orient;
p.orient = { value: orient };
var stack = model.stack();
p.x = x(model.encoding().x, model.scaleName(channel_1.X), model.scale(channel_1.X), orient, stack);
p.y = y(model.encoding().y, model.scaleName(channel_1.Y), model.scale(channel_1.Y), orient, stack);
var _x2 = x2(model.encoding().x, model.encoding().x2, model.scaleName(channel_1.X), model.scale(channel_1.X), orient, stack);
if (_x2) {
p.x2 = _x2;
}
var _y2 = y2(model.encoding().y, model.encoding().y2, model.scaleName(channel_1.Y), model.scale(channel_1.Y), orient, stack);
if (_y2) {
p.y2 = _y2;
}
common_1.applyColorAndOpacity(p, model);
common_1.applyMarkConfig(p, model, ['interpolate', 'tension']);
return p;
}
area.properties = properties;
function x(fieldDef, scaleName, scale, orient, stack) {
if (stack && channel_1.X === stack.fieldChannel) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { suffix: 'start' })
};
}
else if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
else if (fieldDef.value) {
return {
scale: scaleName,
value: fieldDef.value
};
}
}
return { value: 0 };
}
area.x = x;
function x2(xFieldDef, x2FieldDef, scaleName, scale, orient, stack) {
if (orient === config_1.Orient.HORIZONTAL) {
if (stack && channel_1.X === stack.fieldChannel) {
return {
scale: scaleName,
field: fielddef_1.field(xFieldDef, { suffix: 'end' })
};
}
else if (x2FieldDef) {
if (x2FieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(x2FieldDef)
};
}
else if (x2FieldDef.value) {
return {
scale: scaleName,
value: x2FieldDef.value
};
}
}
if (scale.type === scale_1.ScaleType.LOG || scale.zero === false) {
return {
value: 0
};
}
return {
scale: scaleName,
value: 0
};
}
return undefined;
}
area.x2 = x2;
function y(fieldDef, scaleName, scale, orient, stack) {
if (stack && channel_1.Y === stack.fieldChannel) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { suffix: 'start' })
};
}
else if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
else if (fieldDef.value) {
return {
scale: scaleName,
value: fieldDef.value
};
}
}
return { value: 0 };
}
area.y = y;
function y2(yFieldDef, y2FieldDef, scaleName, scale, orient, stack) {
if (orient !== config_1.Orient.HORIZONTAL) {
if (stack && channel_1.Y === stack.fieldChannel) {
return {
scale: scaleName,
field: fielddef_1.field(yFieldDef, { suffix: 'end' })
};
}
else if (y2FieldDef) {
if (y2FieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(y2FieldDef)
};
}
else if (y2FieldDef.value) {
return {
scale: scaleName,
value: y2FieldDef.value
};
}
}
if (scale.type === scale_1.ScaleType.LOG || scale.zero === false) {
return {
field: { group: 'height' }
};
}
return {
scale: scaleName,
value: 0
};
}
return undefined;
}
area.y2 = y2;
})(area = exports.area || (exports.area = {}));
},{"../../channel":10,"../../config":43,"../../fielddef":48,"../../scale":52,"../common":12}],33:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var config_1 = require('../../config');
var fielddef_1 = require('../../fielddef');
var scale_1 = require('../../scale');
var common_1 = require('../common');
var bar;
(function (bar) {
function markType() {
return 'rect';
}
bar.markType = markType;
function properties(model) {
var p = {};
var orient = model.config().mark.orient;
var stack = model.stack();
var xFieldDef = model.encoding().x;
var x2FieldDef = model.encoding().x2;
var xIsMeasure = fielddef_1.isMeasure(xFieldDef) || fielddef_1.isMeasure(x2FieldDef);
if (stack && channel_1.X === stack.fieldChannel) {
p.x = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { suffix: 'start' })
};
p.x2 = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { suffix: 'end' })
};
}
else if (xIsMeasure) {
if (orient === config_1.Orient.HORIZONTAL) {
if (model.has(channel_1.X)) {
p.x = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X)
};
}
else {
p.x = {
scale: model.scaleName(channel_1.X),
value: 0
};
}
if (model.has(channel_1.X2)) {
p.x2 = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X2)
};
}
else {
if (model.scale(channel_1.X).type === scale_1.ScaleType.LOG || model.scale(channel_1.X).zero === false) {
p.x2 = { value: 0 };
}
else {
p.x2 = {
scale: model.scaleName(channel_1.X),
value: 0
};
}
}
}
else {
p.xc = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X)
};
p.width = { value: sizeValue(model, channel_1.X) };
}
}
else {
if (model.has(channel_1.X)) {
if (model.encoding().x.bin) {
if (model.has(channel_1.SIZE) && orient !== config_1.Orient.HORIZONTAL) {
p.xc = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { binSuffix: 'mid' })
};
p.width = {
scale: model.scaleName(channel_1.SIZE),
field: model.field(channel_1.SIZE)
};
}
else {
p.x = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { binSuffix: 'start' }),
offset: 1
};
p.x2 = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { binSuffix: 'end' })
};
}
}
else if (model.scale(channel_1.X).bandSize === scale_1.BANDSIZE_FIT) {
p.x = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X),
offset: 0.5
};
}
else {
p.xc = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X)
};
}
}
else {
p.x = { value: 0, offset: 2 };
}
p.width = model.has(channel_1.X) && model.scale(channel_1.X).bandSize === scale_1.BANDSIZE_FIT ? {
scale: model.scaleName(channel_1.X),
band: true,
offset: -0.5
} : model.has(channel_1.SIZE) && orient !== config_1.Orient.HORIZONTAL ? {
scale: model.scaleName(channel_1.SIZE),
field: model.field(channel_1.SIZE)
} : {
value: sizeValue(model, (channel_1.X))
};
}
var yFieldDef = model.encoding().y;
var y2FieldDef = model.encoding().y2;
var yIsMeasure = fielddef_1.isMeasure(yFieldDef) || fielddef_1.isMeasure(y2FieldDef);
if (stack && channel_1.Y === stack.fieldChannel) {
p.y = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { suffix: 'start' })
};
p.y2 = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { suffix: 'end' })
};
}
else if (yIsMeasure) {
if (orient !== config_1.Orient.HORIZONTAL) {
if (model.has(channel_1.Y)) {
p.y = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y)
};
}
else {
p.y = {
scale: model.scaleName(channel_1.Y),
value: 0
};
}
if (model.has(channel_1.Y2)) {
p.y2 = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y2)
};
}
else {
if (model.scale(channel_1.Y).type === scale_1.ScaleType.LOG || model.scale(channel_1.Y).zero === false) {
p.y2 = {
field: { group: 'height' }
};
}
else {
p.y2 = {
scale: model.scaleName(channel_1.Y),
value: 0
};
}
}
}
else {
p.yc = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y)
};
p.height = { value: sizeValue(model, channel_1.Y) };
}
}
else {
if (model.has(channel_1.Y)) {
if (model.encoding().y.bin) {
if (model.has(channel_1.SIZE) && orient === config_1.Orient.HORIZONTAL) {
p.yc = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { binSuffix: 'mid' })
};
p.height = {
scale: model.scaleName(channel_1.SIZE),
field: model.field(channel_1.SIZE)
};
}
else {
p.y = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { binSuffix: 'start' })
};
p.y2 = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { binSuffix: 'end' }),
offset: 1
};
}
}
else if (model.scale(channel_1.Y).bandSize === scale_1.BANDSIZE_FIT) {
p.y = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y),
offset: 0.5
};
}
else {
p.yc = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y)
};
}
}
else {
p.y2 = {
field: { group: 'height' },
offset: -1
};
}
p.height = model.has(channel_1.Y) && model.scale(channel_1.Y).bandSize === scale_1.BANDSIZE_FIT ? {
scale: model.scaleName(channel_1.Y),
band: true,
offset: -0.5
} : model.has(channel_1.SIZE) && orient === config_1.Orient.HORIZONTAL ? {
scale: model.scaleName(channel_1.SIZE),
field: model.field(channel_1.SIZE)
} : {
value: sizeValue(model, channel_1.Y)
};
}
common_1.applyColorAndOpacity(p, model);
return p;
}
bar.properties = properties;
function sizeValue(model, channel) {
var fieldDef = model.encoding().size;
if (fieldDef && fieldDef.value !== undefined) {
return fieldDef.value;
}
var markConfig = model.config().mark;
if (markConfig.barSize) {
return markConfig.barSize;
}
return model.isOrdinalScale(channel) ?
model.scale(channel).bandSize - 1 :
!model.has(channel) ?
model.config().scale.bandSize - 1 :
markConfig.barThinSize;
}
})(bar = exports.bar || (exports.bar = {}));
},{"../../channel":10,"../../config":43,"../../fielddef":48,"../../scale":52,"../common":12}],34:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var fielddef_1 = require('../../fielddef');
var common_1 = require('../common');
var line;
(function (line) {
function markType() {
return 'line';
}
line.markType = markType;
function properties(model) {
var p = {};
var config = model.config();
p.x = x(model.encoding().x, model.scaleName(channel_1.X), config);
p.y = y(model.encoding().y, model.scaleName(channel_1.Y), config);
var _size = size(model.encoding().size, config);
if (_size) {
p.strokeWidth = _size;
}
common_1.applyColorAndOpacity(p, model);
common_1.applyMarkConfig(p, model, ['interpolate', 'tension']);
return p;
}
line.properties = properties;
function x(fieldDef, scaleName, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
}
return { value: 0 };
}
function y(fieldDef, scaleName, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
}
return { field: { group: 'height' } };
}
function size(fieldDef, config) {
if (fieldDef && fieldDef.value !== undefined) {
return { value: fieldDef.value };
}
return { value: config.mark.lineSize };
}
})(line = exports.line || (exports.line = {}));
},{"../../channel":10,"../../fielddef":48,"../common":12}],35:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var config_1 = require('../../config');
var encoding_1 = require('../../encoding');
var fielddef_1 = require('../../fielddef');
var mark_1 = require('../../mark');
var scale_1 = require('../../scale');
var sort_1 = require('../../sort');
var util_1 = require('../../util');
var area_1 = require('./area');
var bar_1 = require('./bar');
var common_1 = require('../common');
var line_1 = require('./line');
var point_1 = require('./point');
var rule_1 = require('./rule');
var text_1 = require('./text');
var tick_1 = require('./tick');
var markCompiler = {
area: area_1.area,
bar: bar_1.bar,
line: line_1.line,
point: point_1.point,
text: text_1.text,
tick: tick_1.tick,
rule: rule_1.rule,
circle: point_1.circle,
square: point_1.square
};
function parseMark(model) {
if (util_1.contains([mark_1.LINE, mark_1.AREA], model.mark())) {
return parsePathMark(model);
}
else {
return parseNonPathMark(model);
}
}
exports.parseMark = parseMark;
function parsePathMark(model) {
var mark = model.mark();
var isFaceted = model.parent() && model.parent().isFacet();
var dataFrom = { data: model.dataTable() };
var details = detailFields(model);
var pathMarks = [
{
name: model.name('marks'),
type: markCompiler[mark].markType(),
from: util_1.extend(isFaceted || details.length > 0 ? {} : dataFrom, { transform: [{ type: 'sort', by: sortPathBy(model) }] }),
properties: { update: markCompiler[mark].properties(model) }
}
];
if (details.length > 0) {
var facetTransform = { type: 'facet', groupby: details };
var transform = mark === mark_1.AREA && model.stack() ?
stackTransforms(model, true).concat(facetTransform) :
[].concat(facetTransform, model.has(channel_1.ORDER) ? [{ type: 'sort', by: sortBy(model) }] : []);
return [{
name: model.name('pathgroup'),
type: 'group',
from: util_1.extend(isFaceted ? {} : dataFrom, { transform: transform }),
properties: {
update: {
width: { field: { group: 'width' } },
height: { field: { group: 'height' } }
}
},
marks: pathMarks
}];
}
else {
return pathMarks;
}
}
function parseNonPathMark(model) {
var mark = model.mark();
var isFaceted = model.parent() && model.parent().isFacet();
var dataFrom = { data: model.dataTable() };
var marks = [];
if (mark === mark_1.TEXT &&
model.has(channel_1.COLOR) &&
model.config().mark.applyColorToBackground && !model.has(channel_1.X) && !model.has(channel_1.Y)) {
marks.push(util_1.extend({
name: model.name('background'),
type: 'rect'
}, isFaceted ? {} : { from: dataFrom }, { properties: { update: text_1.text.background(model) } }));
}
marks.push(util_1.extend({
name: model.name('marks'),
type: markCompiler[mark].markType()
}, (!isFaceted || model.stack() || model.has(channel_1.ORDER)) ? {
from: util_1.extend(isFaceted ? {} : dataFrom, model.stack() ?
{ transform: stackTransforms(model, false) } :
model.has(channel_1.ORDER) ?
{ transform: [{ type: 'sort', by: sortBy(model) }] } :
{})
} : {}, { properties: { update: markCompiler[mark].properties(model) } }));
return marks;
}
function sortBy(model) {
if (model.has(channel_1.ORDER)) {
var channelDef = model.encoding().order;
if (channelDef instanceof Array) {
return channelDef.map(common_1.sortField);
}
else {
return common_1.sortField(channelDef);
}
}
return null;
}
function sortPathBy(model) {
if (model.mark() === mark_1.LINE && model.has(channel_1.PATH)) {
var channelDef = model.encoding().path;
if (channelDef instanceof Array) {
return channelDef.map(common_1.sortField);
}
else {
return common_1.sortField(channelDef);
}
}
else {
var dimensionChannel = model.config().mark.orient === config_1.Orient.HORIZONTAL ? channel_1.Y : channel_1.X;
var sort = model.sort(dimensionChannel);
if (sort_1.isSortField(sort)) {
return '-' + fielddef_1.field({
aggregate: encoding_1.isAggregate(model.encoding()) ? sort.op : undefined,
field: sort.field
});
}
else {
return '-' + model.field(dimensionChannel, { binSuffix: 'mid' });
}
}
}
function detailFields(model) {
return [channel_1.COLOR, channel_1.DETAIL, channel_1.OPACITY, channel_1.SHAPE].reduce(function (details, channel) {
if (model.has(channel) && !model.fieldDef(channel).aggregate) {
details.push(model.field(channel));
}
return details;
}, []);
}
function stackTransforms(model, impute) {
var stackByFields = getStackByFields(model);
if (impute) {
return [imputeTransform(model, stackByFields), stackTransform(model, stackByFields)];
}
return [stackTransform(model, stackByFields)];
}
function getStackByFields(model) {
var encoding = model.encoding();
return channel_1.STACK_GROUP_CHANNELS.reduce(function (fields, channel) {
var channelEncoding = encoding[channel];
if (encoding_1.has(encoding, channel)) {
if (util_1.isArray(channelEncoding)) {
channelEncoding.forEach(function (fieldDef) {
fields.push(fielddef_1.field(fieldDef));
});
}
else {
var fieldDef = channelEncoding;
var scale = model.scale(channel);
var _field = fielddef_1.field(fieldDef, {
binSuffix: scale && scale.type === scale_1.ScaleType.ORDINAL ? 'range' : 'start'
});
if (!!_field) {
fields.push(_field);
}
}
}
return fields;
}, []);
}
function imputeTransform(model, stackFields) {
var stack = model.stack();
return {
type: 'impute',
field: model.field(stack.fieldChannel),
groupby: stackFields,
orderby: [model.field(stack.groupbyChannel, { binSuffix: 'mid' })],
method: 'value',
value: 0
};
}
function stackTransform(model, stackFields) {
var stack = model.stack();
var encoding = model.encoding();
var sortby = model.has(channel_1.ORDER) ?
(util_1.isArray(encoding[channel_1.ORDER]) ? encoding[channel_1.ORDER] : [encoding[channel_1.ORDER]]).map(common_1.sortField) :
stackFields.map(function (field) {
return '-' + field;
});
var valName = model.field(stack.fieldChannel);
var transform = {
type: 'stack',
groupby: [model.field(stack.groupbyChannel, { binSuffix: 'mid' }) || 'undefined'],
field: model.field(stack.fieldChannel),
sortby: sortby,
output: {
start: valName + '_start',
end: valName + '_end'
}
};
if (stack.offset) {
transform.offset = stack.offset;
}
return transform;
}
},{"../../channel":10,"../../config":43,"../../encoding":46,"../../fielddef":48,"../../mark":51,"../../scale":52,"../../sort":54,"../../util":60,"../common":12,"./area":32,"./bar":33,"./line":34,"./point":36,"./rule":37,"./text":38,"./tick":39}],36:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var fielddef_1 = require('../../fielddef');
var common_1 = require('../common');
var point;
(function (point) {
function markType() {
return 'symbol';
}
point.markType = markType;
function properties(model, fixedShape) {
var p = {};
var config = model.config();
p.x = x(model.encoding().x, model.scaleName(channel_1.X), config);
p.y = y(model.encoding().y, model.scaleName(channel_1.Y), config);
p.size = size(model.encoding().size, model.scaleName(channel_1.SIZE), model.scale(channel_1.SIZE), config);
p.shape = shape(model.encoding().shape, model.scaleName(channel_1.SHAPE), model.scale(channel_1.SHAPE), config, fixedShape);
common_1.applyColorAndOpacity(p, model);
return p;
}
point.properties = properties;
function x(fieldDef, scaleName, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
}
return { value: config.scale.bandSize / 2 };
}
function y(fieldDef, scaleName, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
}
return { value: config.scale.bandSize / 2 };
}
function size(fieldDef, scaleName, scale, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { scaleType: scale.type })
};
}
else if (fieldDef.value !== undefined) {
return { value: fieldDef.value };
}
}
return { value: config.mark.size };
}
function shape(fieldDef, scaleName, scale, config, fixedShape) {
if (fixedShape) {
return { value: fixedShape };
}
else if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { scaleType: scale.type })
};
}
else if (fieldDef.value) {
return { value: fieldDef.value };
}
}
return { value: config.mark.shape };
}
})(point = exports.point || (exports.point = {}));
var circle;
(function (circle) {
function markType() {
return 'symbol';
}
circle.markType = markType;
function properties(model) {
return point.properties(model, 'circle');
}
circle.properties = properties;
})(circle = exports.circle || (exports.circle = {}));
var square;
(function (square) {
function markType() {
return 'symbol';
}
square.markType = markType;
function properties(model) {
return point.properties(model, 'square');
}
square.properties = properties;
})(square = exports.square || (exports.square = {}));
},{"../../channel":10,"../../fielddef":48,"../common":12}],37:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var config_1 = require('../../config');
var common_1 = require('../common');
var rule;
(function (rule) {
function markType() {
return 'rule';
}
rule.markType = markType;
function properties(model) {
var p = {};
if (model.config().mark.orient === config_1.Orient.VERTICAL) {
if (model.has(channel_1.X)) {
p.x = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { binSuffix: 'mid' })
};
}
else {
p.x = { value: 0 };
}
if (model.has(channel_1.Y)) {
p.y = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { binSuffix: 'mid' })
};
}
else {
p.y = { field: { group: 'height' } };
}
if (model.has(channel_1.Y2)) {
p.y2 = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y2, { binSuffix: 'mid' })
};
}
else {
p.y2 = { value: 0 };
}
}
else {
if (model.has(channel_1.Y)) {
p.y = {
scale: model.scaleName(channel_1.Y),
field: model.field(channel_1.Y, { binSuffix: 'mid' })
};
}
else {
p.y = { value: 0 };
}
if (model.has(channel_1.X)) {
p.x = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X, { binSuffix: 'mid' })
};
}
else {
p.x = { value: 0 };
}
if (model.has(channel_1.X2)) {
p.x2 = {
scale: model.scaleName(channel_1.X),
field: model.field(channel_1.X2, { binSuffix: 'mid' })
};
}
else {
p.x2 = { field: { group: 'width' } };
}
}
common_1.applyColorAndOpacity(p, model);
if (model.has(channel_1.SIZE)) {
p.strokeWidth = {
scale: model.scaleName(channel_1.SIZE),
field: model.field(channel_1.SIZE)
};
}
else {
p.strokeWidth = { value: sizeValue(model) };
}
return p;
}
rule.properties = properties;
function sizeValue(model) {
var fieldDef = model.encoding().size;
if (fieldDef && fieldDef.value !== undefined) {
return fieldDef.value;
}
return model.config().mark.ruleSize;
}
})(rule = exports.rule || (exports.rule = {}));
},{"../../channel":10,"../../config":43,"../common":12}],38:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var common_1 = require('../common');
var fielddef_1 = require('../../fielddef');
var type_1 = require('../../type');
var text;
(function (text_1) {
function markType() {
return 'text';
}
text_1.markType = markType;
function background(model) {
return {
x: { value: 0 },
y: { value: 0 },
width: { field: { group: 'width' } },
height: { field: { group: 'height' } },
fill: {
scale: model.scaleName(channel_1.COLOR),
field: model.field(channel_1.COLOR, model.encoding().color.type === type_1.ORDINAL ? { prefix: 'rank' } : {})
}
};
}
text_1.background = background;
function properties(model) {
var p = {};
common_1.applyMarkConfig(p, model, ['angle', 'align', 'baseline', 'dx', 'dy', 'font', 'fontWeight',
'fontStyle', 'radius', 'theta', 'text']);
var config = model.config();
var textFieldDef = model.encoding().text;
p.x = x(model.encoding().x, model.scaleName(channel_1.X), config, textFieldDef);
p.y = y(model.encoding().y, model.scaleName(channel_1.Y), config);
p.fontSize = size(model.encoding().size, model.scaleName(channel_1.SIZE), config);
p.text = text(textFieldDef, model.scaleName(channel_1.TEXT), config);
if (model.config().mark.applyColorToBackground && !model.has(channel_1.X) && !model.has(channel_1.Y)) {
p.fill = { value: 'black' };
var opacity = model.config().mark.opacity;
if (opacity) {
p.opacity = { value: opacity };
}
;
}
else {
common_1.applyColorAndOpacity(p, model);
}
return p;
}
text_1.properties = properties;
function x(xFieldDef, scaleName, config, textFieldDef) {
if (xFieldDef) {
if (xFieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(xFieldDef, { binSuffix: 'mid' })
};
}
}
if (textFieldDef && textFieldDef.type === type_1.QUANTITATIVE) {
return { field: { group: 'width' }, offset: -5 };
}
else {
return { value: config.scale.textBandWidth / 2 };
}
}
function y(yFieldDef, scaleName, config) {
if (yFieldDef) {
if (yFieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(yFieldDef, { binSuffix: 'mid' })
};
}
}
return { value: config.scale.bandSize / 2 };
}
function size(sizeFieldDef, scaleName, config) {
if (sizeFieldDef) {
if (sizeFieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(sizeFieldDef)
};
}
if (sizeFieldDef.value) {
return { value: sizeFieldDef.value };
}
}
return { value: config.mark.fontSize };
}
function text(textFieldDef, scaleName, config) {
if (textFieldDef) {
if (textFieldDef.field) {
if (type_1.QUANTITATIVE === textFieldDef.type) {
var format = common_1.numberFormat(textFieldDef, config.mark.format, config);
var filter = 'number' + (format ? ':\'' + format + '\'' : '');
return {
template: '{{' + fielddef_1.field(textFieldDef, { datum: true }) + ' | ' + filter + '}}'
};
}
else if (type_1.TEMPORAL === textFieldDef.type) {
return {
template: common_1.timeTemplate(fielddef_1.field(textFieldDef, { datum: true }), textFieldDef.timeUnit, config.mark.format, config.mark.shortTimeLabels, config)
};
}
else {
return { field: textFieldDef.field };
}
}
else if (textFieldDef.value) {
return { value: textFieldDef.value };
}
}
return { value: config.mark.text };
}
})(text = exports.text || (exports.text = {}));
},{"../../channel":10,"../../fielddef":48,"../../type":59,"../common":12}],39:[function(require,module,exports){
"use strict";
var channel_1 = require('../../channel');
var config_1 = require('../../config');
var fielddef_1 = require('../../fielddef');
var common_1 = require('../common');
var tick;
(function (tick) {
function markType() {
return 'rect';
}
tick.markType = markType;
function properties(model) {
var p = {};
var config = model.config();
p.xc = x(model.encoding().x, model.scaleName(channel_1.X), config);
p.yc = y(model.encoding().y, model.scaleName(channel_1.Y), config);
if (config.mark.orient === config_1.Orient.HORIZONTAL) {
p.width = size(model.encoding().size, model.scaleName(channel_1.SIZE), config, (model.scale(channel_1.X) || {}).bandSize);
p.height = { value: config.mark.tickThickness };
}
else {
p.width = { value: config.mark.tickThickness };
p.height = size(model.encoding().size, model.scaleName(channel_1.SIZE), config, (model.scale(channel_1.Y) || {}).bandSize);
}
common_1.applyColorAndOpacity(p, model);
return p;
}
tick.properties = properties;
function x(fieldDef, scaleName, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
else if (fieldDef.value) {
return { value: fieldDef.value };
}
}
return { value: config.scale.bandSize / 2 };
}
function y(fieldDef, scaleName, config) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fielddef_1.field(fieldDef, { binSuffix: 'mid' })
};
}
else if (fieldDef.value) {
return { value: fieldDef.value };
}
}
return { value: config.scale.bandSize / 2 };
}
function size(fieldDef, scaleName, config, scaleBandSize) {
if (fieldDef) {
if (fieldDef.field) {
return {
scale: scaleName,
field: fieldDef.field
};
}
else if (fieldDef.value !== undefined) {
return { value: fieldDef.value };
}
}
if (config.mark.tickSize) {
return { value: config.mark.tickSize };
}
var bandSize = scaleBandSize !== undefined ?
scaleBandSize :
config.scale.bandSize;
return { value: bandSize / 1.5 };
}
})(tick = exports.tick || (exports.tick = {}));
},{"../../channel":10,"../../config":43,"../../fielddef":48,"../common":12}],40:[function(require,module,exports){
"use strict";
var channel_1 = require('../channel');
var encoding_1 = require('../encoding');
var fielddef_1 = require('../fielddef');
var scale_1 = require('../scale');
var util_1 = require('../util');
var NameMap = (function () {
function NameMap() {
this._nameMap = {};
}
NameMap.prototype.rename = function (oldName, newName) {
this._nameMap[oldName] = newName;
};
NameMap.prototype.get = function (name) {
while (this._nameMap[name]) {
name = this._nameMap[name];
}
return name;
};
return NameMap;
}());
var Model = (function () {
function Model(spec, parent, parentGivenName) {
this._warnings = [];
this._parent = parent;
this._name = spec.name || parentGivenName;
this._dataNameMap = parent ? parent._dataNameMap : new NameMap();
this._scaleNameMap = parent ? parent._scaleNameMap : new NameMap();
this._sizeNameMap = parent ? parent._sizeNameMap : new NameMap();
this._data = spec.data;
this._description = spec.description;
this._transform = spec.transform;
this.component = { data: null, layout: null, mark: null, scale: null, axis: null, axisGroup: null, gridGroup: null, legend: null };
}
Model.prototype.parse = function () {
this.parseData();
this.parseSelectionData();
this.parseLayoutData();
this.parseScale();
this.parseAxis();
this.parseLegend();
this.parseAxisGroup();
this.parseGridGroup();
this.parseMark();
};
Model.prototype.assembleScales = function () {
return util_1.flatten(util_1.vals(this.component.scale).map(function (scales) {
var arr = [scales.main];
if (scales.colorLegend) {
arr.push(scales.colorLegend);
}
if (scales.binColorLegend) {
arr.push(scales.binColorLegend);
}
return arr;
}));
};
Model.prototype.assembleAxes = function () {
return util_1.vals(this.component.axis);
};
Model.prototype.assembleLegends = function () {
return util_1.vals(this.component.legend);
};
Model.prototype.assembleGroup = function () {
var group = {};
group.marks = this.assembleMarks();
var scales = this.assembleScales();
if (scales.length > 0) {
group.scales = scales;
}
var axes = this.assembleAxes();
if (axes.length > 0) {
group.axes = axes;
}
var legends = this.assembleLegends();
if (legends.length > 0) {
group.legends = legends;
}
return group;
};
Model.prototype.reduce = function (f, init, t) {
return encoding_1.channelMappingReduce(this.channels(), this.mapping(), f, init, t);
};
Model.prototype.forEach = function (f, t) {
encoding_1.channelMappingForEach(this.channels(), this.mapping(), f, t);
};
Model.prototype.parent = function () {
return this._parent;
};
Model.prototype.name = function (text, delimiter) {
if (delimiter === void 0) { delimiter = '_'; }
return (this._name ? this._name + delimiter : '') + text;
};
Model.prototype.description = function () {
return this._description;
};
Model.prototype.data = function () {
return this._data;
};
Model.prototype.renameData = function (oldName, newName) {
this._dataNameMap.rename(oldName, newName);
};
Model.prototype.dataName = function (dataSourceType) {
return this._dataNameMap.get(this.name(String(dataSourceType)));
};
Model.prototype.renameSize = function (oldName, newName) {
this._sizeNameMap.rename(oldName, newName);
};
Model.prototype.channelSizeName = function (channel) {
return this.sizeName(channel === channel_1.X || channel === channel_1.COLUMN ? 'width' : 'height');
};
Model.prototype.sizeName = function (size) {
return this._sizeNameMap.get(this.name(size, '_'));
};
Model.prototype.transform = function () {
return this._transform || {};
};
Model.prototype.field = function (channel, opt) {
if (opt === void 0) { opt = {}; }
var fieldDef = this.fieldDef(channel);
if (fieldDef.bin) {
opt = util_1.extend({
binSuffix: this.scale(channel).type === scale_1.ScaleType.ORDINAL ? 'range' : 'start'
}, opt);
}
return fielddef_1.field(fieldDef, opt);
};
Model.prototype.scale = function (channel) {
return this._scale[channel];
};
Model.prototype.isOrdinalScale = function (channel) {
var scale = this.scale(channel);
return scale && scale.type === scale_1.ScaleType.ORDINAL;
};
Model.prototype.renameScale = function (oldName, newName) {
this._scaleNameMap.rename(oldName, newName);
};
Model.prototype.scaleName = function (channel) {
return this._scaleNameMap.get(this.name(channel + ''));
};
Model.prototype.sort = function (channel) {
return (this.mapping()[channel] || {}).sort;
};
Model.prototype.axis = function (channel) {
return this._axis[channel];
};
Model.prototype.legend = function (channel) {
return this._legend[channel];
};
Model.prototype.config = function () {
return this._config;
};
Model.prototype.addWarning = function (message) {
util_1.warning(message);
this._warnings.push(message);
};
Model.prototype.warnings = function () {
return this._warnings;
};
Model.prototype.isUnit = function () {
return false;
};
Model.prototype.isFacet = function () {
return false;
};
Model.prototype.isLayer = function () {
return false;
};
return Model;
}());
exports.Model = Model;
},{"../channel":10,"../encoding":46,"../fielddef":48,"../scale":52,"../util":60}],41:[function(require,module,exports){
"use strict";
var aggregate_1 = require('../aggregate');
var channel_1 = require('../channel');
var config_1 = require('../config');
var data_1 = require('../data');
var fielddef_1 = require('../fielddef');
var mark_1 = require('../mark');
var scale_1 = require('../scale');
var sort_1 = require('../sort');
var stack_1 = require('../stack');
var type_1 = require('../type');
var util_1 = require('../util');
var timeunit_1 = require('../timeunit');
exports.COLOR_LEGEND = 'color_legend';
exports.COLOR_LEGEND_LABEL = 'color_legend_label';
function parseScaleComponent(model) {
return model.channels().reduce(function (scale, channel) {
if (model.scale(channel)) {
var fieldDef = model.fieldDef(channel);
var scales = {
main: parseMainScale(model, fieldDef, channel)
};
if (channel === channel_1.COLOR && model.legend(channel_1.COLOR) && (fieldDef.type === type_1.ORDINAL || fieldDef.bin || fieldDef.timeUnit)) {
scales.colorLegend = parseColorLegendScale(model, fieldDef);
if (fieldDef.bin) {
scales.binColorLegend = parseBinColorLegendLabel(model, fieldDef);
}
}
scale[channel] = scales;
}
return scale;
}, {});
}
exports.parseScaleComponent = parseScaleComponent;
function parseMainScale(model, fieldDef, channel) {
var scale = model.scale(channel);
var sort = model.sort(channel);
var scaleDef = {
name: model.scaleName(channel),
type: scale.type,
};
if (channel === channel_1.X && model.has(channel_1.X2)) {
if (model.has(channel_1.X)) {
scaleDef.domain = { fields: [domain(scale, model, channel_1.X), domain(scale, model, channel_1.X2)] };
}
else {
scaleDef.domain = domain(scale, model, channel_1.X2);
}
}
else if (channel === channel_1.Y && model.has(channel_1.Y2)) {
if (model.has(channel_1.Y)) {
scaleDef.domain = { fields: [domain(scale, model, channel_1.Y), domain(scale, model, channel_1.Y2)] };
}
else {
scaleDef.domain = domain(scale, model, channel_1.Y2);
}
}
else {
scaleDef.domain = domain(scale, model, channel);
}
util_1.extend(scaleDef, rangeMixins(scale, model, channel));
if (sort && (sort_1.isSortField(sort) ? sort.order : sort) === sort_1.SortOrder.DESCENDING) {
scaleDef.reverse = true;
}
[
'round',
'clamp', 'nice',
'exponent', 'zero',
'points',
'padding'
].forEach(function (property) {
var value = exports[property](scale, channel, fieldDef, model, scaleDef);
if (value !== undefined) {
scaleDef[property] = value;
}
});
return scaleDef;
}
function parseColorLegendScale(model, fieldDef) {
return {
name: model.scaleName(exports.COLOR_LEGEND),
type: scale_1.ScaleType.ORDINAL,
domain: {
data: model.dataTable(),
field: model.field(channel_1.COLOR, (fieldDef.bin || fieldDef.timeUnit) ? {} : { prefix: 'rank' }),
sort: true
},
range: { data: model.dataTable(), field: model.field(channel_1.COLOR), sort: true }
};
}
function parseBinColorLegendLabel(model, fieldDef) {
return {
name: model.scaleName(exports.COLOR_LEGEND_LABEL),
type: scale_1.ScaleType.ORDINAL,
domain: {
data: model.dataTable(),
field: model.field(channel_1.COLOR),
sort: true
},
range: {
data: model.dataTable(),
field: fielddef_1.field(fieldDef, { binSuffix: 'range' }),
sort: {
field: model.field(channel_1.COLOR, { binSuffix: 'start' }),
op: 'min'
}
}
};
}
function scaleType(scale, fieldDef, channel, mark) {
if (!channel_1.hasScale(channel)) {
return null;
}
if (util_1.contains([channel_1.ROW, channel_1.COLUMN, channel_1.SHAPE], channel)) {
if (scale && scale.type !== undefined && scale.type !== scale_1.ScaleType.ORDINAL) {
console.warn('Channel', channel, 'does not work with scale type =', scale.type);
}
return scale_1.ScaleType.ORDINAL;
}
if (scale.type !== undefined) {
return scale.type;
}
switch (fieldDef.type) {
case type_1.NOMINAL:
return scale_1.ScaleType.ORDINAL;
case type_1.ORDINAL:
if (channel === channel_1.COLOR) {
return scale_1.ScaleType.LINEAR;
}
return scale_1.ScaleType.ORDINAL;
case type_1.TEMPORAL:
if (channel === channel_1.COLOR) {
return scale_1.ScaleType.TIME;
}
if (fieldDef.timeUnit) {
return timeunit_1.defaultScaleType(fieldDef.timeUnit);
}
return scale_1.ScaleType.TIME;
case type_1.QUANTITATIVE:
if (fieldDef.bin) {
return util_1.contains([channel_1.X, channel_1.Y, channel_1.COLOR], channel) ? scale_1.ScaleType.LINEAR : scale_1.ScaleType.ORDINAL;
}
return scale_1.ScaleType.LINEAR;
}
return null;
}
exports.scaleType = scaleType;
function scaleBandSize(scaleType, bandSize, scaleConfig, topLevelSize, mark, channel) {
if (scaleType === scale_1.ScaleType.ORDINAL) {
if (topLevelSize === undefined) {
if (bandSize) {
return bandSize;
}
else if (channel === channel_1.X && mark === mark_1.TEXT) {
return scaleConfig.textBandWidth;
}
else {
return scaleConfig.bandSize;
}
}
else {
if (bandSize) {
console.warn('bandSize for', channel, 'overridden as top-level', channel === channel_1.X ? 'width' : 'height', 'is provided.');
}
return scale_1.BANDSIZE_FIT;
}
}
else {
return undefined;
}
}
exports.scaleBandSize = scaleBandSize;
function domain(scale, model, channel) {
var fieldDef = model.fieldDef(channel);
if (scale.domain) {
return scale.domain;
}
if (fieldDef.type === type_1.TEMPORAL) {
if (timeunit_1.rawDomain(fieldDef.timeUnit, channel)) {
return {
data: fieldDef.timeUnit,
field: 'date'
};
}
return {
data: model.dataTable(),
field: model.field(channel),
sort: {
field: model.field(channel),
op: 'min'
}
};
}
var stack = model.stack();
if (stack && channel === stack.fieldChannel) {
if (stack.offset === stack_1.StackOffset.NORMALIZE) {
return [0, 1];
}
return {
data: model.dataName(data_1.STACKED_SCALE),
field: model.field(channel, { prefix: 'sum' })
};
}
var useRawDomain = _useRawDomain(scale, model, channel), sort = domainSort(model, channel, scale.type);
if (useRawDomain) {
return {
data: data_1.SOURCE,
field: model.field(channel, { noAggregate: true })
};
}
else if (fieldDef.bin) {
if (scale.type === scale_1.ScaleType.ORDINAL) {
return {
data: model.dataTable(),
field: model.field(channel, { binSuffix: 'range' }),
sort: {
field: model.field(channel, { binSuffix: 'start' }),
op: 'min'
}
};
}
else if (channel === channel_1.COLOR) {
return {
data: model.dataTable(),
field: model.field(channel, { binSuffix: 'start' })
};
}
else {
return {
data: model.dataTable(),
field: [
model.field(channel, { binSuffix: 'start' }),
model.field(channel, { binSuffix: 'end' })
]
};
}
}
else if (sort) {
return {
data: sort.op ? data_1.SOURCE : model.dataTable(),
field: (fieldDef.type === type_1.ORDINAL && channel === channel_1.COLOR) ? model.field(channel, { prefix: 'rank' }) : model.field(channel),
sort: sort
};
}
else {
return {
data: model.dataTable(),
field: (fieldDef.type === type_1.ORDINAL && channel === channel_1.COLOR) ? model.field(channel, { prefix: 'rank' }) : model.field(channel),
};
}
}
exports.domain = domain;
function domainSort(model, channel, scaleType) {
if (scaleType !== scale_1.ScaleType.ORDINAL) {
return undefined;
}
var sort = model.sort(channel);
if (sort_1.isSortField(sort)) {
return {
op: sort.op,
field: sort.field
};
}
if (util_1.contains([sort_1.SortOrder.ASCENDING, sort_1.SortOrder.DESCENDING, undefined], sort)) {
return true;
}
return undefined;
}
exports.domainSort = domainSort;
function _useRawDomain(scale, model, channel) {
var fieldDef = model.fieldDef(channel);
return scale.useRawDomain &&
fieldDef.aggregate &&
aggregate_1.SHARED_DOMAIN_OPS.indexOf(fieldDef.aggregate) >= 0 &&
((fieldDef.type === type_1.QUANTITATIVE && !fieldDef.bin) ||
(fieldDef.type === type_1.TEMPORAL && util_1.contains([scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.type)));
}
function rangeMixins(scale, model, channel) {
var fieldDef = model.fieldDef(channel);
var scaleConfig = model.config().scale;
if (scale.type === scale_1.ScaleType.ORDINAL && scale.bandSize && scale.bandSize !== scale_1.BANDSIZE_FIT && util_1.contains([channel_1.X, channel_1.Y], channel)) {
return { bandSize: scale.bandSize };
}
if (scale.range && !util_1.contains([channel_1.X, channel_1.Y, channel_1.ROW, channel_1.COLUMN], channel)) {
return { range: scale.range };
}
switch (channel) {
case channel_1.ROW:
return { range: 'height' };
case channel_1.COLUMN:
return { range: 'width' };
}
var unitModel = model;
switch (channel) {
case channel_1.X:
return {
rangeMin: 0,
rangeMax: unitModel.width
};
case channel_1.Y:
return {
rangeMin: unitModel.height,
rangeMax: 0
};
case channel_1.SIZE:
if (unitModel.mark() === mark_1.BAR) {
if (scaleConfig.barSizeRange !== undefined) {
return { range: scaleConfig.barSizeRange };
}
var dimension = model.config().mark.orient === config_1.Orient.HORIZONTAL ? channel_1.Y : channel_1.X;
return { range: [model.config().mark.barThinSize, model.scale(dimension).bandSize] };
}
else if (unitModel.mark() === mark_1.TEXT) {
return { range: scaleConfig.fontSizeRange };
}
else if (unitModel.mark() === mark_1.RULE) {
return { range: scaleConfig.ruleSizeRange };
}
else if (unitModel.mark() === mark_1.TICK) {
return { range: scaleConfig.tickSizeRange };
}
if (scaleConfig.pointSizeRange !== undefined) {
return { range: scaleConfig.pointSizeRange };
}
var bandSize = pointBandSize(unitModel);
return { range: [9, (bandSize - 2) * (bandSize - 2)] };
case channel_1.SHAPE:
return { range: scaleConfig.shapeRange };
case channel_1.COLOR:
if (fieldDef.type === type_1.NOMINAL) {
return { range: scaleConfig.nominalColorRange };
}
return { range: scaleConfig.sequentialColorRange };
case channel_1.OPACITY:
return { range: scaleConfig.opacity };
}
return {};
}
exports.rangeMixins = rangeMixins;
function pointBandSize(model) {
var scaleConfig = model.config().scale;
var hasX = model.has(channel_1.X);
var hasY = model.has(channel_1.Y);
var xIsMeasure = fielddef_1.isMeasure(model.encoding().x);
var yIsMeasure = fielddef_1.isMeasure(model.encoding().y);
if (hasX && hasY) {
return xIsMeasure !== yIsMeasure ?
model.scale(xIsMeasure ? channel_1.Y : channel_1.X).bandSize :
Math.min(model.scale(channel_1.X).bandSize || scaleConfig.bandSize, model.scale(channel_1.Y).bandSize || scaleConfig.bandSize);
}
else if (hasY) {
return yIsMeasure ? model.config().scale.bandSize : model.scale(channel_1.Y).bandSize;
}
else if (hasX) {
return xIsMeasure ? model.config().scale.bandSize : model.scale(channel_1.X).bandSize;
}
return model.config().scale.bandSize;
}
function clamp(scale) {
if (util_1.contains([scale_1.ScaleType.LINEAR, scale_1.ScaleType.POW, scale_1.ScaleType.SQRT,
scale_1.ScaleType.LOG, scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.type)) {
return scale.clamp;
}
return undefined;
}
exports.clamp = clamp;
function exponent(scale) {
if (scale.type === scale_1.ScaleType.POW) {
return scale.exponent;
}
return undefined;
}
exports.exponent = exponent;
function nice(scale, channel, fieldDef) {
if (util_1.contains([scale_1.ScaleType.LINEAR, scale_1.ScaleType.POW, scale_1.ScaleType.SQRT, scale_1.ScaleType.LOG,
scale_1.ScaleType.TIME, scale_1.ScaleType.UTC, scale_1.ScaleType.QUANTIZE], scale.type)) {
if (scale.nice !== undefined) {
return scale.nice;
}
if (util_1.contains([scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.type)) {
return timeunit_1.smallestUnit(fieldDef.timeUnit);
}
return util_1.contains([channel_1.X, channel_1.Y], channel);
}
return undefined;
}
exports.nice = nice;
function padding(scale, channel, __, ___, scaleDef) {
if (scale.type === scale_1.ScaleType.ORDINAL && util_1.contains([channel_1.X, channel_1.Y], channel)) {
return scaleDef.points ? 1 : scale.padding;
}
return undefined;
}
exports.padding = padding;
function points(scale, channel, __, model) {
if (scale.type === scale_1.ScaleType.ORDINAL && util_1.contains([channel_1.X, channel_1.Y], channel)) {
return model.mark() === mark_1.BAR && scale.bandSize === scale_1.BANDSIZE_FIT ? undefined : true;
}
return undefined;
}
exports.points = points;
function round(scale, channel) {
if (util_1.contains([channel_1.X, channel_1.Y, channel_1.ROW, channel_1.COLUMN, channel_1.SIZE], channel) && scale.round !== undefined) {
return scale.round;
}
return undefined;
}
exports.round = round;
function zero(scale, channel, fieldDef) {
if (!util_1.contains([scale_1.ScaleType.TIME, scale_1.ScaleType.UTC, scale_1.ScaleType.ORDINAL], scale.type)) {
if (scale.zero !== undefined) {
return scale.zero;
}
return !scale.domain && !fieldDef.bin && util_1.contains([channel_1.X, channel_1.Y], channel);
}
return undefined;
}
exports.zero = zero;
},{"../aggregate":7,"../channel":10,"../config":43,"../data":44,"../fielddef":48,"../mark":51,"../scale":52,"../sort":54,"../stack":56,"../timeunit":57,"../type":59,"../util":60}],42:[function(require,module,exports){
"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 aggregate_1 = require('../aggregate');
var channel_1 = require('../channel');
var config_1 = require('../config');
var data_1 = require('../data');
var vlEncoding = require('../encoding');
var fielddef_1 = require('../fielddef');
var mark_1 = require('../mark');
var scale_1 = require('../scale');
var type_1 = require('../type');
var util_1 = require('../util');
var axis_1 = require('./axis');
var common_1 = require('./common');
var config_2 = require('./config');
var data_2 = require('./data/data');
var legend_1 = require('./legend');
var layout_1 = require('./layout');
var model_1 = require('./model');
var mark_2 = require('./mark/mark');
var scale_2 = require('./scale');
var stack_1 = require('../stack');
var UnitModel = (function (_super) {
__extends(UnitModel, _super);
function UnitModel(spec, parent, parentGivenName) {
_super.call(this, spec, parent, parentGivenName);
var providedWidth = spec.width !== undefined ? spec.width :
parent ? parent['width'] : undefined;
var providedHeight = spec.height !== undefined ? spec.height :
parent ? parent['height'] : undefined;
var mark = this._mark = spec.mark;
var encoding = this._encoding = this._initEncoding(mark, spec.encoding || {});
var config = this._config = this._initConfig(spec.config, parent, mark, encoding);
this._scale = this._initScale(mark, encoding, config, providedWidth, providedHeight);
this._axis = this._initAxis(encoding, config);
this._legend = this._initLegend(encoding, config);
this._initSize(mark, this._scale, providedWidth, providedHeight, config.cell, config.scale);
this._stack = stack_1.stack(mark, encoding, config);
}
UnitModel.prototype._initEncoding = function (mark, encoding) {
encoding = util_1.duplicate(encoding);
vlEncoding.forEach(encoding, function (fieldDef, channel) {
if (!channel_1.supportMark(channel, mark)) {
console.warn(channel, 'dropped as it is incompatible with', mark);
delete fieldDef.field;
return;
}
if (fieldDef.type) {
fieldDef.type = type_1.getFullName(fieldDef.type);
}
if ((channel === channel_1.PATH || channel === channel_1.ORDER) && !fieldDef.aggregate && fieldDef.type === type_1.QUANTITATIVE) {
fieldDef.aggregate = aggregate_1.AggregateOp.MIN;
}
});
return encoding;
};
UnitModel.prototype._initConfig = function (specConfig, parent, mark, encoding) {
var config = util_1.mergeDeep(util_1.duplicate(config_1.defaultConfig), parent ? parent.config() : {}, specConfig);
config.mark = config_2.initMarkConfig(mark, encoding, config);
return config;
};
UnitModel.prototype._initScale = function (mark, encoding, config, topLevelWidth, topLevelHeight) {
return channel_1.UNIT_SCALE_CHANNELS.reduce(function (_scale, channel) {
if (vlEncoding.has(encoding, channel) ||
(channel === channel_1.X && vlEncoding.has(encoding, channel_1.X2)) ||
(channel === channel_1.Y && vlEncoding.has(encoding, channel_1.Y2))) {
var channelDef = encoding[channel];
var scaleSpec = (channelDef || {}).scale || {};
var _scaleType = scale_2.scaleType(scaleSpec, channelDef, channel, mark);
var scale = _scale[channel] = util_1.extend({
type: _scaleType,
round: config.scale.round,
padding: config.scale.padding,
useRawDomain: config.scale.useRawDomain
}, scaleSpec);
scale.bandSize = scale_2.scaleBandSize(scale.type, scale.bandSize, config.scale, channel === channel_1.X ? topLevelWidth : topLevelHeight, mark, channel);
}
return _scale;
}, {});
};
UnitModel.prototype._initSize = function (mark, scale, width, height, cellConfig, scaleConfig) {
if (width !== undefined) {
this._width = width;
}
else if (scale[channel_1.X]) {
if (scale[channel_1.X].type !== scale_1.ScaleType.ORDINAL || scale[channel_1.X].bandSize === scale_1.BANDSIZE_FIT) {
this._width = cellConfig.width;
}
}
else {
if (mark === mark_1.TEXT) {
this._width = scaleConfig.textBandWidth;
}
else {
this._width = scaleConfig.bandSize;
}
}
if (height !== undefined) {
this._height = height;
}
else if (scale[channel_1.Y]) {
if (scale[channel_1.Y].type !== scale_1.ScaleType.ORDINAL || scale[channel_1.Y].bandSize === scale_1.BANDSIZE_FIT) {
this._height = cellConfig.height;
}
}
else {
this._height = scaleConfig.bandSize;
}
};
UnitModel.prototype._initAxis = function (encoding, config) {
return [channel_1.X, channel_1.Y].reduce(function (_axis, channel) {
if (vlEncoding.has(encoding, channel) ||
(channel === channel_1.X && vlEncoding.has(encoding, channel_1.X2)) ||
(channel === channel_1.Y && vlEncoding.has(encoding, channel_1.Y2))) {
var axisSpec = (encoding[channel] || {}).axis;
if (axisSpec !== false) {
_axis[channel] = util_1.extend({}, config.axis, axisSpec === true ? {} : axisSpec || {});
}
}
return _axis;
}, {});
};
UnitModel.prototype._initLegend = function (encoding, config) {
return channel_1.NONSPATIAL_SCALE_CHANNELS.reduce(function (_legend, channel) {
if (vlEncoding.has(encoding, channel)) {
var legendSpec = encoding[channel].legend;
if (legendSpec !== false) {
_legend[channel] = util_1.extend({}, config.legend, legendSpec === true ? {} : legendSpec || {});
}
}
return _legend;
}, {});
};
Object.defineProperty(UnitModel.prototype, "width", {
get: function () {
return this._width;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UnitModel.prototype, "height", {
get: function () {
return this._height;
},
enumerable: true,
configurable: true
});
UnitModel.prototype.parseData = function () {
this.component.data = data_2.parseUnitData(this);
};
UnitModel.prototype.parseSelectionData = function () {
};
UnitModel.prototype.parseLayoutData = function () {
this.component.layout = layout_1.parseUnitLayout(this);
};
UnitModel.prototype.parseScale = function () {
this.component.scale = scale_2.parseScaleComponent(this);
};
UnitModel.prototype.parseMark = function () {
this.component.mark = mark_2.parseMark(this);
};
UnitModel.prototype.parseAxis = function () {
this.component.axis = axis_1.parseAxisComponent(this, [channel_1.X, channel_1.Y]);
};
UnitModel.prototype.parseAxisGroup = function () {
return null;
};
UnitModel.prototype.parseGridGroup = function () {
return null;
};
UnitModel.prototype.parseLegend = function () {
this.component.legend = legend_1.parseLegendComponent(this);
};
UnitModel.prototype.assembleData = function (data) {
return data_2.assembleData(this, data);
};
UnitModel.prototype.assembleLayout = function (layoutData) {
return layout_1.assembleLayout(this, layoutData);
};
UnitModel.prototype.assembleMarks = function () {
return this.component.mark;
};
UnitModel.prototype.assembleParentGroupProperties = function (cellConfig) {
return common_1.applyConfig({}, cellConfig, common_1.FILL_STROKE_CONFIG.concat(['clip']));
};
UnitModel.prototype.channels = function () {
return channel_1.UNIT_CHANNELS;
};
UnitModel.prototype.mapping = function () {
return this.encoding();
};
UnitModel.prototype.stack = function () {
return this._stack;
};
UnitModel.prototype.toSpec = function (excludeConfig, excludeData) {
var encoding = util_1.duplicate(this._encoding);
var spec;
spec = {
mark: this._mark,
encoding: encoding
};
if (!excludeConfig) {
spec.config = util_1.duplicate(this._config);
}
if (!excludeData) {
spec.data = util_1.duplicate(this._data);
}
return spec;
};
UnitModel.prototype.mark = function () {
return this._mark;
};
UnitModel.prototype.has = function (channel) {
return vlEncoding.has(this._encoding, channel);
};
UnitModel.prototype.encoding = function () {
return this._encoding;
};
UnitModel.prototype.fieldDef = function (channel) {
return this._encoding[channel] || {};
};
UnitModel.prototype.field = function (channel, opt) {
if (opt === void 0) { opt = {}; }
var fieldDef = this.fieldDef(channel);
if (fieldDef.bin) {
opt = util_1.extend({
binSuffix: this.scale(channel).type === scale_1.ScaleType.ORDINAL ? 'range' : 'start'
}, opt);
}
return fielddef_1.field(fieldDef, opt);
};
UnitModel.prototype.dataTable = function () {
return this.dataName(vlEncoding.isAggregate(this._encoding) ? data_1.SUMMARY : data_1.SOURCE);
};
UnitModel.prototype.isUnit = function () {
return true;
};
return UnitModel;
}(model_1.Model));
exports.UnitModel = UnitModel;
},{"../aggregate":7,"../channel":10,"../config":43,"../data":44,"../encoding":46,"../fielddef":48,"../mark":51,"../scale":52,"../stack":56,"../type":59,"../util":60,"./axis":11,"./common":12,"./config":14,"./data/data":17,"./layout":30,"./legend":31,"./mark/mark":35,"./model":40,"./scale":41}],43:[function(require,module,exports){
"use strict";
var scale_1 = require('./scale');
var axis_1 = require('./axis');
var legend_1 = require('./legend');
exports.defaultCellConfig = {
width: 200,
height: 200
};
exports.defaultFacetCellConfig = {
stroke: '#ccc',
strokeWidth: 1
};
var defaultFacetGridConfig = {
color: '#000000',
opacity: 0.4,
offset: 0
};
exports.defaultFacetConfig = {
scale: scale_1.defaultFacetScaleConfig,
axis: axis_1.defaultFacetAxisConfig,
grid: defaultFacetGridConfig,
cell: exports.defaultFacetCellConfig
};
(function (FontWeight) {
FontWeight[FontWeight["NORMAL"] = 'normal'] = "NORMAL";
FontWeight[FontWeight["BOLD"] = 'bold'] = "BOLD";
})(exports.FontWeight || (exports.FontWeight = {}));
var FontWeight = exports.FontWeight;
(function (Shape) {
Shape[Shape["CIRCLE"] = 'circle'] = "CIRCLE";
Shape[Shape["SQUARE"] = 'square'] = "SQUARE";
Shape[Shape["CROSS"] = 'cross'] = "CROSS";
Shape[Shape["DIAMOND"] = 'diamond'] = "DIAMOND";
Shape[Shape["TRIANGLEUP"] = 'triangle-up'] = "TRIANGLEUP";
Shape[Shape["TRIANGLEDOWN"] = 'triangle-down'] = "TRIANGLEDOWN";
})(exports.Shape || (exports.Shape = {}));
var Shape = exports.Shape;
(function (Orient) {
Orient[Orient["HORIZONTAL"] = 'horizontal'] = "HORIZONTAL";
Orient[Orient["VERTICAL"] = 'vertical'] = "VERTICAL";
})(exports.Orient || (exports.Orient = {}));
var Orient = exports.Orient;
(function (HorizontalAlign) {
HorizontalAlign[HorizontalAlign["LEFT"] = 'left'] = "LEFT";
HorizontalAlign[HorizontalAlign["RIGHT"] = 'right'] = "RIGHT";
HorizontalAlign[HorizontalAlign["CENTER"] = 'center'] = "CENTER";
})(exports.HorizontalAlign || (exports.HorizontalAlign = {}));
var HorizontalAlign = exports.HorizontalAlign;
(function (VerticalAlign) {
VerticalAlign[VerticalAlign["TOP"] = 'top'] = "TOP";
VerticalAlign[VerticalAlign["MIDDLE"] = 'middle'] = "MIDDLE";
VerticalAlign[VerticalAlign["BOTTOM"] = 'bottom'] = "BOTTOM";
})(exports.VerticalAlign || (exports.VerticalAlign = {}));
var VerticalAlign = exports.VerticalAlign;
(function (FontStyle) {
FontStyle[FontStyle["NORMAL"] = 'normal'] = "NORMAL";
FontStyle[FontStyle["ITALIC"] = 'italic'] = "ITALIC";
})(exports.FontStyle || (exports.FontStyle = {}));
var FontStyle = exports.FontStyle;
(function (Interpolate) {
Interpolate[Interpolate["LINEAR"] = 'linear'] = "LINEAR";
Interpolate[Interpolate["LINEAR_CLOSED"] = 'linear-closed'] = "LINEAR_CLOSED";
Interpolate[Interpolate["STEP"] = 'step'] = "STEP";
Interpolate[Interpolate["STEP_BEFORE"] = 'step-before'] = "STEP_BEFORE";
Interpolate[Interpolate["STEP_AFTER"] = 'step-after'] = "STEP_AFTER";
Interpolate[Interpolate["BASIS"] = 'basis'] = "BASIS";
Interpolate[Interpolate["BASIS_OPEN"] = 'basis-open'] = "BASIS_OPEN";
Interpolate[Interpolate["BASIS_CLOSED"] = 'basis-closed'] = "BASIS_CLOSED";
Interpolate[Interpolate["CARDINAL"] = 'cardinal'] = "CARDINAL";
Interpolate[Interpolate["CARDINAL_OPEN"] = 'cardinal-open'] = "CARDINAL_OPEN";
Interpolate[Interpolate["CARDINAL_CLOSED"] = 'cardinal-closed'] = "CARDINAL_CLOSED";
Interpolate[Interpolate["BUNDLE"] = 'bundle'] = "BUNDLE";
Interpolate[Interpolate["MONOTONE"] = 'monotone'] = "MONOTONE";
})(exports.Interpolate || (exports.Interpolate = {}));
var Interpolate = exports.Interpolate;
(function (AreaOverlay) {
AreaOverlay[AreaOverlay["LINE"] = 'line'] = "LINE";
AreaOverlay[AreaOverlay["LINEPOINT"] = 'linepoint'] = "LINEPOINT";
AreaOverlay[AreaOverlay["NONE"] = 'none'] = "NONE";
})(exports.AreaOverlay || (exports.AreaOverlay = {}));
var AreaOverlay = exports.AreaOverlay;
exports.defaultOverlayConfig = {
line: false,
pointStyle: { filled: true },
lineStyle: {}
};
exports.defaultMarkConfig = {
color: '#4682b4',
shape: Shape.CIRCLE,
strokeWidth: 2,
size: 30,
barThinSize: 2,
ruleSize: 1,
tickThickness: 1,
fontSize: 10,
baseline: VerticalAlign.MIDDLE,
text: 'Abc',
shortTimeLabels: false,
applyColorToBackground: false
};
exports.defaultConfig = {
numberFormat: 's',
timeFormat: '%Y-%m-%d',
countTitle: 'Number of Records',
cell: exports.defaultCellConfig,
mark: exports.defaultMarkConfig,
overlay: exports.defaultOverlayConfig,
scale: scale_1.defaultScaleConfig,
axis: axis_1.defaultAxisConfig,
legend: legend_1.defaultLegendConfig,
facet: exports.defaultFacetConfig,
};
},{"./axis":8,"./legend":50,"./scale":52}],44:[function(require,module,exports){
"use strict";
var type_1 = require('./type');
(function (DataFormatType) {
DataFormatType[DataFormatType["JSON"] = 'json'] = "JSON";
DataFormatType[DataFormatType["CSV"] = 'csv'] = "CSV";
DataFormatType[DataFormatType["TSV"] = 'tsv'] = "TSV";
DataFormatType[DataFormatType["TOPOJSON"] = 'topojson'] = "TOPOJSON";
})(exports.DataFormatType || (exports.DataFormatType = {}));
var DataFormatType = exports.DataFormatType;
(function (DataTable) {
DataTable[DataTable["SOURCE"] = 'source'] = "SOURCE";
DataTable[DataTable["SUMMARY"] = 'summary'] = "SUMMARY";
DataTable[DataTable["STACKED_SCALE"] = 'stacked_scale'] = "STACKED_SCALE";
DataTable[DataTable["LAYOUT"] = 'layout'] = "LAYOUT";
})(exports.DataTable || (exports.DataTable = {}));
var DataTable = exports.DataTable;
exports.SUMMARY = DataTable.SUMMARY;
exports.SOURCE = DataTable.SOURCE;
exports.STACKED_SCALE = DataTable.STACKED_SCALE;
exports.LAYOUT = DataTable.LAYOUT;
exports.types = {
'boolean': type_1.Type.NOMINAL,
'number': type_1.Type.QUANTITATIVE,
'integer': type_1.Type.QUANTITATIVE,
'date': type_1.Type.TEMPORAL,
'string': type_1.Type.NOMINAL
};
},{"./type":59}],45:[function(require,module,exports){
"use strict";
var util_1 = require('./util');
function isDateTime(o) {
return !!o.year || !!o.quarter || !!o.month || !!o.date || !!o.day ||
!!o.hours || !!o.minutes || !!o.seconds || !!o.milliseconds;
}
exports.isDateTime = isDateTime;
exports.MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
exports.SHORT_MONTHS = exports.MONTHS.map(function (m) { return m.substr(0, 3); });
exports.DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
exports.SHORT_DAYS = exports.DAYS.map(function (d) { return d.substr(0, 3); });
function normalizeQuarter(q) {
if (util_1.isNumber(q)) {
return (q - 1) + '';
}
else {
console.warn('Potentially invalid quarter', q);
return q;
}
}
function normalizeMonth(m) {
if (util_1.isNumber(m)) {
return (m - 1) + '';
}
else {
var lowerM = m.toLowerCase();
var monthIndex = exports.MONTHS.indexOf(lowerM);
if (monthIndex !== -1) {
return monthIndex + '';
}
var shortM = lowerM.substr(0, 3);
var shortMonthIndex = exports.SHORT_MONTHS.indexOf(shortM);
if (shortMonthIndex !== -1) {
return shortMonthIndex + '';
}
console.warn('Potentially invalid month', m);
return m;
}
}
function normalizeDay(d) {
if (util_1.isNumber(d)) {
return (d % 7) + '';
}
else {
var lowerD = d.toLowerCase();
var dayIndex = exports.DAYS.indexOf(lowerD);
if (dayIndex !== -1) {
return dayIndex + '';
}
var shortD = lowerD.substr(0, 3);
var shortDayIndex = exports.SHORT_DAYS.indexOf(shortD);
if (shortDayIndex !== -1) {
return shortDayIndex + '';
}
console.warn('Potentially invalid day', d);
return d;
}
}
function dateTimeExpr(d, normalize) {
if (normalize === void 0) { normalize = false; }
var units = [];
if (normalize && d.day !== undefined) {
for (var _i = 0, _a = ['year', 'quarter', 'month', 'date']; _i < _a.length; _i++) {
var unit = _a[_i];
if (d[unit] !== undefined) {
console.warn('Dropping day from datetime', JSON.stringify(d), 'as day cannot be combined with', unit);
d = util_1.duplicate(d);
delete d.day;
break;
}
}
}
if (d.year !== undefined) {
units.push(d.year);
}
else if (d.day !== undefined) {
units.push(2006);
}
else {
units.push(0);
}
if (d.month !== undefined) {
var month = normalize ? normalizeMonth(d.month) : d.month;
units.push(month);
}
else if (d.quarter !== undefined) {
var quarter = normalize ? normalizeQuarter(d.quarter) : d.quarter;
units.push(quarter + '*3');
}
else {
units.push(0);
}
if (d.date !== undefined) {
units.push(d.date);
}
else if (d.day !== undefined) {
var day = normalize ? normalizeDay(d.day) : d.day;
units.push(day + '+1');
}
else {
units.push(1);
}
for (var _b = 0, _c = ['hours', 'minutes', 'seconds', 'milliseconds']; _b < _c.length; _b++) {
var timeUnit = _c[_b];
if (d[timeUnit] !== undefined) {
units.push(d[timeUnit]);
}
else {
units.push(0);
}
}
return 'datetime(' + units.join(', ') + ')';
}
exports.dateTimeExpr = dateTimeExpr;
},{"./util":60}],46:[function(require,module,exports){
"use strict";
var channel_1 = require('./channel');
var util_1 = require('./util');
function countRetinal(encoding) {
var count = 0;
if (encoding.color) {
count++;
}
if (encoding.opacity) {
count++;
}
if (encoding.size) {
count++;
}
if (encoding.shape) {
count++;
}
return count;
}
exports.countRetinal = countRetinal;
function channels(encoding) {
return channel_1.CHANNELS.filter(function (channel) {
return has(encoding, channel);
});
}
exports.channels = channels;
function has(encoding, channel) {
var channelEncoding = encoding && encoding[channel];
return channelEncoding && (channelEncoding.field !== undefined ||
(util_1.isArray(channelEncoding) && channelEncoding.length > 0));
}
exports.has = has;
function isAggregate(encoding) {
return util_1.some(channel_1.CHANNELS, function (channel) {
if (has(encoding, channel) && encoding[channel].aggregate) {
return true;
}
return false;
});
}
exports.isAggregate = isAggregate;
function isRanged(encoding) {
return encoding && ((!!encoding.x && !!encoding.x2) || (!!encoding.y && !!encoding.y2));
}
exports.isRanged = isRanged;
function fieldDefs(encoding) {
var arr = [];
channel_1.CHANNELS.forEach(function (channel) {
if (has(encoding, channel)) {
if (util_1.isArray(encoding[channel])) {
encoding[channel].forEach(function (fieldDef) {
arr.push(fieldDef);
});
}
else {
arr.push(encoding[channel]);
}
}
});
return arr;
}
exports.fieldDefs = fieldDefs;
;
function forEach(encoding, f, thisArg) {
channelMappingForEach(channel_1.CHANNELS, encoding, f, thisArg);
}
exports.forEach = forEach;
function channelMappingForEach(channels, mapping, f, thisArg) {
var i = 0;
channels.forEach(function (channel) {
if (has(mapping, channel)) {
if (util_1.isArray(mapping[channel])) {
mapping[channel].forEach(function (fieldDef) {
f.call(thisArg, fieldDef, channel, i++);
});
}
else {
f.call(thisArg, mapping[channel], channel, i++);
}
}
});
}
exports.channelMappingForEach = channelMappingForEach;
function map(encoding, f, thisArg) {
return channelMappingMap(channel_1.CHANNELS, encoding, f, thisArg);
}
exports.map = map;
function channelMappingMap(channels, mapping, f, thisArg) {
var arr = [];
channels.forEach(function (channel) {
if (has(mapping, channel)) {
if (util_1.isArray(mapping[channel])) {
mapping[channel].forEach(function (fieldDef) {
arr.push(f.call(thisArg, fieldDef, channel));
});
}
else {
arr.push(f.call(thisArg, mapping[channel], channel));
}
}
});
return arr;
}
exports.channelMappingMap = channelMappingMap;
function reduce(encoding, f, init, thisArg) {
return channelMappingReduce(channel_1.CHANNELS, encoding, f, init, thisArg);
}
exports.reduce = reduce;
function channelMappingReduce(channels, mapping, f, init, thisArg) {
var r = init;
channel_1.CHANNELS.forEach(function (channel) {
if (has(mapping, channel)) {
if (util_1.isArray(mapping[channel])) {
mapping[channel].forEach(function (fieldDef) {
r = f.call(thisArg, r, fieldDef, channel);
});
}
else {
r = f.call(thisArg, r, mapping[channel], channel);
}
}
});
return r;
}
exports.channelMappingReduce = channelMappingReduce;
},{"./channel":10,"./util":60}],47:[function(require,module,exports){
"use strict";
},{}],48:[function(require,module,exports){
"use strict";
var aggregate_1 = require('./aggregate');
var scale_1 = require('./scale');
var type_1 = require('./type');
var util_1 = require('./util');
function field(fieldDef, opt) {
if (opt === void 0) { opt = {}; }
var field = fieldDef.field;
var prefix = opt.prefix;
var suffix = opt.suffix;
if (isCount(fieldDef)) {
field = 'count';
}
else {
var fn = opt.fn;
if (!opt.nofn) {
if (fieldDef.bin) {
fn = 'bin';
suffix = opt.binSuffix || (opt.scaleType === scale_1.ScaleType.ORDINAL ?
'range' :
'start');
}
else if (!opt.noAggregate && fieldDef.aggregate) {
fn = String(fieldDef.aggregate);
}
else if (fieldDef.timeUnit) {
fn = String(fieldDef.timeUnit);
}
}
if (!!fn) {
field = fn + "_" + field;
}
}
if (!!suffix) {
field = field + "_" + suffix;
}
if (!!prefix) {
field = prefix + "_" + field;
}
if (opt.datum) {
field = "datum[\"" + field + "\"]";
}
return field;
}
exports.field = field;
function _isFieldDimension(fieldDef) {
if (util_1.contains([type_1.NOMINAL, type_1.ORDINAL], fieldDef.type)) {
return true;
}
else if (!!fieldDef.bin) {
return true;
}
else if (fieldDef.type === type_1.TEMPORAL) {
return !!fieldDef.timeUnit;
}
return false;
}
function isDimension(fieldDef) {
return fieldDef && fieldDef.field && _isFieldDimension(fieldDef);
}
exports.isDimension = isDimension;
function isMeasure(fieldDef) {
return fieldDef && fieldDef.field && !_isFieldDimension(fieldDef);
}
exports.isMeasure = isMeasure;
function count() {
return { field: '*', aggregate: aggregate_1.AggregateOp.COUNT, type: type_1.QUANTITATIVE };
}
exports.count = count;
function isCount(fieldDef) {
return fieldDef.aggregate === aggregate_1.AggregateOp.COUNT;
}
exports.isCount = isCount;
function title(fieldDef, config) {
if (fieldDef.title != null) {
return fieldDef.title;
}
if (isCount(fieldDef)) {
return config.countTitle;
}
var fn = fieldDef.aggregate || fieldDef.timeUnit || (fieldDef.bin && 'bin');
if (fn) {
return fn.toString().toUpperCase() + '(' + fieldDef.field + ')';
}
else {
return fieldDef.field;
}
}
exports.title = title;
},{"./aggregate":7,"./scale":52,"./type":59,"./util":60}],49:[function(require,module,exports){
"use strict";
var datetime_1 = require('./datetime');
var fielddef_1 = require('./fielddef');
var timeunit_1 = require('./timeunit');
var util_1 = require('./util');
function isEqualFilter(filter) {
return filter && !!filter.field && filter.equal !== undefined;
}
exports.isEqualFilter = isEqualFilter;
function isRangeFilter(filter) {
if (filter && !!filter.field) {
if (util_1.isArray(filter.range) && filter.range.length === 2) {
return true;
}
}
return false;
}
exports.isRangeFilter = isRangeFilter;
function isOneOfFilter(filter) {
return filter && !!filter.field && (util_1.isArray(filter.oneOf) ||
util_1.isArray(filter.in));
}
exports.isOneOfFilter = isOneOfFilter;
function expression(filter) {
if (util_1.isString(filter)) {
return filter;
}
else {
var fieldExpr = filter.timeUnit ?
('time(' + timeunit_1.fieldExpr(filter.timeUnit, filter.field) + ')') :
fielddef_1.field(filter, { datum: true });
if (isEqualFilter(filter)) {
return fieldExpr + '===' + valueExpr(filter.equal, filter.timeUnit);
}
else if (isOneOfFilter(filter)) {
var oneOf = filter.oneOf || filter['in'];
return 'indexof([' +
oneOf.map(function (v) { return valueExpr(v, filter.timeUnit); }).join(',') +
'], ' + fieldExpr + ') !== -1';
}
else if (isRangeFilter(filter)) {
var lower = filter.range[0];
var upper = filter.range[1];
if (lower !== null && upper !== null) {
return 'inrange(' + fieldExpr + ', ' +
valueExpr(lower, filter.timeUnit) + ', ' +
valueExpr(upper, filter.timeUnit) + ')';
}
else if (lower !== null) {
return fieldExpr + ' >= ' + lower;
}
else if (upper !== null) {
return fieldExpr + ' <= ' + upper;
}
}
}
return undefined;
}
exports.expression = expression;
function valueExpr(v, timeUnit) {
if (datetime_1.isDateTime(v)) {
var expr = datetime_1.dateTimeExpr(v, true);
return 'time(' + expr + ')';
}
if (timeunit_1.isSingleTimeUnit(timeUnit)) {
var datetime = {};
datetime[timeUnit] = v;
var expr = datetime_1.dateTimeExpr(datetime, true);
return 'time(' + expr + ')';
}
return JSON.stringify(v);
}
},{"./datetime":45,"./fielddef":48,"./timeunit":57,"./util":60}],50:[function(require,module,exports){
"use strict";
exports.defaultLegendConfig = {
orient: undefined,
shortTimeLabels: false
};
},{}],51:[function(require,module,exports){
"use strict";
(function (Mark) {
Mark[Mark["AREA"] = 'area'] = "AREA";
Mark[Mark["BAR"] = 'bar'] = "BAR";
Mark[Mark["LINE"] = 'line'] = "LINE";
Mark[Mark["POINT"] = 'point'] = "POINT";
Mark[Mark["TEXT"] = 'text'] = "TEXT";
Mark[Mark["TICK"] = 'tick'] = "TICK";
Mark[Mark["RULE"] = 'rule'] = "RULE";
Mark[Mark["CIRCLE"] = 'circle'] = "CIRCLE";
Mark[Mark["SQUARE"] = 'square'] = "SQUARE";
Mark[Mark["ERRORBAR"] = 'errorBar'] = "ERRORBAR";
})(exports.Mark || (exports.Mark = {}));
var Mark = exports.Mark;
exports.AREA = Mark.AREA;
exports.BAR = Mark.BAR;
exports.LINE = Mark.LINE;
exports.POINT = Mark.POINT;
exports.TEXT = Mark.TEXT;
exports.TICK = Mark.TICK;
exports.RULE = Mark.RULE;
exports.CIRCLE = Mark.CIRCLE;
exports.SQUARE = Mark.SQUARE;
exports.ERRORBAR = Mark.ERRORBAR;
exports.PRIMITIVE_MARKS = [exports.AREA, exports.BAR, exports.LINE, exports.POINT, exports.TEXT, exports.TICK, exports.RULE, exports.CIRCLE, exports.SQUARE];
},{}],52:[function(require,module,exports){
"use strict";
(function (ScaleType) {
ScaleType[ScaleType["LINEAR"] = 'linear'] = "LINEAR";
ScaleType[ScaleType["LOG"] = 'log'] = "LOG";
ScaleType[ScaleType["POW"] = 'pow'] = "POW";
ScaleType[ScaleType["SQRT"] = 'sqrt'] = "SQRT";
ScaleType[ScaleType["QUANTILE"] = 'quantile'] = "QUANTILE";
ScaleType[ScaleType["QUANTIZE"] = 'quantize'] = "QUANTIZE";
ScaleType[ScaleType["ORDINAL"] = 'ordinal'] = "ORDINAL";
ScaleType[ScaleType["TIME"] = 'time'] = "TIME";
ScaleType[ScaleType["UTC"] = 'utc'] = "UTC";
})(exports.ScaleType || (exports.ScaleType = {}));
var ScaleType = exports.ScaleType;
(function (NiceTime) {
NiceTime[NiceTime["SECOND"] = 'second'] = "SECOND";
NiceTime[NiceTime["MINUTE"] = 'minute'] = "MINUTE";
NiceTime[NiceTime["HOUR"] = 'hour'] = "HOUR";
NiceTime[NiceTime["DAY"] = 'day'] = "DAY";
NiceTime[NiceTime["WEEK"] = 'week'] = "WEEK";
NiceTime[NiceTime["MONTH"] = 'month'] = "MONTH";
NiceTime[NiceTime["YEAR"] = 'year'] = "YEAR";
})(exports.NiceTime || (exports.NiceTime = {}));
var NiceTime = exports.NiceTime;
(function (BandSize) {
BandSize[BandSize["FIT"] = 'fit'] = "FIT";
})(exports.BandSize || (exports.BandSize = {}));
var BandSize = exports.BandSize;
exports.BANDSIZE_FIT = BandSize.FIT;
exports.defaultScaleConfig = {
round: true,
textBandWidth: 90,
bandSize: 21,
padding: 0.1,
useRawDomain: false,
opacity: [0.3, 0.8],
nominalColorRange: 'category10',
sequentialColorRange: ['#AFC6A3', '#09622A'],
shapeRange: 'shapes',
fontSizeRange: [8, 40],
ruleSizeRange: [1, 5],
tickSizeRange: [1, 20]
};
exports.defaultFacetScaleConfig = {
round: true,
padding: 16
};
},{}],53:[function(require,module,exports){
"use strict";
var aggregate_1 = require('./aggregate');
var timeunit_1 = require('./timeunit');
var type_1 = require('./type');
var vlEncoding = require('./encoding');
var mark_1 = require('./mark');
exports.DELIM = '|';
exports.ASSIGN = '=';
exports.TYPE = ',';
exports.FUNC = '_';
function shorten(spec) {
return 'mark' + exports.ASSIGN + spec.mark +
exports.DELIM + shortenEncoding(spec.encoding);
}
exports.shorten = shorten;
function parse(shorthand, data, config) {
var split = shorthand.split(exports.DELIM), mark = split.shift().split(exports.ASSIGN)[1].trim(), encoding = parseEncoding(split.join(exports.DELIM));
var spec = {
mark: mark_1.Mark[mark],
encoding: encoding
};
if (data !== undefined) {
spec.data = data;
}
if (config !== undefined) {
spec.config = config;
}
return spec;
}
exports.parse = parse;
function shortenEncoding(encoding) {
return vlEncoding.map(encoding, function (fieldDef, channel) {
return channel + exports.ASSIGN + shortenFieldDef(fieldDef);
}).join(exports.DELIM);
}
exports.shortenEncoding = shortenEncoding;
function parseEncoding(encodingShorthand) {
return encodingShorthand.split(exports.DELIM).reduce(function (m, e) {
var split = e.split(exports.ASSIGN), enctype = split[0].trim(), fieldDefShorthand = split[1];
m[enctype] = parseFieldDef(fieldDefShorthand);
return m;
}, {});
}
exports.parseEncoding = parseEncoding;
function shortenFieldDef(fieldDef) {
return (fieldDef.aggregate ? fieldDef.aggregate + exports.FUNC : '') +
(fieldDef.timeUnit ? fieldDef.timeUnit + exports.FUNC : '') +
(fieldDef.bin ? 'bin' + exports.FUNC : '') +
(fieldDef.field || '') + exports.TYPE + type_1.SHORT_TYPE[fieldDef.type];
}
exports.shortenFieldDef = shortenFieldDef;
function shortenFieldDefs(fieldDefs, delim) {
if (delim === void 0) { delim = exports.DELIM; }
return fieldDefs.map(shortenFieldDef).join(delim);
}
exports.shortenFieldDefs = shortenFieldDefs;
function parseFieldDef(fieldDefShorthand) {
var split = fieldDefShorthand.split(exports.TYPE);
var fieldDef = {
field: split[0].trim(),
type: type_1.TYPE_FROM_SHORT_TYPE[split[1].trim()]
};
for (var i = 0; i < aggregate_1.AGGREGATE_OPS.length; i++) {
var a = aggregate_1.AGGREGATE_OPS[i];
if (fieldDef.field.indexOf(a + '_') === 0) {
fieldDef.field = fieldDef.field.substr(a.toString().length + 1);
if (a === aggregate_1.AggregateOp.COUNT && fieldDef.field.length === 0) {
fieldDef.field = '*';
}
fieldDef.aggregate = a;
break;
}
}
for (var i = 0; i < timeunit_1.TIMEUNITS.length; i++) {
var tu = timeunit_1.TIMEUNITS[i];
if (fieldDef.field && fieldDef.field.indexOf(tu + '_') === 0) {
fieldDef.field = fieldDef.field.substr(fieldDef.field.length + 1);
fieldDef.timeUnit = tu;
break;
}
}
if (fieldDef.field && fieldDef.field.indexOf('bin_') === 0) {
fieldDef.field = fieldDef.field.substr(4);
fieldDef.bin = true;
}
return fieldDef;
}
exports.parseFieldDef = parseFieldDef;
},{"./aggregate":7,"./encoding":46,"./mark":51,"./timeunit":57,"./type":59}],54:[function(require,module,exports){
"use strict";
(function (SortOrder) {
SortOrder[SortOrder["ASCENDING"] = 'ascending'] = "ASCENDING";
SortOrder[SortOrder["DESCENDING"] = 'descending'] = "DESCENDING";
SortOrder[SortOrder["NONE"] = 'none'] = "NONE";
})(exports.SortOrder || (exports.SortOrder = {}));
var SortOrder = exports.SortOrder;
function isSortField(sort) {
return !!sort && !!sort['field'] && !!sort['op'];
}
exports.isSortField = isSortField;
},{}],55:[function(require,module,exports){
"use strict";
var config_1 = require('./config');
var encoding_1 = require('./encoding');
var mark_1 = require('./mark');
var stack_1 = require('./stack');
var channel_1 = require('./channel');
var vlEncoding = require('./encoding');
var util_1 = require('./util');
function isFacetSpec(spec) {
return spec['facet'] !== undefined;
}
exports.isFacetSpec = isFacetSpec;
function isExtendedUnitSpec(spec) {
if (isSomeUnitSpec(spec)) {
var hasRow = encoding_1.has(spec.encoding, channel_1.ROW);
var hasColumn = encoding_1.has(spec.encoding, channel_1.COLUMN);
return hasRow || hasColumn;
}
return false;
}
exports.isExtendedUnitSpec = isExtendedUnitSpec;
function isUnitSpec(spec) {
if (isSomeUnitSpec(spec)) {
return !isExtendedUnitSpec(spec);
}
return false;
}
exports.isUnitSpec = isUnitSpec;
function isSomeUnitSpec(spec) {
return spec['mark'] !== undefined;
}
exports.isSomeUnitSpec = isSomeUnitSpec;
function isLayerSpec(spec) {
return spec['layers'] !== undefined;
}
exports.isLayerSpec = isLayerSpec;
function normalize(spec) {
if (isExtendedUnitSpec(spec)) {
return normalizeExtendedUnitSpec(spec);
}
if (isUnitSpec(spec)) {
return normalizeUnitSpec(spec);
}
return spec;
}
exports.normalize = normalize;
function normalizeExtendedUnitSpec(spec) {
var hasRow = encoding_1.has(spec.encoding, channel_1.ROW);
var hasColumn = encoding_1.has(spec.encoding, channel_1.COLUMN);
var encoding = util_1.duplicate(spec.encoding);
delete encoding.column;
delete encoding.row;
return util_1.extend(spec.name ? { name: spec.name } : {}, spec.description ? { description: spec.description } : {}, { data: spec.data }, spec.transform ? { transform: spec.transform } : {}, {
facet: util_1.extend(hasRow ? { row: spec.encoding.row } : {}, hasColumn ? { column: spec.encoding.column } : {}),
spec: normalizeUnitSpec({
mark: spec.mark,
encoding: encoding
})
}, spec.config ? { config: spec.config } : {});
}
exports.normalizeExtendedUnitSpec = normalizeExtendedUnitSpec;
function normalizeUnitSpec(spec) {
var config = spec.config;
var overlayConfig = config && config.overlay;
var overlayWithLine = overlayConfig && spec.mark === mark_1.AREA &&
util_1.contains([config_1.AreaOverlay.LINEPOINT, config_1.AreaOverlay.LINE], overlayConfig.area);
var overlayWithPoint = overlayConfig && ((overlayConfig.line && spec.mark === mark_1.LINE) ||
(overlayConfig.area === config_1.AreaOverlay.LINEPOINT && spec.mark === mark_1.AREA));
if (spec.mark === mark_1.ERRORBAR) {
return normalizeErrorBarUnitSpec(spec);
}
if (encoding_1.isRanged(spec.encoding)) {
return normalizeRangedUnitSpec(spec);
}
if (isStacked(spec)) {
return spec;
}
if (overlayWithPoint || overlayWithLine) {
return normalizeOverlay(spec, overlayWithPoint, overlayWithLine);
}
return spec;
}
exports.normalizeUnitSpec = normalizeUnitSpec;
function normalizeRangedUnitSpec(spec) {
if (spec.encoding) {
var hasX = encoding_1.has(spec.encoding, channel_1.X);
var hasY = encoding_1.has(spec.encoding, channel_1.Y);
var hasX2 = encoding_1.has(spec.encoding, channel_1.X2);
var hasY2 = encoding_1.has(spec.encoding, channel_1.Y2);
if ((hasX2 && !hasX) || (hasY2 && !hasY)) {
var normalizedSpec = util_1.duplicate(spec);
if (hasX2 && !hasX) {
normalizedSpec.encoding.x = normalizedSpec.encoding.x2;
delete normalizedSpec.encoding.x2;
}
if (hasY2 && !hasY) {
normalizedSpec.encoding.y = normalizedSpec.encoding.y2;
delete normalizedSpec.encoding.y2;
}
return normalizedSpec;
}
}
return spec;
}
exports.normalizeRangedUnitSpec = normalizeRangedUnitSpec;
function normalizeErrorBarUnitSpec(spec) {
var layerSpec = util_1.extend(spec.name ? { name: spec.name } : {}, spec.description ? { description: spec.description } : {}, spec.data ? { data: spec.data } : {}, spec.transform ? { transform: spec.transform } : {}, spec.config ? { config: spec.config } : {}, { layers: [] });
if (!spec.encoding) {
return layerSpec;
}
if (spec.mark === mark_1.ERRORBAR) {
var ruleSpec = {
mark: mark_1.RULE,
encoding: util_1.extend(spec.encoding.x ? { x: util_1.duplicate(spec.encoding.x) } : {}, spec.encoding.y ? { y: util_1.duplicate(spec.encoding.y) } : {}, spec.encoding.x2 ? { x2: util_1.duplicate(spec.encoding.x2) } : {}, spec.encoding.y2 ? { y2: util_1.duplicate(spec.encoding.y2) } : {}, {})
};
var lowerTickSpec = {
mark: mark_1.TICK,
encoding: util_1.extend(spec.encoding.x ? { x: util_1.duplicate(spec.encoding.x) } : {}, spec.encoding.y ? { y: util_1.duplicate(spec.encoding.y) } : {}, spec.encoding.size ? { size: util_1.duplicate(spec.encoding.size) } : {}, {})
};
var upperTickSpec = {
mark: mark_1.TICK,
encoding: util_1.extend({
x: spec.encoding.x2 ? util_1.duplicate(spec.encoding.x2) : util_1.duplicate(spec.encoding.x),
y: spec.encoding.y2 ? util_1.duplicate(spec.encoding.y2) : util_1.duplicate(spec.encoding.y)
}, spec.encoding.size ? { size: util_1.duplicate(spec.encoding.size) } : {})
};
layerSpec.layers.push(normalizeUnitSpec(ruleSpec));
layerSpec.layers.push(normalizeUnitSpec(lowerTickSpec));
layerSpec.layers.push(normalizeUnitSpec(upperTickSpec));
}
return layerSpec;
}
exports.normalizeErrorBarUnitSpec = normalizeErrorBarUnitSpec;
function normalizeOverlay(spec, overlayWithPoint, overlayWithLine) {
var outerProps = ['name', 'description', 'data', 'transform'];
var baseSpec = util_1.omit(spec, outerProps.concat('config'));
var baseConfig = util_1.duplicate(spec.config);
delete baseConfig.overlay;
var layerSpec = util_1.extend(util_1.pick(spec, outerProps), { layers: [baseSpec] }, util_1.keys(baseConfig).length > 0 ? { config: baseConfig } : {});
if (overlayWithLine) {
var lineSpec = util_1.duplicate(baseSpec);
lineSpec.mark = mark_1.LINE;
var markConfig = util_1.extend({}, config_1.defaultOverlayConfig.lineStyle, spec.config.overlay.lineStyle);
if (util_1.keys(markConfig).length > 0) {
lineSpec.config = { mark: markConfig };
}
layerSpec.layers.push(lineSpec);
}
if (overlayWithPoint) {
var pointSpec = util_1.duplicate(baseSpec);
pointSpec.mark = mark_1.POINT;
var markConfig = util_1.extend({}, config_1.defaultOverlayConfig.pointStyle, spec.config.overlay.pointStyle);
;
if (util_1.keys(markConfig).length > 0) {
pointSpec.config = { mark: markConfig };
}
layerSpec.layers.push(pointSpec);
}
return layerSpec;
}
exports.normalizeOverlay = normalizeOverlay;
function fieldDefs(spec) {
return vlEncoding.fieldDefs(spec.encoding);
}
exports.fieldDefs = fieldDefs;
;
function isStacked(spec) {
return stack_1.stack(spec.mark, spec.encoding, spec.config) !== null;
}
exports.isStacked = isStacked;
},{"./channel":10,"./config":43,"./encoding":46,"./mark":51,"./stack":56,"./util":60}],56:[function(require,module,exports){
"use strict";
var channel_1 = require('./channel');
var encoding_1 = require('./encoding');
var mark_1 = require('./mark');
var util_1 = require('./util');
(function (StackOffset) {
StackOffset[StackOffset["ZERO"] = 'zero'] = "ZERO";
StackOffset[StackOffset["CENTER"] = 'center'] = "CENTER";
StackOffset[StackOffset["NORMALIZE"] = 'normalize'] = "NORMALIZE";
StackOffset[StackOffset["NONE"] = 'none'] = "NONE";
})(exports.StackOffset || (exports.StackOffset = {}));
var StackOffset = exports.StackOffset;
function stack(mark, encoding, config) {
var stacked = (config && config.mark) ? config.mark.stacked : undefined;
if (util_1.contains([StackOffset.NONE, null, false], stacked)) {
return null;
}
if (!util_1.contains([mark_1.BAR, mark_1.AREA], mark)) {
return null;
}
if (!encoding_1.isAggregate(encoding)) {
return null;
}
var stackByChannels = channel_1.STACK_GROUP_CHANNELS.reduce(function (sc, channel) {
if (encoding_1.has(encoding, channel) && !encoding[channel].aggregate) {
sc.push(channel);
}
return sc;
}, []);
if (stackByChannels.length === 0) {
return null;
}
var hasXField = encoding_1.has(encoding, channel_1.X);
var hasYField = encoding_1.has(encoding, channel_1.Y);
var xIsAggregate = hasXField && !!encoding.x.aggregate;
var yIsAggregate = hasYField && !!encoding.y.aggregate;
if (xIsAggregate !== yIsAggregate) {
return {
groupbyChannel: xIsAggregate ? (hasYField ? channel_1.Y : null) : (hasXField ? channel_1.X : null),
fieldChannel: xIsAggregate ? channel_1.X : channel_1.Y,
stackByChannels: stackByChannels,
offset: stacked || StackOffset.ZERO
};
}
return null;
}
exports.stack = stack;
},{"./channel":10,"./encoding":46,"./mark":51,"./util":60}],57:[function(require,module,exports){
"use strict";
var channel_1 = require('./channel');
var datetime_1 = require('./datetime');
var scale_1 = require('./scale');
var util_1 = require('./util');
(function (TimeUnit) {
TimeUnit[TimeUnit["YEAR"] = 'year'] = "YEAR";
TimeUnit[TimeUnit["MONTH"] = 'month'] = "MONTH";
TimeUnit[TimeUnit["DAY"] = 'day'] = "DAY";
TimeUnit[TimeUnit["DATE"] = 'date'] = "DATE";
TimeUnit[TimeUnit["HOURS"] = 'hours'] = "HOURS";
TimeUnit[TimeUnit["MINUTES"] = 'minutes'] = "MINUTES";
TimeUnit[TimeUnit["SECONDS"] = 'seconds'] = "SECONDS";
TimeUnit[TimeUnit["MILLISECONDS"] = 'milliseconds'] = "MILLISECONDS";
TimeUnit[TimeUnit["YEARMONTH"] = 'yearmonth'] = "YEARMONTH";
TimeUnit[TimeUnit["YEARMONTHDATE"] = 'yearmonthdate'] = "YEARMONTHDATE";
TimeUnit[TimeUnit["YEARMONTHDATEHOURS"] = 'yearmonthdatehours'] = "YEARMONTHDATEHOURS";
TimeUnit[TimeUnit["YEARMONTHDATEHOURSMINUTES"] = 'yearmonthdatehoursminutes'] = "YEARMONTHDATEHOURSMINUTES";
TimeUnit[TimeUnit["YEARMONTHDATEHOURSMINUTESSECONDS"] = 'yearmonthdatehoursminutesseconds'] = "YEARMONTHDATEHOURSMINUTESSECONDS";
TimeUnit[TimeUnit["HOURSMINUTES"] = 'hoursminutes'] = "HOURSMINUTES";
TimeUnit[TimeUnit["HOURSMINUTESSECONDS"] = 'hoursminutesseconds'] = "HOURSMINUTESSECONDS";
TimeUnit[TimeUnit["MINUTESSECONDS"] = 'minutesseconds'] = "MINUTESSECONDS";
TimeUnit[TimeUnit["SECONDSMILLISECONDS"] = 'secondsmilliseconds'] = "SECONDSMILLISECONDS";
TimeUnit[TimeUnit["QUARTER"] = 'quarter'] = "QUARTER";
TimeUnit[TimeUnit["YEARQUARTER"] = 'yearquarter'] = "YEARQUARTER";
TimeUnit[TimeUnit["QUARTERMONTH"] = 'quartermonth'] = "QUARTERMONTH";
TimeUnit[TimeUnit["YEARQUARTERMONTH"] = 'yearquartermonth'] = "YEARQUARTERMONTH";
})(exports.TimeUnit || (exports.TimeUnit = {}));
var TimeUnit = exports.TimeUnit;
exports.SINGLE_TIMEUNITS = [
TimeUnit.YEAR,
TimeUnit.QUARTER,
TimeUnit.MONTH,
TimeUnit.DAY,
TimeUnit.DATE,
TimeUnit.HOURS,
TimeUnit.MINUTES,
TimeUnit.SECONDS,
TimeUnit.MILLISECONDS,
];
var SINGLE_TIMEUNIT_INDEX = exports.SINGLE_TIMEUNITS.reduce(function (d, timeUnit) {
d[timeUnit] = true;
return d;
}, {});
function isSingleTimeUnit(timeUnit) {
return !!SINGLE_TIMEUNIT_INDEX[timeUnit];
}
exports.isSingleTimeUnit = isSingleTimeUnit;
function convert(unit, date) {
var result = new Date(0, 0, 1, 0, 0, 0, 0);
exports.SINGLE_TIMEUNITS.forEach(function (singleUnit) {
if (containsTimeUnit(unit, singleUnit)) {
switch (singleUnit) {
case TimeUnit.DAY:
throw new Error('Cannot convert to TimeUnits containing \'day\'');
case TimeUnit.YEAR:
result.setFullYear(date.getFullYear());
break;
case TimeUnit.QUARTER:
result.setMonth((Math.floor(date.getMonth() / 3)) * 3);
break;
case TimeUnit.MONTH:
result.setMonth(date.getMonth());
break;
case TimeUnit.DATE:
result.setDate(date.getDate());
break;
case TimeUnit.HOURS:
result.setHours(date.getHours());
break;
case TimeUnit.MINUTES:
result.setMinutes(date.getMinutes());
break;
case TimeUnit.SECONDS:
result.setSeconds(date.getSeconds());
break;
case TimeUnit.MILLISECONDS:
result.setMilliseconds(date.getMilliseconds());
break;
}
}
});
return result;
}
exports.convert = convert;
exports.MULTI_TIMEUNITS = [
TimeUnit.YEARQUARTER,
TimeUnit.YEARQUARTERMONTH,
TimeUnit.YEARMONTH,
TimeUnit.YEARMONTHDATE,
TimeUnit.YEARMONTHDATEHOURS,
TimeUnit.YEARMONTHDATEHOURSMINUTES,
TimeUnit.YEARMONTHDATEHOURSMINUTESSECONDS,
TimeUnit.QUARTERMONTH,
TimeUnit.HOURSMINUTES,
TimeUnit.HOURSMINUTESSECONDS,
TimeUnit.MINUTESSECONDS,
TimeUnit.SECONDSMILLISECONDS,
];
var MULTI_TIMEUNIT_INDEX = exports.MULTI_TIMEUNITS.reduce(function (d, timeUnit) {
d[timeUnit] = true;
return d;
}, {});
function isMultiTimeUnit(timeUnit) {
return !!MULTI_TIMEUNIT_INDEX[timeUnit];
}
exports.isMultiTimeUnit = isMultiTimeUnit;
exports.TIMEUNITS = exports.SINGLE_TIMEUNITS.concat(exports.MULTI_TIMEUNITS);
function containsTimeUnit(fullTimeUnit, timeUnit) {
var fullTimeUnitStr = fullTimeUnit.toString();
var timeUnitStr = timeUnit.toString();
var index = fullTimeUnitStr.indexOf(timeUnitStr);
return index > -1 &&
(timeUnit !== TimeUnit.SECONDS ||
index === 0 ||
fullTimeUnitStr.charAt(index - 1) !== 'i');
}
exports.containsTimeUnit = containsTimeUnit;
function defaultScaleType(timeUnit) {
switch (timeUnit) {
case TimeUnit.HOURS:
case TimeUnit.DAY:
case TimeUnit.MONTH:
case TimeUnit.QUARTER:
return scale_1.ScaleType.ORDINAL;
}
return scale_1.ScaleType.TIME;
}
exports.defaultScaleType = defaultScaleType;
function fieldExpr(fullTimeUnit, field) {
var fieldRef = 'datum["' + field + '"]';
function func(timeUnit) {
if (timeUnit === TimeUnit.QUARTER) {
return 'floor(month(' + fieldRef + ')' + '/3)';
}
else {
return timeUnit + '(' + fieldRef + ')';
}
}
var d = exports.SINGLE_TIMEUNITS.reduce(function (_d, tu) {
if (containsTimeUnit(fullTimeUnit, tu)) {
_d[tu] = func(tu);
}
return _d;
}, {});
if (d.day && util_1.keys(d).length > 1) {
console.warn('Time unit "' + fullTimeUnit + '" is not supported. We are replacing it with ', (fullTimeUnit + '').replace('day', 'date') + '.');
delete d.day;
d.date = func(TimeUnit.DATE);
}
return datetime_1.dateTimeExpr(d);
}
exports.fieldExpr = fieldExpr;
function rawDomain(timeUnit, channel) {
if (util_1.contains([channel_1.ROW, channel_1.COLUMN, channel_1.SHAPE, channel_1.COLOR], channel)) {
return null;
}
switch (timeUnit) {
case TimeUnit.SECONDS:
return util_1.range(0, 60);
case TimeUnit.MINUTES:
return util_1.range(0, 60);
case TimeUnit.HOURS:
return util_1.range(0, 24);
case TimeUnit.DAY:
return util_1.range(0, 7);
case TimeUnit.DATE:
return util_1.range(1, 32);
case TimeUnit.MONTH:
return util_1.range(0, 12);
case TimeUnit.QUARTER:
return [0, 3, 6, 9];
}
return null;
}
exports.rawDomain = rawDomain;
function smallestUnit(timeUnit) {
if (!timeUnit) {
return undefined;
}
if (containsTimeUnit(timeUnit, TimeUnit.SECONDS)) {
return 'second';
}
if (containsTimeUnit(timeUnit, TimeUnit.MINUTES)) {
return 'minute';
}
if (containsTimeUnit(timeUnit, TimeUnit.HOURS)) {
return 'hour';
}
if (containsTimeUnit(timeUnit, TimeUnit.DAY) ||
containsTimeUnit(timeUnit, TimeUnit.DATE)) {
return 'day';
}
if (containsTimeUnit(timeUnit, TimeUnit.MONTH)) {
return 'month';
}
if (containsTimeUnit(timeUnit, TimeUnit.YEAR)) {
return 'year';
}
return undefined;
}
exports.smallestUnit = smallestUnit;
function template(timeUnit, field, shortTimeLabels) {
if (!timeUnit) {
return undefined;
}
var dateComponents = [];
if (containsTimeUnit(timeUnit, TimeUnit.YEAR)) {
dateComponents.push(shortTimeLabels ? '%y' : '%Y');
}
if (containsTimeUnit(timeUnit, TimeUnit.QUARTER)) {
dateComponents.push('\'}}Q{{' + field + ' | quarter}}{{' + field + ' | time:\'');
}
if (containsTimeUnit(timeUnit, TimeUnit.MONTH)) {
dateComponents.push(shortTimeLabels ? '%b' : '%B');
}
if (containsTimeUnit(timeUnit, TimeUnit.DAY)) {
dateComponents.push(shortTimeLabels ? '%a' : '%A');
}
else if (containsTimeUnit(timeUnit, TimeUnit.DATE)) {
dateComponents.push('%d');
}
var timeComponents = [];
if (containsTimeUnit(timeUnit, TimeUnit.HOURS)) {
timeComponents.push('%H');
}
if (containsTimeUnit(timeUnit, TimeUnit.MINUTES)) {
timeComponents.push('%M');
}
if (containsTimeUnit(timeUnit, TimeUnit.SECONDS)) {
timeComponents.push('%S');
}
if (containsTimeUnit(timeUnit, TimeUnit.MILLISECONDS)) {
timeComponents.push('%L');
}
var out = [];
if (dateComponents.length > 0) {
out.push(dateComponents.join('-'));
}
if (timeComponents.length > 0) {
out.push(timeComponents.join(':'));
}
if (out.length > 0) {
var template_1 = '{{' + field + ' | time:\'' + out.join(' ') + '\'}}';
var escapedField = field.replace(/(\[|\])/g, '\\$1');
return template_1.replace(new RegExp('{{' + escapedField + ' \\| time:\'\'}}', 'g'), '');
}
else {
return undefined;
}
}
exports.template = template;
},{"./channel":10,"./datetime":45,"./scale":52,"./util":60}],58:[function(require,module,exports){
"use strict";
},{}],59:[function(require,module,exports){
"use strict";
(function (Type) {
Type[Type["QUANTITATIVE"] = 'quantitative'] = "QUANTITATIVE";
Type[Type["ORDINAL"] = 'ordinal'] = "ORDINAL";
Type[Type["TEMPORAL"] = 'temporal'] = "TEMPORAL";
Type[Type["NOMINAL"] = 'nominal'] = "NOMINAL";
})(exports.Type || (exports.Type = {}));
var Type = exports.Type;
exports.QUANTITATIVE = Type.QUANTITATIVE;
exports.ORDINAL = Type.ORDINAL;
exports.TEMPORAL = Type.TEMPORAL;
exports.NOMINAL = Type.NOMINAL;
exports.SHORT_TYPE = {
quantitative: 'Q',
temporal: 'T',
nominal: 'N',
ordinal: 'O'
};
exports.TYPE_FROM_SHORT_TYPE = {
Q: exports.QUANTITATIVE,
T: exports.TEMPORAL,
O: exports.ORDINAL,
N: exports.NOMINAL
};
function getFullName(type) {
var typeString = type;
return exports.TYPE_FROM_SHORT_TYPE[typeString.toUpperCase()] ||
typeString.toLowerCase();
}
exports.getFullName = getFullName;
},{}],60:[function(require,module,exports){
"use strict";
var stringify = require('json-stable-stringify');
var util_1 = require('datalib/src/util');
exports.keys = util_1.keys;
exports.extend = util_1.extend;
exports.duplicate = util_1.duplicate;
exports.isArray = util_1.isArray;
exports.vals = util_1.vals;
exports.truncate = util_1.truncate;
exports.toMap = util_1.toMap;
exports.isObject = util_1.isObject;
exports.isString = util_1.isString;
exports.isNumber = util_1.isNumber;
exports.isBoolean = util_1.isBoolean;
var util_2 = require('datalib/src/util');
var util_3 = require('datalib/src/util');
function pick(obj, props) {
var copy = {};
props.forEach(function (prop) {
if (obj.hasOwnProperty(prop)) {
copy[prop] = obj[prop];
}
});
return copy;
}
exports.pick = pick;
function range(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step === Infinity) {
throw new Error('Infinite range');
}
var range = [], i = -1, j;
if (step < 0) {
while ((j = start + step * ++i) > stop) {
range.push(j);
}
}
else {
while ((j = start + step * ++i) < stop) {
range.push(j);
}
}
return range;
}
exports.range = range;
;
function omit(obj, props) {
var copy = util_2.duplicate(obj);
props.forEach(function (prop) {
delete copy[prop];
});
return copy;
}
exports.omit = omit;
function hash(a) {
if (util_3.isString(a) || util_3.isNumber(a) || util_3.isBoolean(a)) {
return String(a);
}
return stringify(a);
}
exports.hash = hash;
function contains(array, item) {
return array.indexOf(item) > -1;
}
exports.contains = contains;
function without(array, excludedItems) {
return array.filter(function (item) {
return !contains(excludedItems, item);
});
}
exports.without = without;
function union(array, other) {
return array.concat(without(other, array));
}
exports.union = union;
function forEach(obj, f, thisArg) {
if (obj.forEach) {
obj.forEach.call(thisArg, f);
}
else {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
f.call(thisArg, obj[k], k, obj);
}
}
}
}
exports.forEach = forEach;
function reduce(obj, f, init, thisArg) {
if (obj.reduce) {
return obj.reduce.call(thisArg, f, init);
}
else {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
init = f.call(thisArg, init, obj[k], k, obj);
}
}
return init;
}
}
exports.reduce = reduce;
function map(obj, f, thisArg) {
if (obj.map) {
return obj.map.call(thisArg, f);
}
else {
var output = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
output.push(f.call(thisArg, obj[k], k, obj));
}
}
return output;
}
}
exports.map = map;
function some(arr, f) {
var i = 0;
for (var k = 0; k < arr.length; k++) {
if (f(arr[k], k, i++)) {
return true;
}
}
return false;
}
exports.some = some;
function every(arr, f) {
var i = 0;
for (var k = 0; k < arr.length; k++) {
if (!f(arr[k], k, i++)) {
return false;
}
}
return true;
}
exports.every = every;
function flatten(arrays) {
return [].concat.apply([], arrays);
}
exports.flatten = flatten;
function mergeDeep(dest) {
var src = [];
for (var _i = 1; _i < arguments.length; _i++) {
src[_i - 1] = arguments[_i];
}
for (var i = 0; i < src.length; i++) {
dest = deepMerge_(dest, src[i]);
}
return dest;
}
exports.mergeDeep = mergeDeep;
;
function deepMerge_(dest, src) {
if (typeof src !== 'object' || src === null) {
return dest;
}
for (var p in src) {
if (!src.hasOwnProperty(p)) {
continue;
}
if (src[p] === undefined) {
continue;
}
if (typeof src[p] !== 'object' || src[p] === null) {
dest[p] = src[p];
}
else if (typeof dest[p] !== 'object' || dest[p] === null) {
dest[p] = mergeDeep(src[p].constructor === Array ? [] : {}, src[p]);
}
else {
mergeDeep(dest[p], src[p]);
}
}
return dest;
}
function unique(values, f) {
var results = [];
var u = {}, v, i, n;
for (i = 0, n = values.length; i < n; ++i) {
v = f ? f(values[i]) : values[i];
if (v in u) {
continue;
}
u[v] = 1;
results.push(values[i]);
}
return results;
}
exports.unique = unique;
;
function warning(message) {
console.warn('[VL Warning]', message);
}
exports.warning = warning;
function error(message) {
console.error('[VL Error]', message);
}
exports.error = error;
function differ(dict, other) {
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
if (other[key] && dict[key] && other[key] !== dict[key]) {
return true;
}
}
}
return false;
}
exports.differ = differ;
},{"datalib/src/util":2,"json-stable-stringify":3}],61:[function(require,module,exports){
"use strict";
var util_1 = require('./util');
var mark_1 = require('./mark');
exports.DEFAULT_REQUIRED_CHANNEL_MAP = {
text: ['text'],
line: ['x', 'y'],
area: ['x', 'y']
};
exports.DEFAULT_SUPPORTED_CHANNEL_TYPE = {
bar: util_1.toMap(['row', 'column', 'x', 'y', 'size', 'color', 'detail']),
line: util_1.toMap(['row', 'column', 'x', 'y', 'color', 'detail']),
area: util_1.toMap(['row', 'column', 'x', 'y', 'color', 'detail']),
tick: util_1.toMap(['row', 'column', 'x', 'y', 'color', 'detail']),
circle: util_1.toMap(['row', 'column', 'x', 'y', 'color', 'size', 'detail']),
square: util_1.toMap(['row', 'column', 'x', 'y', 'color', 'size', 'detail']),
point: util_1.toMap(['row', 'column', 'x', 'y', 'color', 'size', 'detail', 'shape']),
text: util_1.toMap(['row', 'column', 'size', 'color', 'text'])
};
function getEncodingMappingError(spec, requiredChannelMap, supportedChannelMap) {
if (requiredChannelMap === void 0) { requiredChannelMap = exports.DEFAULT_REQUIRED_CHANNEL_MAP; }
if (supportedChannelMap === void 0) { supportedChannelMap = exports.DEFAULT_SUPPORTED_CHANNEL_TYPE; }
var mark = spec.mark;
var encoding = spec.encoding;
var requiredChannels = requiredChannelMap[mark];
var supportedChannels = supportedChannelMap[mark];
for (var i in requiredChannels) {
if (!(requiredChannels[i] in encoding)) {
return 'Missing encoding channel \"' + requiredChannels[i] +
'\" for mark \"' + mark + '\"';
}
}
for (var channel in encoding) {
if (!supportedChannels[channel]) {
return 'Encoding channel \"' + channel +
'\" is not supported by mark type \"' + mark + '\"';
}
}
if (mark === mark_1.BAR && !encoding.x && !encoding.y) {
return 'Missing both x and y for bar';
}
return null;
}
exports.getEncodingMappingError = getEncodingMappingError;
},{"./mark":51,"./util":60}],62:[function(require,module,exports){
"use strict";
var util_1 = require('./util');
function isUnionedDomain(domain) {
if (!util_1.isArray(domain)) {
return 'fields' in domain;
}
return false;
}
exports.isUnionedDomain = isUnionedDomain;
function isDataRefDomain(domain) {
if (!util_1.isArray(domain)) {
return 'data' in domain;
}
return false;
}
exports.isDataRefDomain = isDataRefDomain;
},{"./util":60}],63:[function(require,module,exports){
"use strict";
exports.axis = require('./axis');
exports.aggregate = require('./aggregate');
exports.bin = require('./bin');
exports.channel = require('./channel');
exports.compile = require('./compile/compile').compile;
exports.config = require('./config');
exports.data = require('./data');
exports.datetime = require('./datetime');
exports.encoding = require('./encoding');
exports.facet = require('./facet');
exports.fieldDef = require('./fielddef');
exports.legend = require('./legend');
exports.mark = require('./mark');
exports.scale = require('./scale');
exports.shorthand = require('./shorthand');
exports.sort = require('./sort');
exports.spec = require('./spec');
exports.stack = require('./stack');
exports.timeUnit = require('./timeunit');
exports.transform = require('./transform');
exports.type = require('./type');
exports.util = require('./util');
exports.validate = require('./validate');
exports.version = '1.2.0';
},{"./aggregate":7,"./axis":8,"./bin":9,"./channel":10,"./compile/compile":13,"./config":43,"./data":44,"./datetime":45,"./encoding":46,"./facet":47,"./fielddef":48,"./legend":50,"./mark":51,"./scale":52,"./shorthand":53,"./sort":54,"./spec":55,"./stack":56,"./timeunit":57,"./transform":58,"./type":59,"./util":60,"./validate":61}]},{},[63])(63)
});
//# sourceMappingURL=vega-lite.js.map
|
// Muaz Khan - https://github.com/muaz-khan
// neizerth - https://github.com/neizerth
// MIT License - https://www.webrtc-experiment.com/licence/
// Documentation - https://github.com/streamproc/MediaStreamRecorder
// ==========================================================
// GifRecorder.js
function GifRecorder(mediaStream) {
// void start(optional long timeSlice)
// timestamp to fire "ondataavailable"
this.start = function(timeSlice) {
timeSlice = timeSlice || 1000;
var imageWidth = this.videoWidth || 320;
var imageHeight = this.videoHeight || 240;
canvas.width = video.width = imageWidth;
canvas.height = video.height = imageHeight;
// external library to record as GIF images
gifEncoder = new GIFEncoder();
// void setRepeat(int iter)
// Sets the number of times the set of GIF frames should be played.
// Default is 1; 0 means play indefinitely.
gifEncoder.setRepeat(0);
// void setFrameRate(Number fps)
// Sets frame rate in frames per second.
// Equivalent to setDelay(1000/fps).
// Using "setDelay" instead of "setFrameRate"
gifEncoder.setDelay(this.frameRate || 200);
// void setQuality(int quality)
// Sets quality of color quantization (conversion of images to the
// maximum 256 colors allowed by the GIF specification).
// Lower values (minimum = 1) produce better colors,
// but slow processing significantly. 10 is the default,
// and produces good color mapping at reasonable speeds.
// Values greater than 20 do not yield significant improvements in speed.
gifEncoder.setQuality(this.quality || 1);
// Boolean start()
// This writes the GIF Header and returns false if it fails.
gifEncoder.start();
startTime = Date.now();
function drawVideoFrame(time) {
lastAnimationFrame = requestAnimationFrame(drawVideoFrame);
if (typeof lastFrameTime === undefined) {
lastFrameTime = time;
}
// ~10 fps
if (time - lastFrameTime < 90) return;
context.drawImage(video, 0, 0, imageWidth, imageHeight);
gifEncoder.addFrame(context);
// console.log('Recording...' + Math.round((Date.now() - startTime) / 1000) + 's');
// console.log("fps: ", 1000 / (time - lastFrameTime));
lastFrameTime = time;
}
lastAnimationFrame = requestAnimationFrame(drawVideoFrame);
timeout = setTimeout(doneRecording, timeSlice);
};
function doneRecording() {
endTime = Date.now();
var gifBlob = new Blob([new Uint8Array(gifEncoder.stream().bin)], {
type: 'image/gif'
});
self.ondataavailable(gifBlob);
// todo: find a way to clear old recorded blobs
gifEncoder.stream().bin = [];
};
this.stop = function() {
if (lastAnimationFrame) {
cancelAnimationFrame(lastAnimationFrame);
clearTimeout(timeout);
doneRecording();
}
};
this.ondataavailable = function() {};
this.onstop = function() {};
// Reference to itself
var self = this;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var video = document.createElement('video');
video.muted = true;
video.autoplay = true;
video.src = URL.createObjectURL(mediaStream);
video.play();
var lastAnimationFrame = null;
var startTime, endTime, lastFrameTime;
var gifEncoder;
var timeout;
}
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry';
/**
* FIXME: using number to represent discrete scale numbers is fragile in essence because of
* floating point numbers imprecision.
*/
function getAndroidAssetSuffix(scale: number): string {
switch (scale) {
case 0.75: return 'ldpi';
case 1: return 'mdpi';
case 1.5: return 'hdpi';
case 2: return 'xhdpi';
case 3: return 'xxhdpi';
case 4: return 'xxxhdpi';
}
throw new Error('no such scale');
}
function getAndroidDrawableFolderName(asset: PackagerAsset, scale: number) {
var suffix = getAndroidAssetSuffix(scale);
if (!suffix) {
throw new Error(
'Don\'t know which android drawable suffix to use for asset: ' +
JSON.stringify(asset)
);
}
const androidFolder = 'drawable-' + suffix;
return androidFolder;
}
function getAndroidResourceIdentifier(asset: PackagerAsset) {
var folderPath = getBasePath(asset);
return (folderPath + '/' + asset.name)
.toLowerCase()
.replace(/\//g, '_') // Encode folder structure in file name
.replace(/([^a-z0-9_])/g, '') // Remove illegal chars
.replace(/^assets_/, ''); // Remove "assets_" prefix
}
function getBasePath(asset: PackagerAsset) {
var basePath = asset.httpServerLocation;
if (basePath[0] === '/') {
basePath = basePath.substr(1);
}
return basePath;
}
module.exports = {
getAndroidAssetSuffix: getAndroidAssetSuffix,
getAndroidDrawableFolderName: getAndroidDrawableFolderName,
getAndroidResourceIdentifier: getAndroidResourceIdentifier,
getBasePath: getBasePath
};
|
/**
* @fileoverview Rule to ensure newline per method call when chaining calls
* @author Rajendra Patil
* @author Burak Yigit Kaya
*/
"use strict";
const astUtils = require("../ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "require a newline after each call in a method chain",
category: "Stylistic Issues",
recommended: false
},
fixable: "whitespace",
schema: [{
type: "object",
properties: {
ignoreChainWithDepth: {
type: "integer",
minimum: 1,
maximum: 10
}
},
additionalProperties: false
}]
},
create(context) {
const options = context.options[0] || {},
ignoreChainWithDepth = options.ignoreChainWithDepth || 2;
const sourceCode = context.getSourceCode();
/**
* Get the prefix of a given MemberExpression node.
* If the MemberExpression node is a computed value it returns a
* left bracket. If not it returns a period.
*
* @param {ASTNode} node - A MemberExpression node to get
* @returns {string} The prefix of the node.
*/
function getPrefix(node) {
return node.computed ? "[" : ".";
}
/**
* Gets the property text of a given MemberExpression node.
* If the text is multiline, this returns only the first line.
*
* @param {ASTNode} node - A MemberExpression node to get.
* @returns {string} The property text of the node.
*/
function getPropertyText(node) {
const prefix = getPrefix(node);
const lines = sourceCode.getText(node.property).split(astUtils.LINEBREAK_MATCHER);
const suffix = node.computed && lines.length === 1 ? "]" : "";
return prefix + lines[0] + suffix;
}
return {
"CallExpression:exit"(node) {
if (!node.callee || node.callee.type !== "MemberExpression") {
return;
}
const callee = node.callee;
let parent = callee.object;
let depth = 1;
while (parent && parent.callee) {
depth += 1;
parent = parent.callee.object;
}
if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) {
context.report({
node: callee.property,
loc: callee.property.loc.start,
message: "Expected line break before `{{callee}}`.",
data: {
callee: getPropertyText(callee)
},
fix(fixer) {
const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken);
return fixer.insertTextBefore(firstTokenAfterObject, "\n");
}
});
}
}
};
}
};
|
// KUTE.js v1.5.98 | © dnp_theme | jQuery Plugin | MIT-License
!function(e,t){if("function"==typeof define&&define.amd)define(["./kute.js","jquery"],function(e,n){return t(n,e),e});else if("object"==typeof module&&"function"==typeof require){var n=require("./kute.js"),r=require("jquery");module.exports=t(r,n)}else{if("undefined"==typeof e.KUTE||"undefined"==typeof e.$&&"undefined"==typeof e.jQuery)throw new Error("jQuery Plugin for KUTE.js depend on KUTE.js and jQuery");var r=e.jQuery||e.$,n=e.KUTE;r.fn.KUTE=t(r,n)}}(this,function(e,t){"use strict";return e.fn.fromTo=function(e,n,r){var i=this.length>1?this:this[0],o=this.length>1?"allFromTo":"fromTo";return t[o](i,e,n,r)},e.fn.to=function(e,n){var r=this.length>1?this:this[0],i=this.length>1?"allTo":"to";return t[i](r,e,n)},this});
|
var fs = require("fs");
var path = require("path");
var config = require("./config");
var eachSeries = require("async-each-series");
var asyncTasks = require("./async-tasks");
var hooks = require("./hooks");
var merge = require("./opts").merge;
var defaultPlugins = {
"sync-options": require("./plugins/sync-options/sync-options.plugin"),
"overview": require("./plugins/overview/overview.plugin"),
"history": require("./plugins/history/history.plugin"),
"plugins": require("./plugins/plugins/plugins.plugin"),
"remote-debug": require("./plugins/remote-debug/remote-debug.plugin"),
"help": require("./plugins/help/help.plugin"),
"connections": require("./plugins/connections/connections.plugin"),
"network-throttle": require("./plugins/network-throttle/network-throttle.plugin")
};
/**
* @param {Object} opts - Any options specifically
* passed to the control panel
* @param {BrowserSync} bs
* @param {EventEmitter} emitter
* @constructor
* @returns {UI}
*/
var UI = function (opts, bs, emitter) {
var ui = this;
ui.bs = bs;
ui.config = config.merge();
ui.events = emitter;
ui.options = merge(opts);
ui.logger = bs.getLogger(ui.config.get("pluginName"));
ui.defaultPlugins = defaultPlugins;
ui.listeners = {};
ui.clients = bs.io.of(bs.options.getIn(["socket", "namespace"]));
ui.socket = bs.io.of(ui.config.getIn(["socket", "namespace"]));
if (ui.options.get("logLevel")) {
ui.logger.setLevel(ui.options.get("logLevel"));
}
/**
*
*/
ui.pluginManager = new bs.utils.easyExtender(defaultPlugins, hooks).init();
/**
* Transform/save data RE: plugins
* @type {*}
*/
ui.bsPlugins = require("./resolve-plugins")(bs.getUserPlugins());
return ui;
};
/**
* Detect an available port
* @returns {UI}
*/
UI.prototype.init = function () {
var ui = this;
eachSeries(
asyncTasks,
taskRunner(ui),
tasksComplete(ui)
);
return this;
};
/**
* @param cb
*/
UI.prototype.getServer = function (cb) {
var ui = this;
if (ui.server) {
return ui.server;
}
this.events.on("ui:running", function () {
cb(null, ui.server);
});
};
/**
* @returns {Array}
*/
UI.prototype.getInitialTemplates = function () {
var prefix = path.resolve(__dirname, "../templates/directives");
return fs.readdirSync(prefix)
.map(function (name) {
return path.resolve(prefix, name);
});
};
/**
* @param event
*/
UI.prototype.delegateEvent = function (event) {
var ui = this;
var listeners = ui.listeners[event.namespace];
if (listeners) {
if (listeners.event) {
listeners.event.call(ui, event);
} else {
if (event.event && listeners[event.event]) {
listeners[event.event].call(ui, event.data);
}
}
}
};
/**
* @param cb
*/
UI.prototype.listen = function (ns, events) {
var ui = this;
if (Array.isArray(ns)) {
ns = ns.join(":");
}
if (!ui.listeners[ns]) {
ui.listeners[ns] = events;
}
};
/**
* @param name
* @param value
* @returns {Map|*}
*/
UI.prototype.setOption = function (name, value) {
var ui = this;
ui.options = ui.options.set(name, value);
return ui.options;
};
/**
* @param path
* @param value
* @returns {Map|*}
*/
UI.prototype.setOptionIn = function (path, value) {
this.options = this.options.setIn(path, value);
return this.options;
};
/**
* @param fn
*/
UI.prototype.setMany = function (fn) {
this.options = this.options.withMutations(fn);
return this.options;
};
/**
* @param path
* @returns {any|*}
*/
UI.prototype.getOptionIn = function (path) {
return this.options.getIn(path);
};
/**
* Run each setup task in sequence
* @param ui
* @returns {Function}
*/
function taskRunner (ui) {
return function (item, cb) {
ui.logger.debug("Starting Step: " + item.step);
/**
* Give each step access to the UI Instance
*/
item.fn(ui, function (err, out) {
if (err) {
return cb(err);
}
if (out) {
handleOut(ui, out);
}
ui.logger.debug("{green:Step Complete: " + item.step);
cb();
});
};
}
/**
* Setup tasks may return options or instance properties to be set
* @param {UI} ui
* @param {Object} out
*/
function handleOut (ui, out) {
if (out.options) {
Object.keys(out.options).forEach(function (key) {
ui.options = ui.options.set(key, out.options[key]);
});
}
if (out.optionsIn) {
out.optionsIn.forEach(function (item) {
ui.options = ui.options.setIn(item.path, item.value);
});
}
if (out.instance) {
Object.keys(out.instance).forEach(function (key) {
ui[key] = out.instance[key];
});
}
}
/**
* All async tasks complete at this point
* @param ui
*/
function tasksComplete (ui) {
return function (err) {
/**
* Log any error according to BrowserSync's Logging level
*/
if (err) {
ui.logger.setOnce("useLevelPrefixes", true).error(err.message || err);
}
/**
* Running event
*/
ui.events.emit("ui:running", {instance: ui, options: ui.options});
/**
* Finally call the user-provided callback
*/
ui.cb(null, ui);
};
}
module.exports = UI;
|
(function(s){function k(b,a){if(b===a)return!0;if("object"==typeof b&&"object"==typeof a){if(Array.isArray(b)!=Array.isArray(a))return!1;if(Array.isArray(b)){if(b.length!=a.length)return!1;for(var c=0;c<b.length;c++)if(!k(b[c],a[c]))return!1}else{for(c in b)if(void 0===a[c]&&void 0!==b[c])return!1;for(c in a)if(void 0===b[c]&&void 0!==a[c])return!1;for(c in b)if(!k(b[c],a[c]))return!1}return!0}return!1}function q(b){return(b=String(b).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/))?
{href:b[0]||"",protocol:b[1]||"",authority:b[2]||"",host:b[3]||"",hostname:b[4]||"",port:b[5]||"",pathname:b[6]||"",search:b[7]||"",hash:b[8]||""}:null}function p(b,a){a=q(a||"");b=q(b||"");var c;if(!a||!b)c=null;else{c=(a.protocol||b.protocol)+(a.protocol||a.authority?a.authority:b.authority);var d;d=a.protocol||a.authority||"/"===a.pathname.charAt(0)?a.pathname:a.pathname?(b.authority&&!b.pathname?"/":"")+b.pathname.slice(0,b.pathname.lastIndexOf("/")+1)+a.pathname:b.pathname;var f=[];d.replace(/^(\.\.?(\/|$))+/,
"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(a){"/.."===a?f.pop():f.push(a)});d=f.join("").replace(/^\//,"/"===d.charAt(0)?"/":"");c=c+d+(a.protocol||a.authority||a.pathname?a.search:a.search||b.search)+a.hash}return c}function m(b,a){void 0==a?a=b.id:"string"==typeof b.id&&(a=p(a,b.id),b.id=a);if("object"==typeof b)if(Array.isArray(b))for(var c=0;c<b.length;c++)m(b[c],a);else if("string"==typeof b.$ref)b.$ref=p(a,b.$ref);else for(c in b)"enum"!=c&&m(b[c],
a)}function g(b,a,c,d,f){if(void 0==b)throw Error("No code supplied for error: "+a);this.code=b;this.message=a;this.dataPath=c?c:"";this.schemaPath=d?d:"";this.subErrors=f?f:null}function r(b,a,c){if("string"==typeof a.id&&a.id.substring(0,c.length)==c){var d=a.id.substring(c.length);if(0<c.length&&"/"==c.charAt(c.length-1)||"#"==d.charAt(0)||"?"==d.charAt(0))void 0==b[a.id]&&(b[a.id]=a)}if("object"==typeof a)for(var f in a)"enum"!=f&&"object"==typeof a[f]&&r(b,a[f],c);return b}var e=function(b,a){this.missing=
[];this.schemas=b?Object.create(b.schemas):{};this.collectMultiple=a;this.errors=[];this.handleError=a?this.collectError:this.returnError};e.prototype.returnError=function(b){return b};e.prototype.collectError=function(b){b&&this.errors.push(b);return null};e.prototype.prefixErrors=function(b,a,c){for(;b<this.errors.length;b++)this.errors[b]=this.errors[b].prefixWith(a,c);return this};e.prototype.getSchema=function(b){if(void 0!=this.schemas[b])return b=this.schemas[b];var a=b,c="";-1!=b.indexOf("#")&&
(c=b.substring(b.indexOf("#")+1),a=b.substring(0,b.indexOf("#")));if(void 0!=this.schemas[a]){b=this.schemas[a];c=decodeURIComponent(c);if(""==c)return b;if("/"!=c.charAt(0))return;for(var c=c.split("/").slice(1),d=0;d<c.length;d++){var f=c[d].replace("~1","/").replace("~0","~");if(void 0==b[f]){b=void 0;break}b=b[f]}if(void 0!=b)return b}void 0==this.missing[a]&&(this.missing.push(a),this.missing[a]=a)};e.prototype.addSchema=function(b,a){var c={};c[b]=a;m(a,b);r(c,a,b);for(var d in c)this.schemas[d]=
c[d];return c};e.prototype.validateAll=function(b,a,c,d){if(void 0!=a.$ref&&(a=this.getSchema(a.$ref),!a))return null;var f=this.errors.length;if((b=this.validateBasic(b,a)||this.validateNumeric(b,a)||this.validateString(b,a)||this.validateArray(b,a)||this.validateObject(b,a)||this.validateCombinations(b,a)||null)||f!=this.errors.length)for(;c&&c.length||d&&d.length;){a=c&&c.length?""+c.pop():null;var e=d&&d.length?""+d.pop():null;b&&(b=b.prefixWith(a,e));this.prefixErrors(f,a,e)}return this.handleError(b)};
e.prototype.validateBasic=function(b,a){var c;return(c=this.validateType(b,a))||(c=this.validateEnum(b,a))?c.prefixWith(null,"type"):null};e.prototype.validateType=function(b,a){if(void 0==a.type)return null;var c=typeof b;null==b?c="null":Array.isArray(b)&&(c="array");var d=a.type;"object"!=typeof d&&(d=[d]);for(var f=0;f<d.length;f++){var e=d[f];if(e==c||"integer"==e&&"number"==c&&0==b%1)return null}return new g(h.INVALID_TYPE,"invalid data type: "+c)};e.prototype.validateEnum=function(b,a){if(void 0==
a["enum"])return null;for(var c=0;c<a["enum"].length;c++)if(k(b,a["enum"][c]))return null;return new g(h.ENUM_MISMATCH,"No enum match for: "+JSON.stringify(b))};e.prototype.validateNumeric=function(b,a){return this.validateMultipleOf(b,a)||this.validateMinMax(b,a)||null};e.prototype.validateMultipleOf=function(b,a){var c=a.multipleOf||a.divisibleBy;return void 0==c?null:"number"==typeof b&&0!=b%c?new g(h.NUMBER_MULTIPLE_OF,"Value "+b+" is not a multiple of "+c):null};e.prototype.validateMinMax=function(b,
a){if("number"!=typeof b)return null;if(void 0!=a.minimum){if(b<a.minimum)return(new g(h.NUMBER_MINIMUM,"Value "+b+" is less than minimum "+a.minimum)).prefixWith(null,"minimum");if(a.exclusiveMinimum&&b==a.minimum)return(new g(h.NUMBER_MINIMUM_EXCLUSIVE,"Value "+b+" is equal to exclusive minimum "+a.minimum)).prefixWith(null,"exclusiveMinimum")}if(void 0!=a.maximum){if(b>a.maximum)return(new g(h.NUMBER_MAXIMUM,"Value "+b+" is greater than maximum "+a.maximum)).prefixWith(null,"maximum");if(a.exclusiveMaximum&&
b==a.maximum)return(new g(h.NUMBER_MAXIMUM_EXCLUSIVE,"Value "+b+" is equal to exclusive maximum "+a.maximum)).prefixWith(null,"exclusiveMaximum")}return null};e.prototype.validateString=function(b,a){return this.validateStringLength(b,a)||this.validateStringPattern(b,a)||null};e.prototype.validateStringLength=function(b,a){return"string"!=typeof b?null:void 0!=a.minLength&&b.length<a.minLength?(new g(h.STRING_LENGTH_SHORT,"String is too short ("+b.length+" chars), minimum "+a.minLength)).prefixWith(null,
"minLength"):void 0!=a.maxLength&&b.length>a.maxLength?(new g(h.STRING_LENGTH_LONG,"String is too long ("+b.length+" chars), maximum "+a.maxLength)).prefixWith(null,"maxLength"):null};e.prototype.validateStringPattern=function(b,a){return"string"!=typeof b||void 0==a.pattern?null:!RegExp(a.pattern).test(b)?(new g(h.STRING_PATTERN,"String does not match pattern")).prefixWith(null,"pattern"):null};e.prototype.validateArray=function(b,a){return!Array.isArray(b)?null:this.validateArrayLength(b,a)||this.validateArrayUniqueItems(b,
a)||this.validateArrayItems(b,a)||null};e.prototype.validateArrayLength=function(b,a){if(void 0!=a.minItems&&b.length<a.minItems){var c=(new g(h.ARRAY_LENGTH_SHORT,"Array is too short ("+b.length+"), minimum "+a.minItems)).prefixWith(null,"minItems");if(this.handleError(c))return c}return void 0!=a.maxItems&&b.length>a.maxItems&&(c=(new g(h.ARRAY_LENGTH_LONG,"Array is too long ("+b.length+" chars), maximum "+a.maxItems)).prefixWith(null,"maxItems"),this.handleError(c))?c:null};e.prototype.validateArrayUniqueItems=
function(b,a){if(a.uniqueItems)for(var c=0;c<b.length;c++)for(var d=c+1;d<b.length;d++)if(k(b[c],b[d])){var f=(new g(h.ARRAY_UNIQUE,"Array items are not unique (indices "+c+" and "+d+")")).prefixWith(null,"uniqueItems");if(this.handleError(f))return f}return null};e.prototype.validateArrayItems=function(b,a){if(void 0==a.items)return null;var c;if(Array.isArray(a.items))for(var d=0;d<b.length;d++)if(d<a.items.length){if(c=this.validateAll(b[d],a.items[d],[d],["items",d]))return c}else{if(void 0!=
a.additionalItems)if("boolean"==typeof a.additionalItems){if(!a.additionalItems&&(c=(new g(h.ARRAY_ADDITIONAL_ITEMS,"Additional items not allowed")).prefixWith(""+d,"additionalItems"),this.handleError(c)))return c}else if(c=this.validateAll(b[d],a.additionalItems,[d],["additionalItems"]))return c}else for(d=0;d<b.length;d++)if(c=this.validateAll(b[d],a.items,[d],["items"]))return c;return null};e.prototype.validateObject=function(b,a){return"object"!=typeof b||null==b||Array.isArray(b)?null:this.validateObjectMinMaxProperties(b,
a)||this.validateObjectRequiredProperties(b,a)||this.validateObjectProperties(b,a)||this.validateObjectDependencies(b,a)||null};e.prototype.validateObjectMinMaxProperties=function(b,a){var c=Object.keys(b);if(void 0!=a.minProperties&&c.length<a.minProperties){var d=(new g(h.OBJECT_PROPERTIES_MINIMUM,"Too few properties defined ("+c.length+"), minimum "+a.minProperties)).prefixWith(null,"minProperties");if(this.handleError(d))return d}return void 0!=a.maxProperties&&c.length>a.maxProperties&&(d=(new g(h.OBJECT_PROPERTIES_MAXIMUM,
"Too many properties defined ("+c.length+"), maximum "+a.maxProperties)).prefixWith(null,"maxProperties"),this.handleError(d))?d:null};e.prototype.validateObjectRequiredProperties=function(b,a){if(void 0!=a.required)for(var c=0;c<a.required.length;c++){var d=a.required[c];if(void 0===b[d]&&(d=(new g(h.OBJECT_REQUIRED,"Missing required property: "+d)).prefixWith(null,""+c).prefixWith(null,"required"),this.handleError(d)))return d}return null};e.prototype.validateObjectProperties=function(b,a){var c,
d;for(d in b){var f=!1;if(void 0!=a.properties&&void 0!=a.properties[d]&&(f=!0,c=this.validateAll(b[d],a.properties[d],[d],["properties",d])))return c;if(void 0!=a.patternProperties)for(var e in a.patternProperties)if(RegExp(e).test(d)&&(f=!0,c=this.validateAll(b[d],a.patternProperties[e],[d],["patternProperties",e])))return c;if(!f&&void 0!=a.additionalProperties)if("boolean"==typeof a.additionalProperties){if(!a.additionalProperties&&(c=(new g(h.OBJECT_ADDITIONAL_PROPERTIES,"Additional properties not allowed")).prefixWith(d,
"additionalProperties"),this.handleError(c)))return c}else if(c=this.validateAll(b[d],a.additionalProperties,[d],["additionalProperties"]))return c}return null};e.prototype.validateObjectDependencies=function(b,a){var c;if(void 0!=a.dependencies)for(var d in a.dependencies)if(void 0!==b[d]){var f=a.dependencies[d];if("string"==typeof f){if(void 0===b[f]&&(c=(new g(h.OBJECT_DEPENDENCY_KEY,"Dependency failed - key must exist: "+f)).prefixWith(null,d).prefixWith(null,"dependencies"),this.handleError(c)))return c}else if(Array.isArray(f))for(var e=
0;e<f.length;e++){if(c=f[e],void 0===b[c]&&(c=(new g(h.OBJECT_DEPENDENCY_KEY,"Dependency failed - key must exist: "+c)).prefixWith(null,""+e).prefixWith(null,d).prefixWith(null,"dependencies"),this.handleError(c)))return c}else if(c=this.validateAll(b,f,[],["dependencies",d]))return c}return null};e.prototype.validateCombinations=function(b,a){return this.validateAllOf(b,a)||this.validateAnyOf(b,a)||this.validateOneOf(b,a)||this.validateNot(b,a)||null};e.prototype.validateAllOf=function(b,a){if(void 0==
a.allOf)return null;for(var c,d=0;d<a.allOf.length;d++)if(c=this.validateAll(b,a.allOf[d],[],["allOf",d]))return c;return null};e.prototype.validateAnyOf=function(b,a){if(void 0==a.anyOf)return null;for(var c=[],d=this.errors.length,e=0;e<a.anyOf.length;e++){var j=this.errors.length,l=this.validateAll(b,a.anyOf[e],[],["anyOf",e]);if(null==l&&j==this.errors.length)return this.errors=this.errors.slice(0,d),null;l&&c.push(l.prefixWith(null,""+e).prefixWith(null,"anyOf"))}c=c.concat(this.errors.slice(d));
this.errors=this.errors.slice(0,d);return new g(h.ANY_OF_MISSING,'Data does not match any schemas from "anyOf"',"","/anyOf",c)};e.prototype.validateOneOf=function(b,a){if(void 0==a.oneOf)return null;for(var c=null,d=[],e=this.errors.length,j=0;j<a.oneOf.length;j++){var l=this.errors.length,k=this.validateAll(b,a.oneOf[j],[],["oneOf",j]);if(null==k&&l==this.errors.length)if(null==c)c=j;else return this.errors=this.errors.slice(0,e),new g(h.ONE_OF_MULTIPLE,'Data is valid against more than one schema from "oneOf": indices '+
c+" and "+j,"","/oneOf");else k&&d.push(k.prefixWith(null,""+j).prefixWith(null,"oneOf"))}return null==c?(d=d.concat(this.errors.slice(e)),this.errors=this.errors.slice(0,e),new g(h.ONE_OF_MISSING,'Data does not match any schemas from "oneOf"',"","/oneOf",d)):null};e.prototype.validateNot=function(b,a){if(void 0==a.not)return null;var c=this.errors.length,d=this.validateAll(b,a.not),e=this.errors.slice(c);this.errors=this.errors.slice(0,c);return null==d&&0==e.length?new g(h.NOT_PASSED,'Data matches schema from "not"',
"","/not"):null};var h={INVALID_TYPE:0,ENUM_MISMATCH:1,ANY_OF_MISSING:10,ONE_OF_MISSING:11,ONE_OF_MULTIPLE:12,NOT_PASSED:13,NUMBER_MULTIPLE_OF:100,NUMBER_MINIMUM:101,NUMBER_MINIMUM_EXCLUSIVE:102,NUMBER_MAXIMUM:103,NUMBER_MAXIMUM_EXCLUSIVE:104,STRING_LENGTH_SHORT:200,STRING_LENGTH_LONG:201,STRING_PATTERN:202,OBJECT_PROPERTIES_MINIMUM:300,OBJECT_PROPERTIES_MAXIMUM:301,OBJECT_REQUIRED:302,OBJECT_ADDITIONAL_PROPERTIES:303,OBJECT_DEPENDENCY_KEY:304,ARRAY_LENGTH_SHORT:400,ARRAY_LENGTH_LONG:401,ARRAY_UNIQUE:402,
ARRAY_ADDITIONAL_ITEMS:403};g.prototype={prefixWith:function(b,a){null!=b&&(b=b.replace("~","~0").replace("/","~1"),this.dataPath="/"+b+this.dataPath);null!=a&&(a=a.replace("~","~0").replace("/","~1"),this.schemaPath="/"+a+this.schemaPath);if(null!=this.subErrors)for(var c=0;c<this.subErrors.length;c++)this.subErrors[c].prefixWith(b,a);return this}};var n=new e;s.tv4={validate:function(b,a){var c=new e(n);"string"==typeof a&&(a={$ref:a});c.addSchema("",a);var d=c.validateAll(b,a);this.error=d;this.missing=
c.missing;return this.valid=null==d},validateResult:function(){var b={};this.validate.apply(b,arguments);return b},validateMultiple:function(b,a){var c=new e(n,!0);"string"==typeof a&&(a={$ref:a});c.addSchema("",a);c.validateAll(b,a);var d={};d.errors=c.errors;d.missing=c.missing;d.valid=0==d.errors.length;return d},addSchema:function(b,a){return n.addSchema(b,a)},getSchema:function(b){return n.getSchema(b)},missing:[],error:null,normSchema:m,resolveUrl:p,errorCodes:h}})("undefined"!==typeof module&&
module.exports?exports:this);
|
module.exports = { prefix: 'far', iconName: 'arrow-alt-circle-right', icon: [512, 512, [], "f35a", "M504 256C504 119 393 8 256 8S8 119 8 256s111 248 248 248 248-111 248-248zm-448 0c0-110.5 89.5-200 200-200s200 89.5 200 200-89.5 200-200 200S56 366.5 56 256zm72 20v-40c0-6.6 5.4-12 12-12h116v-67c0-10.7 12.9-16 20.5-8.5l99 99c4.7 4.7 4.7 12.3 0 17l-99 99c-7.6 7.6-20.5 2.2-20.5-8.5v-67H140c-6.6 0-12-5.4-12-12z"] };
|
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint globalstrict: false */
/* globals PDFJS */
// Initializing PDFJS global object (if still undefined)
if (typeof PDFJS === 'undefined') {
(typeof window !== 'undefined' ? window : this).PDFJS = {};
}
PDFJS.version = '1.0.940';
PDFJS.build = '45ca953';
(function pdfjsWrapper() {
// Use strict in our context only - users might not want it
'use strict';
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
Promise */
'use strict';
var globalScope = (typeof window === 'undefined') ? this : window;
var isWorker = (typeof window === 'undefined');
var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
var TextRenderingMode = {
FILL: 0,
STROKE: 1,
FILL_STROKE: 2,
INVISIBLE: 3,
FILL_ADD_TO_PATH: 4,
STROKE_ADD_TO_PATH: 5,
FILL_STROKE_ADD_TO_PATH: 6,
ADD_TO_PATH: 7,
FILL_STROKE_MASK: 3,
ADD_TO_PATH_FLAG: 4
};
var ImageKind = {
GRAYSCALE_1BPP: 1,
RGB_24BPP: 2,
RGBA_32BPP: 3
};
var AnnotationType = {
WIDGET: 1,
TEXT: 2,
LINK: 3
};
var StreamType = {
UNKNOWN: 0,
FLATE: 1,
LZW: 2,
DCT: 3,
JPX: 4,
JBIG: 5,
A85: 6,
AHX: 7,
CCF: 8,
RL: 9
};
var FontType = {
UNKNOWN: 0,
TYPE1: 1,
TYPE1C: 2,
CIDFONTTYPE0: 3,
CIDFONTTYPE0C: 4,
TRUETYPE: 5,
CIDFONTTYPE2: 6,
TYPE3: 7,
OPENTYPE: 8,
TYPE0: 9,
MMTYPE1: 10
};
// The global PDFJS object exposes the API
// In production, it will be declared outside a global wrapper
// In development, it will be declared here
if (!globalScope.PDFJS) {
globalScope.PDFJS = {};
}
globalScope.PDFJS.pdfBug = false;
PDFJS.VERBOSITY_LEVELS = {
errors: 0,
warnings: 1,
infos: 5
};
// All the possible operations for an operator list.
var OPS = PDFJS.OPS = {
// Intentionally start from 1 so it is easy to spot bad operators that will be
// 0's.
dependency: 1,
setLineWidth: 2,
setLineCap: 3,
setLineJoin: 4,
setMiterLimit: 5,
setDash: 6,
setRenderingIntent: 7,
setFlatness: 8,
setGState: 9,
save: 10,
restore: 11,
transform: 12,
moveTo: 13,
lineTo: 14,
curveTo: 15,
curveTo2: 16,
curveTo3: 17,
closePath: 18,
rectangle: 19,
stroke: 20,
closeStroke: 21,
fill: 22,
eoFill: 23,
fillStroke: 24,
eoFillStroke: 25,
closeFillStroke: 26,
closeEOFillStroke: 27,
endPath: 28,
clip: 29,
eoClip: 30,
beginText: 31,
endText: 32,
setCharSpacing: 33,
setWordSpacing: 34,
setHScale: 35,
setLeading: 36,
setFont: 37,
setTextRenderingMode: 38,
setTextRise: 39,
moveText: 40,
setLeadingMoveText: 41,
setTextMatrix: 42,
nextLine: 43,
showText: 44,
showSpacedText: 45,
nextLineShowText: 46,
nextLineSetSpacingShowText: 47,
setCharWidth: 48,
setCharWidthAndBounds: 49,
setStrokeColorSpace: 50,
setFillColorSpace: 51,
setStrokeColor: 52,
setStrokeColorN: 53,
setFillColor: 54,
setFillColorN: 55,
setStrokeGray: 56,
setFillGray: 57,
setStrokeRGBColor: 58,
setFillRGBColor: 59,
setStrokeCMYKColor: 60,
setFillCMYKColor: 61,
shadingFill: 62,
beginInlineImage: 63,
beginImageData: 64,
endInlineImage: 65,
paintXObject: 66,
markPoint: 67,
markPointProps: 68,
beginMarkedContent: 69,
beginMarkedContentProps: 70,
endMarkedContent: 71,
beginCompat: 72,
endCompat: 73,
paintFormXObjectBegin: 74,
paintFormXObjectEnd: 75,
beginGroup: 76,
endGroup: 77,
beginAnnotations: 78,
endAnnotations: 79,
beginAnnotation: 80,
endAnnotation: 81,
paintJpegXObject: 82,
paintImageMaskXObject: 83,
paintImageMaskXObjectGroup: 84,
paintImageXObject: 85,
paintInlineImageXObject: 86,
paintInlineImageXObjectGroup: 87,
paintImageXObjectRepeat: 88,
paintImageMaskXObjectRepeat: 89,
paintSolidColorImageMask: 90,
constructPath: 91
};
// A notice for devs. These are good for things that are helpful to devs, such
// as warning that Workers were disabled, which is important to devs but not
// end users.
function info(msg) {
if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
console.log('Info: ' + msg);
}
}
// Non-fatal warnings.
function warn(msg) {
if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
console.log('Warning: ' + msg);
}
}
// Fatal errors that should trigger the fallback UI and halt execution by
// throwing an exception.
function error(msg) {
// If multiple arguments were passed, pass them all to the log function.
if (arguments.length > 1) {
var logArguments = ['Error:'];
logArguments.push.apply(logArguments, arguments);
console.log.apply(console, logArguments);
// Join the arguments into a single string for the lines below.
msg = [].join.call(arguments, ' ');
} else {
console.log('Error: ' + msg);
}
console.log(backtrace());
UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
throw new Error(msg);
}
function backtrace() {
try {
throw new Error();
} catch (e) {
return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
}
}
function assert(cond, msg) {
if (!cond) {
error(msg);
}
}
var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
unknown: 'unknown',
forms: 'forms',
javaScript: 'javaScript',
smask: 'smask',
shadingPattern: 'shadingPattern',
font: 'font'
};
var UnsupportedManager = PDFJS.UnsupportedManager =
(function UnsupportedManagerClosure() {
var listeners = [];
return {
listen: function (cb) {
listeners.push(cb);
},
notify: function (featureId) {
warn('Unsupported feature "' + featureId + '"');
for (var i = 0, ii = listeners.length; i < ii; i++) {
listeners[i](featureId);
}
}
};
})();
// Combines two URLs. The baseUrl shall be absolute URL. If the url is an
// absolute URL, it will be returned as is.
function combineUrl(baseUrl, url) {
if (!url) {
return baseUrl;
}
if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
return url;
}
var i;
if (url.charAt(0) === '/') {
// absolute path
i = baseUrl.indexOf('://');
if (url.charAt(1) === '/') {
++i;
} else {
i = baseUrl.indexOf('/', i + 3);
}
return baseUrl.substring(0, i) + url;
} else {
// relative path
var pathLength = baseUrl.length;
i = baseUrl.lastIndexOf('#');
pathLength = i >= 0 ? i : pathLength;
i = baseUrl.lastIndexOf('?', pathLength);
pathLength = i >= 0 ? i : pathLength;
var prefixLength = baseUrl.lastIndexOf('/', pathLength);
return baseUrl.substring(0, prefixLength + 1) + url;
}
}
// Validates if URL is safe and allowed, e.g. to avoid XSS.
function isValidUrl(url, allowRelative) {
if (!url) {
return false;
}
// RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
if (!protocol) {
return allowRelative;
}
protocol = protocol[0].toLowerCase();
switch (protocol) {
case 'http':
case 'https':
case 'ftp':
case 'mailto':
return true;
default:
return false;
}
}
PDFJS.isValidUrl = isValidUrl;
function shadow(obj, prop, value) {
Object.defineProperty(obj, prop, { value: value,
enumerable: true,
configurable: true,
writable: false });
return value;
}
var PasswordResponses = PDFJS.PasswordResponses = {
NEED_PASSWORD: 1,
INCORRECT_PASSWORD: 2
};
var PasswordException = (function PasswordExceptionClosure() {
function PasswordException(msg, code) {
this.name = 'PasswordException';
this.message = msg;
this.code = code;
}
PasswordException.prototype = new Error();
PasswordException.constructor = PasswordException;
return PasswordException;
})();
PDFJS.PasswordException = PasswordException;
var UnknownErrorException = (function UnknownErrorExceptionClosure() {
function UnknownErrorException(msg, details) {
this.name = 'UnknownErrorException';
this.message = msg;
this.details = details;
}
UnknownErrorException.prototype = new Error();
UnknownErrorException.constructor = UnknownErrorException;
return UnknownErrorException;
})();
PDFJS.UnknownErrorException = UnknownErrorException;
var InvalidPDFException = (function InvalidPDFExceptionClosure() {
function InvalidPDFException(msg) {
this.name = 'InvalidPDFException';
this.message = msg;
}
InvalidPDFException.prototype = new Error();
InvalidPDFException.constructor = InvalidPDFException;
return InvalidPDFException;
})();
PDFJS.InvalidPDFException = InvalidPDFException;
var MissingPDFException = (function MissingPDFExceptionClosure() {
function MissingPDFException(msg) {
this.name = 'MissingPDFException';
this.message = msg;
}
MissingPDFException.prototype = new Error();
MissingPDFException.constructor = MissingPDFException;
return MissingPDFException;
})();
PDFJS.MissingPDFException = MissingPDFException;
var UnexpectedResponseException =
(function UnexpectedResponseExceptionClosure() {
function UnexpectedResponseException(msg, status) {
this.name = 'UnexpectedResponseException';
this.message = msg;
this.status = status;
}
UnexpectedResponseException.prototype = new Error();
UnexpectedResponseException.constructor = UnexpectedResponseException;
return UnexpectedResponseException;
})();
PDFJS.UnexpectedResponseException = UnexpectedResponseException;
var NotImplementedException = (function NotImplementedExceptionClosure() {
function NotImplementedException(msg) {
this.message = msg;
}
NotImplementedException.prototype = new Error();
NotImplementedException.prototype.name = 'NotImplementedException';
NotImplementedException.constructor = NotImplementedException;
return NotImplementedException;
})();
var MissingDataException = (function MissingDataExceptionClosure() {
function MissingDataException(begin, end) {
this.begin = begin;
this.end = end;
this.message = 'Missing data [' + begin + ', ' + end + ')';
}
MissingDataException.prototype = new Error();
MissingDataException.prototype.name = 'MissingDataException';
MissingDataException.constructor = MissingDataException;
return MissingDataException;
})();
var XRefParseException = (function XRefParseExceptionClosure() {
function XRefParseException(msg) {
this.message = msg;
}
XRefParseException.prototype = new Error();
XRefParseException.prototype.name = 'XRefParseException';
XRefParseException.constructor = XRefParseException;
return XRefParseException;
})();
function bytesToString(bytes) {
var length = bytes.length;
var MAX_ARGUMENT_COUNT = 8192;
if (length < MAX_ARGUMENT_COUNT) {
return String.fromCharCode.apply(null, bytes);
}
var strBuf = [];
for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
var chunk = bytes.subarray(i, chunkEnd);
strBuf.push(String.fromCharCode.apply(null, chunk));
}
return strBuf.join('');
}
function stringToBytes(str) {
var length = str.length;
var bytes = new Uint8Array(length);
for (var i = 0; i < length; ++i) {
bytes[i] = str.charCodeAt(i) & 0xFF;
}
return bytes;
}
function string32(value) {
return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
(value >> 8) & 0xff, value & 0xff);
}
function log2(x) {
var n = 1, i = 0;
while (x > n) {
n <<= 1;
i++;
}
return i;
}
function readInt8(data, start) {
return (data[start] << 24) >> 24;
}
function readUint16(data, offset) {
return (data[offset] << 8) | data[offset + 1];
}
function readUint32(data, offset) {
return ((data[offset] << 24) | (data[offset + 1] << 16) |
(data[offset + 2] << 8) | data[offset + 3]) >>> 0;
}
// Lazy test the endianness of the platform
// NOTE: This will be 'true' for simulated TypedArrays
function isLittleEndian() {
var buffer8 = new Uint8Array(2);
buffer8[0] = 1;
var buffer16 = new Uint16Array(buffer8.buffer);
return (buffer16[0] === 1);
}
Object.defineProperty(PDFJS, 'isLittleEndian', {
configurable: true,
get: function PDFJS_isLittleEndian() {
return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
}
});
// Lazy test if the userAgant support CanvasTypedArrays
function hasCanvasTypedArrays() {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');
var imageData = ctx.createImageData(1, 1);
return (typeof imageData.data.buffer !== 'undefined');
}
Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
configurable: true,
get: function PDFJS_hasCanvasTypedArrays() {
return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
}
});
var Uint32ArrayView = (function Uint32ArrayViewClosure() {
function Uint32ArrayView(buffer, length) {
this.buffer = buffer;
this.byteLength = buffer.length;
this.length = length === undefined ? (this.byteLength >> 2) : length;
ensureUint32ArrayViewProps(this.length);
}
Uint32ArrayView.prototype = Object.create(null);
var uint32ArrayViewSetters = 0;
function createUint32ArrayProp(index) {
return {
get: function () {
var buffer = this.buffer, offset = index << 2;
return (buffer[offset] | (buffer[offset + 1] << 8) |
(buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
},
set: function (value) {
var buffer = this.buffer, offset = index << 2;
buffer[offset] = value & 255;
buffer[offset + 1] = (value >> 8) & 255;
buffer[offset + 2] = (value >> 16) & 255;
buffer[offset + 3] = (value >>> 24) & 255;
}
};
}
function ensureUint32ArrayViewProps(length) {
while (uint32ArrayViewSetters < length) {
Object.defineProperty(Uint32ArrayView.prototype,
uint32ArrayViewSetters,
createUint32ArrayProp(uint32ArrayViewSetters));
uint32ArrayViewSetters++;
}
}
return Uint32ArrayView;
})();
var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
var Util = PDFJS.Util = (function UtilClosure() {
function Util() {}
var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
// makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
// creating many intermediate strings.
Util.makeCssRgb = function Util_makeCssRgb(rgb) {
rgbBuf[1] = rgb[0];
rgbBuf[3] = rgb[1];
rgbBuf[5] = rgb[2];
return rgbBuf.join('');
};
// Concatenates two transformation matrices together and returns the result.
Util.transform = function Util_transform(m1, m2) {
return [
m1[0] * m2[0] + m1[2] * m2[1],
m1[1] * m2[0] + m1[3] * m2[1],
m1[0] * m2[2] + m1[2] * m2[3],
m1[1] * m2[2] + m1[3] * m2[3],
m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
];
};
// For 2d affine transforms
Util.applyTransform = function Util_applyTransform(p, m) {
var xt = p[0] * m[0] + p[1] * m[2] + m[4];
var yt = p[0] * m[1] + p[1] * m[3] + m[5];
return [xt, yt];
};
Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
var d = m[0] * m[3] - m[1] * m[2];
var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
return [xt, yt];
};
// Applies the transform to the rectangle and finds the minimum axially
// aligned bounding box.
Util.getAxialAlignedBoundingBox =
function Util_getAxialAlignedBoundingBox(r, m) {
var p1 = Util.applyTransform(r, m);
var p2 = Util.applyTransform(r.slice(2, 4), m);
var p3 = Util.applyTransform([r[0], r[3]], m);
var p4 = Util.applyTransform([r[2], r[1]], m);
return [
Math.min(p1[0], p2[0], p3[0], p4[0]),
Math.min(p1[1], p2[1], p3[1], p4[1]),
Math.max(p1[0], p2[0], p3[0], p4[0]),
Math.max(p1[1], p2[1], p3[1], p4[1])
];
};
Util.inverseTransform = function Util_inverseTransform(m) {
var d = m[0] * m[3] - m[1] * m[2];
return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
(m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
};
// Apply a generic 3d matrix M on a 3-vector v:
// | a b c | | X |
// | d e f | x | Y |
// | g h i | | Z |
// M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
// with v as [X,Y,Z]
Util.apply3dTransform = function Util_apply3dTransform(m, v) {
return [
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
];
};
// This calculation uses Singular Value Decomposition.
// The SVD can be represented with formula A = USV. We are interested in the
// matrix S here because it represents the scale values.
Util.singularValueDecompose2dScale =
function Util_singularValueDecompose2dScale(m) {
var transpose = [m[0], m[2], m[1], m[3]];
// Multiply matrix m with its transpose.
var a = m[0] * transpose[0] + m[1] * transpose[2];
var b = m[0] * transpose[1] + m[1] * transpose[3];
var c = m[2] * transpose[0] + m[3] * transpose[2];
var d = m[2] * transpose[1] + m[3] * transpose[3];
// Solve the second degree polynomial to get roots.
var first = (a + d) / 2;
var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
var sx = first + second || 1;
var sy = first - second || 1;
// Scale values are the square roots of the eigenvalues.
return [Math.sqrt(sx), Math.sqrt(sy)];
};
// Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
// For coordinate systems whose origin lies in the bottom-left, this
// means normalization to (BL,TR) ordering. For systems with origin in the
// top-left, this means (TL,BR) ordering.
Util.normalizeRect = function Util_normalizeRect(rect) {
var r = rect.slice(0); // clone rect
if (rect[0] > rect[2]) {
r[0] = rect[2];
r[2] = rect[0];
}
if (rect[1] > rect[3]) {
r[1] = rect[3];
r[3] = rect[1];
}
return r;
};
// Returns a rectangle [x1, y1, x2, y2] corresponding to the
// intersection of rect1 and rect2. If no intersection, returns 'false'
// The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
Util.intersect = function Util_intersect(rect1, rect2) {
function compare(a, b) {
return a - b;
}
// Order points along the axes
var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
result = [];
rect1 = Util.normalizeRect(rect1);
rect2 = Util.normalizeRect(rect2);
// X: first and second points belong to different rectangles?
if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
(orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
// Intersection must be between second and third points
result[0] = orderedX[1];
result[2] = orderedX[2];
} else {
return false;
}
// Y: first and second points belong to different rectangles?
if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
(orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
// Intersection must be between second and third points
result[1] = orderedY[1];
result[3] = orderedY[2];
} else {
return false;
}
return result;
};
Util.sign = function Util_sign(num) {
return num < 0 ? -1 : 1;
};
Util.appendToArray = function Util_appendToArray(arr1, arr2) {
Array.prototype.push.apply(arr1, arr2);
};
Util.prependToArray = function Util_prependToArray(arr1, arr2) {
Array.prototype.unshift.apply(arr1, arr2);
};
Util.extendObj = function extendObj(obj1, obj2) {
for (var key in obj2) {
obj1[key] = obj2[key];
}
};
Util.getInheritableProperty = function Util_getInheritableProperty(dict,
name) {
while (dict && !dict.has(name)) {
dict = dict.get('Parent');
}
if (!dict) {
return null;
}
return dict.get(name);
};
Util.inherit = function Util_inherit(sub, base, prototype) {
sub.prototype = Object.create(base.prototype);
sub.prototype.constructor = sub;
for (var prop in prototype) {
sub.prototype[prop] = prototype[prop];
}
};
Util.loadScript = function Util_loadScript(src, callback) {
var script = document.createElement('script');
var loaded = false;
script.setAttribute('src', src);
if (callback) {
script.onload = function() {
if (!loaded) {
callback();
}
loaded = true;
};
}
document.getElementsByTagName('head')[0].appendChild(script);
};
return Util;
})();
/**
* PDF page viewport created based on scale, rotation and offset.
* @class
* @alias PDFJS.PageViewport
*/
var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
/**
* @constructor
* @private
* @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
* @param scale {number} scale of the viewport.
* @param rotation {number} rotations of the viewport in degrees.
* @param offsetX {number} offset X
* @param offsetY {number} offset Y
* @param dontFlip {boolean} if true, axis Y will not be flipped.
*/
function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
this.viewBox = viewBox;
this.scale = scale;
this.rotation = rotation;
this.offsetX = offsetX;
this.offsetY = offsetY;
// creating transform to convert pdf coordinate system to the normal
// canvas like coordinates taking in account scale and rotation
var centerX = (viewBox[2] + viewBox[0]) / 2;
var centerY = (viewBox[3] + viewBox[1]) / 2;
var rotateA, rotateB, rotateC, rotateD;
rotation = rotation % 360;
rotation = rotation < 0 ? rotation + 360 : rotation;
switch (rotation) {
case 180:
rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
break;
case 90:
rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
break;
case 270:
rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
break;
//case 0:
default:
rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
break;
}
if (dontFlip) {
rotateC = -rotateC; rotateD = -rotateD;
}
var offsetCanvasX, offsetCanvasY;
var width, height;
if (rotateA === 0) {
offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
width = Math.abs(viewBox[3] - viewBox[1]) * scale;
height = Math.abs(viewBox[2] - viewBox[0]) * scale;
} else {
offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
width = Math.abs(viewBox[2] - viewBox[0]) * scale;
height = Math.abs(viewBox[3] - viewBox[1]) * scale;
}
// creating transform for the following operations:
// translate(-centerX, -centerY), rotate and flip vertically,
// scale, and translate(offsetCanvasX, offsetCanvasY)
this.transform = [
rotateA * scale,
rotateB * scale,
rotateC * scale,
rotateD * scale,
offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
];
this.width = width;
this.height = height;
this.fontScale = scale;
}
PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
/**
* Clones viewport with additional properties.
* @param args {Object} (optional) If specified, may contain the 'scale' or
* 'rotation' properties to override the corresponding properties in
* the cloned viewport.
* @returns {PDFJS.PageViewport} Cloned viewport.
*/
clone: function PageViewPort_clone(args) {
args = args || {};
var scale = 'scale' in args ? args.scale : this.scale;
var rotation = 'rotation' in args ? args.rotation : this.rotation;
return new PageViewport(this.viewBox.slice(), scale, rotation,
this.offsetX, this.offsetY, args.dontFlip);
},
/**
* Converts PDF point to the viewport coordinates. For examples, useful for
* converting PDF location into canvas pixel coordinates.
* @param x {number} X coordinate.
* @param y {number} Y coordinate.
* @returns {Object} Object that contains 'x' and 'y' properties of the
* point in the viewport coordinate space.
* @see {@link convertToPdfPoint}
* @see {@link convertToViewportRectangle}
*/
convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
return Util.applyTransform([x, y], this.transform);
},
/**
* Converts PDF rectangle to the viewport coordinates.
* @param rect {Array} xMin, yMin, xMax and yMax coordinates.
* @returns {Array} Contains corresponding coordinates of the rectangle
* in the viewport coordinate space.
* @see {@link convertToViewportPoint}
*/
convertToViewportRectangle:
function PageViewport_convertToViewportRectangle(rect) {
var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
var br = Util.applyTransform([rect[2], rect[3]], this.transform);
return [tl[0], tl[1], br[0], br[1]];
},
/**
* Converts viewport coordinates to the PDF location. For examples, useful
* for converting canvas pixel location into PDF one.
* @param x {number} X coordinate.
* @param y {number} Y coordinate.
* @returns {Object} Object that contains 'x' and 'y' properties of the
* point in the PDF coordinate space.
* @see {@link convertToViewportPoint}
*/
convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
return Util.applyInverseTransform([x, y], this.transform);
}
};
return PageViewport;
})();
var PDFStringTranslateTable = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
];
function stringToPDFString(str) {
var i, n = str.length, strBuf = [];
if (str[0] === '\xFE' && str[1] === '\xFF') {
// UTF16BE BOM
for (i = 2; i < n; i += 2) {
strBuf.push(String.fromCharCode(
(str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
}
} else {
for (i = 0; i < n; ++i) {
var code = PDFStringTranslateTable[str.charCodeAt(i)];
strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
}
}
return strBuf.join('');
}
function stringToUTF8String(str) {
return decodeURIComponent(escape(str));
}
function isEmptyObj(obj) {
for (var key in obj) {
return false;
}
return true;
}
function isBool(v) {
return typeof v === 'boolean';
}
function isInt(v) {
return typeof v === 'number' && ((v | 0) === v);
}
function isNum(v) {
return typeof v === 'number';
}
function isString(v) {
return typeof v === 'string';
}
function isNull(v) {
return v === null;
}
function isName(v) {
return v instanceof Name;
}
function isCmd(v, cmd) {
return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
}
function isDict(v, type) {
if (!(v instanceof Dict)) {
return false;
}
if (!type) {
return true;
}
var dictType = v.get('Type');
return isName(dictType) && dictType.name === type;
}
function isArray(v) {
return v instanceof Array;
}
function isStream(v) {
return typeof v === 'object' && v !== null && v.getBytes !== undefined;
}
function isArrayBuffer(v) {
return typeof v === 'object' && v !== null && v.byteLength !== undefined;
}
function isRef(v) {
return v instanceof Ref;
}
/**
* Promise Capability object.
*
* @typedef {Object} PromiseCapability
* @property {Promise} promise - A promise object.
* @property {function} resolve - Fullfills the promise.
* @property {function} reject - Rejects the promise.
*/
/**
* Creates a promise capability object.
* @alias PDFJS.createPromiseCapability
*
* @return {PromiseCapability} A capability object contains:
* - a Promise, resolve and reject methods.
*/
function createPromiseCapability() {
var capability = {};
capability.promise = new Promise(function (resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
});
return capability;
}
PDFJS.createPromiseCapability = createPromiseCapability;
/**
* Polyfill for Promises:
* The following promise implementation tries to generally implement the
* Promise/A+ spec. Some notable differences from other promise libaries are:
* - There currently isn't a seperate deferred and promise object.
* - Unhandled rejections eventually show an error if they aren't handled.
*
* Based off of the work in:
* https://bugzilla.mozilla.org/show_bug.cgi?id=810490
*/
(function PromiseClosure() {
if (globalScope.Promise) {
// Promises existing in the DOM/Worker, checking presence of all/resolve
if (typeof globalScope.Promise.all !== 'function') {
globalScope.Promise.all = function (iterable) {
var count = 0, results = [], resolve, reject;
var promise = new globalScope.Promise(function (resolve_, reject_) {
resolve = resolve_;
reject = reject_;
});
iterable.forEach(function (p, i) {
count++;
p.then(function (result) {
results[i] = result;
count--;
if (count === 0) {
resolve(results);
}
}, reject);
});
if (count === 0) {
resolve(results);
}
return promise;
};
}
if (typeof globalScope.Promise.resolve !== 'function') {
globalScope.Promise.resolve = function (value) {
return new globalScope.Promise(function (resolve) { resolve(value); });
};
}
if (typeof globalScope.Promise.reject !== 'function') {
globalScope.Promise.reject = function (reason) {
return new globalScope.Promise(function (resolve, reject) {
reject(reason);
});
};
}
if (typeof globalScope.Promise.prototype.catch !== 'function') {
globalScope.Promise.prototype.catch = function (onReject) {
return globalScope.Promise.prototype.then(undefined, onReject);
};
}
return;
}
var STATUS_PENDING = 0;
var STATUS_RESOLVED = 1;
var STATUS_REJECTED = 2;
// In an attempt to avoid silent exceptions, unhandled rejections are
// tracked and if they aren't handled in a certain amount of time an
// error is logged.
var REJECTION_TIMEOUT = 500;
var HandlerManager = {
handlers: [],
running: false,
unhandledRejections: [],
pendingRejectionCheck: false,
scheduleHandlers: function scheduleHandlers(promise) {
if (promise._status === STATUS_PENDING) {
return;
}
this.handlers = this.handlers.concat(promise._handlers);
promise._handlers = [];
if (this.running) {
return;
}
this.running = true;
setTimeout(this.runHandlers.bind(this), 0);
},
runHandlers: function runHandlers() {
var RUN_TIMEOUT = 1; // ms
var timeoutAt = Date.now() + RUN_TIMEOUT;
while (this.handlers.length > 0) {
var handler = this.handlers.shift();
var nextStatus = handler.thisPromise._status;
var nextValue = handler.thisPromise._value;
try {
if (nextStatus === STATUS_RESOLVED) {
if (typeof handler.onResolve === 'function') {
nextValue = handler.onResolve(nextValue);
}
} else if (typeof handler.onReject === 'function') {
nextValue = handler.onReject(nextValue);
nextStatus = STATUS_RESOLVED;
if (handler.thisPromise._unhandledRejection) {
this.removeUnhandeledRejection(handler.thisPromise);
}
}
} catch (ex) {
nextStatus = STATUS_REJECTED;
nextValue = ex;
}
handler.nextPromise._updateStatus(nextStatus, nextValue);
if (Date.now() >= timeoutAt) {
break;
}
}
if (this.handlers.length > 0) {
setTimeout(this.runHandlers.bind(this), 0);
return;
}
this.running = false;
},
addUnhandledRejection: function addUnhandledRejection(promise) {
this.unhandledRejections.push({
promise: promise,
time: Date.now()
});
this.scheduleRejectionCheck();
},
removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
promise._unhandledRejection = false;
for (var i = 0; i < this.unhandledRejections.length; i++) {
if (this.unhandledRejections[i].promise === promise) {
this.unhandledRejections.splice(i);
i--;
}
}
},
scheduleRejectionCheck: function scheduleRejectionCheck() {
if (this.pendingRejectionCheck) {
return;
}
this.pendingRejectionCheck = true;
setTimeout(function rejectionCheck() {
this.pendingRejectionCheck = false;
var now = Date.now();
for (var i = 0; i < this.unhandledRejections.length; i++) {
if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
var unhandled = this.unhandledRejections[i].promise._value;
var msg = 'Unhandled rejection: ' + unhandled;
if (unhandled.stack) {
msg += '\n' + unhandled.stack;
}
warn(msg);
this.unhandledRejections.splice(i);
i--;
}
}
if (this.unhandledRejections.length) {
this.scheduleRejectionCheck();
}
}.bind(this), REJECTION_TIMEOUT);
}
};
function Promise(resolver) {
this._status = STATUS_PENDING;
this._handlers = [];
try {
resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
} catch (e) {
this._reject(e);
}
}
/**
* Builds a promise that is resolved when all the passed in promises are
* resolved.
* @param {array} array of data and/or promises to wait for.
* @return {Promise} New dependant promise.
*/
Promise.all = function Promise_all(promises) {
var resolveAll, rejectAll;
var deferred = new Promise(function (resolve, reject) {
resolveAll = resolve;
rejectAll = reject;
});
var unresolved = promises.length;
var results = [];
if (unresolved === 0) {
resolveAll(results);
return deferred;
}
function reject(reason) {
if (deferred._status === STATUS_REJECTED) {
return;
}
results = [];
rejectAll(reason);
}
for (var i = 0, ii = promises.length; i < ii; ++i) {
var promise = promises[i];
var resolve = (function(i) {
return function(value) {
if (deferred._status === STATUS_REJECTED) {
return;
}
results[i] = value;
unresolved--;
if (unresolved === 0) {
resolveAll(results);
}
};
})(i);
if (Promise.isPromise(promise)) {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
return deferred;
};
/**
* Checks if the value is likely a promise (has a 'then' function).
* @return {boolean} true if value is thenable
*/
Promise.isPromise = function Promise_isPromise(value) {
return value && typeof value.then === 'function';
};
/**
* Creates resolved promise
* @param value resolve value
* @returns {Promise}
*/
Promise.resolve = function Promise_resolve(value) {
return new Promise(function (resolve) { resolve(value); });
};
/**
* Creates rejected promise
* @param reason rejection value
* @returns {Promise}
*/
Promise.reject = function Promise_reject(reason) {
return new Promise(function (resolve, reject) { reject(reason); });
};
Promise.prototype = {
_status: null,
_value: null,
_handlers: null,
_unhandledRejection: null,
_updateStatus: function Promise__updateStatus(status, value) {
if (this._status === STATUS_RESOLVED ||
this._status === STATUS_REJECTED) {
return;
}
if (status === STATUS_RESOLVED &&
Promise.isPromise(value)) {
value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
this._updateStatus.bind(this, STATUS_REJECTED));
return;
}
this._status = status;
this._value = value;
if (status === STATUS_REJECTED && this._handlers.length === 0) {
this._unhandledRejection = true;
HandlerManager.addUnhandledRejection(this);
}
HandlerManager.scheduleHandlers(this);
},
_resolve: function Promise_resolve(value) {
this._updateStatus(STATUS_RESOLVED, value);
},
_reject: function Promise_reject(reason) {
this._updateStatus(STATUS_REJECTED, reason);
},
then: function Promise_then(onResolve, onReject) {
var nextPromise = new Promise(function (resolve, reject) {
this.resolve = resolve;
this.reject = reject;
});
this._handlers.push({
thisPromise: this,
onResolve: onResolve,
onReject: onReject,
nextPromise: nextPromise
});
HandlerManager.scheduleHandlers(this);
return nextPromise;
},
catch: function Promise_catch(onReject) {
return this.then(undefined, onReject);
}
};
globalScope.Promise = Promise;
})();
var StatTimer = (function StatTimerClosure() {
function rpad(str, pad, length) {
while (str.length < length) {
str += pad;
}
return str;
}
function StatTimer() {
this.started = {};
this.times = [];
this.enabled = true;
}
StatTimer.prototype = {
time: function StatTimer_time(name) {
if (!this.enabled) {
return;
}
if (name in this.started) {
warn('Timer is already running for ' + name);
}
this.started[name] = Date.now();
},
timeEnd: function StatTimer_timeEnd(name) {
if (!this.enabled) {
return;
}
if (!(name in this.started)) {
warn('Timer has not been started for ' + name);
}
this.times.push({
'name': name,
'start': this.started[name],
'end': Date.now()
});
// Remove timer from started so it can be called again.
delete this.started[name];
},
toString: function StatTimer_toString() {
var i, ii;
var times = this.times;
var out = '';
// Find the longest name for padding purposes.
var longest = 0;
for (i = 0, ii = times.length; i < ii; ++i) {
var name = times[i]['name'];
if (name.length > longest) {
longest = name.length;
}
}
for (i = 0, ii = times.length; i < ii; ++i) {
var span = times[i];
var duration = span.end - span.start;
out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
}
return out;
}
};
return StatTimer;
})();
PDFJS.createBlob = function createBlob(data, contentType) {
if (typeof Blob !== 'undefined') {
return new Blob([data], { type: contentType });
}
// Blob builder is deprecated in FF14 and removed in FF18.
var bb = new MozBlobBuilder();
bb.append(data);
return bb.getBlob(contentType);
};
PDFJS.createObjectURL = (function createObjectURLClosure() {
// Blob/createObjectURL is not available, falling back to data schema.
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
return function createObjectURL(data, contentType) {
if (!PDFJS.disableCreateObjectURL &&
typeof URL !== 'undefined' && URL.createObjectURL) {
var blob = PDFJS.createBlob(data, contentType);
return URL.createObjectURL(blob);
}
var buffer = 'data:' + contentType + ';base64,';
for (var i = 0, ii = data.length; i < ii; i += 3) {
var b1 = data[i] & 0xFF;
var b2 = data[i + 1] & 0xFF;
var b3 = data[i + 2] & 0xFF;
var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
}
return buffer;
};
})();
function MessageHandler(name, comObj) {
this.name = name;
this.comObj = comObj;
this.callbackIndex = 1;
this.postMessageTransfers = true;
var callbacksCapabilities = this.callbacksCapabilities = {};
var ah = this.actionHandler = {};
ah['console_log'] = [function ahConsoleLog(data) {
console.log.apply(console, data);
}];
ah['console_error'] = [function ahConsoleError(data) {
console.error.apply(console, data);
}];
ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
UnsupportedManager.notify(data);
}];
comObj.onmessage = function messageHandlerComObjOnMessage(event) {
var data = event.data;
if (data.isReply) {
var callbackId = data.callbackId;
if (data.callbackId in callbacksCapabilities) {
var callback = callbacksCapabilities[callbackId];
delete callbacksCapabilities[callbackId];
if ('error' in data) {
callback.reject(data.error);
} else {
callback.resolve(data.data);
}
} else {
error('Cannot resolve callback ' + callbackId);
}
} else if (data.action in ah) {
var action = ah[data.action];
if (data.callbackId) {
Promise.resolve().then(function () {
return action[0].call(action[1], data.data);
}).then(function (result) {
comObj.postMessage({
isReply: true,
callbackId: data.callbackId,
data: result
});
}, function (reason) {
comObj.postMessage({
isReply: true,
callbackId: data.callbackId,
error: reason
});
});
} else {
action[0].call(action[1], data.data);
}
} else {
error('Unknown action from worker: ' + data.action);
}
};
}
MessageHandler.prototype = {
on: function messageHandlerOn(actionName, handler, scope) {
var ah = this.actionHandler;
if (ah[actionName]) {
error('There is already an actionName called "' + actionName + '"');
}
ah[actionName] = [handler, scope];
},
/**
* Sends a message to the comObj to invoke the action with the supplied data.
* @param {String} actionName Action to call.
* @param {JSON} data JSON data to send.
* @param {Array} [transfers] Optional list of transfers/ArrayBuffers
*/
send: function messageHandlerSend(actionName, data, transfers) {
var message = {
action: actionName,
data: data
};
this.postMessage(message, transfers);
},
/**
* Sends a message to the comObj to invoke the action with the supplied data.
* Expects that other side will callback with the response.
* @param {String} actionName Action to call.
* @param {JSON} data JSON data to send.
* @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
* @returns {Promise} Promise to be resolved with response data.
*/
sendWithPromise:
function messageHandlerSendWithPromise(actionName, data, transfers) {
var callbackId = this.callbackIndex++;
var message = {
action: actionName,
data: data,
callbackId: callbackId
};
var capability = createPromiseCapability();
this.callbacksCapabilities[callbackId] = capability;
try {
this.postMessage(message, transfers);
} catch (e) {
capability.reject(e);
}
return capability.promise;
},
/**
* Sends raw message to the comObj.
* @private
* @param message {Object} Raw message.
* @param transfers List of transfers/ArrayBuffers, or undefined.
*/
postMessage: function (message, transfers) {
if (transfers && this.postMessageTransfers) {
this.comObj.postMessage(message, transfers);
} else {
this.comObj.postMessage(message);
}
}
};
function loadJpegStream(id, imageUrl, objs) {
var img = new Image();
img.onload = (function loadJpegStream_onloadClosure() {
objs.resolve(id, img);
});
img.onerror = (function loadJpegStream_onerrorClosure() {
objs.resolve(id, null);
warn('Error during JPEG image loading');
});
img.src = imageUrl;
}
/**
* The maximum allowed image size in total pixels e.g. width * height. Images
* above this value will not be drawn. Use -1 for no limit.
* @var {number}
*/
PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
-1 : PDFJS.maxImageSize);
/**
* The url of where the predefined Adobe CMaps are located. Include trailing
* slash.
* @var {string}
*/
PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
/**
* Specifies if CMaps are binary packed.
* @var {boolean}
*/
PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
/*
* By default fonts are converted to OpenType fonts and loaded via font face
* rules. If disabled, the font will be rendered using a built in font renderer
* that constructs the glyphs with primitive path commands.
* @var {boolean}
*/
PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
false : PDFJS.disableFontFace);
/**
* Path for image resources, mainly for annotation icons. Include trailing
* slash.
* @var {string}
*/
PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
'' : PDFJS.imageResourcesPath);
/**
* Disable the web worker and run all code on the main thread. This will happen
* automatically if the browser doesn't support workers or sending typed arrays
* to workers.
* @var {boolean}
*/
PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
false : PDFJS.disableWorker);
/**
* Path and filename of the worker file. Required when the worker is enabled in
* development mode. If unspecified in the production build, the worker will be
* loaded based on the location of the pdf.js file.
* @var {string}
*/
PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
/**
* Disable range request loading of PDF files. When enabled and if the server
* supports partial content requests then the PDF will be fetched in chunks.
* Enabled (false) by default.
* @var {boolean}
*/
PDFJS.disableRange = (PDFJS.disableRange === undefined ?
false : PDFJS.disableRange);
/**
* Disable streaming of PDF file data. By default PDF.js attempts to load PDF
* in chunks. This default behavior can be disabled.
* @var {boolean}
*/
PDFJS.disableStream = (PDFJS.disableStream === undefined ?
false : PDFJS.disableStream);
/**
* Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
* will automatically keep fetching more data even if it isn't needed to display
* the current page. This default behavior can be disabled.
* @var {boolean}
*/
PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
false : PDFJS.disableAutoFetch);
/**
* Enables special hooks for debugging PDF.js.
* @var {boolean}
*/
PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
/**
* Enables transfer usage in postMessage for ArrayBuffers.
* @var {boolean}
*/
PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
true : PDFJS.postMessageTransfers);
/**
* Disables URL.createObjectURL usage.
* @var {boolean}
*/
PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
false : PDFJS.disableCreateObjectURL);
/**
* Disables WebGL usage.
* @var {boolean}
*/
PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
true : PDFJS.disableWebGL);
/**
* Enables CSS only zooming.
* @var {boolean}
*/
PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
false : PDFJS.useOnlyCssZoom);
/**
* Controls the logging level.
* The constants from PDFJS.VERBOSITY_LEVELS should be used:
* - errors
* - warnings [default]
* - infos
* @var {number}
*/
PDFJS.verbosity = (PDFJS.verbosity === undefined ?
PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
/**
* The maximum supported canvas size in total pixels e.g. width * height.
* The default value is 4096 * 4096. Use -1 for no limit.
* @var {number}
*/
PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
16777216 : PDFJS.maxCanvasPixels);
/**
* Document initialization / loading parameters object.
*
* @typedef {Object} DocumentInitParameters
* @property {string} url - The URL of the PDF.
* @property {TypedArray} data - A typed array with PDF data.
* @property {Object} httpHeaders - Basic authentication headers.
* @property {boolean} withCredentials - Indicates whether or not cross-site
* Access-Control requests should be made using credentials such as cookies
* or authorization headers. The default is false.
* @property {string} password - For decrypting password-protected PDFs.
* @property {TypedArray} initialData - A typed array with the first portion or
* all of the pdf data. Used by the extension since some data is already
* loaded before the switch to range requests.
*/
/**
* @typedef {Object} PDFDocumentStats
* @property {Array} streamTypes - Used stream types in the document (an item
* is set to true if specific stream ID was used in the document).
* @property {Array} fontTypes - Used font type in the document (an item is set
* to true if specific font ID was used in the document).
*/
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedArray|DocumentInitParameters} source Can be a url to
* where a PDF is located, a typed array (Uint8Array) already populated with
* data or parameter object.
*
* @param {Object} pdfDataRangeTransport is optional. It is used if you want
* to manually serve range requests for data in the PDF. See viewer.js for
* an example of pdfDataRangeTransport's interface.
*
* @param {function} passwordCallback is optional. It is used to request a
* password if wrong or no password was provided. The callback receives two
* parameters: function that needs to be called with new password and reason
* (see {PasswordResponses}).
*
* @param {function} progressCallback is optional. It is used to be able to
* monitor the loading progress of the PDF file (necessary to implement e.g.
* a loading bar). The callback receives an {Object} with the properties:
* {number} loaded and {number} total.
*
* @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}
* object.
*/
PDFJS.getDocument = function getDocument(source,
pdfDataRangeTransport,
passwordCallback,
progressCallback) {
var workerInitializedCapability, workerReadyCapability, transport;
if (typeof source === 'string') {
source = { url: source };
} else if (isArrayBuffer(source)) {
source = { data: source };
} else if (typeof source !== 'object') {
error('Invalid parameter in getDocument, need either Uint8Array, ' +
'string or a parameter object');
}
if (!source.url && !source.data) {
error('Invalid parameter array, need either .data or .url');
}
// copy/use all keys as is except 'url' -- full path is required
var params = {};
for (var key in source) {
if (key === 'url' && typeof window !== 'undefined') {
params[key] = combineUrl(window.location.href, source[key]);
continue;
}
params[key] = source[key];
}
workerInitializedCapability = createPromiseCapability();
workerReadyCapability = createPromiseCapability();
transport = new WorkerTransport(workerInitializedCapability,
workerReadyCapability, pdfDataRangeTransport,
progressCallback);
workerInitializedCapability.promise.then(function transportInitialized() {
transport.passwordCallback = passwordCallback;
transport.fetchDocument(params);
});
return workerReadyCapability.promise;
};
/**
* Proxy to a PDFDocument in the worker thread. Also, contains commonly used
* properties that can be read synchronously.
* @class
*/
var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
function PDFDocumentProxy(pdfInfo, transport) {
this.pdfInfo = pdfInfo;
this.transport = transport;
}
PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
/**
* @return {number} Total number of pages the PDF contains.
*/
get numPages() {
return this.pdfInfo.numPages;
},
/**
* @return {string} A unique ID to identify a PDF. Not guaranteed to be
* unique.
*/
get fingerprint() {
return this.pdfInfo.fingerprint;
},
/**
* @param {number} pageNumber The page number to get. The first page is 1.
* @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
* object.
*/
getPage: function PDFDocumentProxy_getPage(pageNumber) {
return this.transport.getPage(pageNumber);
},
/**
* @param {{num: number, gen: number}} ref The page reference. Must have
* the 'num' and 'gen' properties.
* @return {Promise} A promise that is resolved with the page index that is
* associated with the reference.
*/
getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
return this.transport.getPageIndex(ref);
},
/**
* @return {Promise} A promise that is resolved with a lookup table for
* mapping named destinations to reference numbers.
*
* This can be slow for large documents: use getDestination instead
*/
getDestinations: function PDFDocumentProxy_getDestinations() {
return this.transport.getDestinations();
},
/**
* @param {string} id The named destination to get.
* @return {Promise} A promise that is resolved with all information
* of the given named destination.
*/
getDestination: function PDFDocumentProxy_getDestination(id) {
return this.transport.getDestination(id);
},
/**
* @return {Promise} A promise that is resolved with a lookup table for
* mapping named attachments to their content.
*/
getAttachments: function PDFDocumentProxy_getAttachments() {
return this.transport.getAttachments();
},
/**
* @return {Promise} A promise that is resolved with an array of all the
* JavaScript strings in the name tree.
*/
getJavaScript: function PDFDocumentProxy_getJavaScript() {
return this.transport.getJavaScript();
},
/**
* @return {Promise} A promise that is resolved with an {Array} that is a
* tree outline (if it has one) of the PDF. The tree is in the format of:
* [
* {
* title: string,
* bold: boolean,
* italic: boolean,
* color: rgb array,
* dest: dest obj,
* items: array of more items like this
* },
* ...
* ].
*/
getOutline: function PDFDocumentProxy_getOutline() {
return this.transport.getOutline();
},
/**
* @return {Promise} A promise that is resolved with an {Object} that has
* info and metadata properties. Info is an {Object} filled with anything
* available in the information dictionary and similarly metadata is a
* {Metadata} object with information from the metadata section of the PDF.
*/
getMetadata: function PDFDocumentProxy_getMetadata() {
return this.transport.getMetadata();
},
/**
* @return {Promise} A promise that is resolved with a TypedArray that has
* the raw data from the PDF.
*/
getData: function PDFDocumentProxy_getData() {
return this.transport.getData();
},
/**
* @return {Promise} A promise that is resolved when the document's data
* is loaded. It is resolved with an {Object} that contains the length
* property that indicates size of the PDF data in bytes.
*/
getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
return this.transport.downloadInfoCapability.promise;
},
/**
* @returns {Promise} A promise this is resolved with current stats about
* document structures (see {@link PDFDocumentStats}).
*/
getStats: function PDFDocumentProxy_getStats() {
return this.transport.getStats();
},
/**
* Cleans up resources allocated by the document, e.g. created @font-face.
*/
cleanup: function PDFDocumentProxy_cleanup() {
this.transport.startCleanup();
},
/**
* Destroys current document instance and terminates worker.
*/
destroy: function PDFDocumentProxy_destroy() {
this.transport.destroy();
}
};
return PDFDocumentProxy;
})();
/**
* Page text content.
*
* @typedef {Object} TextContent
* @property {array} items - array of {@link TextItem}
* @property {Object} styles - {@link TextStyles} objects, indexed by font
* name.
*/
/**
* Page text content part.
*
* @typedef {Object} TextItem
* @property {string} str - text content.
* @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
* @property {array} transform - transformation matrix.
* @property {number} width - width in device space.
* @property {number} height - height in device space.
* @property {string} fontName - font name used by pdf.js for converted font.
*/
/**
* Text style.
*
* @typedef {Object} TextStyle
* @property {number} ascent - font ascent.
* @property {number} descent - font descent.
* @property {boolean} vertical - text is in vertical mode.
* @property {string} fontFamily - possible font family
*/
/**
* Page render parameters.
*
* @typedef {Object} RenderParameters
* @property {Object} canvasContext - A 2D context of a DOM Canvas object.
* @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
* calling of PDFPage.getViewport method.
* @property {string} intent - Rendering intent, can be 'display' or 'print'
* (default value is 'display').
* @property {Object} imageLayer - (optional) An object that has beginLayout,
* endLayout and appendImage functions.
* @property {function} continueCallback - (optional) A function that will be
* called each time the rendering is paused. To continue
* rendering call the function that is the first argument
* to the callback.
*/
/**
* PDF page operator list.
*
* @typedef {Object} PDFOperatorList
* @property {Array} fnArray - Array containing the operator functions.
* @property {Array} argsArray - Array containing the arguments of the
* functions.
*/
/**
* Proxy to a PDFPage in the worker thread.
* @class
*/
var PDFPageProxy = (function PDFPageProxyClosure() {
function PDFPageProxy(pageIndex, pageInfo, transport) {
this.pageIndex = pageIndex;
this.pageInfo = pageInfo;
this.transport = transport;
this.stats = new StatTimer();
this.stats.enabled = !!globalScope.PDFJS.enableStats;
this.commonObjs = transport.commonObjs;
this.objs = new PDFObjects();
this.cleanupAfterRender = false;
this.pendingDestroy = false;
this.intentStates = {};
}
PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
/**
* @return {number} Page number of the page. First page is 1.
*/
get pageNumber() {
return this.pageIndex + 1;
},
/**
* @return {number} The number of degrees the page is rotated clockwise.
*/
get rotate() {
return this.pageInfo.rotate;
},
/**
* @return {Object} The reference that points to this page. It has 'num' and
* 'gen' properties.
*/
get ref() {
return this.pageInfo.ref;
},
/**
* @return {Array} An array of the visible portion of the PDF page in the
* user space units - [x1, y1, x2, y2].
*/
get view() {
return this.pageInfo.view;
},
/**
* @param {number} scale The desired scale of the viewport.
* @param {number} rotate Degrees to rotate the viewport. If omitted this
* defaults to the page rotation.
* @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
* along with transforms required for rendering.
*/
getViewport: function PDFPageProxy_getViewport(scale, rotate) {
if (arguments.length < 2) {
rotate = this.rotate;
}
return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
},
/**
* @return {Promise} A promise that is resolved with an {Array} of the
* annotation objects.
*/
getAnnotations: function PDFPageProxy_getAnnotations() {
if (this.annotationsPromise) {
return this.annotationsPromise;
}
var promise = this.transport.getAnnotations(this.pageIndex);
this.annotationsPromise = promise;
return promise;
},
/**
* Begins the process of rendering a page to the desired context.
* @param {RenderParameters} params Page render parameters.
* @return {RenderTask} An object that contains the promise, which
* is resolved when the page finishes rendering.
*/
render: function PDFPageProxy_render(params) {
var stats = this.stats;
stats.time('Overall');
// If there was a pending destroy cancel it so no cleanup happens during
// this call to render.
this.pendingDestroy = false;
var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = {};
}
var intentState = this.intentStates[renderingIntent];
// If there's no displayReadyCapability yet, then the operatorList
// was never requested before. Make the request and create the promise.
if (!intentState.displayReadyCapability) {
intentState.receivingOperatorList = true;
intentState.displayReadyCapability = createPromiseCapability();
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false
};
this.stats.time('Page Request');
this.transport.messageHandler.send('RenderPageRequest', {
pageIndex: this.pageNumber - 1,
intent: renderingIntent
});
}
var internalRenderTask = new InternalRenderTask(complete, params,
this.objs,
this.commonObjs,
intentState.operatorList,
this.pageNumber);
if (!intentState.renderTasks) {
intentState.renderTasks = [];
}
intentState.renderTasks.push(internalRenderTask);
var renderTask = new RenderTask(internalRenderTask);
var self = this;
intentState.displayReadyCapability.promise.then(
function pageDisplayReadyPromise(transparency) {
if (self.pendingDestroy) {
complete();
return;
}
stats.time('Rendering');
internalRenderTask.initalizeGraphics(transparency);
internalRenderTask.operatorListChanged();
},
function pageDisplayReadPromiseError(reason) {
complete(reason);
}
);
function complete(error) {
var i = intentState.renderTasks.indexOf(internalRenderTask);
if (i >= 0) {
intentState.renderTasks.splice(i, 1);
}
if (self.cleanupAfterRender) {
self.pendingDestroy = true;
}
self._tryDestroy();
if (error) {
internalRenderTask.capability.reject(error);
} else {
internalRenderTask.capability.resolve();
}
stats.timeEnd('Rendering');
stats.timeEnd('Overall');
}
return renderTask;
},
/**
* @return {Promise} A promise resolved with an {@link PDFOperatorList}
* object that represents page's operator list.
*/
getOperatorList: function PDFPageProxy_getOperatorList() {
function operatorListChanged() {
if (intentState.operatorList.lastChunk) {
intentState.opListReadCapability.resolve(intentState.operatorList);
}
}
var renderingIntent = 'oplist';
if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = {};
}
var intentState = this.intentStates[renderingIntent];
if (!intentState.opListReadCapability) {
var opListTask = {};
opListTask.operatorListChanged = operatorListChanged;
intentState.receivingOperatorList = true;
intentState.opListReadCapability = createPromiseCapability();
intentState.renderTasks = [];
intentState.renderTasks.push(opListTask);
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false
};
this.transport.messageHandler.send('RenderPageRequest', {
pageIndex: this.pageIndex,
intent: renderingIntent
});
}
return intentState.opListReadCapability.promise;
},
/**
* @return {Promise} That is resolved a {@link TextContent}
* object that represent the page text content.
*/
getTextContent: function PDFPageProxy_getTextContent() {
return this.transport.messageHandler.sendWithPromise('GetTextContent', {
pageIndex: this.pageNumber - 1
});
},
/**
* Destroys resources allocated by the page.
*/
destroy: function PDFPageProxy_destroy() {
this.pendingDestroy = true;
this._tryDestroy();
},
/**
* For internal use only. Attempts to clean up if rendering is in a state
* where that's possible.
* @ignore
*/
_tryDestroy: function PDFPageProxy__destroy() {
if (!this.pendingDestroy ||
Object.keys(this.intentStates).some(function(intent) {
var intentState = this.intentStates[intent];
return (intentState.renderTasks.length !== 0 ||
intentState.receivingOperatorList);
}, this)) {
return;
}
Object.keys(this.intentStates).forEach(function(intent) {
delete this.intentStates[intent];
}, this);
this.objs.clear();
this.annotationsPromise = null;
this.pendingDestroy = false;
},
/**
* For internal use only.
* @ignore
*/
_startRenderPage: function PDFPageProxy_startRenderPage(transparency,
intent) {
var intentState = this.intentStates[intent];
// TODO Refactor RenderPageRequest to separate rendering
// and operator list logic
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.resolve(transparency);
}
},
/**
* For internal use only.
* @ignore
*/
_renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
intent) {
var intentState = this.intentStates[intent];
var i, ii;
// Add the new chunk to the current operator list.
for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
intentState.operatorList.argsArray.push(
operatorListChunk.argsArray[i]);
}
intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
// Notify all the rendering tasks there are more operators to be consumed.
for (i = 0; i < intentState.renderTasks.length; i++) {
intentState.renderTasks[i].operatorListChanged();
}
if (operatorListChunk.lastChunk) {
intentState.receivingOperatorList = false;
this._tryDestroy();
}
}
};
return PDFPageProxy;
})();
/**
* For internal use only.
* @ignore
*/
var WorkerTransport = (function WorkerTransportClosure() {
function WorkerTransport(workerInitializedCapability, workerReadyCapability,
pdfDataRangeTransport, progressCallback) {
this.pdfDataRangeTransport = pdfDataRangeTransport;
this.workerInitializedCapability = workerInitializedCapability;
this.workerReadyCapability = workerReadyCapability;
this.progressCallback = progressCallback;
this.commonObjs = new PDFObjects();
this.pageCache = [];
this.pagePromises = [];
this.downloadInfoCapability = createPromiseCapability();
this.passwordCallback = null;
// If worker support isn't disabled explicit and the browser has worker
// support, create a new web worker and test if it/the browser fullfills
// all requirements to run parts of pdf.js in a web worker.
// Right now, the requirement is, that an Uint8Array is still an Uint8Array
// as it arrives on the worker. Chrome added this with version 15.
if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
var workerSrc = PDFJS.workerSrc;
if (!workerSrc) {
error('No PDFJS.workerSrc specified');
}
try {
// Some versions of FF can't create a worker on localhost, see:
// https://bugzilla.mozilla.org/show_bug.cgi?id=683280
var worker = new Worker(workerSrc);
var messageHandler = new MessageHandler('main', worker);
this.messageHandler = messageHandler;
messageHandler.on('test', function transportTest(data) {
var supportTypedArray = data && data.supportTypedArray;
if (supportTypedArray) {
this.worker = worker;
if (!data.supportTransfers) {
PDFJS.postMessageTransfers = false;
}
this.setupMessageHandler(messageHandler);
workerInitializedCapability.resolve();
} else {
this.setupFakeWorker();
}
}.bind(this));
var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
// Some versions of Opera throw a DATA_CLONE_ERR on serializing the
// typed array. Also, checking if we can use transfers.
try {
messageHandler.send('test', testObj, [testObj.buffer]);
} catch (ex) {
info('Cannot use postMessage transfers');
testObj[0] = 0;
messageHandler.send('test', testObj);
}
return;
} catch (e) {
info('The worker has been disabled.');
}
}
// Either workers are disabled, not supported or have thrown an exception.
// Thus, we fallback to a faked worker.
this.setupFakeWorker();
}
WorkerTransport.prototype = {
destroy: function WorkerTransport_destroy() {
this.pageCache = [];
this.pagePromises = [];
var self = this;
this.messageHandler.sendWithPromise('Terminate', null).then(function () {
FontLoader.clear();
if (self.worker) {
self.worker.terminate();
}
});
},
setupFakeWorker: function WorkerTransport_setupFakeWorker() {
globalScope.PDFJS.disableWorker = true;
if (!PDFJS.fakeWorkerFilesLoadedCapability) {
PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
// In the developer build load worker_loader which in turn loads all the
// other files and resolves the promise. In production only the
// pdf.worker.js file is needed.
Util.loadScript(PDFJS.workerSrc, function() {
PDFJS.fakeWorkerFilesLoadedCapability.resolve();
});
}
PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
warn('Setting up fake worker.');
// If we don't use a worker, just post/sendMessage to the main thread.
var fakeWorker = {
postMessage: function WorkerTransport_postMessage(obj) {
fakeWorker.onmessage({data: obj});
},
terminate: function WorkerTransport_terminate() {}
};
var messageHandler = new MessageHandler('main', fakeWorker);
this.setupMessageHandler(messageHandler);
// If the main thread is our worker, setup the handling for the messages
// the main thread sends to it self.
PDFJS.WorkerMessageHandler.setup(messageHandler);
this.workerInitializedCapability.resolve();
}.bind(this));
},
setupMessageHandler:
function WorkerTransport_setupMessageHandler(messageHandler) {
this.messageHandler = messageHandler;
function updatePassword(password) {
messageHandler.send('UpdatePassword', password);
}
var pdfDataRangeTransport = this.pdfDataRangeTransport;
if (pdfDataRangeTransport) {
pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
messageHandler.send('OnDataRange', {
begin: begin,
chunk: chunk
});
});
pdfDataRangeTransport.addProgressListener(function(loaded) {
messageHandler.send('OnDataProgress', {
loaded: loaded
});
});
pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
messageHandler.send('OnDataRange', {
chunk: chunk
});
});
messageHandler.on('RequestDataRange',
function transportDataRange(data) {
pdfDataRangeTransport.requestDataRange(data.begin, data.end);
}, this);
}
messageHandler.on('GetDoc', function transportDoc(data) {
var pdfInfo = data.pdfInfo;
this.numPages = data.pdfInfo.numPages;
var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
this.pdfDocument = pdfDocument;
this.workerReadyCapability.resolve(pdfDocument);
}, this);
messageHandler.on('NeedPassword',
function transportNeedPassword(exception) {
if (this.passwordCallback) {
return this.passwordCallback(updatePassword,
PasswordResponses.NEED_PASSWORD);
}
this.workerReadyCapability.reject(
new PasswordException(exception.message, exception.code));
}, this);
messageHandler.on('IncorrectPassword',
function transportIncorrectPassword(exception) {
if (this.passwordCallback) {
return this.passwordCallback(updatePassword,
PasswordResponses.INCORRECT_PASSWORD);
}
this.workerReadyCapability.reject(
new PasswordException(exception.message, exception.code));
}, this);
messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
this.workerReadyCapability.reject(
new InvalidPDFException(exception.message));
}, this);
messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
this.workerReadyCapability.reject(
new MissingPDFException(exception.message));
}, this);
messageHandler.on('UnexpectedResponse',
function transportUnexpectedResponse(exception) {
this.workerReadyCapability.reject(
new UnexpectedResponseException(exception.message, exception.status));
}, this);
messageHandler.on('UnknownError',
function transportUnknownError(exception) {
this.workerReadyCapability.reject(
new UnknownErrorException(exception.message, exception.details));
}, this);
messageHandler.on('DataLoaded', function transportPage(data) {
this.downloadInfoCapability.resolve(data);
}, this);
messageHandler.on('PDFManagerReady', function transportPage(data) {
if (this.pdfDataRangeTransport) {
this.pdfDataRangeTransport.transportReady();
}
}, this);
messageHandler.on('StartRenderPage', function transportRender(data) {
var page = this.pageCache[data.pageIndex];
page.stats.timeEnd('Page Request');
page._startRenderPage(data.transparency, data.intent);
}, this);
messageHandler.on('RenderPageChunk', function transportRender(data) {
var page = this.pageCache[data.pageIndex];
page._renderPageChunk(data.operatorList, data.intent);
}, this);
messageHandler.on('commonobj', function transportObj(data) {
var id = data[0];
var type = data[1];
if (this.commonObjs.hasData(id)) {
return;
}
switch (type) {
case 'Font':
var exportedData = data[2];
var font;
if ('error' in exportedData) {
var error = exportedData.error;
warn('Error during font loading: ' + error);
this.commonObjs.resolve(id, error);
break;
} else {
font = new FontFaceObject(exportedData);
}
FontLoader.bind(
[font],
function fontReady(fontObjs) {
this.commonObjs.resolve(id, font);
}.bind(this)
);
break;
case 'FontPath':
this.commonObjs.resolve(id, data[2]);
break;
default:
error('Got unknown common object type ' + type);
}
}, this);
messageHandler.on('obj', function transportObj(data) {
var id = data[0];
var pageIndex = data[1];
var type = data[2];
var pageProxy = this.pageCache[pageIndex];
var imageData;
if (pageProxy.objs.hasData(id)) {
return;
}
switch (type) {
case 'JpegStream':
imageData = data[3];
loadJpegStream(id, imageData, pageProxy.objs);
break;
case 'Image':
imageData = data[3];
pageProxy.objs.resolve(id, imageData);
// heuristics that will allow not to store large data
var MAX_IMAGE_SIZE_TO_STORE = 8000000;
if (imageData && 'data' in imageData &&
imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
pageProxy.cleanupAfterRender = true;
}
break;
default:
error('Got unknown object type ' + type);
}
}, this);
messageHandler.on('DocProgress', function transportDocProgress(data) {
if (this.progressCallback) {
this.progressCallback({
loaded: data.loaded,
total: data.total
});
}
}, this);
messageHandler.on('PageError', function transportError(data) {
var page = this.pageCache[data.pageNum - 1];
var intentState = page.intentStates[data.intent];
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.reject(data.error);
} else {
error(data.error);
}
}, this);
messageHandler.on('JpegDecode', function(data) {
var imageUrl = data[0];
var components = data[1];
if (components !== 3 && components !== 1) {
return Promise.reject(
new Error('Only 3 components or 1 component can be returned'));
}
return new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () {
var width = img.width;
var height = img.height;
var size = width * height;
var rgbaLength = size * 4;
var buf = new Uint8Array(size * components);
var tmpCanvas = createScratchCanvas(width, height);
var tmpCtx = tmpCanvas.getContext('2d');
tmpCtx.drawImage(img, 0, 0);
var data = tmpCtx.getImageData(0, 0, width, height).data;
var i, j;
if (components === 3) {
for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
buf[j] = data[i];
buf[j + 1] = data[i + 1];
buf[j + 2] = data[i + 2];
}
} else if (components === 1) {
for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
buf[j] = data[i];
}
}
resolve({ data: buf, width: width, height: height});
};
img.onerror = function () {
reject(new Error('JpegDecode failed to load image'));
};
img.src = imageUrl;
});
});
},
fetchDocument: function WorkerTransport_fetchDocument(source) {
source.disableAutoFetch = PDFJS.disableAutoFetch;
source.disableStream = PDFJS.disableStream;
source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
this.messageHandler.send('GetDocRequest', {
source: source,
disableRange: PDFJS.disableRange,
maxImageSize: PDFJS.maxImageSize,
cMapUrl: PDFJS.cMapUrl,
cMapPacked: PDFJS.cMapPacked,
disableFontFace: PDFJS.disableFontFace,
disableCreateObjectURL: PDFJS.disableCreateObjectURL,
verbosity: PDFJS.verbosity
});
},
getData: function WorkerTransport_getData() {
return this.messageHandler.sendWithPromise('GetData', null);
},
getPage: function WorkerTransport_getPage(pageNumber, capability) {
if (pageNumber <= 0 || pageNumber > this.numPages ||
(pageNumber|0) !== pageNumber) {
return Promise.reject(new Error('Invalid page request'));
}
var pageIndex = pageNumber - 1;
if (pageIndex in this.pagePromises) {
return this.pagePromises[pageIndex];
}
var promise = this.messageHandler.sendWithPromise('GetPage', {
pageIndex: pageIndex
}).then(function (pageInfo) {
var page = new PDFPageProxy(pageIndex, pageInfo, this);
this.pageCache[pageIndex] = page;
return page;
}.bind(this));
this.pagePromises[pageIndex] = promise;
return promise;
},
getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
},
getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
return this.messageHandler.sendWithPromise('GetAnnotations',
{ pageIndex: pageIndex });
},
getDestinations: function WorkerTransport_getDestinations() {
return this.messageHandler.sendWithPromise('GetDestinations', null);
},
getDestination: function WorkerTransport_getDestination(id) {
return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
},
getAttachments: function WorkerTransport_getAttachments() {
return this.messageHandler.sendWithPromise('GetAttachments', null);
},
getJavaScript: function WorkerTransport_getJavaScript() {
return this.messageHandler.sendWithPromise('GetJavaScript', null);
},
getOutline: function WorkerTransport_getOutline() {
return this.messageHandler.sendWithPromise('GetOutline', null);
},
getMetadata: function WorkerTransport_getMetadata() {
return this.messageHandler.sendWithPromise('GetMetadata', null).
then(function transportMetadata(results) {
return {
info: results[0],
metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
};
});
},
getStats: function WorkerTransport_getStats() {
return this.messageHandler.sendWithPromise('GetStats', null);
},
startCleanup: function WorkerTransport_startCleanup() {
this.messageHandler.sendWithPromise('Cleanup', null).
then(function endCleanup() {
for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
var page = this.pageCache[i];
if (page) {
page.destroy();
}
}
this.commonObjs.clear();
FontLoader.clear();
}.bind(this));
}
};
return WorkerTransport;
})();
/**
* A PDF document and page is built of many objects. E.g. there are objects
* for fonts, images, rendering code and such. These objects might get processed
* inside of a worker. The `PDFObjects` implements some basic functions to
* manage these objects.
* @ignore
*/
var PDFObjects = (function PDFObjectsClosure() {
function PDFObjects() {
this.objs = {};
}
PDFObjects.prototype = {
/**
* Internal function.
* Ensures there is an object defined for `objId`.
*/
ensureObj: function PDFObjects_ensureObj(objId) {
if (this.objs[objId]) {
return this.objs[objId];
}
var obj = {
capability: createPromiseCapability(),
data: null,
resolved: false
};
this.objs[objId] = obj;
return obj;
},
/**
* If called *without* callback, this returns the data of `objId` but the
* object needs to be resolved. If it isn't, this function throws.
*
* If called *with* a callback, the callback is called with the data of the
* object once the object is resolved. That means, if you call this
* function and the object is already resolved, the callback gets called
* right away.
*/
get: function PDFObjects_get(objId, callback) {
// If there is a callback, then the get can be async and the object is
// not required to be resolved right now
if (callback) {
this.ensureObj(objId).capability.promise.then(callback);
return null;
}
// If there isn't a callback, the user expects to get the resolved data
// directly.
var obj = this.objs[objId];
// If there isn't an object yet or the object isn't resolved, then the
// data isn't ready yet!
if (!obj || !obj.resolved) {
error('Requesting object that isn\'t resolved yet ' + objId);
}
return obj.data;
},
/**
* Resolves the object `objId` with optional `data`.
*/
resolve: function PDFObjects_resolve(objId, data) {
var obj = this.ensureObj(objId);
obj.resolved = true;
obj.data = data;
obj.capability.resolve(data);
},
isResolved: function PDFObjects_isResolved(objId) {
var objs = this.objs;
if (!objs[objId]) {
return false;
} else {
return objs[objId].resolved;
}
},
hasData: function PDFObjects_hasData(objId) {
return this.isResolved(objId);
},
/**
* Returns the data of `objId` if object exists, null otherwise.
*/
getData: function PDFObjects_getData(objId) {
var objs = this.objs;
if (!objs[objId] || !objs[objId].resolved) {
return null;
} else {
return objs[objId].data;
}
},
clear: function PDFObjects_clear() {
this.objs = {};
}
};
return PDFObjects;
})();
/**
* Allows controlling of the rendering tasks.
* @class
*/
var RenderTask = (function RenderTaskClosure() {
function RenderTask(internalRenderTask) {
this.internalRenderTask = internalRenderTask;
/**
* Promise for rendering task completion.
* @type {Promise}
*/
this.promise = this.internalRenderTask.capability.promise;
}
RenderTask.prototype = /** @lends RenderTask.prototype */ {
/**
* Cancels the rendering task. If the task is currently rendering it will
* not be cancelled until graphics pauses with a timeout. The promise that
* this object extends will resolved when cancelled.
*/
cancel: function RenderTask_cancel() {
this.internalRenderTask.cancel();
},
/**
* Registers callback to indicate the rendering task completion.
*
* @param {function} onFulfilled The callback for the rendering completion.
* @param {function} onRejected The callback for the rendering failure.
* @return {Promise} A promise that is resolved after the onFulfilled or
* onRejected callback.
*/
then: function RenderTask_then(onFulfilled, onRejected) {
return this.promise.then(onFulfilled, onRejected);
}
};
return RenderTask;
})();
/**
* For internal use only.
* @ignore
*/
var InternalRenderTask = (function InternalRenderTaskClosure() {
function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
pageNumber) {
this.callback = callback;
this.params = params;
this.objs = objs;
this.commonObjs = commonObjs;
this.operatorListIdx = null;
this.operatorList = operatorList;
this.pageNumber = pageNumber;
this.running = false;
this.graphicsReadyCallback = null;
this.graphicsReady = false;
this.cancelled = false;
this.capability = createPromiseCapability();
// caching this-bound methods
this._continueBound = this._continue.bind(this);
this._scheduleNextBound = this._scheduleNext.bind(this);
this._nextBound = this._next.bind(this);
}
InternalRenderTask.prototype = {
initalizeGraphics:
function InternalRenderTask_initalizeGraphics(transparency) {
if (this.cancelled) {
return;
}
if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
globalScope.StepperManager.enabled) {
this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
this.stepper.init(this.operatorList);
this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
}
var params = this.params;
this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
this.objs, params.imageLayer);
this.gfx.beginDrawing(params.viewport, transparency);
this.operatorListIdx = 0;
this.graphicsReady = true;
if (this.graphicsReadyCallback) {
this.graphicsReadyCallback();
}
},
cancel: function InternalRenderTask_cancel() {
this.running = false;
this.cancelled = true;
this.callback('cancelled');
},
operatorListChanged: function InternalRenderTask_operatorListChanged() {
if (!this.graphicsReady) {
if (!this.graphicsReadyCallback) {
this.graphicsReadyCallback = this._continueBound;
}
return;
}
if (this.stepper) {
this.stepper.updateOperatorList(this.operatorList);
}
if (this.running) {
return;
}
this._continue();
},
_continue: function InternalRenderTask__continue() {
this.running = true;
if (this.cancelled) {
return;
}
if (this.params.continueCallback) {
this.params.continueCallback(this._scheduleNextBound);
} else {
this._scheduleNext();
}
},
_scheduleNext: function InternalRenderTask__scheduleNext() {
window.requestAnimationFrame(this._nextBound);
},
_next: function InternalRenderTask__next() {
if (this.cancelled) {
return;
}
this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
this.operatorListIdx,
this._continueBound,
this.stepper);
if (this.operatorListIdx === this.operatorList.argsArray.length) {
this.running = false;
if (this.operatorList.lastChunk) {
this.gfx.endDrawing();
this.callback();
}
}
}
};
return InternalRenderTask;
})();
var Metadata = PDFJS.Metadata = (function MetadataClosure() {
function fixMetadata(meta) {
return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
function(code, d1, d2, d3) {
return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
});
var chars = '';
for (var i = 0; i < bytes.length; i += 2) {
var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
code !== 38 && false ? String.fromCharCode(code) :
'&#x' + (0x10000 + code).toString(16).substring(1) + ';';
}
return '>' + chars;
});
}
function Metadata(meta) {
if (typeof meta === 'string') {
// Ghostscript produces invalid metadata
meta = fixMetadata(meta);
var parser = new DOMParser();
meta = parser.parseFromString(meta, 'application/xml');
} else if (!(meta instanceof Document)) {
error('Metadata: Invalid metadata object');
}
this.metaDocument = meta;
this.metadata = {};
this.parse();
}
Metadata.prototype = {
parse: function Metadata_parse() {
var doc = this.metaDocument;
var rdf = doc.documentElement;
if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
rdf = rdf.firstChild;
while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
rdf = rdf.nextSibling;
}
}
var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
return;
}
var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
for (i = 0, length = children.length; i < length; i++) {
desc = children[i];
if (desc.nodeName.toLowerCase() !== 'rdf:description') {
continue;
}
for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
entry = desc.childNodes[ii];
name = entry.nodeName.toLowerCase();
this.metadata[name] = entry.textContent.trim();
}
}
}
},
get: function Metadata_get(name) {
return this.metadata[name] || null;
},
has: function Metadata_has(name) {
return typeof this.metadata[name] !== 'undefined';
}
};
return Metadata;
})();
// <canvas> contexts store most of the state we need natively.
// However, PDF needs a bit more state, which we store here.
// Minimal font size that would be used during canvas fillText operations.
var MIN_FONT_SIZE = 16;
// Maximum font size that would be used during canvas fillText operations.
var MAX_FONT_SIZE = 100;
var MAX_GROUP_SIZE = 4096;
var COMPILE_TYPE3_GLYPHS = true;
function createScratchCanvas(width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
function addContextCurrentTransform(ctx) {
// If the context doesn't expose a `mozCurrentTransform`, add a JS based on.
if (!ctx.mozCurrentTransform) {
// Store the original context
ctx._scaleX = ctx._scaleX || 1.0;
ctx._scaleY = ctx._scaleY || 1.0;
ctx._originalSave = ctx.save;
ctx._originalRestore = ctx.restore;
ctx._originalRotate = ctx.rotate;
ctx._originalScale = ctx.scale;
ctx._originalTranslate = ctx.translate;
ctx._originalTransform = ctx.transform;
ctx._originalSetTransform = ctx.setTransform;
ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];
ctx._transformStack = [];
Object.defineProperty(ctx, 'mozCurrentTransform', {
get: function getCurrentTransform() {
return this._transformMatrix;
}
});
Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
get: function getCurrentTransformInverse() {
// Calculation done using WolframAlpha:
// http://www.wolframalpha.com/input/?
// i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
var m = this._transformMatrix;
var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
var ad_bc = a * d - b * c;
var bc_ad = b * c - a * d;
return [
d / ad_bc,
b / bc_ad,
c / bc_ad,
a / ad_bc,
(d * e - c * f) / bc_ad,
(b * e - a * f) / ad_bc
];
}
});
ctx.save = function ctxSave() {
var old = this._transformMatrix;
this._transformStack.push(old);
this._transformMatrix = old.slice(0, 6);
this._originalSave();
};
ctx.restore = function ctxRestore() {
var prev = this._transformStack.pop();
if (prev) {
this._transformMatrix = prev;
this._originalRestore();
}
};
ctx.translate = function ctxTranslate(x, y) {
var m = this._transformMatrix;
m[4] = m[0] * x + m[2] * y + m[4];
m[5] = m[1] * x + m[3] * y + m[5];
this._originalTranslate(x, y);
};
ctx.scale = function ctxScale(x, y) {
var m = this._transformMatrix;
m[0] = m[0] * x;
m[1] = m[1] * x;
m[2] = m[2] * y;
m[3] = m[3] * y;
this._originalScale(x, y);
};
ctx.transform = function ctxTransform(a, b, c, d, e, f) {
var m = this._transformMatrix;
this._transformMatrix = [
m[0] * a + m[2] * b,
m[1] * a + m[3] * b,
m[0] * c + m[2] * d,
m[1] * c + m[3] * d,
m[0] * e + m[2] * f + m[4],
m[1] * e + m[3] * f + m[5]
];
ctx._originalTransform(a, b, c, d, e, f);
};
ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
this._transformMatrix = [a, b, c, d, e, f];
ctx._originalSetTransform(a, b, c, d, e, f);
};
ctx.rotate = function ctxRotate(angle) {
var cosValue = Math.cos(angle);
var sinValue = Math.sin(angle);
var m = this._transformMatrix;
this._transformMatrix = [
m[0] * cosValue + m[2] * sinValue,
m[1] * cosValue + m[3] * sinValue,
m[0] * (-sinValue) + m[2] * cosValue,
m[1] * (-sinValue) + m[3] * cosValue,
m[4],
m[5]
];
this._originalRotate(angle);
};
}
}
var CachedCanvases = (function CachedCanvasesClosure() {
var cache = {};
return {
getCanvas: function CachedCanvases_getCanvas(id, width, height,
trackTransform) {
var canvasEntry;
if (id in cache) {
canvasEntry = cache[id];
canvasEntry.canvas.width = width;
canvasEntry.canvas.height = height;
// reset canvas transform for emulated mozCurrentTransform, if needed
canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
} else {
var canvas = createScratchCanvas(width, height);
var ctx = canvas.getContext('2d');
if (trackTransform) {
addContextCurrentTransform(ctx);
}
cache[id] = canvasEntry = {canvas: canvas, context: ctx};
}
return canvasEntry;
},
clear: function () {
for (var id in cache) {
var canvasEntry = cache[id];
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
canvasEntry.canvas.width = 0;
canvasEntry.canvas.height = 0;
delete cache[id];
}
}
};
})();
function compileType3Glyph(imgData) {
var POINT_TO_PROCESS_LIMIT = 1000;
var width = imgData.width, height = imgData.height;
var i, j, j0, width1 = width + 1;
var points = new Uint8Array(width1 * (height + 1));
var POINT_TYPES =
new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
// decodes bit-packed mask data
var lineSize = (width + 7) & ~7, data0 = imgData.data;
var data = new Uint8Array(lineSize * height), pos = 0, ii;
for (i = 0, ii = data0.length; i < ii; i++) {
var mask = 128, elem = data0[i];
while (mask > 0) {
data[pos++] = (elem & mask) ? 0 : 255;
mask >>= 1;
}
}
// finding iteresting points: every point is located between mask pixels,
// so there will be points of the (width + 1)x(height + 1) grid. Every point
// will have flags assigned based on neighboring mask pixels:
// 4 | 8
// --P--
// 2 | 1
// We are interested only in points with the flags:
// - outside corners: 1, 2, 4, 8;
// - inside corners: 7, 11, 13, 14;
// - and, intersections: 5, 10.
var count = 0;
pos = 0;
if (data[pos] !== 0) {
points[0] = 1;
++count;
}
for (j = 1; j < width; j++) {
if (data[pos] !== data[pos + 1]) {
points[j] = data[pos] ? 2 : 1;
++count;
}
pos++;
}
if (data[pos] !== 0) {
points[j] = 2;
++count;
}
for (i = 1; i < height; i++) {
pos = i * lineSize;
j0 = i * width1;
if (data[pos - lineSize] !== data[pos]) {
points[j0] = data[pos] ? 1 : 8;
++count;
}
// 'sum' is the position of the current pixel configuration in the 'TYPES'
// array (in order 8-1-2-4, so we can use '>>2' to shift the column).
var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
for (j = 1; j < width; j++) {
sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
(data[pos - lineSize + 1] ? 8 : 0);
if (POINT_TYPES[sum]) {
points[j0 + j] = POINT_TYPES[sum];
++count;
}
pos++;
}
if (data[pos - lineSize] !== data[pos]) {
points[j0 + j] = data[pos] ? 2 : 4;
++count;
}
if (count > POINT_TO_PROCESS_LIMIT) {
return null;
}
}
pos = lineSize * (height - 1);
j0 = i * width1;
if (data[pos] !== 0) {
points[j0] = 8;
++count;
}
for (j = 1; j < width; j++) {
if (data[pos] !== data[pos + 1]) {
points[j0 + j] = data[pos] ? 4 : 8;
++count;
}
pos++;
}
if (data[pos] !== 0) {
points[j0 + j] = 4;
++count;
}
if (count > POINT_TO_PROCESS_LIMIT) {
return null;
}
// building outlines
var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
var outlines = [];
for (i = 0; count && i <= height; i++) {
var p = i * width1;
var end = p + width;
while (p < end && !points[p]) {
p++;
}
if (p === end) {
continue;
}
var coords = [p % width1, i];
var type = points[p], p0 = p, pp;
do {
var step = steps[type];
do {
p += step;
} while (!points[p]);
pp = points[p];
if (pp !== 5 && pp !== 10) {
// set new direction
type = pp;
// delete mark
points[p] = 0;
} else { // type is 5 or 10, ie, a crossing
// set new direction
type = pp & ((0x33 * type) >> 4);
// set new type for "future hit"
points[p] &= (type >> 2 | type << 2);
}
coords.push(p % width1);
coords.push((p / width1) | 0);
--count;
} while (p0 !== p);
outlines.push(coords);
--i;
}
var drawOutline = function(c) {
c.save();
// the path shall be painted in [0..1]x[0..1] space
c.scale(1 / width, -1 / height);
c.translate(0, -height);
c.beginPath();
for (var i = 0, ii = outlines.length; i < ii; i++) {
var o = outlines[i];
c.moveTo(o[0], o[1]);
for (var j = 2, jj = o.length; j < jj; j += 2) {
c.lineTo(o[j], o[j+1]);
}
}
c.fill();
c.beginPath();
c.restore();
};
return drawOutline;
}
var CanvasExtraState = (function CanvasExtraStateClosure() {
function CanvasExtraState(old) {
// Are soft masks and alpha values shapes or opacities?
this.alphaIsShape = false;
this.fontSize = 0;
this.fontSizeScale = 1;
this.textMatrix = IDENTITY_MATRIX;
this.textMatrixScale = 1;
this.fontMatrix = FONT_IDENTITY_MATRIX;
this.leading = 0;
// Current point (in user coordinates)
this.x = 0;
this.y = 0;
// Start of text line (in text coordinates)
this.lineX = 0;
this.lineY = 0;
// Character and word spacing
this.charSpacing = 0;
this.wordSpacing = 0;
this.textHScale = 1;
this.textRenderingMode = TextRenderingMode.FILL;
this.textRise = 0;
// Default fore and background colors
this.fillColor = '#000000';
this.strokeColor = '#000000';
// Note: fill alpha applies to all non-stroking operations
this.fillAlpha = 1;
this.strokeAlpha = 1;
this.lineWidth = 1;
this.activeSMask = null; // nonclonable field (see the save method below)
this.old = old;
}
CanvasExtraState.prototype = {
clone: function CanvasExtraState_clone() {
return Object.create(this);
},
setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
this.x = x;
this.y = y;
}
};
return CanvasExtraState;
})();
var CanvasGraphics = (function CanvasGraphicsClosure() {
// Defines the time the executeOperatorList is going to be executing
// before it stops and shedules a continue of execution.
var EXECUTION_TIME = 15;
// Defines the number of steps before checking the execution time
var EXECUTION_STEPS = 10;
function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
this.ctx = canvasCtx;
this.current = new CanvasExtraState();
this.stateStack = [];
this.pendingClip = null;
this.pendingEOFill = false;
this.res = null;
this.xobjs = null;
this.commonObjs = commonObjs;
this.objs = objs;
this.imageLayer = imageLayer;
this.groupStack = [];
this.processingType3 = null;
// Patterns are painted relative to the initial page/form transform, see pdf
// spec 8.7.2 NOTE 1.
this.baseTransform = null;
this.baseTransformStack = [];
this.groupLevel = 0;
this.smaskStack = [];
this.smaskCounter = 0;
this.tempSMask = null;
if (canvasCtx) {
addContextCurrentTransform(canvasCtx);
}
}
function putBinaryImageData(ctx, imgData) {
if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
ctx.putImageData(imgData, 0, 0);
return;
}
// Put the image data to the canvas in chunks, rather than putting the
// whole image at once. This saves JS memory, because the ImageData object
// is smaller. It also possibly saves C++ memory within the implementation
// of putImageData(). (E.g. in Firefox we make two short-lived copies of
// the data passed to putImageData()). |n| shouldn't be too small, however,
// because too many putImageData() calls will slow things down.
//
// Note: as written, if the last chunk is partial, the putImageData() call
// will (conceptually) put pixels past the bounds of the canvas. But
// that's ok; any such pixels are ignored.
var height = imgData.height, width = imgData.width;
var fullChunkHeight = 16;
var fracChunks = height / fullChunkHeight;
var fullChunks = Math.floor(fracChunks);
var totalChunks = Math.ceil(fracChunks);
var partialChunkHeight = height - fullChunks * fullChunkHeight;
var chunkImgData = ctx.createImageData(width, fullChunkHeight);
var srcPos = 0, destPos;
var src = imgData.data;
var dest = chunkImgData.data;
var i, j, thisChunkHeight, elemsInThisChunk;
// There are multiple forms in which the pixel data can be passed, and
// imgData.kind tells us which one this is.
if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
// Grayscale, 1 bit per pixel (i.e. black-and-white).
var srcLength = src.byteLength;
var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
new Uint32ArrayView(dest);
var dest32DataLength = dest32.length;
var fullSrcDiff = (width + 7) >> 3;
var white = 0xFFFFFFFF;
var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
0xFF000000 : 0x000000FF;
for (i = 0; i < totalChunks; i++) {
thisChunkHeight =
(i < fullChunks) ? fullChunkHeight : partialChunkHeight;
destPos = 0;
for (j = 0; j < thisChunkHeight; j++) {
var srcDiff = srcLength - srcPos;
var k = 0;
var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
var kEndUnrolled = kEnd & ~7;
var mask = 0;
var srcByte = 0;
for (; k < kEndUnrolled; k += 8) {
srcByte = src[srcPos++];
dest32[destPos++] = (srcByte & 128) ? white : black;
dest32[destPos++] = (srcByte & 64) ? white : black;
dest32[destPos++] = (srcByte & 32) ? white : black;
dest32[destPos++] = (srcByte & 16) ? white : black;
dest32[destPos++] = (srcByte & 8) ? white : black;
dest32[destPos++] = (srcByte & 4) ? white : black;
dest32[destPos++] = (srcByte & 2) ? white : black;
dest32[destPos++] = (srcByte & 1) ? white : black;
}
for (; k < kEnd; k++) {
if (mask === 0) {
srcByte = src[srcPos++];
mask = 128;
}
dest32[destPos++] = (srcByte & mask) ? white : black;
mask >>= 1;
}
}
// We ran out of input. Make all remaining pixels transparent.
while (destPos < dest32DataLength) {
dest32[destPos++] = 0;
}
ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
}
} else if (imgData.kind === ImageKind.RGBA_32BPP) {
// RGBA, 32-bits per pixel.
j = 0;
elemsInThisChunk = width * fullChunkHeight * 4;
for (i = 0; i < fullChunks; i++) {
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
srcPos += elemsInThisChunk;
ctx.putImageData(chunkImgData, 0, j);
j += fullChunkHeight;
}
if (i < totalChunks) {
elemsInThisChunk = width * partialChunkHeight * 4;
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
ctx.putImageData(chunkImgData, 0, j);
}
} else if (imgData.kind === ImageKind.RGB_24BPP) {
// RGB, 24-bits per pixel.
thisChunkHeight = fullChunkHeight;
elemsInThisChunk = width * thisChunkHeight;
for (i = 0; i < totalChunks; i++) {
if (i >= fullChunks) {
thisChunkHeight =partialChunkHeight;
elemsInThisChunk = width * thisChunkHeight;
}
destPos = 0;
for (j = elemsInThisChunk; j--;) {
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = 255;
}
ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
}
} else {
error('bad image kind: ' + imgData.kind);
}
}
function putBinaryImageMask(ctx, imgData) {
var height = imgData.height, width = imgData.width;
var fullChunkHeight = 16;
var fracChunks = height / fullChunkHeight;
var fullChunks = Math.floor(fracChunks);
var totalChunks = Math.ceil(fracChunks);
var partialChunkHeight = height - fullChunks * fullChunkHeight;
var chunkImgData = ctx.createImageData(width, fullChunkHeight);
var srcPos = 0;
var src = imgData.data;
var dest = chunkImgData.data;
for (var i = 0; i < totalChunks; i++) {
var thisChunkHeight =
(i < fullChunks) ? fullChunkHeight : partialChunkHeight;
// Expand the mask so it can be used by the canvas. Any required
// inversion has already been handled.
var destPos = 3; // alpha component offset
for (var j = 0; j < thisChunkHeight; j++) {
var mask = 0;
for (var k = 0; k < width; k++) {
if (!mask) {
var elem = src[srcPos++];
mask = 128;
}
dest[destPos] = (elem & mask) ? 0 : 255;
destPos += 4;
mask >>= 1;
}
}
ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);
}
}
function copyCtxState(sourceCtx, destCtx) {
var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
'globalCompositeOperation', 'font'];
for (var i = 0, ii = properties.length; i < ii; i++) {
var property = properties[i];
if (property in sourceCtx) {
destCtx[property] = sourceCtx[property];
}
}
if ('setLineDash' in sourceCtx) {
destCtx.setLineDash(sourceCtx.getLineDash());
destCtx.lineDashOffset = sourceCtx.lineDashOffset;
} else if ('mozDash' in sourceCtx) {
destCtx.mozDash = sourceCtx.mozDash;
destCtx.mozDashOffset = sourceCtx.mozDashOffset;
}
}
function composeSMaskBackdrop(bytes, r0, g0, b0) {
var length = bytes.length;
for (var i = 3; i < length; i += 4) {
var alpha = bytes[i];
if (alpha === 0) {
bytes[i - 3] = r0;
bytes[i - 2] = g0;
bytes[i - 1] = b0;
} else if (alpha < 255) {
var alpha_ = 255 - alpha;
bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
}
}
}
function composeSMaskAlpha(maskData, layerData) {
var length = maskData.length;
var scale = 1 / 255;
for (var i = 3; i < length; i += 4) {
var alpha = maskData[i];
layerData[i] = (layerData[i] * alpha * scale) | 0;
}
}
function composeSMaskLuminosity(maskData, layerData) {
var length = maskData.length;
for (var i = 3; i < length; i += 4) {
var y = ((maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
(maskData[i - 2] * 152) + // * 0.59 ....
(maskData[i - 1] * 28)) | 0; // * 0.11 ....
layerData[i] = (layerData[i] * y) >> 16;
}
}
function genericComposeSMask(maskCtx, layerCtx, width, height,
subtype, backdrop) {
var hasBackdrop = !!backdrop;
var r0 = hasBackdrop ? backdrop[0] : 0;
var g0 = hasBackdrop ? backdrop[1] : 0;
var b0 = hasBackdrop ? backdrop[2] : 0;
var composeFn;
if (subtype === 'Luminosity') {
composeFn = composeSMaskLuminosity;
} else {
composeFn = composeSMaskAlpha;
}
// processing image in chunks to save memory
var PIXELS_TO_PROCESS = 65536;
var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
for (var row = 0; row < height; row += chunkSize) {
var chunkHeight = Math.min(chunkSize, height - row);
var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
if (hasBackdrop) {
composeSMaskBackdrop(maskData.data, r0, g0, b0);
}
composeFn(maskData.data, layerData.data);
maskCtx.putImageData(layerData, 0, row);
}
}
function composeSMask(ctx, smask, layerCtx) {
var mask = smask.canvas;
var maskCtx = smask.context;
ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
smask.offsetX, smask.offsetY);
var backdrop = smask.backdrop || null;
if (WebGLUtils.isEnabled) {
var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
{subtype: smask.subtype, backdrop: backdrop});
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(composed, smask.offsetX, smask.offsetY);
return;
}
genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
smask.subtype, backdrop);
ctx.drawImage(mask, 0, 0);
}
var LINE_CAP_STYLES = ['butt', 'round', 'square'];
var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
var NORMAL_CLIP = {};
var EO_CLIP = {};
CanvasGraphics.prototype = {
beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
// For pdfs that use blend modes we have to clear the canvas else certain
// blend modes can look wrong since we'd be blending with a white
// backdrop. The problem with a transparent backdrop though is we then
// don't get sub pixel anti aliasing on text, so we fill with white if
// we can.
var width = this.ctx.canvas.width;
var height = this.ctx.canvas.height;
if (transparency) {
this.ctx.clearRect(0, 0, width, height);
} else {
this.ctx.mozOpaque = true;
this.ctx.save();
this.ctx.fillStyle = 'rgb(255, 255, 255)';
this.ctx.fillRect(0, 0, width, height);
this.ctx.restore();
}
var transform = viewport.transform;
this.ctx.save();
this.ctx.transform.apply(this.ctx, transform);
this.baseTransform = this.ctx.mozCurrentTransform.slice();
if (this.imageLayer) {
this.imageLayer.beginLayout();
}
},
executeOperatorList: function CanvasGraphics_executeOperatorList(
operatorList,
executionStartIdx, continueCallback,
stepper) {
var argsArray = operatorList.argsArray;
var fnArray = operatorList.fnArray;
var i = executionStartIdx || 0;
var argsArrayLen = argsArray.length;
// Sometimes the OperatorList to execute is empty.
if (argsArrayLen === i) {
return i;
}
var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
typeof continueCallback === 'function');
var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
var steps = 0;
var commonObjs = this.commonObjs;
var objs = this.objs;
var fnId;
while (true) {
if (stepper !== undefined && i === stepper.nextBreakPoint) {
stepper.breakIt(i, continueCallback);
return i;
}
fnId = fnArray[i];
if (fnId !== OPS.dependency) {
this[fnId].apply(this, argsArray[i]);
} else {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var depObjId = deps[n];
var common = depObjId[0] === 'g' && depObjId[1] === '_';
var objsPool = common ? commonObjs : objs;
// If the promise isn't resolved yet, add the continueCallback
// to the promise and bail out.
if (!objsPool.isResolved(depObjId)) {
objsPool.get(depObjId, continueCallback);
return i;
}
}
}
i++;
// If the entire operatorList was executed, stop as were done.
if (i === argsArrayLen) {
return i;
}
// If the execution took longer then a certain amount of time and
// `continueCallback` is specified, interrupt the execution.
if (chunkOperations && ++steps > EXECUTION_STEPS) {
if (Date.now() > endTime) {
continueCallback();
return i;
}
steps = 0;
}
// If the operatorList isn't executed completely yet OR the execution
// time was short enough, do another execution round.
}
},
endDrawing: function CanvasGraphics_endDrawing() {
this.ctx.restore();
CachedCanvases.clear();
WebGLUtils.clear();
if (this.imageLayer) {
this.imageLayer.endLayout();
}
},
// Graphics state
setLineWidth: function CanvasGraphics_setLineWidth(width) {
this.current.lineWidth = width;
this.ctx.lineWidth = width;
},
setLineCap: function CanvasGraphics_setLineCap(style) {
this.ctx.lineCap = LINE_CAP_STYLES[style];
},
setLineJoin: function CanvasGraphics_setLineJoin(style) {
this.ctx.lineJoin = LINE_JOIN_STYLES[style];
},
setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
this.ctx.miterLimit = limit;
},
setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
var ctx = this.ctx;
if ('setLineDash' in ctx) {
ctx.setLineDash(dashArray);
ctx.lineDashOffset = dashPhase;
} else {
ctx.mozDash = dashArray;
ctx.mozDashOffset = dashPhase;
}
},
setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
// Maybe if we one day fully support color spaces this will be important
// for now we can ignore.
// TODO set rendering intent?
},
setFlatness: function CanvasGraphics_setFlatness(flatness) {
// There's no way to control this with canvas, but we can safely ignore.
// TODO set flatness?
},
setGState: function CanvasGraphics_setGState(states) {
for (var i = 0, ii = states.length; i < ii; i++) {
var state = states[i];
var key = state[0];
var value = state[1];
switch (key) {
case 'LW':
this.setLineWidth(value);
break;
case 'LC':
this.setLineCap(value);
break;
case 'LJ':
this.setLineJoin(value);
break;
case 'ML':
this.setMiterLimit(value);
break;
case 'D':
this.setDash(value[0], value[1]);
break;
case 'RI':
this.setRenderingIntent(value);
break;
case 'FL':
this.setFlatness(value);
break;
case 'Font':
this.setFont(value[0], value[1]);
break;
case 'CA':
this.current.strokeAlpha = state[1];
break;
case 'ca':
this.current.fillAlpha = state[1];
this.ctx.globalAlpha = state[1];
break;
case 'BM':
if (value && value.name && (value.name !== 'Normal')) {
var mode = value.name.replace(/([A-Z])/g,
function(c) {
return '-' + c.toLowerCase();
}
).substring(1);
this.ctx.globalCompositeOperation = mode;
if (this.ctx.globalCompositeOperation !== mode) {
warn('globalCompositeOperation "' + mode +
'" is not supported');
}
} else {
this.ctx.globalCompositeOperation = 'source-over';
}
break;
case 'SMask':
if (this.current.activeSMask) {
this.endSMaskGroup();
}
this.current.activeSMask = value ? this.tempSMask : null;
if (this.current.activeSMask) {
this.beginSMaskGroup();
}
this.tempSMask = null;
break;
}
}
},
beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
var activeSMask = this.current.activeSMask;
var drawnWidth = activeSMask.canvas.width;
var drawnHeight = activeSMask.canvas.height;
var cacheId = 'smaskGroupAt' + this.groupLevel;
var scratchCanvas = CachedCanvases.getCanvas(
cacheId, drawnWidth, drawnHeight, true);
var currentCtx = this.ctx;
var currentTransform = currentCtx.mozCurrentTransform;
this.ctx.save();
var groupCtx = scratchCanvas.context;
groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
groupCtx.transform.apply(groupCtx, currentTransform);
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([
['BM', 'Normal'],
['ca', 1],
['CA', 1]
]);
this.groupStack.push(currentCtx);
this.groupLevel++;
},
endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
var groupCtx = this.ctx;
this.groupLevel--;
this.ctx = this.groupStack.pop();
composeSMask(this.ctx, this.current.activeSMask, groupCtx);
this.ctx.restore();
},
save: function CanvasGraphics_save() {
this.ctx.save();
var old = this.current;
this.stateStack.push(old);
this.current = old.clone();
this.current.activeSMask = null;
},
restore: function CanvasGraphics_restore() {
if (this.stateStack.length !== 0) {
if (this.current.activeSMask !== null) {
this.endSMaskGroup();
}
this.current = this.stateStack.pop();
this.ctx.restore();
}
},
transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
this.ctx.transform(a, b, c, d, e, f);
},
// Path
constructPath: function CanvasGraphics_constructPath(ops, args) {
var ctx = this.ctx;
var current = this.current;
var x = current.x, y = current.y;
for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
switch (ops[i] | 0) {
case OPS.rectangle:
x = args[j++];
y = args[j++];
var width = args[j++];
var height = args[j++];
if (width === 0) {
width = this.getSinglePixelWidth();
}
if (height === 0) {
height = this.getSinglePixelWidth();
}
var xw = x + width;
var yh = y + height;
this.ctx.moveTo(x, y);
this.ctx.lineTo(xw, y);
this.ctx.lineTo(xw, yh);
this.ctx.lineTo(x, yh);
this.ctx.lineTo(x, y);
this.ctx.closePath();
break;
case OPS.moveTo:
x = args[j++];
y = args[j++];
ctx.moveTo(x, y);
break;
case OPS.lineTo:
x = args[j++];
y = args[j++];
ctx.lineTo(x, y);
break;
case OPS.curveTo:
x = args[j + 4];
y = args[j + 5];
ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
x, y);
j += 6;
break;
case OPS.curveTo2:
ctx.bezierCurveTo(x, y, args[j], args[j + 1],
args[j + 2], args[j + 3]);
x = args[j + 2];
y = args[j + 3];
j += 4;
break;
case OPS.curveTo3:
x = args[j + 2];
y = args[j + 3];
ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
j += 4;
break;
case OPS.closePath:
ctx.closePath();
break;
}
}
current.setCurrentPoint(x, y);
},
closePath: function CanvasGraphics_closePath() {
this.ctx.closePath();
},
stroke: function CanvasGraphics_stroke(consumePath) {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var strokeColor = this.current.strokeColor;
if (this.current.lineWidth === 0) {
ctx.lineWidth = this.getSinglePixelWidth();
}
// For stroke we want to temporarily change the global alpha to the
// stroking alpha.
ctx.globalAlpha = this.current.strokeAlpha;
if (strokeColor && strokeColor.hasOwnProperty('type') &&
strokeColor.type === 'Pattern') {
// for patterns, we transform to pattern space, calculate
// the pattern, call stroke, and restore to user space
ctx.save();
ctx.strokeStyle = strokeColor.getPattern(ctx, this);
ctx.stroke();
ctx.restore();
} else {
ctx.stroke();
}
if (consumePath) {
this.consumePath();
}
// Restore the global alpha to the fill alpha
ctx.globalAlpha = this.current.fillAlpha;
},
closeStroke: function CanvasGraphics_closeStroke() {
this.closePath();
this.stroke();
},
fill: function CanvasGraphics_fill(consumePath) {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var fillColor = this.current.fillColor;
var needRestore = false;
if (fillColor && fillColor.hasOwnProperty('type') &&
fillColor.type === 'Pattern') {
ctx.save();
ctx.fillStyle = fillColor.getPattern(ctx, this);
needRestore = true;
}
if (this.pendingEOFill) {
if (ctx.mozFillRule !== undefined) {
ctx.mozFillRule = 'evenodd';
ctx.fill();
ctx.mozFillRule = 'nonzero';
} else {
try {
ctx.fill('evenodd');
} catch (ex) {
// shouldn't really happen, but browsers might think differently
ctx.fill();
}
}
this.pendingEOFill = false;
} else {
ctx.fill();
}
if (needRestore) {
ctx.restore();
}
if (consumePath) {
this.consumePath();
}
},
eoFill: function CanvasGraphics_eoFill() {
this.pendingEOFill = true;
this.fill();
},
fillStroke: function CanvasGraphics_fillStroke() {
this.fill(false);
this.stroke(false);
this.consumePath();
},
eoFillStroke: function CanvasGraphics_eoFillStroke() {
this.pendingEOFill = true;
this.fillStroke();
},
closeFillStroke: function CanvasGraphics_closeFillStroke() {
this.closePath();
this.fillStroke();
},
closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
this.pendingEOFill = true;
this.closePath();
this.fillStroke();
},
endPath: function CanvasGraphics_endPath() {
this.consumePath();
},
// Clipping
clip: function CanvasGraphics_clip() {
this.pendingClip = NORMAL_CLIP;
},
eoClip: function CanvasGraphics_eoClip() {
this.pendingClip = EO_CLIP;
},
// Text
beginText: function CanvasGraphics_beginText() {
this.current.textMatrix = IDENTITY_MATRIX;
this.current.textMatrixScale = 1;
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
},
endText: function CanvasGraphics_endText() {
var paths = this.pendingTextPaths;
var ctx = this.ctx;
if (paths === undefined) {
ctx.beginPath();
return;
}
ctx.save();
ctx.beginPath();
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
ctx.setTransform.apply(ctx, path.transform);
ctx.translate(path.x, path.y);
path.addToPath(ctx, path.fontSize);
}
ctx.restore();
ctx.clip();
ctx.beginPath();
delete this.pendingTextPaths;
},
setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
this.current.charSpacing = spacing;
},
setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
this.current.wordSpacing = spacing;
},
setHScale: function CanvasGraphics_setHScale(scale) {
this.current.textHScale = scale / 100;
},
setLeading: function CanvasGraphics_setLeading(leading) {
this.current.leading = -leading;
},
setFont: function CanvasGraphics_setFont(fontRefName, size) {
var fontObj = this.commonObjs.get(fontRefName);
var current = this.current;
if (!fontObj) {
error('Can\'t find font for ' + fontRefName);
}
current.fontMatrix = (fontObj.fontMatrix ?
fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
// A valid matrix needs all main diagonal elements to be non-zero
// This also ensures we bypass FF bugzilla bug #719844.
if (current.fontMatrix[0] === 0 ||
current.fontMatrix[3] === 0) {
warn('Invalid font matrix for font ' + fontRefName);
}
// The spec for Tf (setFont) says that 'size' specifies the font 'scale',
// and in some docs this can be negative (inverted x-y axes).
if (size < 0) {
size = -size;
current.fontDirection = -1;
} else {
current.fontDirection = 1;
}
this.current.font = fontObj;
this.current.fontSize = size;
if (fontObj.isType3Font) {
return; // we don't need ctx.font for Type3 fonts
}
var name = fontObj.loadedName || 'sans-serif';
var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
(fontObj.bold ? 'bold' : 'normal');
var italic = fontObj.italic ? 'italic' : 'normal';
var typeface = '"' + name + '", ' + fontObj.fallbackName;
// Some font backends cannot handle fonts below certain size.
// Keeping the font at minimal size and using the fontSizeScale to change
// the current transformation matrix before the fillText/strokeText.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
this.current.fontSizeScale = size / browserFontSize;
var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
this.ctx.font = rule;
},
setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
this.current.textRenderingMode = mode;
},
setTextRise: function CanvasGraphics_setTextRise(rise) {
this.current.textRise = rise;
},
moveText: function CanvasGraphics_moveText(x, y) {
this.current.x = this.current.lineX += x;
this.current.y = this.current.lineY += y;
},
setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
this.setLeading(-y);
this.moveText(x, y);
},
setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
this.current.textMatrix = [a, b, c, d, e, f];
this.current.textMatrixScale = Math.sqrt(a * a + b * b);
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
},
nextLine: function CanvasGraphics_nextLine() {
this.moveText(0, this.current.leading);
},
paintChar: function CanvasGraphics_paintChar(character, x, y) {
var ctx = this.ctx;
var current = this.current;
var font = current.font;
var textRenderingMode = current.textRenderingMode;
var fontSize = current.fontSize / current.fontSizeScale;
var fillStrokeMode = textRenderingMode &
TextRenderingMode.FILL_STROKE_MASK;
var isAddToPathSet = !!(textRenderingMode &
TextRenderingMode.ADD_TO_PATH_FLAG);
var addToPath;
if (font.disableFontFace || isAddToPathSet) {
addToPath = font.getPathGenerator(this.commonObjs, character);
}
if (font.disableFontFace) {
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
addToPath(ctx, fontSize);
if (fillStrokeMode === TextRenderingMode.FILL ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fill();
}
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.stroke();
}
ctx.restore();
} else {
if (fillStrokeMode === TextRenderingMode.FILL ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fillText(character, x, y);
}
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.strokeText(character, x, y);
}
}
if (isAddToPathSet) {
var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
paths.push({
transform: ctx.mozCurrentTransform,
x: x,
y: y,
fontSize: fontSize,
addToPath: addToPath
});
}
},
get isFontSubpixelAAEnabled() {
// Checks if anti-aliasing is enabled when scaled text is painted.
// On Windows GDI scaled fonts looks bad.
var ctx = document.createElement('canvas').getContext('2d');
ctx.scale(1.5, 1);
ctx.fillText('I', 0, 10);
var data = ctx.getImageData(0, 0, 10, 10).data;
var enabled = false;
for (var i = 3; i < data.length; i += 4) {
if (data[i] > 0 && data[i] < 255) {
enabled = true;
break;
}
}
return shadow(this, 'isFontSubpixelAAEnabled', enabled);
},
showText: function CanvasGraphics_showText(glyphs) {
var current = this.current;
var font = current.font;
if (font.isType3Font) {
return this.showType3Text(glyphs);
}
var fontSize = current.fontSize;
if (fontSize === 0) {
return;
}
var ctx = this.ctx;
var fontSizeScale = current.fontSizeScale;
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var fontDirection = current.fontDirection;
var textHScale = current.textHScale * fontDirection;
var glyphsLength = glyphs.length;
var vertical = font.vertical;
var defaultVMetrics = font.defaultVMetrics;
var widthAdvanceScale = fontSize * current.fontMatrix[0];
var simpleFillText =
current.textRenderingMode === TextRenderingMode.FILL &&
!font.disableFontFace;
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
ctx.translate(current.x, current.y + current.textRise);
if (fontDirection > 0) {
ctx.scale(textHScale, -1);
} else {
ctx.scale(textHScale, 1);
}
var lineWidth = current.lineWidth;
var scale = current.textMatrixScale;
if (scale === 0 || lineWidth === 0) {
lineWidth = this.getSinglePixelWidth();
} else {
lineWidth /= scale;
}
if (fontSizeScale !== 1.0) {
ctx.scale(fontSizeScale, fontSizeScale);
lineWidth /= fontSizeScale;
}
ctx.lineWidth = lineWidth;
var x = 0, i;
for (i = 0; i < glyphsLength; ++i) {
var glyph = glyphs[i];
if (glyph === null) {
// word break
x += fontDirection * wordSpacing;
continue;
} else if (isNum(glyph)) {
x += -glyph * fontSize * 0.001;
continue;
}
var restoreNeeded = false;
var character = glyph.fontChar;
var accent = glyph.accent;
var scaledX, scaledY, scaledAccentX, scaledAccentY;
var width = glyph.width;
if (vertical) {
var vmetric, vx, vy;
vmetric = glyph.vmetric || defaultVMetrics;
vx = glyph.vmetric ? vmetric[1] : width * 0.5;
vx = -vx * widthAdvanceScale;
vy = vmetric[2] * widthAdvanceScale;
width = vmetric ? -vmetric[0] : width;
scaledX = vx / fontSizeScale;
scaledY = (x + vy) / fontSizeScale;
} else {
scaledX = x / fontSizeScale;
scaledY = 0;
}
if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
// some standard fonts may not have the exact width, trying to
// rescale per character
var measuredWidth = ctx.measureText(character).width * 1000 /
fontSize * fontSizeScale;
var characterScaleX = width / measuredWidth;
restoreNeeded = true;
ctx.save();
ctx.scale(characterScaleX, 1);
scaledX /= characterScaleX;
}
if (simpleFillText && !accent) {
// common case
ctx.fillText(character, scaledX, scaledY);
} else {
this.paintChar(character, scaledX, scaledY);
if (accent) {
scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
}
}
var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
x += charWidth;
if (restoreNeeded) {
ctx.restore();
}
}
if (vertical) {
current.y -= x * textHScale;
} else {
current.x += x * textHScale;
}
ctx.restore();
},
showType3Text: function CanvasGraphics_showType3Text(glyphs) {
// Type3 fonts - each glyph is a "mini-PDF"
var ctx = this.ctx;
var current = this.current;
var font = current.font;
var fontSize = current.fontSize;
var fontDirection = current.fontDirection;
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var textHScale = current.textHScale * fontDirection;
var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
var glyphsLength = glyphs.length;
var isTextInvisible =
current.textRenderingMode === TextRenderingMode.INVISIBLE;
var i, glyph, width;
if (isTextInvisible || fontSize === 0) {
return;
}
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
ctx.translate(current.x, current.y);
ctx.scale(textHScale, fontDirection);
for (i = 0; i < glyphsLength; ++i) {
glyph = glyphs[i];
if (glyph === null) {
// word break
this.ctx.translate(wordSpacing, 0);
current.x += wordSpacing * textHScale;
continue;
} else if (isNum(glyph)) {
var spacingLength = -glyph * 0.001 * fontSize;
this.ctx.translate(spacingLength, 0);
current.x += spacingLength * textHScale;
continue;
}
var operatorList = font.charProcOperatorList[glyph.operatorListId];
if (!operatorList) {
warn('Type3 character \"' + glyph.operatorListId +
'\" is not available');
continue;
}
this.processingType3 = glyph;
this.save();
ctx.scale(fontSize, fontSize);
ctx.transform.apply(ctx, fontMatrix);
this.executeOperatorList(operatorList);
this.restore();
var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
width = transformed[0] * fontSize + charSpacing;
ctx.translate(width, 0);
current.x += width * textHScale;
}
ctx.restore();
this.processingType3 = null;
},
// Type3 fonts
setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
// We can safely ignore this since the width should be the same
// as the width in the Widths array.
},
setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
yWidth,
llx,
lly,
urx,
ury) {
// TODO According to the spec we're also suppose to ignore any operators
// that set color or include images while processing this type3 font.
this.ctx.rect(llx, lly, urx - llx, ury - lly);
this.clip();
this.endPath();
},
// Color
getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
var pattern;
if (IR[0] === 'TilingPattern') {
var color = IR[1];
pattern = new TilingPattern(IR, color, this.ctx, this.objs,
this.commonObjs, this.baseTransform);
} else {
pattern = getShadingPatternFromIR(IR);
}
return pattern;
},
setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
this.current.strokeColor = this.getColorN_Pattern(arguments);
},
setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
this.current.fillColor = this.getColorN_Pattern(arguments);
},
setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
var color = Util.makeCssRgb(arguments);
this.ctx.strokeStyle = color;
this.current.strokeColor = color;
},
setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
var color = Util.makeCssRgb(arguments);
this.ctx.fillStyle = color;
this.current.fillColor = color;
},
shadingFill: function CanvasGraphics_shadingFill(patternIR) {
var ctx = this.ctx;
this.save();
var pattern = getShadingPatternFromIR(patternIR);
ctx.fillStyle = pattern.getPattern(ctx, this, true);
var inv = ctx.mozCurrentTransformInverse;
if (inv) {
var canvas = ctx.canvas;
var width = canvas.width;
var height = canvas.height;
var bl = Util.applyTransform([0, 0], inv);
var br = Util.applyTransform([0, height], inv);
var ul = Util.applyTransform([width, 0], inv);
var ur = Util.applyTransform([width, height], inv);
var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
} else {
// HACK to draw the gradient onto an infinite rectangle.
// PDF gradients are drawn across the entire image while
// Canvas only allows gradients to be drawn in a rectangle
// The following bug should allow us to remove this.
// https://bugzilla.mozilla.org/show_bug.cgi?id=664884
this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
}
this.restore();
},
// Images
beginInlineImage: function CanvasGraphics_beginInlineImage() {
error('Should not call beginInlineImage');
},
beginImageData: function CanvasGraphics_beginImageData() {
error('Should not call beginImageData');
},
paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
bbox) {
this.save();
this.baseTransformStack.push(this.baseTransform);
if (isArray(matrix) && 6 === matrix.length) {
this.transform.apply(this, matrix);
}
this.baseTransform = this.ctx.mozCurrentTransform;
if (isArray(bbox) && 4 === bbox.length) {
var width = bbox[2] - bbox[0];
var height = bbox[3] - bbox[1];
this.ctx.rect(bbox[0], bbox[1], width, height);
this.clip();
this.endPath();
}
},
paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
this.restore();
this.baseTransform = this.baseTransformStack.pop();
},
beginGroup: function CanvasGraphics_beginGroup(group) {
this.save();
var currentCtx = this.ctx;
// TODO non-isolated groups - according to Rik at adobe non-isolated
// group results aren't usually that different and they even have tools
// that ignore this setting. Notes from Rik on implmenting:
// - When you encounter an transparency group, create a new canvas with
// the dimensions of the bbox
// - copy the content from the previous canvas to the new canvas
// - draw as usual
// - remove the backdrop alpha:
// alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
// value of your transparency group and 'alphaBackdrop' the alpha of the
// backdrop
// - remove background color:
// colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
if (!group.isolated) {
info('TODO: Support non-isolated groups.');
}
// TODO knockout - supposedly possible with the clever use of compositing
// modes.
if (group.knockout) {
warn('Knockout groups not supported.');
}
var currentTransform = currentCtx.mozCurrentTransform;
if (group.matrix) {
currentCtx.transform.apply(currentCtx, group.matrix);
}
assert(group.bbox, 'Bounding box is required.');
// Based on the current transform figure out how big the bounding box
// will actually be.
var bounds = Util.getAxialAlignedBoundingBox(
group.bbox,
currentCtx.mozCurrentTransform);
// Clip the bounding box to the current canvas.
var canvasBounds = [0,
0,
currentCtx.canvas.width,
currentCtx.canvas.height];
bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
// Use ceil in case we're between sizes so we don't create canvas that is
// too small and make the canvas at least 1x1 pixels.
var offsetX = Math.floor(bounds[0]);
var offsetY = Math.floor(bounds[1]);
var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
var scaleX = 1, scaleY = 1;
if (drawnWidth > MAX_GROUP_SIZE) {
scaleX = drawnWidth / MAX_GROUP_SIZE;
drawnWidth = MAX_GROUP_SIZE;
}
if (drawnHeight > MAX_GROUP_SIZE) {
scaleY = drawnHeight / MAX_GROUP_SIZE;
drawnHeight = MAX_GROUP_SIZE;
}
var cacheId = 'groupAt' + this.groupLevel;
if (group.smask) {
// Using two cache entries is case if masks are used one after another.
cacheId += '_smask_' + ((this.smaskCounter++) % 2);
}
var scratchCanvas = CachedCanvases.getCanvas(
cacheId, drawnWidth, drawnHeight, true);
var groupCtx = scratchCanvas.context;
// Since we created a new canvas that is just the size of the bounding box
// we have to translate the group ctx.
groupCtx.scale(1 / scaleX, 1 / scaleY);
groupCtx.translate(-offsetX, -offsetY);
groupCtx.transform.apply(groupCtx, currentTransform);
if (group.smask) {
// Saving state and cached mask to be used in setGState.
this.smaskStack.push({
canvas: scratchCanvas.canvas,
context: groupCtx,
offsetX: offsetX,
offsetY: offsetY,
scaleX: scaleX,
scaleY: scaleY,
subtype: group.smask.subtype,
backdrop: group.smask.backdrop
});
} else {
// Setup the current ctx so when the group is popped we draw it at the
// right location.
currentCtx.setTransform(1, 0, 0, 1, 0, 0);
currentCtx.translate(offsetX, offsetY);
currentCtx.scale(scaleX, scaleY);
}
// The transparency group inherits all off the current graphics state
// except the blend mode, soft mask, and alpha constants.
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([
['BM', 'Normal'],
['ca', 1],
['CA', 1]
]);
this.groupStack.push(currentCtx);
this.groupLevel++;
},
endGroup: function CanvasGraphics_endGroup(group) {
this.groupLevel--;
var groupCtx = this.ctx;
this.ctx = this.groupStack.pop();
// Turn off image smoothing to avoid sub pixel interpolation which can
// look kind of blurry for some pdfs.
if (this.ctx.imageSmoothingEnabled !== undefined) {
this.ctx.imageSmoothingEnabled = false;
} else {
this.ctx.mozImageSmoothingEnabled = false;
}
if (group.smask) {
this.tempSMask = this.smaskStack.pop();
} else {
this.ctx.drawImage(groupCtx.canvas, 0, 0);
}
this.restore();
},
beginAnnotations: function CanvasGraphics_beginAnnotations() {
this.save();
this.current = new CanvasExtraState();
},
endAnnotations: function CanvasGraphics_endAnnotations() {
this.restore();
},
beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
matrix) {
this.save();
if (isArray(rect) && 4 === rect.length) {
var width = rect[2] - rect[0];
var height = rect[3] - rect[1];
this.ctx.rect(rect[0], rect[1], width, height);
this.clip();
this.endPath();
}
this.transform.apply(this, transform);
this.transform.apply(this, matrix);
},
endAnnotation: function CanvasGraphics_endAnnotation() {
this.restore();
},
paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
var domImage = this.objs.get(objId);
if (!domImage) {
warn('Dependent image isn\'t ready yet');
return;
}
this.save();
var ctx = this.ctx;
// scale the image to the unit square
ctx.scale(1 / w, -1 / h);
ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
0, -h, w, h);
if (this.imageLayer) {
var currentTransform = ctx.mozCurrentTransformInverse;
var position = this.getCanvasPosition(0, 0);
this.imageLayer.appendImage({
objId: objId,
left: position[0],
top: position[1],
width: w / currentTransform[0],
height: h / currentTransform[3]
});
}
this.restore();
},
paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
var ctx = this.ctx;
var width = img.width, height = img.height;
var glyph = this.processingType3;
if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {
var MAX_SIZE_TO_COMPILE = 1000;
if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
glyph.compiled =
compileType3Glyph({data: img.data, width: width, height: height});
} else {
glyph.compiled = null;
}
}
if (glyph && glyph.compiled) {
glyph.compiled(ctx);
return;
}
var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, img);
maskCtx.globalCompositeOperation = 'source-in';
var fillColor = this.current.fillColor;
maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
fillColor.type === 'Pattern') ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
this.paintInlineImageXObject(maskCanvas.canvas);
},
paintImageMaskXObjectRepeat:
function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
scaleY, positions) {
var width = imgData.width;
var height = imgData.height;
var ctx = this.ctx;
var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, imgData);
maskCtx.globalCompositeOperation = 'source-in';
var fillColor = this.current.fillColor;
maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
fillColor.type === 'Pattern') ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
for (var i = 0, ii = positions.length; i < ii; i += 2) {
ctx.save();
ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
ctx.scale(1, -1);
ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
0, -1, 1, 1);
ctx.restore();
}
},
paintImageMaskXObjectGroup:
function CanvasGraphics_paintImageMaskXObjectGroup(images) {
var ctx = this.ctx;
for (var i = 0, ii = images.length; i < ii; i++) {
var image = images[i];
var width = image.width, height = image.height;
var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, image);
maskCtx.globalCompositeOperation = 'source-in';
var fillColor = this.current.fillColor;
maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&
fillColor.type === 'Pattern') ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
ctx.save();
ctx.transform.apply(ctx, image.transform);
ctx.scale(1, -1);
ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
0, -1, 1, 1);
ctx.restore();
}
},
paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
this.paintInlineImageXObject(imgData);
},
paintImageXObjectRepeat:
function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
positions) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
var width = imgData.width;
var height = imgData.height;
var map = [];
for (var i = 0, ii = positions.length; i < ii; i += 2) {
map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
positions[i + 1]], x: 0, y: 0, w: width, h: height});
}
this.paintInlineImageXObjectGroup(imgData, map);
},
paintInlineImageXObject:
function CanvasGraphics_paintInlineImageXObject(imgData) {
var width = imgData.width;
var height = imgData.height;
var ctx = this.ctx;
this.save();
// scale the image to the unit square
ctx.scale(1 / width, -1 / height);
var currentTransform = ctx.mozCurrentTransformInverse;
var a = currentTransform[0], b = currentTransform[1];
var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
var c = currentTransform[2], d = currentTransform[3];
var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
var imgToPaint, tmpCanvas;
// instanceof HTMLElement does not work in jsdom node.js module
if (imgData instanceof HTMLElement || !imgData.data) {
imgToPaint = imgData;
} else {
tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
var tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
imgToPaint = tmpCanvas.canvas;
}
var paintWidth = width, paintHeight = height;
var tmpCanvasId = 'prescale1';
// Vertial or horizontal scaling shall not be more than 2 to not loose the
// pixels during drawImage operation, painting on the temporary canvas(es)
// that are twice smaller in size
while ((widthScale > 2 && paintWidth > 1) ||
(heightScale > 2 && paintHeight > 1)) {
var newWidth = paintWidth, newHeight = paintHeight;
if (widthScale > 2 && paintWidth > 1) {
newWidth = Math.ceil(paintWidth / 2);
widthScale /= paintWidth / newWidth;
}
if (heightScale > 2 && paintHeight > 1) {
newHeight = Math.ceil(paintHeight / 2);
heightScale /= paintHeight / newHeight;
}
tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, newWidth, newHeight);
tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
0, 0, newWidth, newHeight);
imgToPaint = tmpCanvas.canvas;
paintWidth = newWidth;
paintHeight = newHeight;
tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
}
ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
0, -height, width, height);
if (this.imageLayer) {
var position = this.getCanvasPosition(0, -height);
this.imageLayer.appendImage({
imgData: imgData,
left: position[0],
top: position[1],
width: width / currentTransform[0],
height: height / currentTransform[3]
});
}
this.restore();
},
paintInlineImageXObjectGroup:
function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
var ctx = this.ctx;
var w = imgData.width;
var h = imgData.height;
var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
var tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
for (var i = 0, ii = map.length; i < ii; i++) {
var entry = map[i];
ctx.save();
ctx.transform.apply(ctx, entry.transform);
ctx.scale(1, -1);
ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
0, -1, 1, 1);
if (this.imageLayer) {
var position = this.getCanvasPosition(entry.x, entry.y);
this.imageLayer.appendImage({
imgData: imgData,
left: position[0],
top: position[1],
width: w,
height: h
});
}
ctx.restore();
}
},
paintSolidColorImageMask:
function CanvasGraphics_paintSolidColorImageMask() {
this.ctx.fillRect(0, 0, 1, 1);
},
// Marked content
markPoint: function CanvasGraphics_markPoint(tag) {
// TODO Marked content.
},
markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
// TODO Marked content.
},
beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
// TODO Marked content.
},
beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
tag, properties) {
// TODO Marked content.
},
endMarkedContent: function CanvasGraphics_endMarkedContent() {
// TODO Marked content.
},
// Compatibility
beginCompat: function CanvasGraphics_beginCompat() {
// TODO ignore undefined operators (should we do that anyway?)
},
endCompat: function CanvasGraphics_endCompat() {
// TODO stop ignoring undefined operators
},
// Helper functions
consumePath: function CanvasGraphics_consumePath() {
var ctx = this.ctx;
if (this.pendingClip) {
if (this.pendingClip === EO_CLIP) {
if (ctx.mozFillRule !== undefined) {
ctx.mozFillRule = 'evenodd';
ctx.clip();
ctx.mozFillRule = 'nonzero';
} else {
try {
ctx.clip('evenodd');
} catch (ex) {
// shouldn't really happen, but browsers might think differently
ctx.clip();
}
}
} else {
ctx.clip();
}
this.pendingClip = null;
}
ctx.beginPath();
},
getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
var inverse = this.ctx.mozCurrentTransformInverse;
// max of the current horizontal and vertical scale
return Math.sqrt(Math.max(
(inverse[0] * inverse[0] + inverse[1] * inverse[1]),
(inverse[2] * inverse[2] + inverse[3] * inverse[3])));
},
getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
var transform = this.ctx.mozCurrentTransform;
return [
transform[0] * x + transform[2] * y + transform[4],
transform[1] * x + transform[3] * y + transform[5]
];
}
};
for (var op in OPS) {
CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
}
return CanvasGraphics;
})();
var WebGLUtils = (function WebGLUtilsClosure() {
function loadShader(gl, code, shaderType) {
var shader = gl.createShader(shaderType);
gl.shaderSource(shader, code);
gl.compileShader(shader);
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
var errorMsg = gl.getShaderInfoLog(shader);
throw new Error('Error during shader compilation: ' + errorMsg);
}
return shader;
}
function createVertexShader(gl, code) {
return loadShader(gl, code, gl.VERTEX_SHADER);
}
function createFragmentShader(gl, code) {
return loadShader(gl, code, gl.FRAGMENT_SHADER);
}
function createProgram(gl, shaders) {
var program = gl.createProgram();
for (var i = 0, ii = shaders.length; i < ii; ++i) {
gl.attachShader(program, shaders[i]);
}
gl.linkProgram(program);
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var errorMsg = gl.getProgramInfoLog(program);
throw new Error('Error during program linking: ' + errorMsg);
}
return program;
}
function createTexture(gl, image, textureId) {
gl.activeTexture(textureId);
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Set the parameters so we can render any size image.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
return texture;
}
var currentGL, currentCanvas;
function generageGL() {
if (currentGL) {
return;
}
currentCanvas = document.createElement('canvas');
currentGL = currentCanvas.getContext('webgl',
{ premultipliedalpha: false });
}
var smaskVertexShaderCode = '\
attribute vec2 a_position; \
attribute vec2 a_texCoord; \
\
uniform vec2 u_resolution; \
\
varying vec2 v_texCoord; \
\
void main() { \
vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
\
v_texCoord = a_texCoord; \
} ';
var smaskFragmentShaderCode = '\
precision mediump float; \
\
uniform vec4 u_backdrop; \
uniform int u_subtype; \
uniform sampler2D u_image; \
uniform sampler2D u_mask; \
\
varying vec2 v_texCoord; \
\
void main() { \
vec4 imageColor = texture2D(u_image, v_texCoord); \
vec4 maskColor = texture2D(u_mask, v_texCoord); \
if (u_backdrop.a > 0.0) { \
maskColor.rgb = maskColor.rgb * maskColor.a + \
u_backdrop.rgb * (1.0 - maskColor.a); \
} \
float lum; \
if (u_subtype == 0) { \
lum = maskColor.a; \
} else { \
lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
maskColor.b * 0.11; \
} \
imageColor.a *= lum; \
imageColor.rgb *= imageColor.a; \
gl_FragColor = imageColor; \
} ';
var smaskCache = null;
function initSmaskGL() {
var canvas, gl;
generageGL();
canvas = currentCanvas;
currentCanvas = null;
gl = currentGL;
currentGL = null;
// setup a GLSL program
var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
var program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
var cache = {};
cache.gl = gl;
cache.canvas = canvas;
cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
cache.positionLocation = gl.getAttribLocation(program, 'a_position');
cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
var texLayerLocation = gl.getUniformLocation(program, 'u_image');
var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
// provide texture coordinates for the rectangle.
var texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texCoordLocation);
gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
gl.uniform1i(texLayerLocation, 0);
gl.uniform1i(texMaskLocation, 1);
smaskCache = cache;
}
function composeSMask(layer, mask, properties) {
var width = layer.width, height = layer.height;
if (!smaskCache) {
initSmaskGL();
}
var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
canvas.width = width;
canvas.height = height;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.uniform2f(cache.resolutionLocation, width, height);
if (properties.backdrop) {
gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
properties.backdrop[1], properties.backdrop[2], 1);
} else {
gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
}
gl.uniform1i(cache.subtypeLocation,
properties.subtype === 'Luminosity' ? 1 : 0);
// Create a textures
var texture = createTexture(gl, layer, gl.TEXTURE0);
var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
// Create a buffer and put a single clipspace rectangle in
// it (2 triangles)
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0, 0,
width, 0,
0, height,
0, height,
width, 0,
width, height]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.positionLocation);
gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
// draw
gl.clearColor(0, 0, 0, 0);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 6);
gl.flush();
gl.deleteTexture(texture);
gl.deleteTexture(maskTexture);
gl.deleteBuffer(buffer);
return canvas;
}
var figuresVertexShaderCode = '\
attribute vec2 a_position; \
attribute vec3 a_color; \
\
uniform vec2 u_resolution; \
uniform vec2 u_scale; \
uniform vec2 u_offset; \
\
varying vec4 v_color; \
\
void main() { \
vec2 position = (a_position + u_offset) * u_scale; \
vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
\
v_color = vec4(a_color / 255.0, 1.0); \
} ';
var figuresFragmentShaderCode = '\
precision mediump float; \
\
varying vec4 v_color; \
\
void main() { \
gl_FragColor = v_color; \
} ';
var figuresCache = null;
function initFiguresGL() {
var canvas, gl;
generageGL();
canvas = currentCanvas;
currentCanvas = null;
gl = currentGL;
currentGL = null;
// setup a GLSL program
var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
var program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
var cache = {};
cache.gl = gl;
cache.canvas = canvas;
cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
cache.positionLocation = gl.getAttribLocation(program, 'a_position');
cache.colorLocation = gl.getAttribLocation(program, 'a_color');
figuresCache = cache;
}
function drawFigures(width, height, backgroundColor, figures, context) {
if (!figuresCache) {
initFiguresGL();
}
var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
canvas.width = width;
canvas.height = height;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.uniform2f(cache.resolutionLocation, width, height);
// count triangle points
var count = 0;
var i, ii, rows;
for (i = 0, ii = figures.length; i < ii; i++) {
switch (figures[i].type) {
case 'lattice':
rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
break;
case 'triangles':
count += figures[i].coords.length;
break;
}
}
// transfer data
var coords = new Float32Array(count * 2);
var colors = new Uint8Array(count * 3);
var coordsMap = context.coords, colorsMap = context.colors;
var pIndex = 0, cIndex = 0;
for (i = 0, ii = figures.length; i < ii; i++) {
var figure = figures[i], ps = figure.coords, cs = figure.colors;
switch (figure.type) {
case 'lattice':
var cols = figure.verticesPerRow;
rows = (ps.length / cols) | 0;
for (var row = 1; row < rows; row++) {
var offset = row * cols + 1;
for (var col = 1; col < cols; col++, offset++) {
coords[pIndex] = coordsMap[ps[offset - cols - 1]];
coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
coords[pIndex + 2] = coordsMap[ps[offset - cols]];
coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
coords[pIndex + 4] = coordsMap[ps[offset - 1]];
coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
colors[cIndex] = colorsMap[cs[offset - cols - 1]];
colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
colors[cIndex + 3] = colorsMap[cs[offset - cols]];
colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
colors[cIndex + 6] = colorsMap[cs[offset - 1]];
colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
coords[pIndex + 6] = coords[pIndex + 2];
coords[pIndex + 7] = coords[pIndex + 3];
coords[pIndex + 8] = coords[pIndex + 4];
coords[pIndex + 9] = coords[pIndex + 5];
coords[pIndex + 10] = coordsMap[ps[offset]];
coords[pIndex + 11] = coordsMap[ps[offset] + 1];
colors[cIndex + 9] = colors[cIndex + 3];
colors[cIndex + 10] = colors[cIndex + 4];
colors[cIndex + 11] = colors[cIndex + 5];
colors[cIndex + 12] = colors[cIndex + 6];
colors[cIndex + 13] = colors[cIndex + 7];
colors[cIndex + 14] = colors[cIndex + 8];
colors[cIndex + 15] = colorsMap[cs[offset]];
colors[cIndex + 16] = colorsMap[cs[offset] + 1];
colors[cIndex + 17] = colorsMap[cs[offset] + 2];
pIndex += 12;
cIndex += 18;
}
}
break;
case 'triangles':
for (var j = 0, jj = ps.length; j < jj; j++) {
coords[pIndex] = coordsMap[ps[j]];
coords[pIndex + 1] = coordsMap[ps[j] + 1];
colors[cIndex] = colorsMap[cs[i]];
colors[cIndex + 1] = colorsMap[cs[j] + 1];
colors[cIndex + 2] = colorsMap[cs[j] + 2];
pIndex += 2;
cIndex += 3;
}
break;
}
}
// draw
if (backgroundColor) {
gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
backgroundColor[2] / 255, 1.0);
} else {
gl.clearColor(0, 0, 0, 0);
}
gl.clear(gl.COLOR_BUFFER_BIT);
var coordsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.positionLocation);
gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
var colorsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.colorLocation);
gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
0, 0);
gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
gl.drawArrays(gl.TRIANGLES, 0, count);
gl.flush();
gl.deleteBuffer(coordsBuffer);
gl.deleteBuffer(colorsBuffer);
return canvas;
}
function cleanup() {
if (smaskCache && smaskCache.canvas) {
smaskCache.canvas.width = 0;
smaskCache.canvas.height = 0;
}
if (figuresCache && figuresCache.canvas) {
figuresCache.canvas.width = 0;
figuresCache.canvas.height = 0;
}
smaskCache = null;
figuresCache = null;
}
return {
get isEnabled() {
if (PDFJS.disableWebGL) {
return false;
}
var enabled = false;
try {
generageGL();
enabled = !!currentGL;
} catch (e) { }
return shadow(this, 'isEnabled', enabled);
},
composeSMask: composeSMask,
drawFigures: drawFigures,
clear: cleanup
};
})();
var ShadingIRs = {};
ShadingIRs.RadialAxial = {
fromIR: function RadialAxial_fromIR(raw) {
var type = raw[1];
var colorStops = raw[2];
var p0 = raw[3];
var p1 = raw[4];
var r0 = raw[5];
var r1 = raw[6];
return {
type: 'Pattern',
getPattern: function RadialAxial_getPattern(ctx) {
var grad;
if (type === 'axial') {
grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
} else if (type === 'radial') {
grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
}
for (var i = 0, ii = colorStops.length; i < ii; ++i) {
var c = colorStops[i];
grad.addColorStop(c[0], c[1]);
}
return grad;
}
};
}
};
var createMeshCanvas = (function createMeshCanvasClosure() {
function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
// Very basic Gouraud-shaded triangle rasterization algorithm.
var coords = context.coords, colors = context.colors;
var bytes = data.data, rowSize = data.width * 4;
var tmp;
if (coords[p1 + 1] > coords[p2 + 1]) {
tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
}
if (coords[p2 + 1] > coords[p3 + 1]) {
tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
}
if (coords[p1 + 1] > coords[p2 + 1]) {
tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
}
var x1 = (coords[p1] + context.offsetX) * context.scaleX;
var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
var x2 = (coords[p2] + context.offsetX) * context.scaleX;
var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
var x3 = (coords[p3] + context.offsetX) * context.scaleX;
var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
if (y1 >= y3) {
return;
}
var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
var minY = Math.round(y1), maxY = Math.round(y3);
var xa, car, cag, cab;
var xb, cbr, cbg, cbb;
var k;
for (var y = minY; y <= maxY; y++) {
if (y < y2) {
k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
xa = x1 - (x1 - x2) * k;
car = c1r - (c1r - c2r) * k;
cag = c1g - (c1g - c2g) * k;
cab = c1b - (c1b - c2b) * k;
} else {
k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
xa = x2 - (x2 - x3) * k;
car = c2r - (c2r - c3r) * k;
cag = c2g - (c2g - c3g) * k;
cab = c2b - (c2b - c3b) * k;
}
k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
xb = x1 - (x1 - x3) * k;
cbr = c1r - (c1r - c3r) * k;
cbg = c1g - (c1g - c3g) * k;
cbb = c1b - (c1b - c3b) * k;
var x1_ = Math.round(Math.min(xa, xb));
var x2_ = Math.round(Math.max(xa, xb));
var j = rowSize * y + x1_ * 4;
for (var x = x1_; x <= x2_; x++) {
k = (xa - x) / (xa - xb);
k = k < 0 ? 0 : k > 1 ? 1 : k;
bytes[j++] = (car - (car - cbr) * k) | 0;
bytes[j++] = (cag - (cag - cbg) * k) | 0;
bytes[j++] = (cab - (cab - cbb) * k) | 0;
bytes[j++] = 255;
}
}
}
function drawFigure(data, figure, context) {
var ps = figure.coords;
var cs = figure.colors;
var i, ii;
switch (figure.type) {
case 'lattice':
var verticesPerRow = figure.verticesPerRow;
var rows = Math.floor(ps.length / verticesPerRow) - 1;
var cols = verticesPerRow - 1;
for (i = 0; i < rows; i++) {
var q = i * verticesPerRow;
for (var j = 0; j < cols; j++, q++) {
drawTriangle(data, context,
ps[q], ps[q + 1], ps[q + verticesPerRow],
cs[q], cs[q + 1], cs[q + verticesPerRow]);
drawTriangle(data, context,
ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
}
}
break;
case 'triangles':
for (i = 0, ii = ps.length; i < ii; i += 3) {
drawTriangle(data, context,
ps[i], ps[i + 1], ps[i + 2],
cs[i], cs[i + 1], cs[i + 2]);
}
break;
default:
error('illigal figure');
break;
}
}
function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
backgroundColor) {
// we will increase scale on some weird factor to let antialiasing take
// care of "rough" edges
var EXPECTED_SCALE = 1.1;
// MAX_PATTERN_SIZE is used to avoid OOM situation.
var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
var offsetX = Math.floor(bounds[0]);
var offsetY = Math.floor(bounds[1]);
var boundsWidth = Math.ceil(bounds[2]) - offsetX;
var boundsHeight = Math.ceil(bounds[3]) - offsetY;
var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
EXPECTED_SCALE)), MAX_PATTERN_SIZE);
var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
EXPECTED_SCALE)), MAX_PATTERN_SIZE);
var scaleX = boundsWidth / width;
var scaleY = boundsHeight / height;
var context = {
coords: coords,
colors: colors,
offsetX: -offsetX,
offsetY: -offsetY,
scaleX: 1 / scaleX,
scaleY: 1 / scaleY
};
var canvas, tmpCanvas, i, ii;
if (WebGLUtils.isEnabled) {
canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
figures, context);
// https://bugzilla.mozilla.org/show_bug.cgi?id=972126
tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
tmpCanvas.context.drawImage(canvas, 0, 0);
canvas = tmpCanvas.canvas;
} else {
tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
var tmpCtx = tmpCanvas.context;
var data = tmpCtx.createImageData(width, height);
if (backgroundColor) {
var bytes = data.data;
for (i = 0, ii = bytes.length; i < ii; i += 4) {
bytes[i] = backgroundColor[0];
bytes[i + 1] = backgroundColor[1];
bytes[i + 2] = backgroundColor[2];
bytes[i + 3] = 255;
}
}
for (i = 0; i < figures.length; i++) {
drawFigure(data, figures[i], context);
}
tmpCtx.putImageData(data, 0, 0);
canvas = tmpCanvas.canvas;
}
return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
scaleX: scaleX, scaleY: scaleY};
}
return createMeshCanvas;
})();
ShadingIRs.Mesh = {
fromIR: function Mesh_fromIR(raw) {
//var type = raw[1];
var coords = raw[2];
var colors = raw[3];
var figures = raw[4];
var bounds = raw[5];
var matrix = raw[6];
//var bbox = raw[7];
var background = raw[8];
return {
type: 'Pattern',
getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
var scale;
if (shadingFill) {
scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
} else {
// Obtain scale from matrix and current transformation matrix.
scale = Util.singularValueDecompose2dScale(owner.baseTransform);
if (matrix) {
var matrixScale = Util.singularValueDecompose2dScale(matrix);
scale = [scale[0] * matrixScale[0],
scale[1] * matrixScale[1]];
}
}
// Rasterizing on the main thread since sending/queue large canvases
// might cause OOM.
var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
colors, figures, shadingFill ? null : background);
if (!shadingFill) {
ctx.setTransform.apply(ctx, owner.baseTransform);
if (matrix) {
ctx.transform.apply(ctx, matrix);
}
}
ctx.translate(temporaryPatternCanvas.offsetX,
temporaryPatternCanvas.offsetY);
ctx.scale(temporaryPatternCanvas.scaleX,
temporaryPatternCanvas.scaleY);
return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
}
};
}
};
ShadingIRs.Dummy = {
fromIR: function Dummy_fromIR() {
return {
type: 'Pattern',
getPattern: function Dummy_fromIR_getPattern() {
return 'hotpink';
}
};
}
};
function getShadingPatternFromIR(raw) {
var shadingIR = ShadingIRs[raw[0]];
if (!shadingIR) {
error('Unknown IR type: ' + raw[0]);
}
return shadingIR.fromIR(raw);
}
var TilingPattern = (function TilingPatternClosure() {
var PaintType = {
COLORED: 1,
UNCOLORED: 2
};
var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
this.operatorList = IR[2];
this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
this.bbox = IR[4];
this.xstep = IR[5];
this.ystep = IR[6];
this.paintType = IR[7];
this.tilingType = IR[8];
this.color = color;
this.objs = objs;
this.commonObjs = commonObjs;
this.baseTransform = baseTransform;
this.type = 'Pattern';
this.ctx = ctx;
}
TilingPattern.prototype = {
createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
var operatorList = this.operatorList;
var bbox = this.bbox;
var xstep = this.xstep;
var ystep = this.ystep;
var paintType = this.paintType;
var tilingType = this.tilingType;
var color = this.color;
var objs = this.objs;
var commonObjs = this.commonObjs;
info('TilingType: ' + tilingType);
var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
var topLeft = [x0, y0];
// we want the canvas to be as large as the step size
var botRight = [x0 + xstep, y0 + ystep];
var width = botRight[0] - topLeft[0];
var height = botRight[1] - topLeft[1];
// Obtain scale from matrix and current transformation matrix.
var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
var curMatrixScale = Util.singularValueDecompose2dScale(
this.baseTransform);
var combinedScale = [matrixScale[0] * curMatrixScale[0],
matrixScale[1] * curMatrixScale[1]];
// MAX_PATTERN_SIZE is used to avoid OOM situation.
// Use width and height values that are as close as possible to the end
// result when the pattern is used. Too low value makes the pattern look
// blurry. Too large value makes it look too crispy.
width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
MAX_PATTERN_SIZE);
height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
MAX_PATTERN_SIZE);
var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
var tmpCtx = tmpCanvas.context;
var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
graphics.groupLevel = owner.groupLevel;
this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
this.setScale(width, height, xstep, ystep);
this.transformToScale(graphics);
// transform coordinates to pattern space
var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
graphics.transform.apply(graphics, tmpTranslate);
this.clipBbox(graphics, bbox, x0, y0, x1, y1);
graphics.executeOperatorList(operatorList);
return tmpCanvas.canvas;
},
setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
this.scale = [width / xstep, height / ystep];
},
transformToScale: function TilingPattern_transformToScale(graphics) {
var scale = this.scale;
var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
graphics.transform.apply(graphics, tmpScale);
},
scaleToContext: function TilingPattern_scaleToContext() {
var scale = this.scale;
this.ctx.scale(1 / scale[0], 1 / scale[1]);
},
clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
if (bbox && isArray(bbox) && bbox.length === 4) {
var bboxWidth = x1 - x0;
var bboxHeight = y1 - y0;
graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
graphics.clip();
graphics.endPath();
}
},
setFillAndStrokeStyleToContext:
function setFillAndStrokeStyleToContext(context, paintType, color) {
switch (paintType) {
case PaintType.COLORED:
var ctx = this.ctx;
context.fillStyle = ctx.fillStyle;
context.strokeStyle = ctx.strokeStyle;
break;
case PaintType.UNCOLORED:
var cssColor = Util.makeCssRgb(color);
context.fillStyle = cssColor;
context.strokeStyle = cssColor;
break;
default:
error('Unsupported paint type: ' + paintType);
}
},
getPattern: function TilingPattern_getPattern(ctx, owner) {
var temporaryPatternCanvas = this.createPatternCanvas(owner);
ctx = this.ctx;
ctx.setTransform.apply(ctx, this.baseTransform);
ctx.transform.apply(ctx, this.matrix);
this.scaleToContext();
return ctx.createPattern(temporaryPatternCanvas, 'repeat');
}
};
return TilingPattern;
})();
PDFJS.disableFontFace = false;
var FontLoader = {
insertRule: function fontLoaderInsertRule(rule) {
var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.id = 'PDFJS_FONT_STYLE_TAG';
document.documentElement.getElementsByTagName('head')[0].appendChild(
styleElement);
}
var styleSheet = styleElement.sheet;
styleSheet.insertRule(rule, styleSheet.cssRules.length);
},
clear: function fontLoaderClear() {
var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
if (styleElement) {
styleElement.parentNode.removeChild(styleElement);
}
this.nativeFontFaces.forEach(function(nativeFontFace) {
document.fonts.delete(nativeFontFace);
});
this.nativeFontFaces.length = 0;
},
get loadTestFont() {
// This is a CFF font with 1 glyph for '.' that fills its entire width and
// height.
return shadow(this, 'loadTestFont', atob(
'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
'ABAAAAAAAAAAAD6AAAAAAAAA=='
));
},
loadTestFontId: 0,
loadingContext: {
requests: [],
nextRequestId: 0
},
isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
if (isWorker) {
return false;
}
// User agent string sniffing is bad, but there is no reliable way to tell
// if font is fully loaded and ready to be used with canvas.
var userAgent = window.navigator.userAgent;
var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
if (m && m[1] >= 14) {
return true;
}
// TODO other browsers
if (userAgent === 'node') {
return true;
}
return false;
})(),
nativeFontFaces: [],
isFontLoadingAPISupported: !isWorker && !!document.fonts,
addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
this.nativeFontFaces.push(nativeFontFace);
document.fonts.add(nativeFontFace);
},
bind: function fontLoaderBind(fonts, callback) {
assert(!isWorker, 'bind() shall be called from main thread');
var rules = [];
var fontsToLoad = [];
var fontLoadPromises = [];
for (var i = 0, ii = fonts.length; i < ii; i++) {
var font = fonts[i];
// Add the font to the DOM only once or skip if the font
// is already loaded.
if (font.attached || font.loading === false) {
continue;
}
font.attached = true;
if (this.isFontLoadingAPISupported) {
var nativeFontFace = font.createNativeFontFace();
if (nativeFontFace) {
fontLoadPromises.push(nativeFontFace.loaded);
}
} else {
var rule = font.bindDOM();
if (rule) {
rules.push(rule);
fontsToLoad.push(font);
}
}
}
var request = FontLoader.queueLoadingCallback(callback);
if (this.isFontLoadingAPISupported) {
Promise.all(fontsToLoad).then(function() {
request.complete();
});
} else if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
} else {
request.complete();
}
},
queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
function LoadLoader_completeRequest() {
assert(!request.end, 'completeRequest() cannot be called twice');
request.end = Date.now();
// sending all completed requests in order how they were queued
while (context.requests.length > 0 && context.requests[0].end) {
var otherRequest = context.requests.shift();
setTimeout(otherRequest.callback, 0);
}
}
var context = FontLoader.loadingContext;
var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
var request = {
id: requestId,
complete: LoadLoader_completeRequest,
callback: callback,
started: Date.now()
};
context.requests.push(request);
return request;
},
prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
fonts,
request) {
/** Hack begin */
// There's currently no event when a font has finished downloading so the
// following code is a dirty hack to 'guess' when a font is
// ready. It's assumed fonts are loaded in order, so add a known test
// font after the desired fonts and then test for the loading of that
// test font.
function int32(data, offset) {
return (data.charCodeAt(offset) << 24) |
(data.charCodeAt(offset + 1) << 16) |
(data.charCodeAt(offset + 2) << 8) |
(data.charCodeAt(offset + 3) & 0xff);
}
function spliceString(s, offset, remove, insert) {
var chunk1 = s.substr(0, offset);
var chunk2 = s.substr(offset + remove);
return chunk1 + insert + chunk2;
}
var i, ii;
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext('2d');
var called = 0;
function isFontReady(name, callback) {
called++;
// With setTimeout clamping this gives the font ~100ms to load.
if(called > 30) {
warn('Load test font never loaded.');
callback();
return;
}
ctx.font = '30px ' + name;
ctx.fillText('.', 0, 20);
var imageData = ctx.getImageData(0, 0, 1, 1);
if (imageData.data[3] > 0) {
callback();
return;
}
setTimeout(isFontReady.bind(null, name, callback));
}
var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
// Chromium seems to cache fonts based on a hash of the actual font data,
// so the font must be modified for each load test else it will appear to
// be loaded already.
// TODO: This could maybe be made faster by avoiding the btoa of the full
// font by splitting it in chunks before hand and padding the font id.
var data = this.loadTestFont;
var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
loadTestFontId);
// CFF checksum is important for IE, adjusting it
var CFF_CHECKSUM_OFFSET = 16;
var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
var checksum = int32(data, CFF_CHECKSUM_OFFSET);
for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
}
if (i < loadTestFontId.length) { // align to 4 bytes boundary
checksum = (checksum - XXXX_VALUE +
int32(loadTestFontId + 'XXX', i)) | 0;
}
data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
url + '}';
FontLoader.insertRule(rule);
var names = [];
for (i = 0, ii = fonts.length; i < ii; i++) {
names.push(fonts[i].loadedName);
}
names.push(loadTestFontId);
var div = document.createElement('div');
div.setAttribute('style',
'visibility: hidden;' +
'width: 10px; height: 10px;' +
'position: absolute; top: 0px; left: 0px;');
for (i = 0, ii = names.length; i < ii; ++i) {
var span = document.createElement('span');
span.textContent = 'Hi';
span.style.fontFamily = names[i];
div.appendChild(span);
}
document.body.appendChild(div);
isFontReady(loadTestFontId, function() {
document.body.removeChild(div);
request.complete();
});
/** Hack end */
}
};
var FontFaceObject = (function FontFaceObjectClosure() {
function FontFaceObject(name, file, properties) {
this.compiledGlyphs = {};
if (arguments.length === 1) {
// importing translated data
var data = arguments[0];
for (var i in data) {
this[i] = data[i];
}
return;
}
}
FontFaceObject.prototype = {
createNativeFontFace: function FontFaceObject_createNativeFontFace() {
if (!this.data) {
return null;
}
if (PDFJS.disableFontFace) {
this.disableFontFace = true;
return null;
}
var nativeFontFace = new FontFace(this.loadedName, this.data, {});
FontLoader.addNativeFontFace(nativeFontFace);
if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
globalScope['FontInspector'].enabled) {
globalScope['FontInspector'].fontAdded(this);
}
return nativeFontFace;
},
bindDOM: function FontFaceObject_bindDOM() {
if (!this.data) {
return null;
}
if (PDFJS.disableFontFace) {
this.disableFontFace = true;
return null;
}
var data = bytesToString(new Uint8Array(this.data));
var fontName = this.loadedName;
// Add the font-face rule to the document
var url = ('url(data:' + this.mimetype + ';base64,' +
window.btoa(data) + ');');
var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
FontLoader.insertRule(rule);
if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
globalScope['FontInspector'].enabled) {
globalScope['FontInspector'].fontAdded(this, url);
}
return rule;
},
getPathGenerator: function FontLoader_getPathGenerator(objs, character) {
if (!(character in this.compiledGlyphs)) {
var js = objs.get(this.loadedName + '_path_' + character);
/*jshint -W054 */
this.compiledGlyphs[character] = new Function('c', 'size', js);
}
return this.compiledGlyphs[character];
}
};
return FontFaceObject;
})();
var HIGHLIGHT_OFFSET = 4; // px
var ANNOT_MIN_SIZE = 10; // px
var AnnotationUtils = (function AnnotationUtilsClosure() {
// TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
function setTextStyles(element, item, fontObj) {
var style = element.style;
style.fontSize = item.fontSize + 'px';
style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
if (!fontObj) {
return;
}
style.fontWeight = fontObj.black ?
(fontObj.bold ? 'bolder' : 'bold') :
(fontObj.bold ? 'bold' : 'normal');
style.fontStyle = fontObj.italic ? 'italic' : 'normal';
var fontName = fontObj.loadedName;
var fontFamily = fontName ? '"' + fontName + '", ' : '';
// Use a reasonable default font if the font doesn't specify a fallback
var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
style.fontFamily = fontFamily + fallbackName;
}
// TODO(mack): Remove this, it's not really that helpful.
function getEmptyContainer(tagName, rect, borderWidth) {
var bWidth = borderWidth || 0;
var element = document.createElement(tagName);
element.style.borderWidth = bWidth + 'px';
var width = rect[2] - rect[0] - 2 * bWidth;
var height = rect[3] - rect[1] - 2 * bWidth;
element.style.width = width + 'px';
element.style.height = height + 'px';
return element;
}
function initContainer(item) {
var container = getEmptyContainer('section', item.rect, item.borderWidth);
container.style.backgroundColor = item.color;
var color = item.color;
var rgb = [];
for (var i = 0; i < 3; ++i) {
rgb[i] = Math.round(color[i] * 255);
}
item.colorCssRgb = Util.makeCssRgb(rgb);
var highlight = document.createElement('div');
highlight.className = 'annotationHighlight';
highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';
highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';
highlight.setAttribute('hidden', true);
item.highlightElement = highlight;
container.appendChild(item.highlightElement);
return container;
}
function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
var element = getEmptyContainer('div', item.rect, 0);
element.style.display = 'table';
var content = document.createElement('div');
content.textContent = item.fieldValue;
var textAlignment = item.textAlignment;
content.style.textAlign = ['left', 'center', 'right'][textAlignment];
content.style.verticalAlign = 'middle';
content.style.display = 'table-cell';
var fontObj = item.fontRefName ?
commonObjs.getData(item.fontRefName) : null;
setTextStyles(content, item, fontObj);
element.appendChild(content);
return element;
}
function getHtmlElementForTextAnnotation(item) {
var rect = item.rect;
// sanity check because of OOo-generated PDFs
if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
rect[3] = rect[1] + ANNOT_MIN_SIZE;
}
if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
}
var container = initContainer(item);
container.className = 'annotText';
var image = document.createElement('img');
image.style.height = container.style.height;
image.style.width = container.style.width;
var iconName = item.name;
image.src = PDFJS.imageResourcesPath + 'annotation-' +
iconName.toLowerCase() + '.svg';
image.alt = '[{{type}} Annotation]';
image.dataset.l10nId = 'text_annotation_type';
image.dataset.l10nArgs = JSON.stringify({type: iconName});
var contentWrapper = document.createElement('div');
contentWrapper.className = 'annotTextContentWrapper';
contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
contentWrapper.style.top = '-10px';
var content = document.createElement('div');
content.className = 'annotTextContent';
content.setAttribute('hidden', true);
var i, ii;
if (item.hasBgColor) {
var color = item.color;
var rgb = [];
for (i = 0; i < 3; ++i) {
// Enlighten the color (70%)
var c = Math.round(color[i] * 255);
rgb[i] = Math.round((255 - c) * 0.7) + c;
}
content.style.backgroundColor = Util.makeCssRgb(rgb);
}
var title = document.createElement('h1');
var text = document.createElement('p');
title.textContent = item.title;
if (!item.content && !item.title) {
content.setAttribute('hidden', true);
} else {
var e = document.createElement('span');
var lines = item.content.split(/(?:\r\n?|\n)/);
for (i = 0, ii = lines.length; i < ii; ++i) {
var line = lines[i];
e.appendChild(document.createTextNode(line));
if (i < (ii - 1)) {
e.appendChild(document.createElement('br'));
}
}
text.appendChild(e);
var pinned = false;
var showAnnotation = function showAnnotation(pin) {
if (pin) {
pinned = true;
}
if (content.hasAttribute('hidden')) {
container.style.zIndex += 1;
content.removeAttribute('hidden');
}
};
var hideAnnotation = function hideAnnotation(unpin) {
if (unpin) {
pinned = false;
}
if (!content.hasAttribute('hidden') && !pinned) {
container.style.zIndex -= 1;
content.setAttribute('hidden', true);
}
};
var toggleAnnotation = function toggleAnnotation() {
if (pinned) {
hideAnnotation(true);
} else {
showAnnotation(true);
}
};
image.addEventListener('click', function image_clickHandler() {
toggleAnnotation();
}, false);
image.addEventListener('mouseover', function image_mouseOverHandler() {
showAnnotation();
}, false);
image.addEventListener('mouseout', function image_mouseOutHandler() {
hideAnnotation();
}, false);
content.addEventListener('click', function content_clickHandler() {
hideAnnotation(true);
}, false);
}
content.appendChild(title);
content.appendChild(text);
contentWrapper.appendChild(content);
container.appendChild(image);
container.appendChild(contentWrapper);
return container;
}
function getHtmlElementForLinkAnnotation(item) {
var container = initContainer(item);
container.className = 'annotLink';
container.style.borderColor = item.colorCssRgb;
container.style.borderStyle = 'solid';
var link = document.createElement('a');
link.href = link.title = item.url || '';
container.appendChild(link);
return container;
}
function getHtmlElement(data, objs) {
switch (data.annotationType) {
case AnnotationType.WIDGET:
return getHtmlElementForTextWidgetAnnotation(data, objs);
case AnnotationType.TEXT:
return getHtmlElementForTextAnnotation(data);
case AnnotationType.LINK:
return getHtmlElementForLinkAnnotation(data);
default:
throw new Error('Unsupported annotationType: ' + data.annotationType);
}
}
return {
getHtmlElement: getHtmlElement
};
})();
PDFJS.AnnotationUtils = AnnotationUtils;
var SVG_DEFAULTS = {
fontStyle: 'normal',
fontWeight: 'normal',
fillColor: '#000000'
};
var convertImgDataToPng = (function convertImgDataToPngClosure() {
var PNG_HEADER =
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
var CHUNK_WRAPPER_SIZE = 12;
var crcTable = new Int32Array(256);
for (var i = 0; i < 256; i++) {
var c = i;
for (var h = 0; h < 8; h++) {
if (c & 1) {
c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
} else {
c = (c >> 1) & 0x7fffffff;
}
}
crcTable[i] = c;
}
function crc32(data, start, end) {
var crc = -1;
for (var i = start; i < end; i++) {
var a = (crc ^ data[i]) & 0xff;
var b = crcTable[a];
crc = (crc >>> 8) ^ b;
}
return crc ^ -1;
}
function writePngChunk(type, body, data, offset) {
var p = offset;
var len = body.length;
data[p] = len >> 24 & 0xff;
data[p + 1] = len >> 16 & 0xff;
data[p + 2] = len >> 8 & 0xff;
data[p + 3] = len & 0xff;
p += 4;
data[p] = type.charCodeAt(0) & 0xff;
data[p + 1] = type.charCodeAt(1) & 0xff;
data[p + 2] = type.charCodeAt(2) & 0xff;
data[p + 3] = type.charCodeAt(3) & 0xff;
p += 4;
data.set(body, p);
p += body.length;
var crc = crc32(data, offset + 4, p);
data[p] = crc >> 24 & 0xff;
data[p + 1] = crc >> 16 & 0xff;
data[p + 2] = crc >> 8 & 0xff;
data[p + 3] = crc & 0xff;
}
function adler32(data, start, end) {
var a = 1;
var b = 0;
for (var i = start; i < end; ++i) {
a = (a + (data[i] & 0xff)) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
function encode(imgData, kind) {
var width = imgData.width;
var height = imgData.height;
var bitDepth, colorType, lineSize;
var bytes = imgData.data;
switch (kind) {
case ImageKind.GRAYSCALE_1BPP:
colorType = 0;
bitDepth = 1;
lineSize = (width + 7) >> 3;
break;
case ImageKind.RGB_24BPP:
colorType = 2;
bitDepth = 8;
lineSize = width * 3;
break;
case ImageKind.RGBA_32BPP:
colorType = 6;
bitDepth = 8;
lineSize = width * 4;
break;
default:
throw new Error('invalid format');
}
// prefix every row with predictor 0
var literals = new Uint8Array((1 + lineSize) * height);
var offsetLiterals = 0, offsetBytes = 0;
var y, i;
for (y = 0; y < height; ++y) {
literals[offsetLiterals++] = 0; // no prediction
literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
offsetLiterals);
offsetBytes += lineSize;
offsetLiterals += lineSize;
}
if (kind === ImageKind.GRAYSCALE_1BPP) {
// inverting for B/W
offsetLiterals = 0;
for (y = 0; y < height; y++) {
offsetLiterals++; // skipping predictor
for (i = 0; i < lineSize; i++) {
literals[offsetLiterals++] ^= 0xFF;
}
}
}
var ihdr = new Uint8Array([
width >> 24 & 0xff,
width >> 16 & 0xff,
width >> 8 & 0xff,
width & 0xff,
height >> 24 & 0xff,
height >> 16 & 0xff,
height >> 8 & 0xff,
height & 0xff,
bitDepth, // bit depth
colorType, // color type
0x00, // compression method
0x00, // filter method
0x00 // interlace method
]);
var len = literals.length;
var maxBlockLength = 0xFFFF;
var deflateBlocks = Math.ceil(len / maxBlockLength);
var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
var pi = 0;
idat[pi++] = 0x78; // compression method and flags
idat[pi++] = 0x9c; // flags
var pos = 0;
while (len > maxBlockLength) {
// writing non-final DEFLATE blocks type 0 and length of 65535
idat[pi++] = 0x00;
idat[pi++] = 0xff;
idat[pi++] = 0xff;
idat[pi++] = 0x00;
idat[pi++] = 0x00;
idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
pi += maxBlockLength;
pos += maxBlockLength;
len -= maxBlockLength;
}
// writing non-final DEFLATE blocks type 0
idat[pi++] = 0x01;
idat[pi++] = len & 0xff;
idat[pi++] = len >> 8 & 0xff;
idat[pi++] = (~len & 0xffff) & 0xff;
idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
idat.set(literals.subarray(pos), pi);
pi += literals.length - pos;
var adler = adler32(literals, 0, literals.length); // checksum
idat[pi++] = adler >> 24 & 0xff;
idat[pi++] = adler >> 16 & 0xff;
idat[pi++] = adler >> 8 & 0xff;
idat[pi++] = adler & 0xff;
// PNG will consists: header, IHDR+data, IDAT+data, and IEND.
var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
ihdr.length + idat.length;
var data = new Uint8Array(pngLength);
var offset = 0;
data.set(PNG_HEADER, offset);
offset += PNG_HEADER.length;
writePngChunk('IHDR', ihdr, data, offset);
offset += CHUNK_WRAPPER_SIZE + ihdr.length;
writePngChunk('IDATA', idat, data, offset);
offset += CHUNK_WRAPPER_SIZE + idat.length;
writePngChunk('IEND', new Uint8Array(0), data, offset);
return PDFJS.createObjectURL(data, 'image/png');
}
return function convertImgDataToPng(imgData) {
var kind = (imgData.kind === undefined ?
ImageKind.GRAYSCALE_1BPP : imgData.kind);
return encode(imgData, kind);
};
})();
var SVGExtraState = (function SVGExtraStateClosure() {
function SVGExtraState() {
this.fontSizeScale = 1;
this.fontWeight = SVG_DEFAULTS.fontWeight;
this.fontSize = 0;
this.textMatrix = IDENTITY_MATRIX;
this.fontMatrix = FONT_IDENTITY_MATRIX;
this.leading = 0;
// Current point (in user coordinates)
this.x = 0;
this.y = 0;
// Start of text line (in text coordinates)
this.lineX = 0;
this.lineY = 0;
// Character and word spacing
this.charSpacing = 0;
this.wordSpacing = 0;
this.textHScale = 1;
this.textRise = 0;
// Default foreground and background colors
this.fillColor = SVG_DEFAULTS.fillColor;
this.strokeColor = '#000000';
this.fillAlpha = 1;
this.strokeAlpha = 1;
this.lineWidth = 1;
this.lineJoin = '';
this.lineCap = '';
this.miterLimit = 0;
this.dashArray = [];
this.dashPhase = 0;
this.dependencies = [];
// Clipping
this.clipId = '';
this.pendingClip = false;
this.maskId = '';
}
SVGExtraState.prototype = {
clone: function SVGExtraState_clone() {
return Object.create(this);
},
setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
this.x = x;
this.y = y;
}
};
return SVGExtraState;
})();
var SVGGraphics = (function SVGGraphicsClosure() {
function createScratchSVG(width, height) {
var NS = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(NS, 'svg:svg');
svg.setAttributeNS(null, 'version', '1.1');
svg.setAttributeNS(null, 'width', width + 'px');
svg.setAttributeNS(null, 'height', height + 'px');
svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
return svg;
}
function opListToTree(opList) {
var opTree = [];
var tmp = [];
var opListLen = opList.length;
for (var x = 0; x < opListLen; x++) {
if (opList[x].fn === 'save') {
opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
tmp.push(opTree);
opTree = opTree[opTree.length - 1].items;
continue;
}
if(opList[x].fn === 'restore') {
opTree = tmp.pop();
} else {
opTree.push(opList[x]);
}
}
return opTree;
}
/**
* Formats float number.
* @param value {number} number to format.
* @returns {string}
*/
function pf(value) {
if (value === (value | 0)) { // integer number
return value.toString();
}
var s = value.toFixed(10);
var i = s.length - 1;
if (s[i] !== '0') {
return s;
}
// removing trailing zeros
do {
i--;
} while (s[i] === '0');
return s.substr(0, s[i] === '.' ? i : i + 1);
}
/**
* Formats transform matrix. The standard rotation, scale and translate
* matrices are replaced by their shorter forms, and for identity matrix
* returns empty string to save the memory.
* @param m {Array} matrix to format.
* @returns {string}
*/
function pm(m) {
if (m[4] === 0 && m[5] === 0) {
if (m[1] === 0 && m[2] === 0) {
if (m[0] === 1 && m[3] === 1) {
return '';
}
return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
}
if (m[0] === m[3] && m[1] === -m[2]) {
var a = Math.acos(m[0]) * 180 / Math.PI;
return 'rotate(' + pf(a) + ')';
}
} else {
if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
}
}
return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
}
function SVGGraphics(commonObjs, objs) {
this.current = new SVGExtraState();
this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
this.transformStack = [];
this.extraStack = [];
this.commonObjs = commonObjs;
this.objs = objs;
this.pendingEOFill = false;
this.embedFonts = false;
this.embeddedFonts = {};
this.cssStyle = null;
}
var NS = 'http://www.w3.org/2000/svg';
var XML_NS = 'http://www.w3.org/XML/1998/namespace';
var XLINK_NS = 'http://www.w3.org/1999/xlink';
var LINE_CAP_STYLES = ['butt', 'round', 'square'];
var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
var clipCount = 0;
var maskCount = 0;
SVGGraphics.prototype = {
save: function SVGGraphics_save() {
this.transformStack.push(this.transformMatrix);
var old = this.current;
this.extraStack.push(old);
this.current = old.clone();
},
restore: function SVGGraphics_restore() {
this.transformMatrix = this.transformStack.pop();
this.current = this.extraStack.pop();
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
this.pgrp.appendChild(this.tgrp);
},
group: function SVGGraphics_group(items) {
this.save();
this.executeOpTree(items);
this.restore();
},
loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
var fnArray = operatorList.fnArray;
var fnArrayLen = fnArray.length;
var argsArray = operatorList.argsArray;
var self = this;
for (var i = 0; i < fnArrayLen; i++) {
if (OPS.dependency === fnArray[i]) {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var obj = deps[n];
var common = obj.substring(0, 2) === 'g_';
var promise;
if (common) {
promise = new Promise(function(resolve) {
self.commonObjs.get(obj, resolve);
});
} else {
promise = new Promise(function(resolve) {
self.objs.get(obj, resolve);
});
}
this.current.dependencies.push(promise);
}
}
}
return Promise.all(this.current.dependencies);
},
transform: function SVGGraphics_transform(a, b, c, d, e, f) {
var transformMatrix = [a, b, c, d, e, f];
this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
transformMatrix);
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
},
getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
this.svg = createScratchSVG(viewport.width, viewport.height);
this.viewport = viewport;
return this.loadDependencies(operatorList).then(function () {
this.transformMatrix = IDENTITY_MATRIX;
this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
this.defs = document.createElementNS(NS, 'svg:defs');
this.pgrp.appendChild(this.defs);
this.pgrp.appendChild(this.tgrp);
this.svg.appendChild(this.pgrp);
var opTree = this.convertOpList(operatorList);
this.executeOpTree(opTree);
return this.svg;
}.bind(this));
},
convertOpList: function SVGGraphics_convertOpList(operatorList) {
var argsArray = operatorList.argsArray;
var fnArray = operatorList.fnArray;
var fnArrayLen = fnArray.length;
var REVOPS = [];
var opList = [];
for (var op in OPS) {
REVOPS[OPS[op]] = op;
}
for (var x = 0; x < fnArrayLen; x++) {
var fnId = fnArray[x];
opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
}
return opListToTree(opList);
},
executeOpTree: function SVGGraphics_executeOpTree(opTree) {
var opTreeLen = opTree.length;
for(var x = 0; x < opTreeLen; x++) {
var fn = opTree[x].fn;
var fnId = opTree[x].fnId;
var args = opTree[x].args;
switch (fnId | 0) {
case OPS.beginText:
this.beginText();
break;
case OPS.setLeading:
this.setLeading(args);
break;
case OPS.setLeadingMoveText:
this.setLeadingMoveText(args[0], args[1]);
break;
case OPS.setFont:
this.setFont(args);
break;
case OPS.showText:
this.showText(args[0]);
break;
case OPS.showSpacedText:
this.showText(args[0]);
break;
case OPS.endText:
this.endText();
break;
case OPS.moveText:
this.moveText(args[0], args[1]);
break;
case OPS.setCharSpacing:
this.setCharSpacing(args[0]);
break;
case OPS.setWordSpacing:
this.setWordSpacing(args[0]);
break;
case OPS.setTextMatrix:
this.setTextMatrix(args[0], args[1], args[2],
args[3], args[4], args[5]);
break;
case OPS.setLineWidth:
this.setLineWidth(args[0]);
break;
case OPS.setLineJoin:
this.setLineJoin(args[0]);
break;
case OPS.setLineCap:
this.setLineCap(args[0]);
break;
case OPS.setMiterLimit:
this.setMiterLimit(args[0]);
break;
case OPS.setFillRGBColor:
this.setFillRGBColor(args[0], args[1], args[2]);
break;
case OPS.setStrokeRGBColor:
this.setStrokeRGBColor(args[0], args[1], args[2]);
break;
case OPS.setDash:
this.setDash(args[0], args[1]);
break;
case OPS.setGState:
this.setGState(args[0]);
break;
case OPS.fill:
this.fill();
break;
case OPS.eoFill:
this.eoFill();
break;
case OPS.stroke:
this.stroke();
break;
case OPS.fillStroke:
this.fillStroke();
break;
case OPS.eoFillStroke:
this.eoFillStroke();
break;
case OPS.clip:
this.clip('nonzero');
break;
case OPS.eoClip:
this.clip('evenodd');
break;
case OPS.paintSolidColorImageMask:
this.paintSolidColorImageMask();
break;
case OPS.paintJpegXObject:
this.paintJpegXObject(args[0], args[1], args[2]);
break;
case OPS.paintImageXObject:
this.paintImageXObject(args[0]);
break;
case OPS.paintInlineImageXObject:
this.paintInlineImageXObject(args[0]);
break;
case OPS.paintImageMaskXObject:
this.paintImageMaskXObject(args[0]);
break;
case OPS.paintFormXObjectBegin:
this.paintFormXObjectBegin(args[0], args[1]);
break;
case OPS.paintFormXObjectEnd:
this.paintFormXObjectEnd();
break;
case OPS.closePath:
this.closePath();
break;
case OPS.closeStroke:
this.closeStroke();
break;
case OPS.closeFillStroke:
this.closeFillStroke();
break;
case OPS.nextLine:
this.nextLine();
break;
case OPS.transform:
this.transform(args[0], args[1], args[2], args[3],
args[4], args[5]);
break;
case OPS.constructPath:
this.constructPath(args[0], args[1]);
break;
case OPS.endPath:
this.endPath();
break;
case 92:
this.group(opTree[x].items);
break;
default:
warn('Unimplemented method '+ fn);
break;
}
}
},
setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
this.current.wordSpacing = wordSpacing;
},
setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
this.current.charSpacing = charSpacing;
},
nextLine: function SVGGraphics_nextLine() {
this.moveText(0, this.current.leading);
},
setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
var current = this.current;
this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
current.xcoords = [];
current.tspan = document.createElementNS(NS, 'svg:tspan');
current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
current.tspan.setAttributeNS(null, 'font-size',
pf(current.fontSize) + 'px');
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
current.txtElement = document.createElementNS(NS, 'svg:text');
current.txtElement.appendChild(current.tspan);
},
beginText: function SVGGraphics_beginText() {
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
this.current.textMatrix = IDENTITY_MATRIX;
this.current.lineMatrix = IDENTITY_MATRIX;
this.current.tspan = document.createElementNS(NS, 'svg:tspan');
this.current.txtElement = document.createElementNS(NS, 'svg:text');
this.current.txtgrp = document.createElementNS(NS, 'svg:g');
this.current.xcoords = [];
},
moveText: function SVGGraphics_moveText(x, y) {
var current = this.current;
this.current.x = this.current.lineX += x;
this.current.y = this.current.lineY += y;
current.xcoords = [];
current.tspan = document.createElementNS(NS, 'svg:tspan');
current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
current.tspan.setAttributeNS(null, 'font-size',
pf(current.fontSize) + 'px');
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
},
showText: function SVGGraphics_showText(glyphs) {
var current = this.current;
var font = current.font;
var fontSize = current.fontSize;
if (fontSize === 0) {
return;
}
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var fontDirection = current.fontDirection;
var textHScale = current.textHScale * fontDirection;
var glyphsLength = glyphs.length;
var vertical = font.vertical;
var widthAdvanceScale = fontSize * current.fontMatrix[0];
var x = 0, i;
for (i = 0; i < glyphsLength; ++i) {
var glyph = glyphs[i];
if (glyph === null) {
// word break
x += fontDirection * wordSpacing;
continue;
} else if (isNum(glyph)) {
x += -glyph * fontSize * 0.001;
continue;
}
current.xcoords.push(current.x + x * textHScale);
var width = glyph.width;
var character = glyph.fontChar;
var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
x += charWidth;
current.tspan.textContent += character;
}
if (vertical) {
current.y -= x * textHScale;
} else {
current.x += x * textHScale;
}
current.tspan.setAttributeNS(null, 'x',
current.xcoords.map(pf).join(' '));
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
current.tspan.setAttributeNS(null, 'font-size',
pf(current.fontSize) + 'px');
if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
}
if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
}
if (current.fillColor !== SVG_DEFAULTS.fillColor) {
current.tspan.setAttributeNS(null, 'fill', current.fillColor);
}
current.txtElement.setAttributeNS(null, 'transform',
pm(current.textMatrix) +
' scale(1, -1)' );
current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
current.txtElement.appendChild(current.tspan);
current.txtgrp.appendChild(current.txtElement);
this.tgrp.appendChild(current.txtElement);
},
setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
this.setLeading(-y);
this.moveText(x, y);
},
addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
if (!this.cssStyle) {
this.cssStyle = document.createElementNS(NS, 'svg:style');
this.cssStyle.setAttributeNS(null, 'type', 'text/css');
this.defs.appendChild(this.cssStyle);
}
var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
this.cssStyle.textContent +=
'@font-face { font-family: "' + fontObj.loadedName + '";' +
' src: url(' + url + '); }\n';
},
setFont: function SVGGraphics_setFont(details) {
var current = this.current;
var fontObj = this.commonObjs.get(details[0]);
var size = details[1];
this.current.font = fontObj;
if (this.embedFonts && fontObj.data &&
!this.embeddedFonts[fontObj.loadedName]) {
this.addFontStyle(fontObj);
this.embeddedFonts[fontObj.loadedName] = fontObj;
}
current.fontMatrix = (fontObj.fontMatrix ?
fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
(fontObj.bold ? 'bold' : 'normal');
var italic = fontObj.italic ? 'italic' : 'normal';
if (size < 0) {
size = -size;
current.fontDirection = -1;
} else {
current.fontDirection = 1;
}
current.fontSize = size;
current.fontFamily = fontObj.loadedName;
current.fontWeight = bold;
current.fontStyle = italic;
current.tspan = document.createElementNS(NS, 'svg:tspan');
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
current.xcoords = [];
},
endText: function SVGGraphics_endText() {
if (this.current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
},
// Path properties
setLineWidth: function SVGGraphics_setLineWidth(width) {
this.current.lineWidth = width;
},
setLineCap: function SVGGraphics_setLineCap(style) {
this.current.lineCap = LINE_CAP_STYLES[style];
},
setLineJoin: function SVGGraphics_setLineJoin(style) {
this.current.lineJoin = LINE_JOIN_STYLES[style];
},
setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
this.current.miterLimit = limit;
},
setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
var color = Util.makeCssRgb(arguments);
this.current.strokeColor = color;
},
setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
var color = Util.makeCssRgb(arguments);
this.current.fillColor = color;
this.current.tspan = document.createElementNS(NS, 'svg:tspan');
this.current.xcoords = [];
},
setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
this.current.dashArray = dashArray;
this.current.dashPhase = dashPhase;
},
constructPath: function SVGGraphics_constructPath(ops, args) {
var current = this.current;
var x = current.x, y = current.y;
current.path = document.createElementNS(NS, 'svg:path');
var d = [];
var opLength = ops.length;
for (var i = 0, j = 0; i < opLength; i++) {
switch (ops[i] | 0) {
case OPS.rectangle:
x = args[j++];
y = args[j++];
var width = args[j++];
var height = args[j++];
var xw = x + width;
var yh = y + height;
d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
'L', pf(x), pf(yh), 'Z');
break;
case OPS.moveTo:
x = args[j++];
y = args[j++];
d.push('M', pf(x), pf(y));
break;
case OPS.lineTo:
x = args[j++];
y = args[j++];
d.push('L', pf(x) , pf(y));
break;
case OPS.curveTo:
x = args[j + 4];
y = args[j + 5];
d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
pf(args[j + 3]), pf(x), pf(y));
j += 6;
break;
case OPS.curveTo2:
x = args[j + 2];
y = args[j + 3];
d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
pf(args[j + 2]), pf(args[j + 3]));
j += 4;
break;
case OPS.curveTo3:
x = args[j + 2];
y = args[j + 3];
d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
pf(x), pf(y));
j += 4;
break;
case OPS.closePath:
d.push('Z');
break;
}
}
current.path.setAttributeNS(null, 'd', d.join(' '));
current.path.setAttributeNS(null, 'stroke-miterlimit',
pf(current.miterLimit));
current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
current.path.setAttributeNS(null, 'stroke-width',
pf(current.lineWidth) + 'px');
current.path.setAttributeNS(null, 'stroke-dasharray',
current.dashArray.map(pf).join(' '));
current.path.setAttributeNS(null, 'stroke-dashoffset',
pf(current.dashPhase) + 'px');
current.path.setAttributeNS(null, 'fill', 'none');
this.tgrp.appendChild(current.path);
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
// Saving a reference in current.element so that it can be addressed
// in 'fill' and 'stroke'
current.element = current.path;
current.setCurrentPoint(x, y);
},
endPath: function SVGGraphics_endPath() {
var current = this.current;
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
},
clip: function SVGGraphics_clip(type) {
var current = this.current;
// Add current path to clipping path
current.clipId = 'clippath' + clipCount;
clipCount++;
this.clippath = document.createElementNS(NS, 'svg:clipPath');
this.clippath.setAttributeNS(null, 'id', current.clipId);
var clipElement = current.element.cloneNode();
if (type === 'evenodd') {
clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
} else {
clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
}
this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
this.clippath.appendChild(clipElement);
this.defs.appendChild(this.clippath);
// Create a new group with that attribute
current.pendingClip = true;
this.cgrp = document.createElementNS(NS, 'svg:g');
this.cgrp.setAttributeNS(null, 'clip-path',
'url(#' + current.clipId + ')');
this.pgrp.appendChild(this.cgrp);
},
closePath: function SVGGraphics_closePath() {
var current = this.current;
var d = current.path.getAttributeNS(null, 'd');
d += 'Z';
current.path.setAttributeNS(null, 'd', d);
},
setLeading: function SVGGraphics_setLeading(leading) {
this.current.leading = -leading;
},
setTextRise: function SVGGraphics_setTextRise(textRise) {
this.current.textRise = textRise;
},
setHScale: function SVGGraphics_setHScale(scale) {
this.current.textHScale = scale / 100;
},
setGState: function SVGGraphics_setGState(states) {
for (var i = 0, ii = states.length; i < ii; i++) {
var state = states[i];
var key = state[0];
var value = state[1];
switch (key) {
case 'LW':
this.setLineWidth(value);
break;
case 'LC':
this.setLineCap(value);
break;
case 'LJ':
this.setLineJoin(value);
break;
case 'ML':
this.setMiterLimit(value);
break;
case 'D':
this.setDash(value[0], value[1]);
break;
case 'RI':
break;
case 'FL':
break;
case 'Font':
this.setFont(value);
break;
case 'CA':
break;
case 'ca':
break;
case 'BM':
break;
case 'SMask':
break;
}
}
},
fill: function SVGGraphics_fill() {
var current = this.current;
current.element.setAttributeNS(null, 'fill', current.fillColor);
},
stroke: function SVGGraphics_stroke() {
var current = this.current;
current.element.setAttributeNS(null, 'stroke', current.strokeColor);
current.element.setAttributeNS(null, 'fill', 'none');
},
eoFill: function SVGGraphics_eoFill() {
var current = this.current;
current.element.setAttributeNS(null, 'fill', current.fillColor);
current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
},
fillStroke: function SVGGraphics_fillStroke() {
// Order is important since stroke wants fill to be none.
// First stroke, then if fill needed, it will be overwritten.
this.stroke();
this.fill();
},
eoFillStroke: function SVGGraphics_eoFillStroke() {
this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
this.fillStroke();
},
closeStroke: function SVGGraphics_closeStroke() {
this.closePath();
this.stroke();
},
closeFillStroke: function SVGGraphics_closeFillStroke() {
this.closePath();
this.fillStroke();
},
paintSolidColorImageMask:
function SVGGraphics_paintSolidColorImageMask() {
var current = this.current;
var rect = document.createElementNS(NS, 'svg:rect');
rect.setAttributeNS(null, 'x', '0');
rect.setAttributeNS(null, 'y', '0');
rect.setAttributeNS(null, 'width', '1px');
rect.setAttributeNS(null, 'height', '1px');
rect.setAttributeNS(null, 'fill', current.fillColor);
this.tgrp.appendChild(rect);
},
paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
var current = this.current;
var imgObj = this.objs.get(objId);
var imgEl = document.createElementNS(NS, 'svg:image');
imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
imgEl.setAttributeNS(null, 'x', '0');
imgEl.setAttributeNS(null, 'y', pf(-h));
imgEl.setAttributeNS(null, 'transform',
'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
this.tgrp.appendChild(imgEl);
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
},
paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
this.paintInlineImageXObject(imgData);
},
paintInlineImageXObject:
function SVGGraphics_paintInlineImageXObject(imgData, mask) {
var current = this.current;
var width = imgData.width;
var height = imgData.height;
var imgSrc = convertImgDataToPng(imgData);
var cliprect = document.createElementNS(NS, 'svg:rect');
cliprect.setAttributeNS(null, 'x', '0');
cliprect.setAttributeNS(null, 'y', '0');
cliprect.setAttributeNS(null, 'width', pf(width));
cliprect.setAttributeNS(null, 'height', pf(height));
current.element = cliprect;
this.clip('nonzero');
var imgEl = document.createElementNS(NS, 'svg:image');
imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
imgEl.setAttributeNS(null, 'x', '0');
imgEl.setAttributeNS(null, 'y', pf(-height));
imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
imgEl.setAttributeNS(null, 'transform',
'scale(' + pf(1 / width) + ' ' +
pf(-1 / height) + ')');
if (mask) {
mask.appendChild(imgEl);
} else {
this.tgrp.appendChild(imgEl);
}
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
},
paintImageMaskXObject:
function SVGGraphics_paintImageMaskXObject(imgData) {
var current = this.current;
var width = imgData.width;
var height = imgData.height;
var fillColor = current.fillColor;
current.maskId = 'mask' + maskCount++;
var mask = document.createElementNS(NS, 'svg:mask');
mask.setAttributeNS(null, 'id', current.maskId);
var rect = document.createElementNS(NS, 'svg:rect');
rect.setAttributeNS(null, 'x', '0');
rect.setAttributeNS(null, 'y', '0');
rect.setAttributeNS(null, 'width', pf(width));
rect.setAttributeNS(null, 'height', pf(height));
rect.setAttributeNS(null, 'fill', fillColor);
rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
this.defs.appendChild(mask);
this.tgrp.appendChild(rect);
this.paintInlineImageXObject(imgData, mask);
},
paintFormXObjectBegin:
function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
this.save();
if (isArray(matrix) && matrix.length === 6) {
this.transform(matrix[0], matrix[1], matrix[2],
matrix[3], matrix[4], matrix[5]);
}
if (isArray(bbox) && bbox.length === 4) {
var width = bbox[2] - bbox[0];
var height = bbox[3] - bbox[1];
var cliprect = document.createElementNS(NS, 'svg:rect');
cliprect.setAttributeNS(null, 'x', bbox[0]);
cliprect.setAttributeNS(null, 'y', bbox[1]);
cliprect.setAttributeNS(null, 'width', pf(width));
cliprect.setAttributeNS(null, 'height', pf(height));
this.current.element = cliprect;
this.clip('nonzero');
this.endPath();
}
},
paintFormXObjectEnd:
function SVGGraphics_paintFormXObjectEnd() {
this.restore();
}
};
return SVGGraphics;
})();
PDFJS.SVGGraphics = SVGGraphics;
}).call((typeof window === 'undefined') ? this : window);
if (!PDFJS.workerSrc && typeof document !== 'undefined') {
// workerSrc is not set -- using last script url to define default location
PDFJS.workerSrc = (function () {
'use strict';
var scriptTagContainer = document.body ||
document.getElementsByTagName('head')[0];
var pdfjsSrc = scriptTagContainer.lastChild.src;
return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
})();
}
|
"use strict";
describe('fbutil', function() {
beforeEach(function() {
module('mock.firebase');
module('firebase.utils');
});
describe('handler', function() {
it('should have tests');
});
describe('defer', function() {
it('should have tests');
});
describe('ref', function() {
it('should have tests');
});
});
|
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var _ = require('underscore'),
React = require('react'),
classes = require('classnames');
var Option = React.createClass({
displayName: 'Value',
propTypes: {
label: React.PropTypes.string.isRequired
},
blockEvent: function(event) {
event.stopPropagation();
},
render: function() {
return React.createElement("div", {className: "Select-item"},
React.createElement("span", {className: "Select-item-icon", onMouseDown: this.blockEvent, onClick: this.props.onRemove}, "×"),
React.createElement("span", {className: "Select-item-label"}, this.props.label)
);
}
});
module.exports = Option;
},{"classnames":2,"react":undefined,"underscore":undefined}],2:[function(require,module,exports){
function classnames() {
var args = arguments, classes = [];
for (var i = 0; i < args.length; i++) {
if (args[i] && 'string' === typeof args[i]) {
classes.push(args[i]);
} else if ('object' === typeof args[i]) {
classes = classes.concat(Object.keys(args[i]).filter(function(cls) {
return args[i][cls];
}));
}
}
return classes.join(' ') || undefined;
}
module.exports = classnames;
},{}],3:[function(require,module,exports){
var React = require('react');
var sizerStyle = { position: 'absolute', visibility: 'hidden', height: 0, width: 0, overflow: 'scroll', whiteSpace: 'nowrap' };
var AutosizeInput = React.createClass({
displayName: 'AutosizeInput',
propTypes: {
value: React.PropTypes.any, // field value
defaultValue: React.PropTypes.any, // default field value
onChange: React.PropTypes.func, // onChange handler: function(newValue) {}
style: React.PropTypes.object, // css styles for the outer element
className: React.PropTypes.string, // className for the outer element
inputStyle: React.PropTypes.object, // css styles for the input element
inputClassName: React.PropTypes.string // className for the input element
},
getDefaultProps: function() {
return {
minWidth: 1
};
},
getInitialState: function() {
return {
inputWidth: this.props.minWidth
};
},
componentDidMount: function() {
this.copyInputStyles();
this.updateInputWidth();
},
componentDidUpdate: function() {
this.updateInputWidth();
},
copyInputStyles: function() {
if (!this.isMounted() || !window.getComputedStyle) {
return;
}
var inputStyle = window.getComputedStyle(this.refs.input.getDOMNode());
var widthNode = this.refs.sizer.getDOMNode();
widthNode.style.fontSize = inputStyle.fontSize;
widthNode.style.fontFamily = inputStyle.fontFamily;
},
updateInputWidth: function() {
if (!this.isMounted()) {
return;
}
var newInputWidth = this.refs.sizer.getDOMNode().scrollWidth + 2;
if (newInputWidth < this.props.minWidth) {
newInputWidth = this.props.minWidth;
}
if (newInputWidth !== this.state.inputWidth) {
this.setState({
inputWidth: newInputWidth
});
}
},
getInput: function() {
return this.refs.input;
},
focus: function() {
this.refs.input.getDOMNode().focus();
},
select: function() {
this.refs.input.getDOMNode().select();
},
render: function() {
var nbspValue = (this.props.value || '').replace(/ /g, ' ');
var wrapperStyle = this.props.style || {};
wrapperStyle.display = 'inline-block';
var inputStyle = this.props.inputStyle || {};
inputStyle.width = this.state.inputWidth;
return (
React.createElement("div", {className: this.props.className, style: wrapperStyle},
React.createElement("input", React.__spread({}, this.props, {ref: "input", className: this.props.inputClassName, style: inputStyle})),
React.createElement("div", {ref: "sizer", style: sizerStyle, dangerouslySetInnerHTML: { __html: nbspValue}})
)
);
}
});
module.exports = AutosizeInput;
},{"react":undefined}],"react-select":[function(require,module,exports){
var _ = require('underscore'),
React = require('react'),
Input = require('react-input-autosize'),
classes = require('classnames'),
Value = require('./value');
var requestId = 0;
var Select = React.createClass({
displayName: 'Select',
propTypes: {
value: React.PropTypes.any, // initial field value
multi: React.PropTypes.bool, // multi-value input
options: React.PropTypes.array, // array of options
delimiter: React.PropTypes.string, // delimiter to use to join multiple values
asyncOptions: React.PropTypes.func, // function to call to get options
autoload: React.PropTypes.bool, // whether to auto-load the default async options set
placeholder: React.PropTypes.string, // field placeholder, displayed when there's no value
name: React.PropTypes.string, // field name, for hidden <input /> tag
onChange: React.PropTypes.func, // onChange handler: function(newValue) {}
className: React.PropTypes.string // className for the outer element
},
getDefaultProps: function() {
return {
value: undefined,
options: [],
delimiter: ',',
asyncOptions: undefined,
autoload: true,
placeholder: '',
name: undefined,
onChange: undefined,
className: undefined
};
},
getInitialState: function() {
return {
/*
* set by getStateFromValue on componentWillMount:
* - value
* - values
* - inputValue
* - placeholder
* - focusedOption
*/
options: this.props.options,
isFocused: false,
isOpen: false,
isLoading: false
};
},
componentWillMount: function() {
this._optionsCache = {};
this.setState(this.getStateFromValue(this.props.value));
if (this.props.asyncOptions && this.props.autoload) {
this.autoloadAsyncOptions();
}
},
componentWillUnmount: function() {
clearTimeout(this._blurTimeout);
clearTimeout(this._focusTimeout);
},
componentDidUpdate: function() {
console.log('component did update, focus: ' + this._focusAfterUpdate);
if (this._focusAfterUpdate) {
clearTimeout(this._blurTimeout);
this._focusTimeout = setTimeout(function() {
this.refs.input.focus();
this._focusAfterUpdate = false;
}.bind(this), 50);
}
},
initValuesArray: function(values) {
if (!Array.isArray(values)) {
if ('string' === typeof values) {
values = values.split(this.props.delimiter);
} else {
values = values ? [values] : []
}
};
return values.map(function(val) {
return ('string' === typeof val) ? val = _.findWhere(this.state.options, { value: val }) || { value: val, label: val } : val;
}.bind(this));
},
getStateFromValue: function(value) {
var values = this.initValuesArray(value);
return {
value: values.map(function(v) { return v.value }).join(this.props.delimiter),
values: values,
inputValue: '',
placeholder: !this.props.multi && values.length ? values[0].label : this.props.placeholder || 'Select...',
focusedOption: !this.props.multi ? values[0] : null
};
},
setValue: function(value) {
this._focusAfterUpdate = true;
var newState = this.getStateFromValue(value);
newState.isOpen = false;
this.fireChangeEvent(newState);
this.setState(newState);
},
selectValue: function(value) {
this[this.props.multi ? 'addValue' : 'setValue'](value);
},
addValue: function(value) {
this.setValue(this.state.values.concat(value));
},
popValue: function() {
this.setValue(_.initial(this.state.values));
},
removeValue: function(value) {
this.setValue(_.without(this.state.values, value));
},
clearValue: function() {
this.setValue(null);
},
resetValue: function() {
this.setValue(this.state.value);
},
fireChangeEvent: function(newState) {
if (newState.value !== this.state.value && this.props.onChange) {
this.props.onChange(newState.value, newState.values);
}
},
handleMouseDown: function(event) {
event.stopPropagation();
event.preventDefault();
if (this.state.isFocused) {
this.setState({
isOpen: true
});
} else {
this._openAfterFocus = true;
this.refs.input.focus();
}
},
handleInputFocus: function() {
this.setState({
isFocused: true,
isOpen: this.state.isOpen || this._openAfterFocus
});
this._openAfterFocus = false;
},
handleInputBlur: function(event) {
this._blurTimeout = setTimeout(function() {
console.log('blur: ' + this._focusAfterUpdate);
if (this._focusAfterUpdate) return;
this.setState({
isOpen: false,
isFocused: false
});
}.bind(this), 50);
},
handleKeyDown: function(event) {
switch (event.keyCode) {
case 8: // backspace
if (!this.state.inputValue) {
this.popValue();
}
return;
break;
case 9: // tab
if (event.shiftKey || !this.state.isOpen || !this.state.focusedOption) {
return;
}
this.selectFocusedOption();
break;
case 13: // enter
this.selectFocusedOption();
break;
case 27: // escape
if (this.state.isOpen) {
this.resetValue();
} else {
this.clearValue();
}
break;
case 38: // up
this.focusPreviousOption();
break;
case 40: // down
this.focusNextOption();
break;
default: return;
}
event.preventDefault();
},
handleInputChange: function(event) {
if (this.props.asyncOptions) {
this.setState({
isLoading: true,
inputValue: event.target.value
});
this.loadAsyncOptions(event.target.value, {
isLoading: false,
isOpen: true
});
} else {
this.setState({
isOpen: true,
inputValue: event.target.value
});
}
},
autoloadAsyncOptions: function() {
this.loadAsyncOptions('', {}, function() {});
},
loadAsyncOptions: function(input, state) {
for (var i = 0; i <= input.length; i++) {
var cacheKey = input.slice(0, i);
if (this._optionsCache[cacheKey] && (input === cacheKey || this._optionsCache[cacheKey].complete)) {
this.setState(_.extend({
options: this._optionsCache[cacheKey].options
}, state));
return;
}
}
var thisRequestId = this._currentRequestId = requestId++;
this.props.asyncOptions(input, function(err, data) {
this._optionsCache[input] = data;
if (thisRequestId !== this._currentRequestId) {
return;
}
this.setState(_.extend({
options: data.options
}, state));
}.bind(this));
},
filterOptions: function() {
var values = this.state.values.map(function(i) {
return i.value;
});
var filterOption = function(op) {
if (this.props.multi && _.contains(values, op.value)) return false;
return (
!this.state.inputValue
|| op.value.toLowerCase().indexOf(this.state.inputValue.toLowerCase()) >= 0
|| op.label.toLowerCase().indexOf(this.state.inputValue.toLowerCase()) >= 0
);
}
return _.filter(this.state.options, filterOption, this);
},
selectFocusedOption: function() {
return this.selectValue(this.state.focusedOption);
},
focusOption: function(op) {
this.setState({
focusedOption: op
});
},
focusNextOption: function() {
this.focusAdjacentOption('next');
},
focusPreviousOption: function() {
this.focusAdjacentOption('previous');
},
focusAdjacentOption: function(dir) {
var ops = this.filterOptions();
if (!this.state.isOpen) {
this.setState({
isOpen: true,
inputValue: '',
focusedOption: this.state.focusedOption || ops[dir === 'next' ? 0 : ops.length - 1]
});
return;
}
if (!ops.length) {
return;
}
var focusedIndex = -1;
for (var i = 0; i < ops.length; i++) {
if (this.state.focusedOption === ops[i]) {
focusedIndex = i;
break;
}
}
var focusedOption = ops[0];
if (dir === 'next' && focusedIndex > -1 && focusedIndex < ops.length - 1) {
focusedOption = ops[focusedIndex + 1];
} else if (dir === 'previous') {
if (focusedIndex > 0) {
focusedOption = ops[focusedIndex - 1];
} else {
focusedOption = ops[ops.length - 1];
}
}
this.setState({
focusedOption: focusedOption
});
},
unfocusOption: function(op) {
if (this.state.focusedOption === op) {
this.setState({
focusedOption: null
});
}
},
buildMenu: function() {
var ops = _.map(this.filterOptions(), function(op) {
var optionClass = classes({
'Select-option': true,
'is-focused': this.state.focusedOption === op
});
var mouseEnter = this.focusOption.bind(this, op),
mouseLeave = this.unfocusOption.bind(this, op),
mouseDown = this.selectValue.bind(this, op);
return React.createElement("div", {key: 'option-' + op.value, className: optionClass, onMouseEnter: mouseEnter, onMouseLeave: mouseLeave, onMouseDown: mouseDown}, op.label);
}, this);
return ops.length ? ops : React.createElement('div', { className: "Select-noresults" }, "No results found");
},
render: function() {
var selectClass = classes('Select', this.props.className, {
'is-multi': this.props.multi,
'is-open': this.state.isOpen,
'is-focused': this.state.isFocused,
'is-loading': this.state.isLoading,
'has-value': this.state.value
});
var value = [];
if (this.props.multi) {
this.state.values.forEach(function(val) {
props = _.extend({
key: val.value,
onRemove: this.removeValue.bind(this, val)
}, val);
value.push(React.createElement(Value, props));
}, this);
}
if (!this.state.inputValue && (!this.props.multi || !value.length)) {
value.push(React.createElement("div", {className: "Select-placeholder", key: "placeholder"}, this.state.placeholder));
}
var loading = this.state.isLoading ? React.createElement('span', { className: "Select-loading" }) : null;
var clear = this.state.value ? React.createElement("span", {className: "Select-clear", onMouseDown: this.clearValue, dangerouslySetInnerHTML: { __html: '×'}}) : null;
var menu = this.state.isOpen ? React.createElement("div", {className: "Select-menu"}, this.buildMenu()) : null;
return (
React.createElement("div", {ref: "wrapper", className: selectClass},
React.createElement("input", {type: "hidden", ref: "value", name: this.props.name, value: this.state.value}),
React.createElement("div", {className: "Select-control", ref: "control", onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown},
value,
React.createElement(Input, {className: "Select-input", tabIndex: this.props.tabIndex, ref: "input", value: this.state.inputValue, onFocus: this.handleInputFocus, onBlur: this.handleInputBlur, onChange: this.handleInputChange, minWidth: "5"}),
React.createElement("span", {className: "Select-arrow"}),
loading,
clear
),
menu
)
);
}
});
module.exports = Select;
},{"./value":1,"classnames":2,"react":undefined,"react-input-autosize":3,"underscore":undefined}]},{},[]);
|
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.events.KeyEventTest');
goog.setTestOnly('goog.events.KeyEventTest');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.testing.events');
goog.require('goog.testing.jsunit');
goog.require('goog.userAgent');
function setUp() {
// Have this based on a fictitious DOCUMENT_MODE constant.
goog.userAgent.isDocumentMode = function(mode) {
return mode <= goog.userAgent.DOCUMENT_MODE;
};
}
/**
* Tests the key handler for the IE 8 and lower behavior.
*/
function testIe8StyleKeyHandling() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = true;
goog.userAgent.GECKO = false;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = false;
goog.userAgent.WINDOWS = true;
goog.userAgent.LINUX = false;
goog.userAgent.VERSION = 8;
goog.userAgent.DOCUMENT_MODE = 8;
goog.events.KeyHandler.USES_KEYDOWN_ = true;
assertIe8StyleKeyHandling();
}
/**
* Tests the key handler for the IE 8 and lower behavior.
*/
function testIe8StyleKeyHandlingInIe9DocumentMode() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = true;
goog.userAgent.GECKO = false;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = false;
goog.userAgent.WINDOWS = true;
goog.userAgent.LINUX = false;
goog.userAgent.VERSION = 9; // Try IE9 in IE8 document mode.
goog.userAgent.DOCUMENT_MODE = 8;
goog.events.KeyHandler.USES_KEYDOWN_ = true;
assertIe8StyleKeyHandling();
}
function assertIe8StyleKeyHandling() {
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, goog.events.KeyCodes.ENTER);
fireKeyPress(keyHandler, goog.events.KeyCodes.ENTER);
assertEquals(
'Enter should fire a key event with the keycode 13',
goog.events.KeyCodes.ENTER, keyEvent.keyCode);
assertEquals(
'Enter should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.ESC);
fireKeyPress(keyHandler, goog.events.KeyCodes.ESC);
assertEquals(
'Esc should fire a key event with the keycode 27',
goog.events.KeyCodes.ESC, keyEvent.keyCode);
assertEquals(
'Esc should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.UP);
assertEquals(
'Up should fire a key event with the keycode 38', goog.events.KeyCodes.UP,
keyEvent.keyCode);
assertEquals(
'Up should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(
keyHandler, goog.events.KeyCodes.SEVEN, undefined, undefined, undefined,
undefined, true);
fireKeyPress(
keyHandler, 38, undefined, undefined, undefined, undefined, true);
assertEquals(
'Shift+7 should fire a key event with the keycode 55',
goog.events.KeyCodes.SEVEN, keyEvent.keyCode);
assertEquals(
'Shift+7 should fire a key event with the charcode 38', 38,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, 97);
assertEquals(
'Lower case a should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Lower case a should fire a key event with the charcode 97', 97,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, 65);
assertEquals(
'Upper case A should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Upper case A should fire a key event with the charcode 65', 65,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.DELETE);
assertEquals(
'Delete should fire a key event with the keycode 46',
goog.events.KeyCodes.DELETE, keyEvent.keyCode);
assertEquals(
'Delete should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.PERIOD);
fireKeyPress(keyHandler, 46);
assertEquals(
'Period should fire a key event with the keycode 190',
goog.events.KeyCodes.PERIOD, keyEvent.keyCode);
assertEquals(
'Period should fire a key event with the charcode 46', 46,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.CTRL);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
assertEquals(
'A with control down should fire a key event', goog.events.KeyCodes.A,
keyEvent.keyCode);
// On IE, when Ctrl+<key> is held down, there is a KEYDOWN, a KEYPRESS, and
// then a series of KEYDOWN events for each repeat.
fireKeyDown(keyHandler, goog.events.KeyCodes.B, undefined, undefined, true);
fireKeyPress(keyHandler, goog.events.KeyCodes.B, undefined, undefined, true);
assertEquals(
'B with control down should fire a key event', goog.events.KeyCodes.B,
keyEvent.keyCode);
assertTrue('Ctrl should be down.', keyEvent.ctrlKey);
assertFalse(
'Should not have repeat=true on the first key press.', keyEvent.repeat);
// Fire one repeated keydown event.
fireKeyDown(keyHandler, goog.events.KeyCodes.B, undefined, undefined, true);
assertEquals(
'A with control down should fire a key event', goog.events.KeyCodes.B,
keyEvent.keyCode);
assertTrue('Should have repeat=true on key repeat.', keyEvent.repeat);
assertTrue('Ctrl should be down.', keyEvent.ctrlKey);
}
/**
* Tests special cases for IE9.
*/
function testIe9StyleKeyHandling() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = true;
goog.userAgent.GECKO = false;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = false;
goog.userAgent.WINDOWS = true;
goog.userAgent.LINUX = false;
goog.userAgent.VERSION = 9;
goog.userAgent.DOCUMENT_MODE = 9;
goog.events.KeyHandler.USES_KEYDOWN_ = true;
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, goog.events.KeyCodes.ENTER);
fireKeyPress(keyHandler, goog.events.KeyCodes.ENTER);
assertEquals(
'Enter should fire a key event with the keycode 13',
goog.events.KeyCodes.ENTER, keyEvent.keyCode);
assertEquals(
'Enter should fire a key event with the charcode 0', 0,
keyEvent.charCode);
}
/**
* Tests the key handler for the Gecko behavior.
*/
function testGeckoStyleKeyHandling() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = false;
goog.userAgent.GECKO = true;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = false;
goog.userAgent.WINDOWS = true;
goog.userAgent.LINUX = false;
goog.events.KeyHandler.USES_KEYDOWN_ = false;
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, goog.events.KeyCodes.ENTER);
fireKeyPress(keyHandler, goog.events.KeyCodes.ENTER);
assertEquals(
'Enter should fire a key event with the keycode 13',
goog.events.KeyCodes.ENTER, keyEvent.keyCode);
assertEquals(
'Enter should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.ESC);
fireKeyPress(keyHandler, goog.events.KeyCodes.ESC);
assertEquals(
'Esc should fire a key event with the keycode 27',
goog.events.KeyCodes.ESC, keyEvent.keyCode);
assertEquals(
'Esc should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.UP);
fireKeyPress(keyHandler, goog.events.KeyCodes.UP);
assertEquals(
'Up should fire a key event with the keycode 38', goog.events.KeyCodes.UP,
keyEvent.keyCode);
assertEquals(
'Up should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(
keyHandler, goog.events.KeyCodes.SEVEN, undefined, undefined, undefined,
undefined, true);
fireKeyPress(
keyHandler, undefined, 38, undefined, undefined, undefined, true);
assertEquals(
'Shift+7 should fire a key event with the keycode 55',
goog.events.KeyCodes.SEVEN, keyEvent.keyCode);
assertEquals(
'Shift+7 should fire a key event with the charcode 38', 38,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, undefined, 97);
assertEquals(
'Lower case a should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Lower case a should fire a key event with the charcode 97', 97,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, undefined, 65);
assertEquals(
'Upper case A should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Upper case A should fire a key event with the charcode 65', 65,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.DELETE);
fireKeyPress(keyHandler, goog.events.KeyCodes.DELETE);
assertEquals(
'Delete should fire a key event with the keycode 46',
goog.events.KeyCodes.DELETE, keyEvent.keyCode);
assertEquals(
'Delete should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.PERIOD);
fireKeyPress(keyHandler, undefined, 46);
assertEquals(
'Period should fire a key event with the keycode 190',
goog.events.KeyCodes.PERIOD, keyEvent.keyCode);
assertEquals(
'Period should fire a key event with the charcode 46', 46,
keyEvent.charCode);
}
/**
* Tests the key handler for the Safari 3 behavior.
*/
function testSafari3StyleKeyHandling() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = false;
goog.userAgent.GECKO = false;
goog.userAgent.WEBKIT = true;
goog.userAgent.MAC = true;
goog.userAgent.WINDOWS = false;
goog.userAgent.LINUX = false;
goog.events.KeyHandler.USES_KEYDOWN_ = true;
goog.userAgent.VERSION = 525.3;
var keyEvent, keyHandler = new goog.events.KeyHandler();
// Make sure all events are caught while testing
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, goog.events.KeyCodes.ENTER);
fireKeyPress(keyHandler, goog.events.KeyCodes.ENTER);
assertEquals(
'Enter should fire a key event with the keycode 13',
goog.events.KeyCodes.ENTER, keyEvent.keyCode);
assertEquals(
'Enter should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyUp(keyHandler, goog.events.KeyCodes.ENTER);
// Add a listener to ensure that an extra ENTER event is not dispatched
// by a subsequent keypress.
var enterCheck = goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY, function(e) {
assertNotEquals(
'Unexpected ENTER keypress dispatched', e.keyCode,
goog.events.KeyCodes.ENTER);
});
fireKeyDown(keyHandler, goog.events.KeyCodes.ESC);
assertEquals(
'Esc should fire a key event with the keycode 27',
goog.events.KeyCodes.ESC, keyEvent.keyCode);
assertEquals(
'Esc should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyPress(keyHandler, goog.events.KeyCodes.ESC);
goog.events.unlistenByKey(enterCheck);
fireKeyDown(keyHandler, goog.events.KeyCodes.UP);
assertEquals(
'Up should fire a key event with the keycode 38', goog.events.KeyCodes.UP,
keyEvent.keyCode);
assertEquals(
'Up should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(
keyHandler, goog.events.KeyCodes.SEVEN, undefined, undefined, undefined,
undefined, true);
fireKeyPress(keyHandler, 38, 38, undefined, undefined, undefined, true);
assertEquals(
'Shift+7 should fire a key event with the keycode 55',
goog.events.KeyCodes.SEVEN, keyEvent.keyCode);
assertEquals(
'Shift+7 should fire a key event with the charcode 38', 38,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, 97, 97);
assertEquals(
'Lower case a should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Lower case a should fire a key event with the charcode 97', 97,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, 65, 65);
assertEquals(
'Upper case A should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Upper case A should fire a key event with the charcode 65', 65,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.CTRL);
fireKeyDown(keyHandler, goog.events.KeyCodes.A, null, null, true /*ctrl*/);
assertEquals(
'A with control down should fire a key event', goog.events.KeyCodes.A,
keyEvent.keyCode);
// Test that Alt-Tab outside the window doesn't break things.
fireKeyDown(keyHandler, goog.events.KeyCodes.ALT);
keyEvent.keyCode = -1; // Reset the event.
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
assertEquals('Should not have dispatched an Alt-A', -1, keyEvent.keyCode);
fireKeyPress(keyHandler, 65, 65);
assertEquals(
'Alt should be ignored since it isn\'t currently depressed',
goog.events.KeyCodes.A, keyEvent.keyCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.DELETE);
assertEquals(
'Delete should fire a key event with the keycode 46',
goog.events.KeyCodes.DELETE, keyEvent.keyCode);
assertEquals(
'Delete should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.PERIOD);
fireKeyPress(keyHandler, 46, 46);
assertEquals(
'Period should fire a key event with the keycode 190',
goog.events.KeyCodes.PERIOD, keyEvent.keyCode);
assertEquals(
'Period should fire a key event with the charcode 46', 46,
keyEvent.charCode);
// Safari sends zero key code for non-latin characters.
fireKeyDown(keyHandler, 0, 0);
fireKeyPress(keyHandler, 1092, 1092);
assertEquals(
'Cyrillic small letter "Ef" should fire a key event with ' +
'the keycode 0',
0, keyEvent.keyCode);
assertEquals(
'Cyrillic small letter "Ef" should fire a key event with ' +
'the charcode 1092',
1092, keyEvent.charCode);
}
/**
* Tests the key handler for the Opera behavior.
*/
function testOperaStyleKeyHandling() {
goog.userAgent.OPERA = true;
goog.userAgent.IE = false;
goog.userAgent.GECKO = false;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = false;
goog.userAgent.WINDOWS = true;
goog.userAgent.LINUX = false;
goog.events.KeyHandler.USES_KEYDOWN_ = false;
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, goog.events.KeyCodes.ENTER);
fireKeyPress(keyHandler, goog.events.KeyCodes.ENTER);
assertEquals(
'Enter should fire a key event with the keycode 13',
goog.events.KeyCodes.ENTER, keyEvent.keyCode);
assertEquals(
'Enter should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.ESC);
fireKeyPress(keyHandler, goog.events.KeyCodes.ESC);
assertEquals(
'Esc should fire a key event with the keycode 27',
goog.events.KeyCodes.ESC, keyEvent.keyCode);
assertEquals(
'Esc should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.UP);
fireKeyPress(keyHandler, goog.events.KeyCodes.UP);
assertEquals(
'Up should fire a key event with the keycode 38', goog.events.KeyCodes.UP,
keyEvent.keyCode);
assertEquals(
'Up should fire a key event with the charcode 0', 0, keyEvent.charCode);
fireKeyDown(
keyHandler, goog.events.KeyCodes.SEVEN, undefined, undefined, undefined,
undefined, true);
fireKeyPress(
keyHandler, 38, undefined, undefined, undefined, undefined, true);
assertEquals(
'Shift+7 should fire a key event with the keycode 55',
goog.events.KeyCodes.SEVEN, keyEvent.keyCode);
assertEquals(
'Shift+7 should fire a key event with the charcode 38', 38,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, 97);
assertEquals(
'Lower case a should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Lower case a should fire a key event with the charcode 97', 97,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.A);
fireKeyPress(keyHandler, 65);
assertEquals(
'Upper case A should fire a key event with the keycode 65',
goog.events.KeyCodes.A, keyEvent.keyCode);
assertEquals(
'Upper case A should fire a key event with the charcode 65', 65,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.DELETE);
fireKeyPress(keyHandler, goog.events.KeyCodes.DELETE);
assertEquals(
'Delete should fire a key event with the keycode 46',
goog.events.KeyCodes.DELETE, keyEvent.keyCode);
assertEquals(
'Delete should fire a key event with the charcode 0', 0,
keyEvent.charCode);
fireKeyDown(keyHandler, goog.events.KeyCodes.PERIOD);
fireKeyPress(keyHandler, 46);
assertEquals(
'Period should fire a key event with the keycode 190',
goog.events.KeyCodes.PERIOD, keyEvent.keyCode);
assertEquals(
'Period should fire a key event with the charcode 46', 46,
keyEvent.charCode);
}
function testGeckoOnMacAltHandling() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = false;
goog.userAgent.GECKO = true;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = true;
goog.userAgent.WINDOWS = false;
goog.userAgent.LINUX = false;
goog.userAgent.EDGE = false;
goog.events.KeyHandler.SAVE_ALT_FOR_KEYPRESS_ = true;
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(
keyHandler, goog.events.KeyCodes.COMMA, 0, null, false, true, false);
fireKeyPress(keyHandler, 0, 8804, null, false, false, false);
assertEquals(
'should fire a key event with COMMA', goog.events.KeyCodes.COMMA,
keyEvent.keyCode);
assertEquals(
'should fire a key event with alt key set', true, keyEvent.altKey);
// Scenario: alt down, a down, a press, a up (should say alt is true),
// alt up.
keyEvent = undefined;
fireKeyDown(keyHandler, 18, 0, null, false, true, false);
fireKeyDown(keyHandler, goog.events.KeyCodes.A, 0, null, false, true, false);
fireKeyPress(keyHandler, 0, 229, null, false, false, false);
assertEquals(
'should fire a key event with alt key set', true, keyEvent.altKey);
fireKeyUp(keyHandler, 0, 229, null, false, true, false);
assertEquals('alt key should still be set', true, keyEvent.altKey);
fireKeyUp(keyHandler, 18, 0, null, false, false, false);
}
function testGeckoEqualSign() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = false;
goog.userAgent.GECKO = true;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = false;
goog.userAgent.WINDOWS = true;
goog.userAgent.LINUX = false;
goog.events.KeyHandler.USES_KEYDOWN_ = false;
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, 61, 0);
fireKeyPress(keyHandler, 0, 61);
assertEquals(
'= should fire should fire a key event with the keyCode 187',
goog.events.KeyCodes.EQUALS, keyEvent.keyCode);
assertEquals(
'= should fire a key event with the charCode 61',
goog.events.KeyCodes.FF_EQUALS, keyEvent.charCode);
}
function testMacGeckoSlash() {
goog.userAgent.OPERA = false;
goog.userAgent.IE = false;
goog.userAgent.GECKO = true;
goog.userAgent.WEBKIT = false;
goog.userAgent.MAC = true;
goog.userAgent.WINDOWS = false;
goog.userAgent.LINUX = false;
goog.events.KeyHandler.USES_KEYDOWN_ = false;
var keyEvent, keyHandler = new goog.events.KeyHandler();
goog.events.listen(
keyHandler, goog.events.KeyHandler.EventType.KEY,
function(e) { keyEvent = e; });
fireKeyDown(keyHandler, 0, 63, null, false, false, true);
fireKeyPress(keyHandler, 0, 63, null, false, false, true);
assertEquals(
'/ should fire a key event with the keyCode 191',
goog.events.KeyCodes.SLASH, keyEvent.keyCode);
assertEquals(
'? should fire a key event with the charCode 63',
goog.events.KeyCodes.QUESTION_MARK, keyEvent.charCode);
}
function testGetElement() {
var target = goog.dom.createDom(goog.dom.TagName.DIV);
var target2 = goog.dom.createDom(goog.dom.TagName.DIV);
var keyHandler = new goog.events.KeyHandler();
assertNull(keyHandler.getElement());
keyHandler.attach(target);
assertEquals(target, keyHandler.getElement());
keyHandler.attach(target2);
assertNotEquals(target, keyHandler.getElement());
assertEquals(target2, keyHandler.getElement());
var doc = goog.dom.getDocument();
keyHandler.attach(doc);
assertEquals(doc, keyHandler.getElement());
keyHandler = new goog.events.KeyHandler(doc);
assertEquals(doc, keyHandler.getElement());
keyHandler = new goog.events.KeyHandler(target);
assertEquals(target, keyHandler.getElement());
}
function testDetach() {
var target = goog.dom.createDom(goog.dom.TagName.DIV);
var keyHandler = new goog.events.KeyHandler(target);
assertEquals(target, keyHandler.getElement());
fireKeyDown(keyHandler, 0, 63, null, false, false, true);
fireKeyPress(keyHandler, 0, 63, null, false, false, true);
keyHandler.detach();
assertNull(keyHandler.getElement());
// All listeners should be cleared.
assertNull(keyHandler.keyDownKey_);
assertNull(keyHandler.keyPressKey_);
assertNull(keyHandler.keyUpKey_);
// All key related state should be cleared.
assertEquals('Last key should be -1', -1, keyHandler.lastKey_);
assertEquals('keycode should be -1', -1, keyHandler.keyCode_);
}
function testCapturePhase() {
var gotInCapturePhase;
var gotInBubblePhase;
var target = goog.dom.createDom(goog.dom.TagName.DIV);
goog.events.listen(
new goog.events.KeyHandler(target, false /* bubble */),
goog.events.KeyHandler.EventType.KEY, function() {
gotInBubblePhase = true;
assertTrue(gotInCapturePhase);
});
goog.events.listen(
new goog.events.KeyHandler(target, true /* capture */),
goog.events.KeyHandler.EventType.KEY,
function() { gotInCapturePhase = true; });
goog.testing.events.fireKeySequence(target, goog.events.KeyCodes.ESC);
assertTrue(gotInBubblePhase);
}
function fireKeyDown(
keyHandler, keyCode, opt_charCode, opt_keyIdentifier, opt_ctrlKey,
opt_altKey, opt_shiftKey) {
var fakeEvent = createFakeKeyEvent(
goog.events.EventType.KEYDOWN, keyCode, opt_charCode, opt_keyIdentifier,
opt_ctrlKey, opt_altKey, opt_shiftKey);
keyHandler.handleKeyDown_(fakeEvent);
return fakeEvent.returnValue_;
}
function fireKeyPress(
keyHandler, keyCode, opt_charCode, opt_keyIdentifier, opt_ctrlKey,
opt_altKey, opt_shiftKey) {
var fakeEvent = createFakeKeyEvent(
goog.events.EventType.KEYPRESS, keyCode, opt_charCode, opt_keyIdentifier,
opt_ctrlKey, opt_altKey, opt_shiftKey);
keyHandler.handleEvent(fakeEvent);
return fakeEvent.returnValue_;
}
function fireKeyUp(
keyHandler, keyCode, opt_charCode, opt_keyIdentifier, opt_ctrlKey,
opt_altKey, opt_shiftKey) {
var fakeEvent = createFakeKeyEvent(
goog.events.EventType.KEYUP, keyCode, opt_charCode, opt_keyIdentifier,
opt_ctrlKey, opt_altKey, opt_shiftKey);
keyHandler.handleKeyup_(fakeEvent);
return fakeEvent.returnValue_;
}
function createFakeKeyEvent(
type, keyCode, opt_charCode, opt_keyIdentifier, opt_ctrlKey, opt_altKey,
opt_shiftKey) {
var event = {
type: type,
keyCode: keyCode,
charCode: opt_charCode || undefined,
keyIdentifier: opt_keyIdentifier || undefined,
ctrlKey: opt_ctrlKey || false,
altKey: opt_altKey || false,
shiftKey: opt_shiftKey || false,
timeStamp: goog.now()
};
return new goog.events.BrowserEvent(event);
}
|
var createHash = require('crypto').createHash;
function get_header(header, credentials, opts) {
var type = header.split(' ')[0],
user = credentials[0],
pass = credentials[1];
if (type == 'Digest') {
return digest.generate(header, user, pass, opts.method, opts.path);
} else if (type == 'Basic') {
return basic(user, pass);
}
}
////////////////////
// basic
function md5(string) {
return createHash('md5').update(string).digest('hex');
}
function basic(user, pass) {
var str = typeof pass == 'undefined' ? user : [user, pass].join(':');
return 'Basic ' + new Buffer(str).toString('base64');
}
////////////////////
// digest
// logic inspired from https://github.com/simme/node-http-digest-client
var digest = {};
digest.parse_header = function(header) {
var challenge = {},
matches = header.match(/([a-z0-9_-]+)="?([a-z0-9=\/\.@\s-]+)"?/gi);
for (var i = 0, l = matches.length; i < l; i++) {
var parts = matches[i].split('='),
key = parts.shift(),
val = parts.join('=').replace(/^"/, '').replace(/"$/, '');
challenge[key] = val;
}
return challenge;
}
digest.update_nc = function(nc) {
var max = 99999999;
nc++;
if (nc > max)
nc = 1;
var padding = new Array(8).join('0') + '';
nc = nc + '';
return padding.substr(0, 8 - nc.length) + nc;
}
digest.generate = function(header, user, pass, method, path) {
var nc = 1,
cnonce = null,
challenge = digest.parse_header(header);
var ha1 = md5(user + ':' + challenge.realm + ':' + pass),
ha2 = md5(method.toUpperCase() + ':' + path),
resp = [ha1, challenge.nonce];
if (typeof challenge.qop === 'string') {
cnonce = md5(Math.random().toString(36)).substr(0, 8);
nc = digest.update_nc(nc);
resp = resp.concat(nc, cnonce);
}
resp = resp.concat(challenge.qop, ha2);
var params = {
uri : path,
realm : challenge.realm,
nonce : challenge.nonce,
username : user,
response : md5(resp.join(':'))
}
if (challenge.qop) {
params.qop = challenge.qop;
}
if (challenge.opaque) {
params.opaque = challenge.opaque;
}
if (cnonce) {
params.nc = nc;
params.cnonce = cnonce;
}
header = []
for (var k in params)
header.push(k + '="' + params[k] + '"')
return 'Digest ' + header.join(', ');
}
module.exports = {
header : get_header,
basic : basic,
digest : digest.generate
}
|
/*jshint node:true*/
module.exports = {
description: ''
// locals: function(options) {
// // Return custom template variables here.
// return {
// foo: options.entity.options.foo
// };
// }
// afterInstall: function(options) {
// // Perform extra work here.
// }
};
|
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides data persistence using HTML5 local storage
* mechanism. Local storage must be available under window.localStorage,
* see: http://www.w3.org/TR/webstorage/#the-localstorage-attribute.
*
*/
goog.provide('goog.storage.mechanism.HTML5LocalStorage');
goog.require('goog.storage.mechanism.HTML5WebStorage');
/**
* Provides a storage mechanism that uses HTML5 local storage.
*
* @constructor
* @struct
* @extends {goog.storage.mechanism.HTML5WebStorage}
*/
goog.storage.mechanism.HTML5LocalStorage = function() {
var storage = null;
/** @preserveTry */
try {
// May throw an exception in cases where the local storage object
// is visible but access to it is disabled.
storage = window.localStorage || null;
} catch (e) {
}
goog.storage.mechanism.HTML5LocalStorage.base(this, 'constructor', storage);
};
goog.inherits(
goog.storage.mechanism.HTML5LocalStorage,
goog.storage.mechanism.HTML5WebStorage);
|
/* jshint latedef: true,
undef:true
*/
foo();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.