path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
src/main/scripts/modules/sea-siege/react/views/card/header.js | twuni/sea-siege | import React from 'react';
import Component from '../../components/component';
import ManaCost from './mana-cost';
const {object, string} = React.PropTypes;
class Header extends Component {
static get propTypes() {
return Component.withPropTypes({
title: string.isRequired,
cost: object
});
}
render() {
return <header className={this.classNames}>
<h1>{this.props.title}</h1>
<aside>
<ManaCost {...this.props.cost}/>
</aside>
</header>
}
}
export default Header;
|
src/components/Main.js | tenghuiliu/demo-by-react | require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import ReactDOM from 'react-dom';
// 获取images数据
var imageDatas = require('../sources/imageData.json');
/**
* 利用只执行函数,将图片名信息转成图片URL路径信息
* @param {[type]} imageDatasArr: images数据数组
* @return {[type]} imageDatasArr: 含有图片URL路径信息images数据数组
*/
imageDatas = (function getImageURL(imageDatasArr){
for (var i = 0; i < imageDatasArr.length; i++) {
var singleImageData = imageDatasArr[i];
singleImageData.imageURL = require('../images/' + singleImageData.fileName);
imageDatasArr[i] = singleImageData;
}
return imageDatasArr;
})(imageDatas);
/**
* 获取区间内的一个随机数
* @param {[type]} low 开始范围
* @param {[type]} high 结束范围
* @return {[type]} 随机数
*/
function getRangeRandom(low, high){
return Math.floor(Math.random() * (high - low) + low);
}
/**
* 获取 0-30 之间的一个任意正负值
* @return num 0-30 之间的一个任意正负值
*/
function get30DegRandom() {
return Math.floor((Math.random() > 0.5 ? '':'-') + Math.floor(Math.random() * 30));
}
// 图片组件
var ImgFigure = React.createClass({
/**
* ImgFigure的点击处理函数
* @param {Event} e
* @return
*/
handleClick: function (e) {
// 判断居中还是翻转
if(this.props.arrange.isCenter){
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
},
render: function(){
var styleObj = {};
// 如果props属性中指定了这张图片的位置,则使用
if(this.props.arrange.pos){
styleObj = this.props.arrange.pos;
}
// 如果图片的旋转角度有值且不为0,天假旋转角度
if(this.props.arrange.rotate){
(['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function(value) {
styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)';
}.bind(this));
}
let imgFigureClassName = "img-figure";
// 判断是否需要添加 图片反面样式
imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
if (this.props.arrange.isCenter) {
styleObj["zIndex"] = 11;
}
return (
<figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}>
<img src={this.props.data.imageURL}
alt={this.props.data.title} />
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick} >
<p>
{this.props.data.desc}
</p>
</div>
</figcaption>
</figure >
);
}
});
/**
* 控制图片组件
*/
var ControllerUnit = React.createClass({
handleClick: function (e) {
// 如果点击的是当前选中态的按钮,则翻转图片,否则居中图片
if(this.props.arrange.isCenter){
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
},
render: function(){
var controllerUnitClassName = "controller-unit";
// 如果对应的是居中图片,显示控制按钮的居中态
if(this.props.arrange.isCenter){
controllerUnitClassName += " is-center";
// 如果同时对应的是翻转图片, 显示控制按钮的翻转台
if (this.props.arrange.isInverse) {
controllerUnitClassName += " is-inverse";
}
}
return (
<span className={controllerUnitClassName} onClick={this.handleClick}></span>
);
}
});
// 总入口组件
var AppComponent = React.createClass({
/**
* 常数
*/
Constant: {
centerPos: {
left: 0,
right: 0
},
hPosRange: { // 水平方向的取值范围
leftSecX: [0, 0],
rightSecX: [0, 0],
y: [0, 0]
},
vPosRange: { // 垂直方向的取值范围
x: [0, 0],
topY: [0, 0]
}
},
/**
* 翻转图片
* @param {num} index 输入当前被执行inverse操作的图片对应的图片信息数组的index值
* @return {Function} 这是一个必报函数,其内return一个真正待被执行的函数
*/
inverse: function(index){
return function () {
var imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}.bind(this);
},
/*
* 重新布局所有图片
* @param centerIndex 指定居中排布哪个图片
* @return
*/
rearrange: function(centerIndex){
var imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr = [],
topImgNum = Math.floor(Math.random() * 2), // 取一个或不取
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);
// 首先居中 centerIndex 的图片,且居中的图片不需要旋转
imgsArrangeCenterArr[0] = {
pos: centerPos,
rotate: 0,
isCenter: true
};
// 去除要布局上侧的图片的状态信息
topImgSpliceIndex = Math.floor(Math.random() * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);
// 布局位于上侧图片
imgsArrangeTopArr.forEach(function (value, index) {
imgsArrangeTopArr[index] = {
pos: {
top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
},
rotate: get30DegRandom(),
isCenter: false
}
});
// 布局左右两侧的图片
for (var i = 0 ,j = imgsArrangeArr.length, k = j / 2; i < j; i++) {
var hPosRangeLORX = null;
// 前半部分布局在左边,右半部分布局在右边
if(i < k){
hPosRangeLORX = hPosRangeLeftSecX;
} else {
hPosRangeLORX = hPosRangeRightSecX;
}
// 图片布局信息
imgsArrangeArr[i] = {
pos: {
top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
},
rotate: get30DegRandom(),
isCenter: false
}
}
// 合并去除的状态
if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);
// 设置组件状态渲染dom界面
this.setState({
imgsArrangeArr: imgsArrangeArr
});
},
/**
* 利用 rearrange函数,居中对应index的图片
* @param {num} index 要居中图片对应index
* @return {Function}
*/
center: function (index) {
return function () {
this.rearrange(index);
}.bind(this);
},
/**
* 设置状态,状态改变就会重新渲染dom
* @return {[type]}
*/
getInitialState: function(){
return {
imgsArrangeArr:[
/* {
pos: { // 定位
left: 0,
top: 0
},
rotate: 0 ,// 旋转角度
isInverse: false, // 图片正反面
isCenter: false // 图片是否居中
}*/
]
};
},
/**
* react加载组件后, 为每张图片计算器位置的范围
* @return {[type]}
*/
componentDidMount: function(){
// 首先拿到舞台的大小
var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
stageW = stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2)
;
// 拿到一个imageFigure的大小
var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0),
imgW = imgFigureDOM.scrollWidth,
imgH = imgFigureDOM.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2)
;
// 计算中心图片的位置点
this.Constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
};
// 计算水平方向, 左侧右侧区域图片排布位置的取值范围
this.Constant.hPosRange.leftSecX[0] = -halfImgW; // 最左侧x
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; // 左侧中心区x
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; // 最右侧x
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; // 右侧中心区x
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH; // ?
// 计算垂直方向: 上侧区域图片排布位置的取值范围
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;//?
this.Constant.vPosRange.x[1] = halfStageW;//?
var imgsArrangeArr = this.state.imgsArrangeArr;
// 排布图片
this.rearrange(getRangeRandom(0,imgsArrangeArr.length));// 初始第一张在中间
},
render: function() {
var controllerUnits = [], // 图片控制器集合
imgFigures = []; // 图片组件集合
// 通过bind绑定this,使得forEach函数内的this是指向外部组件,才可以调用状态
imageDatas.forEach(function(value ,index){
// 判断是否绑定了imgsArrangeArr状态
if(!this.state.imgsArrangeArr[index]){
// 初始化imgsArrangeArr状态
this.state.imgsArrangeArr[index] = {
pos: {
left: 0,
top: 0
},
rotate: 0,
isInverse: false,
isCenter: false
}
}
imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index}
arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)}
center={this.center(index)} />);
controllerUnits.push(<ControllerUnit key={index}
arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)}
center={this.center(index)}
/>);
}.bind(this));
// 返回要渲染的界面内容
return (
<section className="stage" ref="stage">
<section className="image-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
});
AppComponent.defaultProps = {
};
export default AppComponent;
|
classic/src/scenes/wbfa/generated/FARBell.free.js | wavebox/waveboxapp | import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBell } from '@fortawesome/free-regular-svg-icons/faBell'
export default class FARBell extends React.Component {
render () {
return (<FontAwesomeIcon {...this.props} icon={faBell} />)
}
}
|
docs/app/Components/ComponentDoc/ComponentControls/ComponentControlsToolTip.js | shengnian/shengnian-ui-react | import PropTypes from 'prop-types'
import React from 'react'
import { Popup } from 'shengnian-ui-react'
const toolTipStyle = {
padding: '0.5em',
textAlign: 'center',
width: 100,
}
const ComponentControlsToolTip = ({ children, content }) => (
<Popup
content={content}
inverted
mouseEnterDelay={800}
position='top center'
size='tiny'
style={toolTipStyle}
trigger={children}
/>
)
ComponentControlsToolTip.propTypes = {
children: PropTypes.node,
content: PropTypes.node,
}
export default ComponentControlsToolTip
|
app/javascript/flavours/glitch/features/ui/components/zoomable_image.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from 'flavours/glitch/components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
compress: { id: 'lightbox.compress', defaultMessage: 'Compress image view box' },
expand: { id: 'lightbox.expand', defaultMessage: 'Expand image view box' },
});
const MIN_SCALE = 1;
const MAX_SCALE = 4;
const NAV_BAR_HEIGHT = 66;
const getMidpoint = (p1, p2) => ({
x: (p1.clientX + p2.clientX) / 2,
y: (p1.clientY + p2.clientY) / 2,
});
const getDistance = (p1, p2) =>
Math.sqrt(Math.pow(p1.clientX - p2.clientX, 2) + Math.pow(p1.clientY - p2.clientY, 2));
const clamp = (min, max, value) => Math.min(max, Math.max(min, value));
// Normalizing mousewheel speed across browsers
// copy from: https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
const normalizeWheel = event => {
// Reasonable defaults
const PIXEL_STEP = 10;
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
let sX = 0,
sY = 0, // spinX, spinY
pX = 0,
pY = 0; // pixelX, pixelY
// 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) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else { // delta in PAGE units
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,
};
};
export default @injectIntl
class ZoomableImage extends React.PureComponent {
static propTypes = {
alt: PropTypes.string,
src: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
onClick: PropTypes.func,
zoomButtonHidden: PropTypes.bool,
intl: PropTypes.object.isRequired,
}
static defaultProps = {
alt: '',
width: null,
height: null,
};
state = {
scale: MIN_SCALE,
zoomMatrix: {
type: null, // 'width' 'height'
fullScreen: null, // bool
rate: null, // full screen scale rate
clientWidth: null,
clientHeight: null,
offsetWidth: null,
offsetHeight: null,
clientHeightFixed: null,
scrollTop: null,
scrollLeft: null,
translateX: null,
translateY: null,
},
zoomState: 'expand', // 'expand' 'compress'
navigationHidden: false,
dragPosition: { top: 0, left: 0, x: 0, y: 0 },
dragged: false,
lockScroll: { x: 0, y: 0 },
lockTranslate: { x: 0, y: 0 },
}
removers = [];
container = null;
image = null;
lastTouchEndTime = 0;
lastDistance = 0;
componentDidMount () {
let handler = this.handleTouchStart;
this.container.addEventListener('touchstart', handler);
this.removers.push(() => this.container.removeEventListener('touchstart', handler));
handler = this.handleTouchMove;
// on Chrome 56+, touch event listeners will default to passive
// https://www.chromestatus.com/features/5093566007214080
this.container.addEventListener('touchmove', handler, { passive: false });
this.removers.push(() => this.container.removeEventListener('touchend', handler));
handler = this.mouseDownHandler;
this.container.addEventListener('mousedown', handler);
this.removers.push(() => this.container.removeEventListener('mousedown', handler));
handler = this.mouseWheelHandler;
this.container.addEventListener('wheel', handler);
this.removers.push(() => this.container.removeEventListener('wheel', handler));
// Old Chrome
this.container.addEventListener('mousewheel', handler);
this.removers.push(() => this.container.removeEventListener('mousewheel', handler));
// Old Firefox
this.container.addEventListener('DOMMouseScroll', handler);
this.removers.push(() => this.container.removeEventListener('DOMMouseScroll', handler));
this.initZoomMatrix();
}
componentWillUnmount () {
this.removeEventListeners();
}
componentDidUpdate () {
this.setState({ zoomState: this.state.scale >= this.state.zoomMatrix.rate ? 'compress' : 'expand' });
if (this.state.scale === MIN_SCALE) {
this.container.style.removeProperty('cursor');
}
}
UNSAFE_componentWillReceiveProps () {
// reset when slide to next image
if (this.props.zoomButtonHidden) {
this.setState({
scale: MIN_SCALE,
lockTranslate: { x: 0, y: 0 },
}, () => {
this.container.scrollLeft = 0;
this.container.scrollTop = 0;
});
}
}
removeEventListeners () {
this.removers.forEach(listeners => listeners());
this.removers = [];
}
mouseWheelHandler = e => {
e.preventDefault();
const event = normalizeWheel(e);
if (this.state.zoomMatrix.type === 'width') {
// full width, scroll vertical
this.container.scrollTop = Math.max(this.container.scrollTop + event.pixelY, this.state.lockScroll.y);
} else {
// full height, scroll horizontal
this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelY, this.state.lockScroll.x);
}
// lock horizontal scroll
this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelX, this.state.lockScroll.x);
}
mouseDownHandler = e => {
this.container.style.cursor = 'grabbing';
this.container.style.userSelect = 'none';
this.setState({ dragPosition: {
left: this.container.scrollLeft,
top: this.container.scrollTop,
// Get the current mouse position
x: e.clientX,
y: e.clientY,
} });
this.image.addEventListener('mousemove', this.mouseMoveHandler);
this.image.addEventListener('mouseup', this.mouseUpHandler);
}
mouseMoveHandler = e => {
const dx = e.clientX - this.state.dragPosition.x;
const dy = e.clientY - this.state.dragPosition.y;
this.container.scrollLeft = Math.max(this.state.dragPosition.left - dx, this.state.lockScroll.x);
this.container.scrollTop = Math.max(this.state.dragPosition.top - dy, this.state.lockScroll.y);
this.setState({ dragged: true });
}
mouseUpHandler = () => {
this.container.style.cursor = 'grab';
this.container.style.removeProperty('user-select');
this.image.removeEventListener('mousemove', this.mouseMoveHandler);
this.image.removeEventListener('mouseup', this.mouseUpHandler);
}
handleTouchStart = e => {
if (e.touches.length !== 2) return;
this.lastDistance = getDistance(...e.touches);
}
handleTouchMove = e => {
const { scrollTop, scrollHeight, clientHeight } = this.container;
if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) {
// prevent propagating event to MediaModal
e.stopPropagation();
return;
}
if (e.touches.length !== 2) return;
e.preventDefault();
e.stopPropagation();
const distance = getDistance(...e.touches);
const midpoint = getMidpoint(...e.touches);
const _MAX_SCALE = Math.max(MAX_SCALE, this.state.zoomMatrix.rate);
const scale = clamp(MIN_SCALE, _MAX_SCALE, this.state.scale * distance / this.lastDistance);
this.zoom(scale, midpoint);
this.lastMidpoint = midpoint;
this.lastDistance = distance;
}
zoom(nextScale, midpoint) {
const { scale, zoomMatrix } = this.state;
const { scrollLeft, scrollTop } = this.container;
// math memo:
// x = (scrollLeft + midpoint.x) / scrollWidth
// x' = (nextScrollLeft + midpoint.x) / nextScrollWidth
// scrollWidth = clientWidth * scale
// scrollWidth' = clientWidth * nextScale
// Solve x = x' for nextScrollLeft
const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x;
const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y;
this.setState({ scale: nextScale }, () => {
this.container.scrollLeft = nextScrollLeft;
this.container.scrollTop = nextScrollTop;
// reset the translateX/Y constantly
if (nextScale < zoomMatrix.rate) {
this.setState({
lockTranslate: {
x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
},
});
}
});
}
handleClick = e => {
// don't propagate event to MediaModal
e.stopPropagation();
const dragged = this.state.dragged;
this.setState({ dragged: false });
if (dragged) return;
const handler = this.props.onClick;
if (handler) handler();
this.setState({ navigationHidden: !this.state.navigationHidden });
}
handleMouseDown = e => {
e.preventDefault();
}
initZoomMatrix = () => {
const { width, height } = this.props;
const { clientWidth, clientHeight } = this.container;
const { offsetWidth, offsetHeight } = this.image;
const clientHeightFixed = clientHeight - NAV_BAR_HEIGHT;
const type = width / height < clientWidth / clientHeightFixed ? 'width' : 'height';
const fullScreen = type === 'width' ? width > clientWidth : height > clientHeightFixed;
const rate = type === 'width' ? Math.min(clientWidth, width) / offsetWidth : Math.min(clientHeightFixed, height) / offsetHeight;
const scrollTop = type === 'width' ? (clientHeight - offsetHeight) / 2 - NAV_BAR_HEIGHT : (clientHeightFixed - offsetHeight) / 2;
const scrollLeft = (clientWidth - offsetWidth) / 2;
const translateX = type === 'width' ? (width - offsetWidth) / (2 * rate) : 0;
const translateY = type === 'height' ? (height - offsetHeight) / (2 * rate) : 0;
this.setState({
zoomMatrix: {
type: type,
fullScreen: fullScreen,
rate: rate,
clientWidth: clientWidth,
clientHeight: clientHeight,
offsetWidth: offsetWidth,
offsetHeight: offsetHeight,
clientHeightFixed: clientHeightFixed,
scrollTop: scrollTop,
scrollLeft: scrollLeft,
translateX: translateX,
translateY: translateY,
},
});
}
handleZoomClick = e => {
e.preventDefault();
e.stopPropagation();
const { scale, zoomMatrix } = this.state;
if ( scale >= zoomMatrix.rate ) {
this.setState({
scale: MIN_SCALE,
lockScroll: {
x: 0,
y: 0,
},
lockTranslate: {
x: 0,
y: 0,
},
}, () => {
this.container.scrollLeft = 0;
this.container.scrollTop = 0;
});
} else {
this.setState({
scale: zoomMatrix.rate,
lockScroll: {
x: zoomMatrix.scrollLeft,
y: zoomMatrix.scrollTop,
},
lockTranslate: {
x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX,
y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY,
},
}, () => {
this.container.scrollLeft = zoomMatrix.scrollLeft;
this.container.scrollTop = zoomMatrix.scrollTop;
});
}
this.container.style.cursor = 'grab';
this.container.style.removeProperty('user-select');
}
setContainerRef = c => {
this.container = c;
}
setImageRef = c => {
this.image = c;
}
render () {
const { alt, src, width, height, intl } = this.props;
const { scale, lockTranslate } = this.state;
const overflow = scale === MIN_SCALE ? 'hidden' : 'scroll';
const zoomButtonShouldHide = this.state.navigationHidden || this.props.zoomButtonHidden || this.state.zoomMatrix.rate <= MIN_SCALE ? 'media-modal__zoom-button--hidden' : '';
const zoomButtonTitle = this.state.zoomState === 'compress' ? intl.formatMessage(messages.compress) : intl.formatMessage(messages.expand);
return (
<React.Fragment>
<IconButton
className={`media-modal__zoom-button ${zoomButtonShouldHide}`}
title={zoomButtonTitle}
icon={this.state.zoomState}
onClick={this.handleZoomClick}
size={40}
style={{
fontSize: '30px', /* Fontawesome's fa-compress fa-expand is larger than fa-close */
}}
/>
<div
className='zoomable-image'
ref={this.setContainerRef}
style={{ overflow }}
>
<img
role='presentation'
ref={this.setImageRef}
alt={alt}
title={alt}
src={src}
width={width}
height={height}
style={{
transform: `scale(${scale}) translate(-${lockTranslate.x}px, -${lockTranslate.y}px)`,
transformOrigin: '0 0',
}}
draggable={false}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
/>
</div>
</React.Fragment>
);
}
}
|
ajax/libs/extjs/4.2.1/src/form/Basic.js | SimeonC/cdnjs | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314)
*/
/**
* Provides input field management, validation, submission, and form loading services for the collection
* of {@link Ext.form.field.Field Field} instances within a {@link Ext.container.Container}. It is recommended
* that you use a {@link Ext.form.Panel} as the form container, as that has logic to automatically
* hook up an instance of {@link Ext.form.Basic} (plus other conveniences related to field configuration.)
*
* ## Form Actions
*
* The Basic class delegates the handling of form loads and submits to instances of {@link Ext.form.action.Action}.
* See the various Action implementations for specific details of each one's functionality, as well as the
* documentation for {@link #doAction} which details the configuration options that can be specified in
* each action call.
*
* The default submit Action is {@link Ext.form.action.Submit}, which uses an Ajax request to submit the
* form's values to a configured URL. To enable normal browser submission of an Ext form, use the
* {@link #standardSubmit} config option.
*
* ## File uploads
*
* File uploads are not performed using normal 'Ajax' techniques; see the description for
* {@link #hasUpload} for details. If you're using file uploads you should read the method description.
*
* ## Example usage:
*
* @example
* Ext.create('Ext.form.Panel', {
* title: 'Basic Form',
* renderTo: Ext.getBody(),
* bodyPadding: 5,
* width: 350,
*
* // Any configuration items here will be automatically passed along to
* // the Ext.form.Basic instance when it gets created.
*
* // The form will submit an AJAX request to this URL when submitted
* url: 'save-form.php',
*
* items: [{
* xtype: 'textfield',
* fieldLabel: 'Field',
* name: 'theField'
* }],
*
* buttons: [{
* text: 'Submit',
* handler: function() {
* // The getForm() method returns the Ext.form.Basic instance:
* var form = this.up('form').getForm();
* if (form.isValid()) {
* // Submit the Ajax request and handle the response
* form.submit({
* success: function(form, action) {
* Ext.Msg.alert('Success', action.result.message);
* },
* failure: function(form, action) {
* Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
* }
* });
* }
* }
* }]
* });
*
* @docauthor Jason Johnston <jason@sencha.com>
*/
Ext.define('Ext.form.Basic', {
extend: 'Ext.util.Observable',
alternateClassName: 'Ext.form.BasicForm',
requires: ['Ext.util.MixedCollection', 'Ext.form.action.Load', 'Ext.form.action.Submit',
'Ext.window.MessageBox', 'Ext.data.Errors', 'Ext.util.DelayedTask'],
/**
* Creates new form.
* @param {Ext.container.Container} owner The component that is the container for the form, usually a {@link Ext.form.Panel}
* @param {Object} config Configuration options. These are normally specified in the config to the
* {@link Ext.form.Panel} constructor, which passes them along to the BasicForm automatically.
*/
constructor: function(owner, config) {
var me = this,
reader;
/**
* @property {Ext.container.Container} owner
* The container component to which this BasicForm is attached.
*/
me.owner = owner;
me.checkValidityTask = new Ext.util.DelayedTask(me.checkValidity, me);
me.checkDirtyTask = new Ext.util.DelayedTask(me.checkDirty, me);
// We use the monitor here as opposed to event bubbling. The problem with bubbling is it doesn't
// let us react to items being added/remove at different places in the hierarchy which may have an
// impact on the dirty/valid state.
me.monitor = new Ext.container.Monitor({
selector: '[isFormField]',
scope: me,
addHandler: me.onFieldAdd,
removeHandler: me.onFieldRemove
});
me.monitor.bind(owner);
Ext.apply(me, config);
// Normalize the paramOrder to an Array
if (Ext.isString(me.paramOrder)) {
me.paramOrder = me.paramOrder.split(/[\s,|]/);
}
reader = me.reader;
if (reader && !reader.isReader) {
if (typeof reader === 'string') {
reader = {
type: reader
};
}
me.reader = Ext.createByAlias('reader.' + reader.type, reader);
}
reader = me.errorReader;
if (reader && !reader.isReader) {
if (typeof reader === 'string') {
reader = {
type: reader
};
}
me.errorReader = Ext.createByAlias('reader.' + reader.type, reader);
}
me.addEvents(
/**
* @event beforeaction
* Fires before any action is performed. Return false to cancel the action.
* @param {Ext.form.Basic} this
* @param {Ext.form.action.Action} action The {@link Ext.form.action.Action} to be performed
*/
'beforeaction',
/**
* @event actionfailed
* Fires when an action fails.
* @param {Ext.form.Basic} this
* @param {Ext.form.action.Action} action The {@link Ext.form.action.Action} that failed
*/
'actionfailed',
/**
* @event actioncomplete
* Fires when an action is completed.
* @param {Ext.form.Basic} this
* @param {Ext.form.action.Action} action The {@link Ext.form.action.Action} that completed
*/
'actioncomplete',
/**
* @event validitychange
* Fires when the validity of the entire form changes.
* @param {Ext.form.Basic} this
* @param {Boolean} valid `true` if the form is now valid, `false` if it is now invalid.
*/
'validitychange',
/**
* @event dirtychange
* Fires when the dirty state of the entire form changes.
* @param {Ext.form.Basic} this
* @param {Boolean} dirty `true` if the form is now dirty, `false` if it is no longer dirty.
*/
'dirtychange'
);
me.callParent();
},
/**
* Do any post layout initialization
* @private
*/
initialize : function() {
this.initialized = true;
this.onValidityChange(!this.hasInvalidField());
},
/**
* @cfg {String} method
* The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
*/
/**
* @cfg {Object/Ext.data.reader.Reader} reader
* An Ext.data.reader.Reader (e.g. {@link Ext.data.reader.Xml}) instance or
* configuration to be used to read data when executing 'load' actions. This
* is optional as there is built-in support for processing JSON responses.
*/
/**
* @cfg {Object/Ext.data.reader.Reader} errorReader
* An Ext.data.reader.Reader (e.g. {@link Ext.data.reader.Xml}) instance or
* configuration to be used to read field error messages returned from 'submit' actions.
* This is optional as there is built-in support for processing JSON responses.
*
* The Records which provide messages for the invalid Fields must use the
* Field name (or id) as the Record ID, and must contain a field called 'msg'
* which contains the error message.
*
* The errorReader does not have to be a full-blown implementation of a
* Reader. It simply needs to implement a `read(xhr)` function
* which returns an Array of Records in an object with the following
* structure:
*
* {
* records: recordArray
* }
*/
/**
* @cfg {String} url
* The URL to use for form actions if one isn't supplied in the
* {@link #doAction doAction} options.
*/
/**
* @cfg {Object} baseParams
* Parameters to pass with all requests. e.g. baseParams: `{id: '123', foo: 'bar'}`.
*
* Parameters are encoded as standard HTTP parameters using {@link Ext.Object#toQueryString}.
*/
/**
* @cfg {Number} timeout
* Timeout for form actions in seconds.
*/
timeout: 30,
/**
* @cfg {Object} api
* If specified, load and submit actions will be handled with {@link Ext.form.action.DirectLoad DirectLoad}
* and {@link Ext.form.action.DirectSubmit DirectSubmit}. Methods which have been imported by
* {@link Ext.direct.Manager} can be specified here to load and submit forms. API methods may also be
* specified as strings. See {@link Ext.data.proxy.Direct#directFn}. Such as the following:
*
* api: {
* load: App.ss.MyProfile.load,
* submit: App.ss.MyProfile.submit
* }
*
* Load actions can use {@link #paramOrder} or {@link #paramsAsHash} to customize how the load method
* is invoked. Submit actions will always use a standard form submit. The `formHandler` configuration
* (see Ext.direct.RemotingProvider#action) must be set on the associated server-side method which has
* been imported by {@link Ext.direct.Manager}.
*/
/**
* @cfg {String/String[]} paramOrder
* A list of params to be executed server side. Only used for the {@link #api} `load`
* configuration.
*
* Specify the params in the order in which they must be executed on the
* server-side as either (1) an Array of String values, or (2) a String of params
* delimited by either whitespace, comma, or pipe. For example,
* any of the following would be acceptable:
*
* paramOrder: ['param1','param2','param3']
* paramOrder: 'param1 param2 param3'
* paramOrder: 'param1,param2,param3'
* paramOrder: 'param1|param2|param'
*/
/**
* @cfg {Boolean} paramsAsHash
* Only used for the {@link #api} `load` configuration. If true, parameters will be sent as a
* single hash collection of named arguments. Providing a {@link #paramOrder} nullifies this
* configuration.
*/
paramsAsHash: false,
//<locale>
/**
* @cfg {String} waitTitle
* The default title to show for the waiting message box
*/
waitTitle: 'Please Wait...',
//</locale>
/**
* @cfg {Boolean} trackResetOnLoad
* If set to true, {@link #reset}() resets to the last loaded or {@link #setValues}() data instead of
* when the form was first created.
*/
trackResetOnLoad: false,
/**
* @cfg {Boolean} standardSubmit
* If set to true, a standard HTML form submit is used instead of a XHR (Ajax) style form submission.
* All of the field values, plus any additional params configured via {@link #baseParams}
* and/or the `options` to {@link #submit}, will be included in the values submitted in the form.
*/
/**
* @cfg {Boolean} jsonSubmit
* If set to true, the field values are sent as JSON in the request body.
* All of the field values, plus any additional params configured via {@link #baseParams}
* and/or the `options` to {@link #submit}, will be included in the values POSTed in the body of the request.
*/
/**
* @cfg {String/HTMLElement/Ext.Element} waitMsgTarget
* By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
* element by passing it or its id or mask the form itself by passing in true.
*/
// Private
wasDirty: false,
/**
* Destroys this object.
*/
destroy: function() {
var me = this,
mon = me.monitor;
if (mon) {
mon.unbind();
me.monitor = null;
}
me.clearListeners();
me.checkValidityTask.cancel();
me.checkDirtyTask.cancel();
},
onFieldAdd: function(field){
var me = this;
me.mon(field, 'validitychange', me.checkValidityDelay, me);
me.mon(field, 'dirtychange', me.checkDirtyDelay, me);
if (me.initialized) {
me.checkValidityDelay();
}
},
onFieldRemove: function(field){
var me = this;
me.mun(field, 'validitychange', me.checkValidityDelay, me);
me.mun(field, 'dirtychange', me.checkDirtyDelay, me);
if (me.initialized) {
me.checkValidityDelay();
}
},
/**
* Return all the {@link Ext.form.field.Field} components in the owner container.
* @return {Ext.util.MixedCollection} Collection of the Field objects
*/
getFields: function() {
return this.monitor.getItems();
},
/**
* @private
* Finds and returns the set of all items bound to fields inside this form
* @return {Ext.util.MixedCollection} The set of all bound form field items
*/
getBoundItems: function() {
var boundItems = this._boundItems;
if (!boundItems || boundItems.getCount() === 0) {
boundItems = this._boundItems = new Ext.util.MixedCollection();
boundItems.addAll(this.owner.query('[formBind]'));
}
return boundItems;
},
/**
* Returns true if the form contains any invalid fields. No fields will be marked as invalid
* as a result of calling this; to trigger marking of fields use {@link #isValid} instead.
*/
hasInvalidField: function() {
return !!this.getFields().findBy(function(field) {
var preventMark = field.preventMark,
isValid;
field.preventMark = true;
isValid = field.isValid();
field.preventMark = preventMark;
return !isValid;
});
},
/**
* Returns true if client-side validation on the form is successful. Any invalid fields will be
* marked as invalid. If you only want to determine overall form validity without marking anything,
* use {@link #hasInvalidField} instead.
* @return {Boolean}
*/
isValid: function() {
var me = this,
invalid;
Ext.suspendLayouts();
invalid = me.getFields().filterBy(function(field) {
return !field.validate();
});
Ext.resumeLayouts(true);
return invalid.length < 1;
},
/**
* Check whether the validity of the entire form has changed since it was last checked, and
* if so fire the {@link #validitychange validitychange} event. This is automatically invoked
* when an individual field's validity changes.
*/
checkValidity: function() {
var me = this,
valid = !me.hasInvalidField();
if (valid !== me.wasValid) {
me.onValidityChange(valid);
me.fireEvent('validitychange', me, valid);
me.wasValid = valid;
}
},
checkValidityDelay: function(){
this.checkValidityTask.delay(10);
},
/**
* @private
* Handle changes in the form's validity. If there are any sub components with
* `formBind=true` then they are enabled/disabled based on the new validity.
* @param {Boolean} valid
*/
onValidityChange: function(valid) {
var boundItems = this.getBoundItems(),
items, i, iLen, cmp;
if (boundItems) {
items = boundItems.items;
iLen = items.length;
for (i = 0; i < iLen; i++) {
cmp = items[i];
if (cmp.disabled === valid) {
cmp.setDisabled(!valid);
}
}
}
},
/**
* Returns `true` if any fields in this form have changed from their original values.
*
* Note that if this BasicForm was configured with {@link Ext.form.Basic#trackResetOnLoad
* trackResetOnLoad} then the Fields' *original values* are updated when the values are
* loaded by {@link Ext.form.Basic#setValues setValues} or {@link #loadRecord}.
*
* @return {Boolean}
*/
isDirty: function() {
return !!this.getFields().findBy(function(f) {
return f.isDirty();
});
},
checkDirtyDelay: function(){
this.checkDirtyTask.delay(10);
},
/**
* Check whether the dirty state of the entire form has changed since it was last checked, and
* if so fire the {@link #dirtychange dirtychange} event. This is automatically invoked
* when an individual field's `dirty` state changes.
*/
checkDirty: function() {
var dirty = this.isDirty();
if (dirty !== this.wasDirty) {
this.fireEvent('dirtychange', this, dirty);
this.wasDirty = dirty;
}
},
/**
* Returns `true` if the form contains a file upload field. This is used to determine the method for submitting the
* form: File uploads are not performed using normal 'Ajax' techniques, that is they are **not** performed using
* XMLHttpRequests. Instead a hidden `<form>` element containing all the fields is created temporarily and submitted
* with its [target][1] set to refer to a dynamically generated, hidden `<iframe>` which is inserted into the document
* but removed after the return data has been gathered.
*
* The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON
* to send the return object, then the [Content-Type][2] header must be set to "text/html" in order to tell the
* browser to insert the text unchanged into the document body.
*
* Characters which are significant to an HTML parser must be sent as HTML entities, so encode `"<"` as `"<"`,
* `"&"` as `"&"` etc.
*
* The response text is retrieved from the document, and a fake XMLHttpRequest object is created containing a
* responseText property in order to conform to the requirements of event handlers and callbacks.
*
* Be aware that file upload packets are sent with the content type [multipart/form][3] and some server technologies
* (notably JEE) may require some custom processing in order to retrieve parameter names and parameter values from
* the packet content.
*
* [1]: http://www.w3.org/TR/REC-html40/present/frames.html#adef-target
* [2]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
* [3]: http://www.faqs.org/rfcs/rfc2388.html
*
* @return {Boolean}
*/
hasUpload: function() {
return !!this.getFields().findBy(function(f) {
return f.isFileUpload();
});
},
/**
* Performs a predefined action (an implementation of {@link Ext.form.action.Action}) to perform application-
* specific processing.
*
* @param {String/Ext.form.action.Action} action The name of the predefined action type, or instance of {@link
* Ext.form.action.Action} to perform.
*
* @param {Object} [options] The options to pass to the {@link Ext.form.action.Action} that will get created,
* if the action argument is a String.
*
* All of the config options listed below are supported by both the {@link Ext.form.action.Submit submit} and
* {@link Ext.form.action.Load load} actions unless otherwise noted (custom actions could also accept other
* config options):
*
* @param {String} options.url
* The url for the action (defaults to the form's {@link #url}.)
*
* @param {String} options.method
* The form method to use (defaults to the form's method, or POST if not defined)
*
* @param {String/Object} options.params
* The params to pass (defaults to the form's baseParams, or none if not defined)
*
* Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode Ext.Object.toQueryString}.
*
* @param {Object} options.headers
* Request headers to set for the action.
*
* @param {Function} options.success
* The callback that will be invoked after a successful response (see top of {@link Ext.form.action.Submit submit}
* and {@link Ext.form.action.Load load} for a description of what constitutes a successful response).
* @param {Ext.form.Basic} options.success.form The form that requested the action.
* @param {Ext.form.action.Action} options.success.action The Action object which performed the operation.
* The action object contains these properties of interest:
*
* - {@link Ext.form.action.Action#response response}
* - {@link Ext.form.action.Action#result result} - interrogate for custom postprocessing
* - {@link Ext.form.action.Action#type type}
*
* @param {Function} options.failure
* The callback that will be invoked after a failed transaction attempt.
* @param {Ext.form.Basic} options.failure.form The form that requested the action.
* @param {Ext.form.action.Action} options.failure.action The Action object which performed the operation.
* The action object contains these properties of interest:
*
* - {@link Ext.form.action.Action#failureType failureType}
* - {@link Ext.form.action.Action#response response}
* - {@link Ext.form.action.Action#result result} - interrogate for custom postprocessing
* - {@link Ext.form.action.Action#type type}
*
* @param {Object} options.scope
* The scope in which to call the callback functions (The this reference for the callback functions).
*
* @param {Boolean} options.clientValidation
* Submit Action only. Determines whether a Form's fields are validated in a final call to {@link
* Ext.form.Basic#isValid isValid} prior to submission. Set to false to prevent this. If undefined, pre-submission
* field validation is performed.
*
* @return {Ext.form.Basic} this
*/
doAction: function(action, options) {
if (Ext.isString(action)) {
action = Ext.ClassManager.instantiateByAlias('formaction.' + action, Ext.apply({}, options, {form: this}));
}
if (this.fireEvent('beforeaction', this, action) !== false) {
this.beforeAction(action);
Ext.defer(action.run, 100, action);
}
return this;
},
/**
* Shortcut to {@link #doAction do} a {@link Ext.form.action.Submit submit action}. This will use the
* {@link Ext.form.action.Submit AJAX submit action} by default. If the {@link #standardSubmit} config
* is enabled it will use a standard form element to submit, or if the {@link #api} config is present
* it will use the {@link Ext.form.action.DirectLoad Ext.direct.Direct submit action}.
*
* The following code:
*
* myFormPanel.getForm().submit({
* clientValidation: true,
* url: 'updateConsignment.php',
* params: {
* newStatus: 'delivered'
* },
* success: function(form, action) {
* Ext.Msg.alert('Success', action.result.msg);
* },
* failure: function(form, action) {
* switch (action.failureType) {
* case Ext.form.action.Action.CLIENT_INVALID:
* Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
* break;
* case Ext.form.action.Action.CONNECT_FAILURE:
* Ext.Msg.alert('Failure', 'Ajax communication failed');
* break;
* case Ext.form.action.Action.SERVER_INVALID:
* Ext.Msg.alert('Failure', action.result.msg);
* }
* }
* });
*
* would process the following server response for a successful submission:
*
* {
* "success":true, // note this is Boolean, not string
* "msg":"Consignment updated"
* }
*
* and the following server response for a failed submission:
*
* {
* "success":false, // note this is Boolean, not string
* "msg":"You do not have permission to perform this operation"
* }
*
* @param {Object} options The options to pass to the action (see {@link #doAction} for details).
* @return {Ext.form.Basic} this
*/
submit: function(options) {
options = options || {};
var me = this,
action;
if (options.standardSubmit || me.standardSubmit) {
action = 'standardsubmit';
} else {
action = me.api ? 'directsubmit' : 'submit';
}
return me.doAction(action, options);
},
/**
* Shortcut to {@link #doAction do} a {@link Ext.form.action.Load load action}.
* @param {Object} options The options to pass to the action (see {@link #doAction} for details)
* @return {Ext.form.Basic} this
*/
load: function(options) {
return this.doAction(this.api ? 'directload' : 'load', options);
},
/**
* Persists the values in this form into the passed {@link Ext.data.Model} object in a beginEdit/endEdit block.
* If the record is not specified, it will attempt to update (if it exists) the record provided to loadRecord.
* @param {Ext.data.Model} [record] The record to edit
* @return {Ext.form.Basic} this
*/
updateRecord: function(record) {
record = record || this._record;
if (!record) {
//<debug>
Ext.Error.raise("A record is required.");
//</debug>
return this;
}
var fields = record.fields.items,
values = this.getFieldValues(),
obj = {},
i = 0,
len = fields.length,
name;
for (; i < len; ++i) {
name = fields[i].name;
if (values.hasOwnProperty(name)) {
obj[name] = values[name];
}
}
record.beginEdit();
record.set(obj);
record.endEdit();
return this;
},
/**
* Loads an {@link Ext.data.Model} into this form by calling {@link #setValues} with the
* {@link Ext.data.Model#raw record data}.
* See also {@link #trackResetOnLoad}.
* @param {Ext.data.Model} record The record to load
* @return {Ext.form.Basic} this
*/
loadRecord: function(record) {
this._record = record;
return this.setValues(record.getData());
},
/**
* Returns the last Ext.data.Model instance that was loaded via {@link #loadRecord}
* @return {Ext.data.Model} The record
*/
getRecord: function() {
return this._record;
},
/**
* @private
* Called before an action is performed via {@link #doAction}.
* @param {Ext.form.action.Action} action The Action instance that was invoked
*/
beforeAction: function(action) {
var me = this,
waitMsg = action.waitMsg,
maskCls = Ext.baseCSSPrefix + 'mask-loading',
fields = me.getFields().items,
f,
fLen = fields.length,
field, waitMsgTarget;
// Call HtmlEditor's syncValue before actions
for (f = 0; f < fLen; f++) {
field = fields[f];
if (field.isFormField && field.syncValue) {
field.syncValue();
}
}
if (waitMsg) {
waitMsgTarget = me.waitMsgTarget;
if (waitMsgTarget === true) {
me.owner.el.mask(waitMsg, maskCls);
} else if (waitMsgTarget) {
waitMsgTarget = me.waitMsgTarget = Ext.get(waitMsgTarget);
waitMsgTarget.mask(waitMsg, maskCls);
} else {
me.floatingAncestor = me.owner.up('[floating]');
// https://sencha.jira.com/browse/EXTJSIV-6397
// When the "wait" MessageBox is hidden, the ZIndexManager activates the previous
// topmost floating item which would be any Window housing this form.
// That kicks off a delayed focus call on that Window.
// So if any form post submit processing displayed a MessageBox, that gets
// stomped on.
// The solution is to not move focus at all during this process.
if (me.floatingAncestor) {
me.savePreventFocusOnActivate = me.floatingAncestor.preventFocusOnActivate;
me.floatingAncestor.preventFocusOnActivate = true;
}
Ext.MessageBox.wait(waitMsg, action.waitTitle || me.waitTitle);
}
}
},
/**
* @private
* Called after an action is performed via {@link #doAction}.
* @param {Ext.form.action.Action} action The Action instance that was invoked
* @param {Boolean} success True if the action completed successfully, false, otherwise.
*/
afterAction: function(action, success) {
var me = this;
if (action.waitMsg) {
var messageBox = Ext.MessageBox,
waitMsgTarget = me.waitMsgTarget;
if (waitMsgTarget === true) {
me.owner.el.unmask();
} else if (waitMsgTarget) {
waitMsgTarget.unmask();
} else {
messageBox.hide();
}
}
// Restore setting of any floating ancestor which was manipulated in beforeAction
if (me.floatingAncestor) {
me.floatingAncestor.preventFocusOnActivate = me.savePreventFocusOnActivate;
}
if (success) {
if (action.reset) {
me.reset();
}
Ext.callback(action.success, action.scope || action, [me, action]);
me.fireEvent('actioncomplete', me, action);
} else {
Ext.callback(action.failure, action.scope || action, [me, action]);
me.fireEvent('actionfailed', me, action);
}
},
/**
* Find a specific {@link Ext.form.field.Field} in this form by id or name.
* @param {String} id The value to search for (specify either a {@link Ext.Component#id id} or
* {@link Ext.form.field.Field#getName name or hiddenName}).
* @return {Ext.form.field.Field} The first matching field, or `null` if none was found.
*/
findField: function(id) {
return this.getFields().findBy(function(f) {
return f.id === id || f.getName() === id;
});
},
/**
* Mark fields in this form invalid in bulk.
* @param {Object/Object[]/Ext.data.Errors} errors
* Either an array in the form `[{id:'fieldId', msg:'The message'}, ...]`,
* an object hash of `{id: msg, id2: msg2}`, or a {@link Ext.data.Errors} object.
* @return {Ext.form.Basic} this
*/
markInvalid: function(errors) {
var me = this,
e, eLen, error, value,
key;
function mark(fieldId, msg) {
var field = me.findField(fieldId);
if (field) {
field.markInvalid(msg);
}
}
if (Ext.isArray(errors)) {
eLen = errors.length;
for (e = 0; e < eLen; e++) {
error = errors[e];
mark(error.id, error.msg);
}
} else if (errors instanceof Ext.data.Errors) {
eLen = errors.items.length;
for (e = 0; e < eLen; e++) {
error = errors.items[e];
mark(error.field, error.message);
}
} else {
for (key in errors) {
if (errors.hasOwnProperty(key)) {
value = errors[key];
mark(key, value, errors);
}
}
}
return this;
},
/**
* Set values for fields in this form in bulk.
*
* @param {Object/Object[]} values Either an array in the form:
*
* [{id:'clientName', value:'Fred. Olsen Lines'},
* {id:'portOfLoading', value:'FXT'},
* {id:'portOfDischarge', value:'OSL'} ]
*
* or an object hash of the form:
*
* {
* clientName: 'Fred. Olsen Lines',
* portOfLoading: 'FXT',
* portOfDischarge: 'OSL'
* }
*
* @return {Ext.form.Basic} this
*/
setValues: function(values) {
var me = this,
v, vLen, val, field;
function setVal(fieldId, val) {
var field = me.findField(fieldId);
if (field) {
field.setValue(val);
if (me.trackResetOnLoad) {
field.resetOriginalValue();
}
}
}
// Suspend here because setting the value on a field could trigger
// a layout, for example if an error gets set, or it's a display field
Ext.suspendLayouts();
if (Ext.isArray(values)) {
// array of objects
vLen = values.length;
for (v = 0; v < vLen; v++) {
val = values[v];
setVal(val.id, val.value);
}
} else {
// object hash
Ext.iterate(values, setVal);
}
Ext.resumeLayouts(true);
return this;
},
/**
* Retrieves the fields in the form as a set of key/value pairs, using their
* {@link Ext.form.field.Field#getSubmitData getSubmitData()} method to collect the values.
* If multiple fields return values under the same name those values will be combined into an Array.
* This is similar to {@link Ext.form.Basic#getFieldValues getFieldValues} except that this method
* collects only String values for submission, while getFieldValues collects type-specific data
* values (e.g. Date objects for date fields.)
*
* @param {Boolean} [asString=false] If true, will return the key/value collection as a single
* URL-encoded param string.
* @param {Boolean} [dirtyOnly=false] If true, only fields that are dirty will be included in the result.
* @param {Boolean} [includeEmptyText=false] If true, the configured emptyText of empty fields will be used.
* @param {Boolean} [useDataValues=false] If true, the {@link Ext.form.field.Field#getModelData getModelData}
* method is used to retrieve values from fields, otherwise the {@link Ext.form.field.Field#getSubmitData getSubmitData}
* method is used.
* @return {String/Object}
*/
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
var values = {},
fields = this.getFields().items,
f,
fLen = fields.length,
isArray = Ext.isArray,
field, data, val, bucket, name;
for (f = 0; f < fLen; f++) {
field = fields[f];
if (!dirtyOnly || field.isDirty()) {
data = field[useDataValues ? 'getModelData' : 'getSubmitData'](includeEmptyText);
if (Ext.isObject(data)) {
for (name in data) {
if (data.hasOwnProperty(name)) {
val = data[name];
if (includeEmptyText && val === '') {
val = field.emptyText || '';
}
if (values.hasOwnProperty(name)) {
bucket = values[name];
if (!isArray(bucket)) {
bucket = values[name] = [bucket];
}
if (isArray(val)) {
values[name] = bucket.concat(val);
} else {
bucket.push(val);
}
} else {
values[name] = val;
}
}
}
}
}
}
if (asString) {
values = Ext.Object.toQueryString(values);
}
return values;
},
/**
* Retrieves the fields in the form as a set of key/value pairs, using their
* {@link Ext.form.field.Field#getModelData getModelData()} method to collect the values.
* If multiple fields return values under the same name those values will be combined into an Array.
* This is similar to {@link #getValues} except that this method collects type-specific data values
* (e.g. Date objects for date fields) while getValues returns only String values for submission.
*
* @param {Boolean} [dirtyOnly=false] If true, only fields that are dirty will be included in the result.
* @return {Object}
*/
getFieldValues: function(dirtyOnly) {
return this.getValues(false, dirtyOnly, false, true);
},
/**
* Clears all invalid field messages in this form.
* @return {Ext.form.Basic} this
*/
clearInvalid: function() {
Ext.suspendLayouts();
var me = this,
fields = me.getFields().items,
f,
fLen = fields.length;
for (f = 0; f < fLen; f++) {
fields[f].clearInvalid();
}
Ext.resumeLayouts(true);
return me;
},
/**
* Resets all fields in this form. By default, any record bound by {@link #loadRecord}
* will be retained.
* @param {Boolean} [resetRecord=false] True to unbind any record set
* by {@link #loadRecord}
* @return {Ext.form.Basic} this
*/
reset: function(resetRecord) {
Ext.suspendLayouts();
var me = this,
fields = me.getFields().items,
f,
fLen = fields.length;
for (f = 0; f < fLen; f++) {
fields[f].reset();
}
Ext.resumeLayouts(true);
if (resetRecord === true) {
delete me._record;
}
return me;
},
/**
* Calls {@link Ext#apply Ext.apply} for all fields in this form with the passed object.
* @param {Object} obj The object to be applied
* @return {Ext.form.Basic} this
*/
applyToFields: function(obj) {
var fields = this.getFields().items,
f,
fLen = fields.length;
for (f = 0; f < fLen; f++) {
Ext.apply(fields[f], obj);
}
return this;
},
/**
* Calls {@link Ext#applyIf Ext.applyIf} for all field in this form with the passed object.
* @param {Object} obj The object to be applied
* @return {Ext.form.Basic} this
*/
applyIfToFields: function(obj) {
var fields = this.getFields().items,
f,
fLen = fields.length;
for (f = 0; f < fLen; f++) {
Ext.applyIf(fields[f], obj);
}
return this;
}
});
|
ajax/libs/jquery/1.11.3/jquery.min.js | HealthIndicators/cdnjs | /*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){
return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
//# sourceMappingURL=jquery.min.map |
example/App.js | bodyflex/react-native-simple-modal | import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import Modal from 'react-native-simple-modal';
export default class App extends React.Component {
state = { open: false };
modalDidOpen = () => console.log('Modal did open.');
modalDidClose = () => {
this.setState({ open: false });
console.log('Modal did close.');
};
moveUp = () => this.setState({ offset: -100 });
resetPosition = () => this.setState({ offset: 0 });
openModal = () => this.setState({ open: true });
closeModal = () => this.setState({ open: false });
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<TouchableOpacity onPress={this.openModal}>
<Text>Open modal</Text>
</TouchableOpacity>
<Modal
offset={this.state.offset}
open={this.state.open}
modalDidOpen={this.modalDidOpen}
modalDidClose={this.modalDidClose}
style={{ alignItems: 'center' }}
>
<View style={{ alignItems: 'center' }}>
<Text style={{ fontSize: 20, marginBottom: 10 }}>Hello world!</Text>
<TouchableOpacity style={{ margin: 5 }} onPress={this.moveUp}>
<Text>Move modal up</Text>
</TouchableOpacity>
<TouchableOpacity
style={{ margin: 5 }}
onPress={this.resetPosition}
>
<Text>Reset modal position</Text>
</TouchableOpacity>
<TouchableOpacity style={{ margin: 5 }} onPress={this.closeModal}>
<Text>Close modal</Text>
</TouchableOpacity>
</View>
</Modal>
</View>
);
}
}
|
src/Survey/Complex/Plant/Edit/Main/index.js | NERC-CEH/irecord-app | import { observer } from 'mobx-react';
import React from 'react';
import { IonButton, IonLabel, IonList } from '@ionic/react';
import DynamicMenuAttrs from 'Components/DynamicMenuAttrs';
import AppMain from 'Components/Main';
import PropTypes from 'prop-types';
import SpeciesList from './components/SpeciesList';
import './styles.scss';
@observer
class Component extends React.Component {
static propTypes = {
surveySample: PropTypes.object.isRequired,
history: PropTypes.object,
url: PropTypes.string.isRequired,
onDelete: PropTypes.func.isRequired,
onToggleSpeciesSort: PropTypes.func.isRequired,
speciesListSortedByTime: PropTypes.bool.isRequired,
};
render() {
const {
surveySample,
url,
history,
onDelete,
onToggleSpeciesSort,
speciesListSortedByTime,
} = this.props;
// calculate unique taxa
const uniqueTaxa = {};
surveySample.samples.forEach(childSample => {
const occ = childSample.occurrences[0];
if (occ) {
const taxon = occ.attrs.taxon || {};
uniqueTaxa[taxon.warehouse_id] = true;
}
});
return (
<AppMain>
<IonList lines="full" class="core inputs">
<DynamicMenuAttrs model={surveySample} url={url} noWrapper />
</IonList>
<IonButton
color="primary"
expand="block"
id="add"
onClick={() => {
history.push(
`/survey/complex/plant/${surveySample.cid}/edit/smp/new`
);
}}
>
<IonLabel>{t('Add Species')}</IonLabel>
</IonButton>
<SpeciesList
surveySample={surveySample}
onDelete={onDelete}
url={url}
onToggleSpeciesSort={onToggleSpeciesSort}
speciesListSortedByTime={speciesListSortedByTime}
/>
</AppMain>
);
}
}
export default Component;
|
src/scripts/components/navigation.js | melonmanchan/teamboard-client-react | import page from 'page';
import React from 'react';
import Action from '../actions';
import UserAction from '../actions/user';
import SettingsAction from '../actions/settings';
import BroadcastAction from '../actions/broadcast';
import UserStore from '../stores/user';
import Avatar from '../components/avatar';
import Dropdown from '../components/dropdown';
import MemberDialog from '../components/dialog/board-members';
import UserVoice from '../components/user-voice';
import InfoView from './dialog/view-info';
import AboutView from './dialog/view-about';
/**
*
*/
export default React.createClass({
propTypes: {
title: React.PropTypes.string.isRequired,
showHelp: React.PropTypes.bool,
reviewActive: React.PropTypes.bool,
killReview: React.PropTypes.func,
board: (props) => {
if(!props.board instanceof Board) throw new Error();
}
},
getInitialState() {
return {
dropdown: false, localesDropdown: false,
feedback: false, infoActive: false,
aboutActive: false, membersActive: false
}
},
showWorkspace() {
return page.show('/boards');
},
toggleMembersDialog() {
this.setState({ membersActive: !this.state.membersActive });
},
toggleDropdown() {
this.setState({ dropdown: !this.state.dropdown });
if(this.state.localesDropdown)
this.setState({ localesDropdown: !this.state.localesDropdown });
},
toggleInfoView() {
this.setState({ infoActive: !this.state.infoActive });
},
toggleAboutView() {
this.setState({ aboutActive: !this.state.aboutActive });
},
CancelReview(){
return !this.props.reviewActive ? null : (
<div onClick={() => {this.props.killReview(false)}}
className="review active">
<span className="fa fa-fw fa-times"></span>
</div>
);
},
render() {
let infoDialog = null;
let aboutDialog = null;
let infoIcon = null;
if(!this.state.infoActive) {
infoIcon = 'question';
infoDialog = null;
} else {
infoIcon = 'times';
infoDialog = <InfoView onDismiss = { this.toggleInfoView } />;
}
if(!this.state.aboutActive) {
aboutDialog = null;
} else {
aboutDialog = <AboutView onDismiss = { this.toggleAboutView } />;
}
let infoButtonClass =
React.addons.classSet({
infobutton: true,
pulsate: localStorage.getItem('infovisited') === null
? true : false,
active: this.state.infoActive
});
let userButtonClass =
React.addons.classSet({
'avatar-wrapper': true,
active: this.state.dropdown
});
let membersButtonClass =
React.addons.classSet({
members: true,
active: this.state.membersActive
});
let boardMembersDialog = null;
if (this.state.membersActive) {
boardMembersDialog = <MemberDialog board={this.props.board} onDismiss={this.toggleMembersDialog}/>
}
let showBoardMembers = !this.props.showBoardMembers ? null : (
<div id="members" onClick={this.toggleMembersDialog} className={membersButtonClass}>
<span className="fa fa-fw fa-users">
<span className="user-amount">
{this.props.board.members.size}
</span>
</span>
</div>
);
let showInfo = !this.props.showHelp ? null : (
<div id="info" onClick={this.toggleInfoView} className={infoButtonClass}>
<span className={`fa fa-fw fa-${infoIcon}`}></span>
</div>
);
let isProfileDisabled = UserStore.getUser().type === 'standard';
let items = [
{ icon: 'user', content: 'Profile', disabled: !isProfileDisabled,
onClick: () => {
if(isProfileDisabled) {
return page.show('/profile');
}
}
},
{ icon: 'language', content: 'Localization', disabled: true,
onClick: () => {
//this.setState({ localesDropdown: !this.state.localesDropdown });
}
},
{
content: (
<UserVoice>
<span className="fa fa-fw fa-bullhorn" />
Feedback
</UserVoice>
)
},
{
onClick: () => {
this.toggleAboutView();
},
icon: 'info', content: 'About'
},
{
onClick: () => {
UserAction.logout()
.catch((err) => {
BroadcastAction.add(err, Action.User.Logout);
});
},
icon: 'sign-out', content: 'Logout'
}
];
let locales = [
{flag: 'fi', content: 'Suomi', onClick: () => {
SettingsAction.setSetting('locale', 'fi');
this.toggleDropdown();
}
},
{flag: 'se', content: 'Svenska', onClick: () => {
SettingsAction.setSetting('locale', 'se');
this.toggleDropdown();
}
},
{flag: 'ru', content: 'русский', onClick: () => {
SettingsAction.setSetting('locale', 'ru');
this.toggleDropdown();
}
},
{flag: 'gb', content: 'English', onClick: () => {
SettingsAction.setSetting('locale', 'en');
this.toggleDropdown();
}
}
]
let user = UserStore.getUser();
let name = user.get('username');
let avatarURL = user.get('avatar');
let userType = user.get('type');
return (
<nav id="nav" className="nav">
<img className="logo" src="/dist/assets/img/logo.svg"
onClick={this.showWorkspace} />
<h1 className="title">{this.props.title}</h1>
{this.CancelReview()}
{showBoardMembers}
{showInfo}
<div id="avatar" onClick={this.toggleDropdown} className={userButtonClass}>
<Avatar size={30} name={name}
imageurl={avatarURL}
isOnline={true}
usertype={userType}>
</Avatar>
</div>
<Dropdown className='options' show={this.state.dropdown} items={items} />
<Dropdown className='locales' show={this.state.localesDropdown} items={locales} />
{infoDialog}
{boardMembersDialog}
{aboutDialog}
</nav>
);
}
});
|
src/containers/Root.js | 199911/experimental-blog | import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
import FrontPage from '../pages/FrontPage';
import ArticlePage from '../pages/ArticlePage';
const Root = () => (
<Router>
<div>
<Route exact path="/react-blog/" component={FrontPage}/>
<Route exact path="/react-blog/:postSlug" component={ArticlePage}/>
</div>
</Router>
)
export default Root
|
ajax/libs/shariff/1.4.5/shariff.complete.js | x112358/cdnjs |
/*
* shariff - v1.4.4 - 01.12.2014
* https://github.com/heiseonline/shariff
* Copyright (c) 2014 Ines Pauer, Philipp Busse, Sebastian Hilbig, Erich Kramer, Deniz Sesli
* Licensed under the MIT <http://www.opensource.org/licenses/mit-license.php> license
*/
(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){
!function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=e.length,n=it.type(e);return"function"===n||it.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(it.isFunction(t))return it.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return it.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ft.test(t))return it.filter(t,e,n);t=it.filter(t,e)}return it.grep(e,function(e){return it.inArray(e,t)>=0!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t=xt[e]={};return it.each(e.match(bt)||[],function(e,n){t[n]=!0}),t}function a(){ht.addEventListener?(ht.removeEventListener("DOMContentLoaded",s,!1),e.removeEventListener("load",s,!1)):(ht.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(ht.addEventListener||"load"===event.type||"complete"===ht.readyState)&&(a(),it.ready())}function l(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Et,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Nt.test(n)?it.parseJSON(n):n}catch(i){}it.data(e,t,n)}else n=void 0}return n}function u(e){var t;for(t in e)if(("data"!==t||!it.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(it.acceptData(e)){var i,o,a=it.expando,s=e.nodeType,l=s?it.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=J.pop()||it.guid++:a),l[u]||(l[u]=s?{}:{toJSON:it.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=it.extend(l[u],t):l[u].data=it.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[it.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[it.camelCase(t)])):i=o,i}}function d(e,t,n){if(it.acceptData(e)){var r,i,o=e.nodeType,a=o?it.cache:e,s=o?e[it.expando]:it.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){it.isArray(t)?t=t.concat(it.map(t,it.camelCase)):t in r?t=[t]:(t=it.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!u(r):!it.isEmptyObject(r))return}(n||(delete a[s].data,u(a[s])))&&(o?it.cleanData([e],!0):nt.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function f(){return!0}function p(){return!1}function h(){try{return ht.activeElement}catch(e){}}function m(e){var t=Ot.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function g(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Ct?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Ct?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||it.nodeName(r,t)?o.push(r):it.merge(o,g(r,t));return void 0===t||t&&it.nodeName(e,t)?it.merge([e],o):o}function v(e){jt.test(e.type)&&(e.defaultChecked=e.checked)}function y(e,t){return it.nodeName(e,"table")&&it.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function b(e){return e.type=(null!==it.find.attr(e,"type"))+"/"+e.type,e}function x(e){var t=Vt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function w(e,t){for(var n,r=0;null!=(n=e[r]);r++)it._data(n,"globalEval",!t||it._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&it.hasData(e)){var n,r,i,o=it._data(e),a=it._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)it.event.add(t,n,s[n][r])}a.data&&(a.data=it.extend({},a.data))}}function C(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!nt.noCloneEvent&&t[it.expando]){i=it._data(t);for(r in i.events)it.removeEvent(t,r,i.handle);t.removeAttribute(it.expando)}"script"===n&&t.text!==e.text?(b(t).text=e.text,x(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),nt.html5Clone&&e.innerHTML&&!it.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&jt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function N(t,n){var r,i=it(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:it.css(i[0],"display");return i.detach(),o}function E(e){var t=ht,n=Zt[e];return n||(n=N(e,t),"none"!==n&&n||(Kt=(Kt||it("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Kt[0].contentWindow||Kt[0].contentDocument).document,t.write(),t.close(),n=N(e,t),Kt.detach()),Zt[e]=n),n}function k(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function S(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=pn.length;i--;)if(t=pn[i]+n,t in e)return t;return r}function A(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=it._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[a]=it._data(r,"olddisplay",E(r.nodeName)))):(i=At(r),(n&&"none"!==n||!i)&&it._data(r,"olddisplay",i?n:it.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function D(e,t,n){var r=un.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function j(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=it.css(e,n+St[o],!0,i)),r?("content"===n&&(a-=it.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(a-=it.css(e,"border"+St[o]+"Width",!0,i))):(a+=it.css(e,"padding"+St[o],!0,i),"padding"!==n&&(a+=it.css(e,"border"+St[o]+"Width",!0,i)));return a}function L(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=en(e),a=nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=tn(e,t,o),(0>i||null==i)&&(i=e.style[t]),rn.test(i))return i;r=a&&(nt.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+j(e,t,n||(a?"border":"content"),r,o)+"px"}function H(e,t,n,r,i){return new H.prototype.init(e,t,n,r,i)}function _(){return setTimeout(function(){hn=void 0}),hn=it.now()}function q(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=St[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function M(e,t,n){for(var r,i=(xn[t]||[]).concat(xn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function O(e,t,n){var r,i,o,a,s,l,u,c,d=this,f={},p=e.style,h=e.nodeType&&At(e),m=it._data(e,"fxshow");n.queue||(s=it._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,it.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],u=it.css(e,"display"),c="none"===u?it._data(e,"olddisplay")||E(e.nodeName):u,"inline"===c&&"none"===it.css(e,"float")&&(nt.inlineBlockNeedsLayout&&"inline"!==E(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",nt.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],gn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||it.style(e,r)}else u=void 0;if(it.isEmptyObject(f))"inline"===("none"===u?E(e.nodeName):u)&&(p.display=u);else{m?"hidden"in m&&(h=m.hidden):m=it._data(e,"fxshow",{}),o&&(m.hidden=!h),h?it(e).show():d.done(function(){it(e).hide()}),d.done(function(){var t;it._removeData(e,"fxshow");for(t in f)it.style(e,t,f[t])});for(r in f)a=M(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function F(e,t){var n,r,i,o,a;for(n in e)if(r=it.camelCase(n),i=t[r],o=e[n],it.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=it.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function B(e,t,n){var r,i,o=0,a=bn.length,s=it.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=hn||_(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:it.extend({},t),opts:it.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:hn||_(),duration:n.duration,tweens:[],createTween:function(t,n){var r=it.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(F(c,u.opts.specialEasing);a>o;o++)if(r=bn[o].call(u,e,c,u.opts))return r;return it.map(c,M,u),it.isFunction(u.opts.start)&&u.opts.start.call(e,u),it.fx.timer(it.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function P(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(bt)||[];if(it.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function R(e,t,n,r){function i(s){var l;return o[s]=!0,it.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===In;return i(t.dataTypes[0])||!o["*"]&&i("*")}function W(e,t){var n,r,i=it.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&it.extend(!0,e,n),e}function $(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function z(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function I(e,t,n,r){var i;if(it.isArray(t))it.each(t,function(t,i){n||Jn.test(e)?r(e,i):I(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==it.type(t))r(e,t);else for(i in t)I(e+"["+i+"]",t[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function U(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function V(e){return it.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,G=J.concat,Q=J.push,K=J.indexOf,Z={},et=Z.toString,tt=Z.hasOwnProperty,nt={},rt="1.11.1",it=function(e,t){return new it.fn.init(e,t)},ot=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,st=/-([\da-z])/gi,lt=function(e,t){return t.toUpperCase()};it.fn=it.prototype={jquery:rt,constructor:it,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=it.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return it.each(this,e,t)},map:function(e){return this.pushStack(it.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},it.extend=it.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||it.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(it.isPlainObject(n)||(t=it.isArray(n)))?(t?(t=!1,o=e&&it.isArray(e)?e:[]):o=e&&it.isPlainObject(e)?e:{},a[r]=it.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},it.extend({expando:"jQuery"+(rt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===it.type(e)},isArray:Array.isArray||function(e){return"array"===it.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!it.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==it.type(e)||e.nodeType||it.isWindow(e))return!1;try{if(e.constructor&&!tt.call(e,"constructor")&&!tt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(nt.ownLast)for(t in e)return tt.call(e,t);for(t in e);return void 0===t||tt.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Z[et.call(e)]||"object":typeof e},globalEval:function(t){t&&it.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(at,"ms-").replace(st,lt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(ot,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?it.merge(r,"string"==typeof e?[e]:e):Q.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(K)return K.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),l=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&l.push(i);else for(o in e)i=t(e[o],o,r),null!=i&&l.push(i);return G.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),it.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||it.guid++,r):void 0},now:function(){return+new Date},support:nt}),it.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()});var ut=function(e){function t(e,t,n,r){var i,o,a,s,l,u,d,p,h,m;if((t?t.ownerDocument||t:R)!==H&&L(t),t=t||H,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(q&&!r){if(i=yt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!M||!M.test(e))){if(p=d=P,h=t,m=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(u=E(e),(d=t.getAttribute("id"))?p=d.replace(xt,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",l=u.length;l--;)u[l]=p+f(u[l]);h=bt.test(e)&&c(t.parentNode)||t,m=u.join(",")}if(m)try{return Z.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{d||t.removeAttribute("id")}}}return S(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||J)-(~e.sourceIndex||J);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&typeof e.getElementsByTagName!==V&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=$++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[P]||(t[P]={}),(s=l[r])&&s[0]===W&&s[1]===o)return u[2]=s[2];if(l[r]=u,u[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,l),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=g(b,p),i(u,[],s,l),c=u.length;c--;)(d=u[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);o(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=o?tt.call(r,d):f[c])>-1&&(r[u]=!(a[u]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,l):Z.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),u=p(function(e){return tt.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r))}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(lt,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&T.find.TAG("*",u),x=W+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a!==H&&a);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0;f=e[d++];)if(f(c,a,s)){l.push(c);break}u&&(W=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=Q.call(l));v=g(v)}Z.apply(l,v),u&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(l)}return u&&(W=x,A=y),m};return i?r(a):a}var x,w,T,C,N,E,k,S,A,D,j,L,H,_,q,M,O,F,B,P="sizzle"+-new Date,R=e.document,W=0,$=0,z=n(),I=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V="undefined",J=1<<31,Y={}.hasOwnProperty,G=[],Q=G.pop,K=G.push,Z=G.push,et=G.slice,tt=G.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},nt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="\\["+rt+"*("+it+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",st=":("+it+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+at+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),ct=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),dt=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),ft=new RegExp(st),pt=new RegExp("^"+ot+"$"),ht={ID:new RegExp("^#("+it+")"),CLASS:new RegExp("^\\.("+it+")"),TAG:new RegExp("^("+it.replace("w","w*")+")"),ATTR:new RegExp("^"+at),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+nt+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},mt=/^(?:input|select|textarea|button)$/i,gt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,yt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,bt=/[+~]/,xt=/'|\\/g,wt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),Tt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Z.apply(G=et.call(R.childNodes),R.childNodes),G[R.childNodes.length].nodeType}catch(Ct){Z={apply:G.length?function(e,t){K.apply(e,et.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},L=t.setDocument=function(e){var t,n=e?e.ownerDocument||e:R,r=n.defaultView;return n!==H&&9===n.nodeType&&n.documentElement?(H=n,_=n.documentElement,q=!N(n),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){L()},!1):r.attachEvent&&r.attachEvent("onunload",function(){L()})),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=vt.test(n.getElementsByClassName)&&i(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),w.getById=i(function(e){return _.appendChild(e).id=P,!n.getElementsByName||!n.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if(typeof t.getElementById!==V&&q){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){var n=typeof e.getAttributeNode!==V&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==V?t.getElementsByTagName(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},T.find.CLASS=w.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==V&&q?t.getElementsByClassName(e):void 0},O=[],M=[],(w.qsa=vt.test(n.querySelectorAll))&&(i(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&M.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+rt+"*(?:value|"+nt+")"),e.querySelectorAll(":checked").length||M.push(":checked")}),i(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(w.matchesSelector=vt.test(F=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&i(function(e){w.disconnectedMatch=F.call(e,"div"),F.call(e,"[s!='']:x"),O.push("!=",st)}),M=M.length&&new RegExp(M.join("|")),O=O.length&&new RegExp(O.join("|")),t=vt.test(_.compareDocumentPosition),B=t||vt.test(_.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!w.sortDetached&&t.compareDocumentPosition(e)===r?e===n||e.ownerDocument===R&&B(R,e)?-1:t===n||t.ownerDocument===R&&B(R,t)?1:D?tt.call(D,e)-tt.call(D,t):0:4&r?-1:1)}:function(e,t){if(e===t)return j=!0,0;var r,i=0,o=e.parentNode,s=t.parentNode,l=[e],u=[t];if(!o||!s)return e===n?-1:t===n?1:o?-1:s?1:D?tt.call(D,e)-tt.call(D,t):0;if(o===s)return a(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===R?-1:u[i]===R?1:0},n):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(dt,"='$1']"),!(!w.matchesSelector||!q||O&&O.test(n)||M&&M.test(n)))try{var r=F.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&Y.call(T.attrHandle,t.toLowerCase())?n(e,t,!q):void 0;return void 0!==r?r:w.attributes||!q?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,Tt),e[3]=(e[3]||e[4]||e[5]||"").replace(wt,Tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return ht.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ft.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(wt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=z[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&z(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==V&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(c=g[P]||(g[P]={}),u=c[e]||[],p=u[0]===W&&u[1],f=u[0]===W&&u[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){c[e]=[W,p,f];break}}else if(y&&(u=(t[P]||(t[P]={}))[e])&&u[0]===W)f=u[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[P]||(d[P]={}))[e]=[W,f]),d!==t)););return f-=i,f===r||f%r===0&&f/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=tt.call(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(lt,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return pt.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(wt,Tt).toLowerCase(),function(t){var n;do if(n=q?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return gt.test(e.nodeName)},input:function(e){return mt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=l(x);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=I[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=T.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in T.filter)!(i=ht[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));
if(!r)break}return n?s.length:s?t.error(e):I(e,l).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,d=!r&&E(e=u.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&q&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(wt,Tt),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=ht.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((l=T.find[s])&&(r=l(a.matches[0].replace(wt,Tt),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return Z.apply(n,r),n;break}}return(u||k(e,d))(r,t,!q,n,bt.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(nt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);it.find=ut,it.expr=ut.selectors,it.expr[":"]=it.expr.pseudos,it.unique=ut.uniqueSort,it.text=ut.getText,it.isXMLDoc=ut.isXML,it.contains=ut.contains;var ct=it.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;it.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?it.find.matchesSelector(r,e)?[r]:[]:it.find.matches(e,it.grep(t,function(e){return 1===e.nodeType}))},it.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(it(e).filter(function(){for(t=0;i>t;t++)if(it.contains(r[t],this))return!0}));for(t=0;i>t;t++)it.find(e,r[t],n);return n=this.pushStack(i>1?it.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&ct.test(e)?it(e):e||[],!1).length}});var pt,ht=e.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=it.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pt).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof it?t[0]:t,it.merge(this,it.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:ht,!0)),dt.test(n[1])&&it.isPlainObject(t))for(n in t)it.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=ht.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pt.find(e);this.length=1,this[0]=r}return this.context=ht,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):it.isFunction(e)?"undefined"!=typeof pt.ready?pt.ready(e):e(it):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),it.makeArray(e,this))};gt.prototype=it.fn,pt=it(ht);var vt=/^(?:parents|prev(?:Until|All))/,yt={children:!0,contents:!0,next:!0,prev:!0};it.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!it(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),it.fn.extend({has:function(e){var t,n=it(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(it.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ct.test(e)||"string"!=typeof e?it(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&it.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?it.unique(o):o)},index:function(e){return e?"string"==typeof e?it.inArray(this[0],it(e)):it.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(it.unique(it.merge(this.get(),it(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),it.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return it.dir(e,"parentNode")},parentsUntil:function(e,t,n){return it.dir(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return it.dir(e,"nextSibling")},prevAll:function(e){return it.dir(e,"previousSibling")},nextUntil:function(e,t,n){return it.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return it.dir(e,"previousSibling",n)},siblings:function(e){return it.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return it.sibling(e.firstChild)},contents:function(e){return it.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:it.merge([],e.childNodes)}},function(e,t){it.fn[e]=function(n,r){var i=it.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=it.filter(r,i)),this.length>1&&(yt[e]||(i=it.unique(i)),vt.test(e)&&(i=i.reverse())),this.pushStack(i)}});var bt=/\S+/g,xt={};it.Callbacks=function(e){e="string"==typeof e?xt[e]||o(e):it.extend({},e);var t,n,r,i,a,s,l=[],u=!e.once&&[],c=function(o){for(n=e.memory&&o,r=!0,a=s||0,s=0,i=l.length,t=!0;l&&i>a;a++)if(l[a].apply(o[0],o[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,l&&(u?u.length&&c(u.shift()):n?l=[]:d.disable())},d={add:function(){if(l){var r=l.length;!function o(t){it.each(t,function(t,n){var r=it.type(n);"function"===r?e.unique&&d.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=l.length:n&&(s=r,c(n))}return this},remove:function(){return l&&it.each(arguments,function(e,n){for(var r;(r=it.inArray(n,l,r))>-1;)l.splice(r,1),t&&(i>=r&&i--,a>=r&&a--)}),this},has:function(e){return e?it.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=u=n=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,n||d.disable(),this},locked:function(){return!u},fireWith:function(e,n){return!l||r&&!u||(n=n||[],n=[e,n.slice?n.slice():n],t?u.push(n):c(n)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},it.extend({Deferred:function(e){var t=[["resolve","done",it.Callbacks("once memory"),"resolved"],["reject","fail",it.Callbacks("once memory"),"rejected"],["notify","progress",it.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return it.Deferred(function(n){it.each(t,function(t,o){var a=it.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&it.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?it.extend(e,r):r}},i={};return r.pipe=r.then,it.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&it.isFunction(e.promise)?a:0,l=1===s?e:it.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&it.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var wt;it.fn.ready=function(e){return it.ready.promise().done(e),this},it.extend({isReady:!1,readyWait:1,holdReady:function(e){e?it.readyWait++:it.ready(!0)},ready:function(e){if(e===!0?!--it.readyWait:!it.isReady){if(!ht.body)return setTimeout(it.ready);it.isReady=!0,e!==!0&&--it.readyWait>0||(wt.resolveWith(ht,[it]),it.fn.triggerHandler&&(it(ht).triggerHandler("ready"),it(ht).off("ready")))}}}),it.ready.promise=function(t){if(!wt)if(wt=it.Deferred(),"complete"===ht.readyState)setTimeout(it.ready);else if(ht.addEventListener)ht.addEventListener("DOMContentLoaded",s,!1),e.addEventListener("load",s,!1);else{ht.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&ht.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!it.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a(),it.ready()}}()}return wt.promise(t)};var Tt,Ct="undefined";for(Tt in it(nt))break;nt.ownLast="0"!==Tt,nt.inlineBlockNeedsLayout=!1,it(function(){var e,t,n,r;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",nt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=ht.createElement("div");if(null==nt.deleteExpando){nt.deleteExpando=!0;try{delete e.test}catch(t){nt.deleteExpando=!1}}e=null}(),it.acceptData=function(e){var t=it.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Nt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Et=/([A-Z])/g;it.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?it.cache[e[it.expando]]:e[it.expando],!!e&&!u(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),it.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=it.data(o),1===o.nodeType&&!it._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=it.camelCase(r.slice(5)),l(o,r,i[r])));it._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){it.data(this,e)}):arguments.length>1?this.each(function(){it.data(this,e,t)}):o?l(o,e,it.data(o,e)):void 0},removeData:function(e){return this.each(function(){it.removeData(this,e)})}}),it.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=it._data(e,t),n&&(!r||it.isArray(n)?r=it._data(e,t,it.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=it.queue(e,t),r=n.length,i=n.shift(),o=it._queueHooks(e,t),a=function(){it.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return it._data(e,n)||it._data(e,n,{empty:it.Callbacks("once memory").add(function(){it._removeData(e,t+"queue"),it._removeData(e,n)})})}}),it.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?it.queue(this[0],e):void 0===t?this:this.each(function(){var n=it.queue(this,e,t);it._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&it.dequeue(this,e)})},dequeue:function(e){return this.each(function(){it.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=it.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=it._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var kt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,St=["Top","Right","Bottom","Left"],At=function(e,t){return e=t||e,"none"===it.css(e,"display")||!it.contains(e.ownerDocument,e)},Dt=it.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===it.type(n)){i=!0;for(s in n)it.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,it.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(it(e),n)})),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},jt=/^(?:checkbox|radio)$/i;!function(){var e=ht.createElement("input"),t=ht.createElement("div"),n=ht.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",nt.leadingWhitespace=3===t.firstChild.nodeType,nt.tbody=!t.getElementsByTagName("tbody").length,nt.htmlSerialize=!!t.getElementsByTagName("link").length,nt.html5Clone="<:nav></:nav>"!==ht.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),nt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",nt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",nt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,nt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){nt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==nt.deleteExpando){nt.deleteExpando=!0;try{delete t.test}catch(r){nt.deleteExpando=!1}}}(),function(){var t,n,r=ht.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(nt[t+"Bubbles"]=n in e)||(r.setAttribute(n,"t"),nt[t+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Lt=/^(?:input|select|textarea)$/i,Ht=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,qt=/^(?:focusinfocus|focusoutblur)$/,Mt=/^([^.]*)(?:\.(.+)|)$/;it.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it._data(e);if(g){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=it.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return typeof it===Ct||e&&it.event.triggered===e.type?void 0:it.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(bt)||[""],s=t.length;s--;)o=Mt.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(u=it.event.special[p]||{},p=(i?u.delegateType:u.bindType)||p,u=it.event.special[p]||{},d=it.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&it.expr.match.needsContext.test(i),namespace:h.join(".")},l),(f=a[p])||(f=a[p]=[],f.delegateCount=0,u.setup&&u.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),u.add&&(u.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),it.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it.hasData(e)&&it._data(e);if(g&&(c=g.events)){for(t=(t||"").match(bt)||[""],u=t.length;u--;)if(s=Mt.exec(t[u])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=it.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;o--;)a=f[o],!i&&m!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));l&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||it.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)it.event.remove(e,p+t[u],n,r,!0);it.isEmptyObject(c)&&(delete g.handle,it._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,l,u,c,d,f=[r||ht],p=tt.call(t,"type")?t.type:t,h=tt.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||ht,3!==r.nodeType&&8!==r.nodeType&&!qt.test(p+it.event.triggered)&&(p.indexOf(".")>=0&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[it.expando]?t:new it.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.namespace_re=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:it.makeArray(n,[t]),u=it.event.special[p]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!it.isWindow(r)){for(l=u.delegateType||p,qt.test(l+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||ht)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?l:u.bindType||p,o=(it._data(s,"events")||{})[t.type]&&it._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&it.acceptData(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(f.pop(),n)===!1)&&it.acceptData(r)&&a&&r[p]&&!it.isWindow(r)){c=r[a],c&&(r[a]=null),it.event.triggered=p;try{r[p]()}catch(m){}it.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=it.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),l=(it._data(this,"events")||{})[e.type]||[],u=it.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=it.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((it.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?it(n,this).index(l)>=0:it.find(n,this,null,[l]).length),i[n]&&i.push(r);i.length&&a.push({elem:l,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[it.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=_t.test(i)?this.mouseHooks:Ht.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new it.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||ht),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||ht,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==h()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return it.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return it.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=it.extend(new it.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?it.event.trigger(i,null,t):it.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},it.removeEvent=ht.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===Ct&&(e[r]=null),e.detachEvent(r,n))},it.Event=function(e,t){return this instanceof it.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:p):this.type=e,t&&it.extend(this,t),this.timeStamp=e&&e.timeStamp||it.now(),void(this[it.expando]=!0)):new it.Event(e,t)},it.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},it.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){it.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!it.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),nt.submitBubbles||(it.event.special.submit={setup:function(){return it.nodeName(this,"form")?!1:void it.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=it.nodeName(t,"input")||it.nodeName(t,"button")?t.form:void 0;n&&!it._data(n,"submitBubbles")&&(it.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),it._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&it.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return it.nodeName(this,"form")?!1:void it.event.remove(this,"._submit")}}),nt.changeBubbles||(it.event.special.change={setup:function(){return Lt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(it.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),it.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),it.event.simulate("change",this,e,!0)})),!1):void it.event.add(this,"beforeactivate._change",function(e){var t=e.target;Lt.test(t.nodeName)&&!it._data(t,"changeBubbles")&&(it.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||it.event.simulate("change",this.parentNode,e,!0)}),it._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return it.event.remove(this,"._change"),!Lt.test(this.nodeName)}}),nt.focusinBubbles||it.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){it.event.simulate(t,e.target,it.event.fix(e),!0)};it.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=it._data(r,t);i||r.addEventListener(e,n,!0),it._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=it._data(r,t)-1;i?it._data(r,t,i):(r.removeEventListener(e,n,!0),it._removeData(r,t))}}}),it.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return it().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=it.guid++)),this.each(function(){it.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,it(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){it.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){it.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?it.event.trigger(e,t,n,!0):void 0}});var Ot="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Ft=/ jQuery\d+="(?:null|\d+)"/g,Bt=new RegExp("<(?:"+Ot+")[\\s/>]","i"),Pt=/^\s+/,Rt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Wt=/<([\w:]+)/,$t=/<tbody/i,zt=/<|&#?\w+;/,It=/<(?:script|style|link)/i,Xt=/checked\s*(?:[^=]|=\s*.checked.)/i,Ut=/^$|\/(?:java|ecma)script/i,Vt=/^true\/(.*)/,Jt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Yt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:nt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Gt=m(ht),Qt=Gt.appendChild(ht.createElement("div"));Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td,it.extend({clone:function(e,t,n){var r,i,o,a,s,l=it.contains(e.ownerDocument,e);if(nt.html5Clone||it.isXMLDoc(e)||!Bt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qt.innerHTML=e.outerHTML,Qt.removeChild(o=Qt.firstChild)),!(nt.noCloneEvent&&nt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||it.isXMLDoc(e)))for(r=g(o),s=g(e),a=0;null!=(i=s[a]);++a)r[a]&&C(i,r[a]);if(t)if(n)for(s=s||g(e),r=r||g(o),a=0;null!=(i=s[a]);a++)T(i,r[a]);else T(e,o);return r=g(o,"script"),r.length>0&&w(r,!l&&g(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c,d=e.length,f=m(t),p=[],h=0;d>h;h++)if(o=e[h],o||0===o)if("object"===it.type(o))it.merge(p,o.nodeType?[o]:o);else if(zt.test(o)){for(s=s||f.appendChild(t.createElement("div")),l=(Wt.exec(o)||["",""])[1].toLowerCase(),c=Yt[l]||Yt._default,s.innerHTML=c[1]+o.replace(Rt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!nt.leadingWhitespace&&Pt.test(o)&&p.push(t.createTextNode(Pt.exec(o)[0])),!nt.tbody)for(o="table"!==l||$t.test(o)?"<table>"!==c[1]||$t.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)it.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(it.merge(p,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=f.lastChild}else p.push(t.createTextNode(o));for(s&&f.removeChild(s),nt.appendChecked||it.grep(g(p,"input"),v),h=0;o=p[h++];)if((!r||-1===it.inArray(o,r))&&(a=it.contains(o.ownerDocument,o),s=g(f.appendChild(o),"script"),a&&w(s),n))for(i=0;o=s[i++];)Ut.test(o.type||"")&&n.push(o);return s=null,f},cleanData:function(e,t){for(var n,r,i,o,a=0,s=it.expando,l=it.cache,u=nt.deleteExpando,c=it.event.special;null!=(n=e[a]);a++)if((t||it.acceptData(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?it.event.remove(n,r):it.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u?delete n[s]:typeof n.removeAttribute!==Ct?n.removeAttribute(s):n[s]=null,J.push(i))}}}),it.fn.extend({text:function(e){return Dt(this,function(e){return void 0===e?it.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ht).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?it.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||it.cleanData(g(n)),n.parentNode&&(t&&it.contains(n.ownerDocument,n)&&w(g(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&it.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&it.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return it.clone(this,e,t)})},html:function(e){return Dt(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Ft,""):void 0;if(!("string"!=typeof e||It.test(e)||!nt.htmlSerialize&&Bt.test(e)||!nt.leadingWhitespace&&Pt.test(e)||Yt[(Wt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Rt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(it.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,it.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=G.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,d=u-1,f=e[0],p=it.isFunction(f);if(p||u>1&&"string"==typeof f&&!nt.checkClone&&Xt.test(f))return this.each(function(n){var r=c.eq(n);p&&(e[0]=f.call(this,n,r.html())),r.domManip(e,t)});if(u&&(s=it.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=it.map(g(s,"script"),b),i=o.length;u>l;l++)r=s,l!==d&&(r=it.clone(r,!0,!0),i&&it.merge(o,g(r,"script"))),t.call(this[l],r,l);if(i)for(a=o[o.length-1].ownerDocument,it.map(o,x),l=0;i>l;l++)r=o[l],Ut.test(r.type||"")&&!it._data(r,"globalEval")&&it.contains(a,r)&&(r.src?it._evalUrl&&it._evalUrl(r.src):it.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Jt,"")));s=n=null}return this}}),it.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){it.fn[e]=function(e){for(var n,r=0,i=[],o=it(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),it(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Kt,Zt={};!function(){var e;nt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=ht.getElementsByTagName("body")[0],n&&n.style?(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ht.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var en,tn,nn=/^margin/,rn=new RegExp("^("+kt+")(?!px)[a-z%]+$","i"),on=/^(top|right|bottom|left)$/;e.getComputedStyle?(en=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||it.contains(e.ownerDocument,e)||(a=it.style(e,t)),rn.test(a)&&nn.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):ht.documentElement.currentStyle&&(en=function(e){return e.currentStyle
},tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),rn.test(a)&&!on.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function t(){var t,n,r,i;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),t.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,l=!0,e.getComputedStyle&&(o="1%"!==(e.getComputedStyle(t,null)||{}).top,a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width,i=t.appendChild(ht.createElement("div")),i.style.cssText=t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",t.style.width="1px",l=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)),t.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=t.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,l;n=ht.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",nt.opacity="0.5"===r.opacity,nt.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",nt.clearCloneStyle="content-box"===n.style.backgroundClip,nt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,it.extend(nt,{reliableHiddenOffsets:function(){return null==s&&t(),s},boxSizingReliable:function(){return null==a&&t(),a},pixelPosition:function(){return null==o&&t(),o},reliableMarginRight:function(){return null==l&&t(),l}}))}(),it.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var an=/alpha\([^)]*\)/i,sn=/opacity\s*=\s*([^)]*)/,ln=/^(none|table(?!-c[ea]).+)/,un=new RegExp("^("+kt+")(.*)$","i"),cn=new RegExp("^([+-])=("+kt+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},fn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];it.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=tn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":nt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=it.camelCase(t),l=e.style;if(t=it.cssProps[s]||(it.cssProps[s]=S(l,s)),a=it.cssHooks[t]||it.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=cn.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(it.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||it.cssNumber[s]||(n+="px"),nt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=it.camelCase(t);return t=it.cssProps[s]||(it.cssProps[s]=S(e.style,s)),a=it.cssHooks[t]||it.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=tn(e,t,r)),"normal"===o&&t in fn&&(o=fn[t]),""===n||n?(i=parseFloat(o),n===!0||it.isNumeric(i)?i||0:o):o}}),it.each(["height","width"],function(e,t){it.cssHooks[t]={get:function(e,n,r){return n?ln.test(it.css(e,"display"))&&0===e.offsetWidth?it.swap(e,dn,function(){return L(e,t,r)}):L(e,t,r):void 0},set:function(e,n,r){var i=r&&en(e);return D(e,n,r?j(e,t,r,nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,i),i):0)}}}),nt.opacity||(it.cssHooks.opacity={get:function(e,t){return sn.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=it.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===it.trim(o.replace(an,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=an.test(o)?o.replace(an,i):o+" "+i)}}),it.cssHooks.marginRight=k(nt.reliableMarginRight,function(e,t){return t?it.swap(e,{display:"inline-block"},tn,[e,"marginRight"]):void 0}),it.each({margin:"",padding:"",border:"Width"},function(e,t){it.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+St[r]+t]=o[r]||o[r-2]||o[0];return i}},nn.test(e)||(it.cssHooks[e+t].set=D)}),it.fn.extend({css:function(e,t){return Dt(this,function(e,t,n){var r,i,o={},a=0;if(it.isArray(t)){for(r=en(e),i=t.length;i>a;a++)o[t[a]]=it.css(e,t[a],!1,r);return o}return void 0!==n?it.style(e,t,n):it.css(e,t)},e,t,arguments.length>1)},show:function(){return A(this,!0)},hide:function(){return A(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){At(this)?it(this).show():it(this).hide()})}}),it.Tween=H,H.prototype={constructor:H,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(it.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.pos=t=this.options.duration?it.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=it.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){it.fx.step[e.prop]?it.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[it.cssProps[e.prop]]||it.cssHooks[e.prop])?it.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},it.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},it.fx=H.prototype.init,it.fx.step={};var hn,mn,gn=/^(?:toggle|show|hide)$/,vn=new RegExp("^(?:([+-])=|)("+kt+")([a-z%]*)$","i"),yn=/queueHooks$/,bn=[O],xn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=vn.exec(t),o=i&&i[3]||(it.cssNumber[e]?"":"px"),a=(it.cssNumber[e]||"px"!==o&&+r)&&vn.exec(it.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,it.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};it.Animation=it.extend(B,{tweener:function(e,t){it.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],xn[n]=xn[n]||[],xn[n].unshift(t)},prefilter:function(e,t){t?bn.unshift(e):bn.push(e)}}),it.speed=function(e,t,n){var r=e&&"object"==typeof e?it.extend({},e):{complete:n||!n&&t||it.isFunction(e)&&e,duration:e,easing:n&&t||t&&!it.isFunction(t)&&t};return r.duration=it.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in it.fx.speeds?it.fx.speeds[r.duration]:it.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){it.isFunction(r.old)&&r.old.call(this),r.queue&&it.dequeue(this,r.queue)},r},it.fn.extend({fadeTo:function(e,t,n,r){return this.filter(At).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=it.isEmptyObject(e),o=it.speed(t,n,r),a=function(){var t=B(this,it.extend({},e),o);(i||it._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=it.timers,a=it._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&yn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&it.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=it._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=it.timers,a=r?r.length:0;for(n.finish=!0,it.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),it.each(["toggle","show","hide"],function(e,t){var n=it.fn[t];it.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(q(t,!0),e,r,i)}}),it.each({slideDown:q("show"),slideUp:q("hide"),slideToggle:q("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){it.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),it.timers=[],it.fx.tick=function(){var e,t=it.timers,n=0;for(hn=it.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||it.fx.stop(),hn=void 0},it.fx.timer=function(e){it.timers.push(e),e()?it.fx.start():it.timers.pop()},it.fx.interval=13,it.fx.start=function(){mn||(mn=setInterval(it.fx.tick,it.fx.interval))},it.fx.stop=function(){clearInterval(mn),mn=null},it.fx.speeds={slow:600,fast:200,_default:400},it.fn.delay=function(e,t){return e=it.fx?it.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=ht.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=ht.createElement("select"),i=n.appendChild(ht.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",nt.getSetAttribute="t"!==t.className,nt.style=/top/.test(r.getAttribute("style")),nt.hrefNormalized="/a"===r.getAttribute("href"),nt.checkOn=!!e.value,nt.optSelected=i.selected,nt.enctype=!!ht.createElement("form").enctype,n.disabled=!0,nt.optDisabled=!i.disabled,e=ht.createElement("input"),e.setAttribute("value",""),nt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),nt.radioValue="t"===e.value}();var wn=/\r/g;it.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=it.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,it(this).val()):e,null==i?i="":"number"==typeof i?i+="":it.isArray(i)&&(i=it.map(i,function(e){return null==e?"":e+""})),t=it.valHooks[this.type]||it.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=it.valHooks[i.type]||it.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(wn,""):null==n?"":n)}}}),it.extend({valHooks:{option:{get:function(e){var t=it.find.attr(e,"value");return null!=t?t:it.trim(it.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(nt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&it.nodeName(n.parentNode,"optgroup"))){if(t=it(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=it.makeArray(t),a=i.length;a--;)if(r=i[a],it.inArray(it.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),it.each(["radio","checkbox"],function(){it.valHooks[this]={set:function(e,t){return it.isArray(t)?e.checked=it.inArray(it(e).val(),t)>=0:void 0}},nt.checkOn||(it.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Tn,Cn,Nn=it.expr.attrHandle,En=/^(?:checked|selected)$/i,kn=nt.getSetAttribute,Sn=nt.input;it.fn.extend({attr:function(e,t){return Dt(this,it.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){it.removeAttr(this,e)})}}),it.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Ct?it.prop(e,t,n):(1===o&&it.isXMLDoc(e)||(t=t.toLowerCase(),r=it.attrHooks[t]||(it.expr.match.bool.test(t)?Cn:Tn)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=it.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void it.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(bt);if(o&&1===e.nodeType)for(;n=o[i++];)r=it.propFix[n]||n,it.expr.match.bool.test(n)?Sn&&kn||!En.test(n)?e[r]=!1:e[it.camelCase("default-"+n)]=e[r]=!1:it.attr(e,n,""),e.removeAttribute(kn?n:r)},attrHooks:{type:{set:function(e,t){if(!nt.radioValue&&"radio"===t&&it.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Cn={set:function(e,t,n){return t===!1?it.removeAttr(e,n):Sn&&kn||!En.test(n)?e.setAttribute(!kn&&it.propFix[n]||n,n):e[it.camelCase("default-"+n)]=e[n]=!0,n}},it.each(it.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Nn[t]||it.find.attr;Nn[t]=Sn&&kn||!En.test(t)?function(e,t,r){var i,o;return r||(o=Nn[t],Nn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Nn[t]=o),i}:function(e,t,n){return n?void 0:e[it.camelCase("default-"+t)]?t.toLowerCase():null}}),Sn&&kn||(it.attrHooks.value={set:function(e,t,n){return it.nodeName(e,"input")?void(e.defaultValue=t):Tn&&Tn.set(e,t,n)}}),kn||(Tn={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Nn.id=Nn.name=Nn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},it.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Tn.set},it.attrHooks.contenteditable={set:function(e,t,n){Tn.set(e,""===t?!1:t,n)}},it.each(["width","height"],function(e,t){it.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),nt.style||(it.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var An=/^(?:input|select|textarea|button|object)$/i,Dn=/^(?:a|area)$/i;it.fn.extend({prop:function(e,t){return Dt(this,it.prop,e,t,arguments.length>1)},removeProp:function(e){return e=it.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),it.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!it.isXMLDoc(e),o&&(t=it.propFix[t]||t,i=it.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=it.find.attr(e,"tabindex");return t?parseInt(t,10):An.test(e.nodeName)||Dn.test(e.nodeName)&&e.href?0:-1}}}}),nt.hrefNormalized||it.each(["href","src"],function(e,t){it.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),nt.optSelected||(it.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),it.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){it.propFix[this.toLowerCase()]=this}),nt.enctype||(it.propFix.enctype="encoding");var jn=/[\t\r\n\f]/g;it.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u="string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=it.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?it.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(it.isFunction(e)?function(n){it(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=it(this),o=e.match(bt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Ct||"boolean"===n)&&(this.className&&it._data(this,"__className__",this.className),this.className=this.className||e===!1?"":it._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(jn," ").indexOf(t)>=0)return!0;return!1}}),it.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){it.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),it.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var Ln=it.now(),Hn=/\?/,_n=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;it.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=it.trim(t+"");return i&&!it.trim(i.replace(_n,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():it.error("Invalid JSON: "+t)},it.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new DOMParser,n=r.parseFromString(t,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||it.error("Invalid XML: "+t),n};var qn,Mn,On=/#.*$/,Fn=/([?&])_=[^&]*/,Bn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Pn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Rn=/^(?:GET|HEAD)$/,Wn=/^\/\//,$n=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,zn={},In={},Xn="*/".concat("*");try{Mn=location.href}catch(Un){Mn=ht.createElement("a"),Mn.href="",Mn=Mn.href}qn=$n.exec(Mn.toLowerCase())||[],it.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mn,type:"GET",isLocal:Pn.test(qn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":it.parseJSON,"text xml":it.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?W(W(e,it.ajaxSettings),t):W(it.ajaxSettings,e)},ajaxPrefilter:P(zn),ajaxTransport:P(In),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,T=t;2!==b&&(b=2,s&&clearTimeout(s),u=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=$(d,w,n)),y=z(d,y,w,i),i?(d.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(it.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(it.etag[o]=x)),204===e||"HEAD"===d.type?T="nocontent":304===e?T="notmodified":(T=y.state,c=y.data,v=y.error,i=!v)):(v=T,(e||!T)&&(T="error",0>e&&(e=0))),w.status=e,w.statusText=(t||T)+"",i?h.resolveWith(f,[c,T,w]):h.rejectWith(f,[w,T,v]),w.statusCode(g),g=void 0,l&&p.trigger(i?"ajaxSuccess":"ajaxError",[w,d,i?c:v]),m.fireWith(f,[w,T]),l&&(p.trigger("ajaxComplete",[w,d]),--it.active||it.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,d=it.ajaxSetup({},t),f=d.context||d,p=d.context&&(f.nodeType||f.jquery)?it(f):it.event,h=it.Deferred(),m=it.Callbacks("once memory"),g=d.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Bn.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return u&&u.abort(t),n(0,t),this}};if(h.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,d.url=((e||d.url||Mn)+"").replace(On,"").replace(Wn,qn[1]+"//"),d.type=t.method||t.type||d.method||d.type,d.dataTypes=it.trim(d.dataType||"*").toLowerCase().match(bt)||[""],null==d.crossDomain&&(r=$n.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]===qn[1]&&r[2]===qn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(qn[3]||("http:"===qn[1]?"80":"443")))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=it.param(d.data,d.traditional)),R(zn,d,t,w),2===b)return w;l=d.global,l&&0===it.active++&&it.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Rn.test(d.type),o=d.url,d.hasContent||(d.data&&(o=d.url+=(Hn.test(o)?"&":"?")+d.data,delete d.data),d.cache===!1&&(d.url=Fn.test(o)?o.replace(Fn,"$1_="+Ln++):o+(Hn.test(o)?"&":"?")+"_="+Ln++)),d.ifModified&&(it.lastModified[o]&&w.setRequestHeader("If-Modified-Since",it.lastModified[o]),it.etag[o]&&w.setRequestHeader("If-None-Match",it.etag[o])),(d.data&&d.hasContent&&d.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",d.contentType),w.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+Xn+"; q=0.01":""):d.accepts["*"]);for(i in d.headers)w.setRequestHeader(i,d.headers[i]);if(d.beforeSend&&(d.beforeSend.call(f,w,d)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](d[i]);if(u=R(In,d,t,w)){w.readyState=1,l&&p.trigger("ajaxSend",[w,d]),d.async&&d.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},d.timeout));try{b=1,u.send(v,n)}catch(T){if(!(2>b))throw T;n(-1,T)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return it.get(e,t,n,"json")},getScript:function(e,t){return it.get(e,void 0,t,"script")}}),it.each(["get","post"],function(e,t){it[t]=function(e,n,r,i){return it.isFunction(n)&&(i=i||r,r=n,n=void 0),it.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),it.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){it.fn[t]=function(e){return this.on(t,e)}}),it._evalUrl=function(e){return it.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},it.fn.extend({wrapAll:function(e){if(it.isFunction(e))return this.each(function(t){it(this).wrapAll(e.call(this,t))});if(this[0]){var t=it(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(it.isFunction(e)?function(t){it(this).wrapInner(e.call(this,t))}:function(){var t=it(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=it.isFunction(e);return this.each(function(n){it(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){it.nodeName(this,"body")||it(this).replaceWith(this.childNodes)}).end()}}),it.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!nt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||it.css(e,"display"))},it.expr.filters.visible=function(e){return!it.expr.filters.hidden(e)};var Vn=/%20/g,Jn=/\[\]$/,Yn=/\r?\n/g,Gn=/^(?:submit|button|image|reset|file)$/i,Qn=/^(?:input|select|textarea|keygen)/i;it.param=function(e,t){var n,r=[],i=function(e,t){t=it.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=it.ajaxSettings&&it.ajaxSettings.traditional),it.isArray(e)||e.jquery&&!it.isPlainObject(e))it.each(e,function(){i(this.name,this.value)});else for(n in e)I(n,e[n],t,i);return r.join("&").replace(Vn,"+")},it.fn.extend({serialize:function(){return it.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=it.prop(this,"elements");return e?it.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!it(this).is(":disabled")&&Qn.test(this.nodeName)&&!Gn.test(e)&&(this.checked||!jt.test(e))}).map(function(e,t){var n=it(this).val();return null==n?null:it.isArray(n)?it.map(n,function(e){return{name:t.name,value:e.replace(Yn,"\r\n")}}):{name:t.name,value:n.replace(Yn,"\r\n")}}).get()}}),it.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||U()}:X;var Kn=0,Zn={},er=it.ajaxSettings.xhr();e.ActiveXObject&&it(e).on("unload",function(){for(var e in Zn)Zn[e](void 0,!0)}),nt.cors=!!er&&"withCredentials"in er,er=nt.ajax=!!er,er&&it.ajaxTransport(function(e){if(!e.crossDomain||nt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Kn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,l,u;if(t&&(i||4===o.readyState))if(delete Zn[a],t=void 0,o.onreadystatechange=it.noop,i)4!==o.readyState&&o.abort();else{u={},s=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=u.text?200:404}u&&r(s,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Zn[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),it.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return it.globalEval(e),e}}}),it.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),it.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=ht.head||it("head")[0]||ht.documentElement;return{send:function(r,i){t=ht.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],nr=/(=)\?(?=&|$)|\?\?/;it.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||it.expando+"_"+Ln++;return this[e]=!0,e}}),it.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(nr.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&nr.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=it.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(nr,"$1"+i):t.jsonp!==!1&&(t.url+=(Hn.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||it.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,tr.push(i)),a&&it.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),it.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||ht;var r=dt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=it.buildFragment([e],t,i),i&&i.length&&it(i).remove(),it.merge([],r.childNodes))};var rr=it.fn.load;it.fn.load=function(e,t,n){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=it.trim(e.slice(s,e.length)),e=e.slice(0,s)),it.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&it.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?it("<div>").append(it.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},it.expr.filters.animated=function(e){return it.grep(it.timers,function(t){return e===t.elem}).length};var ir=e.document.documentElement;it.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=it.css(e,"position"),d=it(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=it.css(e,"top"),l=it.css(e,"left"),u=("absolute"===c||"fixed"===c)&&it.inArray("auto",[o,l])>-1,u?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),it.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},it.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){it.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,it.contains(t,i)?(typeof i.getBoundingClientRect!==Ct&&(r=i.getBoundingClientRect()),n=V(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===it.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),it.nodeName(e[0],"html")||(n=e.offset()),n.top+=it.css(e[0],"borderTopWidth",!0),n.left+=it.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-it.css(r,"marginTop",!0),left:t.left-n.left-it.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||ir;e&&!it.nodeName(e,"html")&&"static"===it.css(e,"position");)e=e.offsetParent;return e||ir})}}),it.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);it.fn[e]=function(r){return Dt(this,function(e,r,i){var o=V(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?it(o).scrollLeft():i,n?i:it(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),it.each(["top","left"],function(e,t){it.cssHooks[t]=k(nt.pixelPosition,function(e,n){return n?(n=tn(e,t),rn.test(n)?it(e).position()[t]+"px":n):void 0})}),it.each({Height:"height",Width:"width"},function(e,t){it.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){it.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Dt(this,function(t,n,r){var i;return it.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?it.css(t,n,a):it.style(t,n,r,a)
},t,o?r:void 0,o,null)}})}),it.fn.size=function(){return this.length},it.fn.andSelf=it.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return it});var or=e.jQuery,ar=e.$;return it.noConflict=function(t){return e.$===it&&(e.$=ar),t&&e.jQuery===it&&(e.jQuery=or),it},typeof t===Ct&&(e.jQuery=e.$=it),it});
},{}],2:[function(require,module,exports){
"use strict";module.exports=function(e){var r=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"teilen",en:"share"},name:"facebook",title:{de:"Bei Facebook teilen",en:"Share on Facebook"},shareUrl:"https://www.facebook.com/sharer/sharer.php?u="+r+e.getReferrerTrack()}};
},{}],3:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!0,shareText:"+1",name:"googleplus",title:{de:"Bei Google+ teilen",en:"Share on Google+"},shareUrl:"https://plus.google.com/share?url="+e.getURL()+e.getReferrerTrack()}};
},{}],4:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!1,shareText:"Info",name:"info",title:{de:"weitere Informationen",en:"more information"},shareUrl:e.getInfoUrl()}};
},{}],5:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!1,shareText:"mail",name:"mail",title:{de:"Per E-Mail versenden",en:"Send by email"},shareUrl:e.getURL()+"?view=mail"}};
},{}],6:[function(require,module,exports){
"use strict";var $=require("jquery");module.exports=function(e){return{popup:!0,shareText:"tweet",name:"twitter",title:{de:"Bei Twitter teilen",en:"Share on Twitter"},shareUrl:"https://twitter.com/intent/tweet?text="+e.getShareText()+"&url="+e.getURL()+e.getReferrerTrack()}};
},{"jquery":1}],7:[function(require,module,exports){
"use strict";module.exports=function(e){return{popup:!1,shareText:"WhatsApp",name:"whatsapp",title:{de:"Bei Whatsapp teilen",en:"Share on Whatsapp"},shareUrl:"whatsapp://send?text="+e.getShareText()+"%20"+e.getURL()+e.getReferrerTrack()}};
},{}],8:[function(require,module,exports){
(function (global){
"use strict";var $=require("jquery"),_Shariff=function(t,e){var r=this;this.element=t,this.options=$.extend({},this.defaults,e,$(t).data());var n=[require("./services/facebook"),require("./services/googleplus"),require("./services/twitter"),require("./services/whatsapp"),require("./services/mail"),require("./services/info")];this.services=$.map(this.options.services,function(t){var e;return n.forEach(function(n){return n=n(r),n.name===t?(e=n,null):void 0}),e}),this._addButtonList(),null!==this.options.backendUrl&&this.getShares().then($.proxy(this._updateCounts,this))};_Shariff.prototype={defaults:{theme:"color",backendUrl:null,infoUrl:"http://ct.de/-2467514",lang:"de",orientation:"horizontal",referrerTrack:null,services:["twitter","facebook","googleplus","info"],url:function(){var t=global.document.location.href,e=$("link[rel=canonical]").attr("href")||this.getMeta("og:url")||"";return e.length>0&&(e.indexOf("http")<0&&(e=global.document.location.protocol+"//"+global.document.location.host+e),t=e),t}},$socialshareElement:function(){return $(this.element)},getLocalized:function(t,e){return"object"==typeof t[e]?t[e][this.options.lang]:"string"==typeof t[e]?t[e]:void 0},getMeta:function(t){var e=$('meta[name="'+t+'"],[property="'+t+'"]').attr("content");return e||""},getInfoUrl:function(){return this.options.infoUrl},getURL:function(){var t=this.options.url;return"function"==typeof t?$.proxy(t,this)():t},getReferrerTrack:function(){return this.options.referrerTrack||""},getShares:function(){return $.getJSON(this.options.backendUrl+"?url="+encodeURIComponent(this.getURL()))},_updateCounts:function(t){var e=this;$.each(t,function(t,r){r>=1e3&&(r=Math.round(r/1e3)+"k"),$(e.element).find("."+t+" a").append('<span class="share_count">'+r)})},_addButtonList:function(){var t=this,e=this.$socialshareElement(),r="theme-"+this.options.theme,n="orientation-"+this.options.orientation,i=$("<ul>").addClass(r).addClass(n);this.services.forEach(function(e){var r=$('<li class="shariff-button">').addClass(e.name),n='<span class="share_text">'+t.getLocalized(e,"shareText"),o=$("<a>").attr("href",e.shareUrl).append(n);e.popup?o.attr("rel","popup"):o.attr("target","_blank"),o.attr("title",t.getLocalized(e,"title")),r.append(o),i.append(r)}),i.on("click",'[rel="popup"]',function(t){t.preventDefault();var e=$(this).attr("href"),r=$(this).attr("title"),n="600",i="460",o="width="+n+",height="+i;global.window.open(e,r,o)}),e.append(i)},abbreviateText:function(t,e){var r=decodeURIComponent(t);if(r.length<=e)return t;var n=r.substring(0,e-1).lastIndexOf(" ");return r=encodeURIComponent(r.substring(0,n))+"…"},getShareText:function(){var t=this.getMeta("DC.title"),e=this.getMeta("DC.creator");return t.length>0&&e.length>0?t+=" - "+e:t=$("title").text(),encodeURIComponent(this.abbreviateText(t,120))}},module.exports=_Shariff,$(".shariff").each(function(){this.shariff=new _Shariff(this)});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./services/facebook":2,"./services/googleplus":3,"./services/info":4,"./services/mail":5,"./services/twitter":6,"./services/whatsapp":7,"jquery":1}]},{},[8]);
|
packages/cf-component-table/src/TableHeadCell.js | mdno/mdno.github.io | import React from 'react';
import PropTypes from 'prop-types';
class TableHeadCell extends React.Component {
render() {
const { className, ...props } = this.props;
let _className = 'cf-table__cell cf-table__cell--head';
if (className && className.trim()) {
_className += ' ' + className.trim();
}
return (
<th className={_className} {...props}>
{this.props.children}
</th>
);
}
}
TableHeadCell.propTypes = {
className: PropTypes.string,
children: PropTypes.node
};
TableHeadCell.defaultProps = {
className: ''
};
export default TableHeadCell;
|
examples/js/remote/remote-store-alternative.js | prajapati-parth/react-bootstrap-table | import React from 'react';
import RemoteAlternative from './remote-alternative';
function getProducts() {
const products = [];
const startId = products.length;
for (let i = 0; i < 12; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: Math.floor((Math.random() * 2000) + 1)
});
}
return products;
}
export default class RemoteStoreAlternative extends React.Component {
constructor(props) {
super(props);
this.products = getProducts();
this.state = {
data: this.products
};
}
onCellEdit = (row, fieldName, value) => {
const { data } = this.state;
let rowIdx;
const targetRow = data.find((prod, i) => {
if (prod.id === row.id) {
rowIdx = i;
return true;
}
return false;
});
if (targetRow) {
targetRow[fieldName] = value;
data[rowIdx] = targetRow;
this.setState({ data });
}
}
onAddRow = (row) => {
this.products.push(row);
this.setState({
data: this.products
});
}
onDeleteRow = (row) => {
this.products = this.products.filter((product) => {
return product.id !== row[0];
});
this.setState({
data: this.products
});
}
render() {
return (
<RemoteAlternative
onCellEdit={ this.onCellEdit }
onAddRow={ this.onAddRow }
onDeleteRow={ this.onDeleteRow }
{ ...this.state } />
);
}
}
|
client/src/index.js | egdbear/simple-chat | import ReactDOM from 'react-dom';
import React from 'react';
import Router from './routing';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { Provider } from 'react-redux';
import store from './store';
injectTapEventPlugin();
ReactDOM.render(
<Provider store={store}>
<Router />
</Provider>,
document.getElementById('root')
);
|
node_modules/_antd@2.13.4@antd/es/carousel/index.js | ligangwolai/blog | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import debounce from 'lodash.debounce';
// matchMedia polyfill for
// https://github.com/WickyNilliams/enquire.js/issues/82
if (typeof window !== 'undefined') {
var matchMediaPolyfill = function matchMediaPolyfill(mediaQuery) {
return {
media: mediaQuery,
matches: false,
addListener: function addListener() {},
removeListener: function removeListener() {}
};
};
window.matchMedia = window.matchMedia || matchMediaPolyfill;
}
// Use require over import (will be lifted up)
// make sure matchMedia polyfill run before require('react-slick')
// Fix https://github.com/ant-design/ant-design/issues/6560
// Fix https://github.com/ant-design/ant-design/issues/3308
var SlickCarousel = require('react-slick')['default'];
var Carousel = function (_React$Component) {
_inherits(Carousel, _React$Component);
function Carousel() {
_classCallCheck(this, Carousel);
var _this = _possibleConstructorReturn(this, (Carousel.__proto__ || Object.getPrototypeOf(Carousel)).call(this));
_this.onWindowResized = function () {
// Fix https://github.com/ant-design/ant-design/issues/2550
var slick = _this.refs.slick;
var autoplay = _this.props.autoplay;
if (autoplay && slick && slick.innerSlider && slick.innerSlider.autoPlay) {
slick.innerSlider.autoPlay();
}
};
_this.onWindowResized = debounce(_this.onWindowResized, 500, {
leading: false
});
return _this;
}
_createClass(Carousel, [{
key: 'componentDidMount',
value: function componentDidMount() {
var autoplay = this.props.autoplay;
if (autoplay) {
window.addEventListener('resize', this.onWindowResized);
}
var slick = this.refs.slick;
// https://github.com/ant-design/ant-design/issues/7191
this.innerSlider = slick && slick.innerSlider;
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
var autoplay = this.props.autoplay;
if (autoplay) {
window.removeEventListener('resize', this.onWindowResized);
this.onWindowResized.cancel();
}
}
}, {
key: 'render',
value: function render() {
var props = _extends({}, this.props);
if (props.effect === 'fade') {
props.fade = true;
}
var className = props.prefixCls;
if (props.vertical) {
className = className + ' ' + className + '-vertical';
}
return React.createElement(
'div',
{ className: className },
React.createElement(SlickCarousel, _extends({ ref: 'slick' }, props))
);
}
}]);
return Carousel;
}(React.Component);
export default Carousel;
Carousel.defaultProps = {
dots: true,
arrows: false,
prefixCls: 'ant-carousel',
draggable: false
}; |
fields/types/location/LocationField.js | Tangcuyu/keystone | import _ from 'lodash';
import React from 'react';
import Field from '../Field';
import { Button, Checkbox, FormField, FormInput, FormNote, FormRow } from 'elemental';
/**
* TODO:
* - Remove dependency on underscore
* - Custom path support
*/
module.exports = Field.create({
displayName: 'LocationField',
getInitialState () {
return {
collapsedFields: {},
improve: false,
overwrite: false,
};
},
componentWillMount () {
var collapsedFields = {};
_.forEach(['number', 'name', 'street2', 'geo'], (i) => {
if (!this.props.value[i]) {
collapsedFields[i] = true;
}
}, this);
this.setState({
collapsedFields: collapsedFields,
});
},
componentDidUpdate (prevProps, prevState) {
if (prevState.fieldsCollapsed && !this.state.fieldsCollapsed) {
this.refs.number.getDOMNode().focus();
}
},
shouldCollapse () {
return this.props.collapse && !this.formatValue();
},
uncollapseFields () {
this.setState({
collapsedFields: {},
});
},
fieldChanged (path, event) {
var value = this.props.value;
value[path] = event.target.value;
this.props.onChange({
path: this.props.path,
value: value,
});
},
geoChanged (i, event) {
var value = this.props.value;
if (!value.geo) {
value.geo = ['', ''];
}
value.geo[i] = event.target.value;
this.props.onChange({
path: this.props.path,
value: value,
});
},
formatValue () {
return _.compact([
this.props.value.number,
this.props.value.name,
this.props.value.street1,
this.props.value.street2,
this.props.value.suburb,
this.props.value.state,
this.props.value.postcode,
this.props.value.country,
]).join(', ');
},
renderValue () {
return <FormInput noedit>{this.formatValue() || '(no value)'}</FormInput>;
},
renderField (path, label, collapse) { // eslint-disable-line no-unused-vars
if (this.state.collapsedFields[path]) {
return null;
}
return (
<FormField label={label} className="form-field--secondary" htmlFor={this.props.path + '.' + path}>
<FormInput name={this.props.path + '.' + path} ref={path} value={this.props.value[path]} onChange={this.fieldChanged.bind(this, path)} placeholder={label} />
</FormField>
);
},
renderSuburbState () {
return (
<FormField label="Suburb / State" className="form-field--secondary" htmlFor={this.props.path + '.suburb'}>
<FormRow>
<FormField width="two-thirds" className="form-field--secondary">
<FormInput name={this.props.path + '.suburb'} ref="suburb" value={this.props.value.suburb} onChange={this.fieldChanged.bind(this, 'suburb')} placeholder="Suburb" />
</FormField>
<FormField width="one-third" className="form-field--secondary">
<FormInput name={this.props.path + '.state'} ref="state" value={this.props.value.state} onChange={this.fieldChanged.bind(this, 'state')} placeholder="State" />
</FormField>
</FormRow>
</FormField>
);
},
renderPostcodeCountry () {
return (
<FormField label="Postcode / Country" className="form-field--secondary" htmlFor={this.props.path + '.postcode'}>
<FormRow>
<FormField width="one-third" className="form-field--secondary">
<FormInput name={this.props.path + '.postcode'} ref="postcode" value={this.props.value.postcode} onChange={this.fieldChanged.bind(this, 'postcode')} placeholder="Post Code" />
</FormField>
<FormField width="two-thirds" className="form-field--secondary">
<FormInput name={this.props.path + '.country'} ref="country" value={this.props.value.country} onChange={this.fieldChanged.bind(this, 'country')} placeholder="Country" />
</FormField>
</FormRow>
</FormField>
);
},
renderGeo () {
if (this.state.collapsedFields.geo) {
return null;
}
return (
<FormField label="Lat / Lng" className="form-field--secondary" htmlFor={this.props.paths.geo}>
<FormRow>
<FormField width="one-half" className="form-field--secondary">
<FormInput name={this.props.paths.geo} ref="geo1" value={this.props.value.geo ? this.props.value.geo[1] : ''} onChange={this.geoChanged.bind(this, 1)} placeholder="Latitude" />
</FormField>
<FormField width="one-half" className="form-field--secondary">
<FormInput name={this.props.paths.geo} ref="geo0" value={this.props.value.geo ? this.props.value.geo[0] : ''} onChange={this.geoChanged.bind(this, 0)} placeholder="Longitude" />
</FormField>
</FormRow>
</FormField>
);
},
updateGoogleOption (key, e) {
var newState = {};
newState[key] = e.target.checked;
this.setState(newState);
},
renderGoogleOptions () {
if (!this.props.enableMapsAPI) return null;
var replace = this.state.improve ? (
<Checkbox
label="Replace existing data"
name={this.props.paths.overwrite}
onChange={this.updateGoogleOption.bind(this, 'overwrite')}
checked={this.state.overwrite} />
) : null;
return (
<FormField offsetAbsentLabel>
<Checkbox
label="Autodetect and improve location on save"
name={this.props.paths.improve}
onChange={this.updateGoogleOption.bind(this, 'improve')}
checked={this.state.improve}
title="When checked, this will attempt to fill missing fields. It will also get the lat/long" />
{replace}
</FormField>
);
},
renderNote () {
if (!this.props.note) return null;
return (
<FormField offsetAbsentLabel>
<FormNote note={this.props.note} />
</FormField>
);
},
renderUI () {
if (!this.shouldRenderField()) {
return (
<FormField label={this.props.label}>{this.renderValue()}</FormField>
);
}
/* eslint-disable no-script-url */
var showMore = !_.isEmpty(this.state.collapsedFields)
? <Button type="link" className="collapsed-field-label" onClick={this.uncollapseFields}>(show more fields)</Button>
: null;
/* eslint-enable */
return (
<div>
<FormField label={this.props.label}>
{showMore}
</FormField>
{this.renderField('number', 'PO Box / Shop', true)}
{this.renderField('name', 'Building Name', true)}
{this.renderField('street1', 'Street Address')}
{this.renderField('street2', 'Street Address 2', true)}
{this.renderSuburbState()}
{this.renderPostcodeCountry()}
{this.renderGeo()}
{this.renderGoogleOptions()}
{this.renderNote()}
</div>
);
},
});
|
ajax/libs/forerunnerdb/1.3.749/fdb-all.min.js | dada0423/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/Grid"),a("../lib/NodeApiClient"),a("../lib/BinaryLog");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":11,"../lib/Grid":13,"../lib/Highchart":14,"../lib/NodeApiClient":30,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":42,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":9,"../lib/Shim.IE8":41}],3:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":34,"./Shared":40}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared"),j=function(){this.init.apply(this,arguments)},j.prototype.init=function(a){var b=this;b._logCounter=0,b._parent=a,b.size(1e3)},d.addModule("BinaryLog",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Events"),f=d.modules.Collection,h=d.modules.Db,e=d.modules.ReactorIO,g=f.prototype.init,i=h.prototype.init,d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"size"),j.prototype.attachIO=function(){var a=this;a._io||(a._log=new f(a._parent.name()+"-BinaryLog",{capped:!0,size:a.size()}),a._log.objectId=function(b){return b||(b=++a._logCounter),b},a._io=new e(a._parent,a,function(b){return a._log.insert({type:b.type,data:b.data}),!1}))},j.prototype.detachIO=function(){var a=this;a._io&&(a._log.drop(),a._io.drop(),delete a._log,delete a._io)},f.prototype.init=function(){g.apply(this,arguments),this._binaryLog=new j(this)},d.finishModule("BinaryLog"),b.exports=j},{"./Shared":40}],5:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":34,"./Shared":40}],6:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],7:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);
q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":15,"./IndexBinaryTree":16,"./IndexHashMap":17,"./KeyValueStore":18,"./Metrics":19,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],8:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":7,"./Shared":40}],9:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":10,"./Metrics.js":19,"./Overload":32,"./Shared":40}],10:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":19,"./Overload":32,"./Shared":40}],11:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":7,"./Shared":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],13:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")
},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":38,"./Shared":40,"./View":42}],14:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":32,"./Shared":40}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":5,"./GeoHash":12,"./Path":34,"./Shared":40}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":5,"./Path":34,"./Shared":40}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":34,"./Shared":40}],18:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":40}],19:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":31,"./Shared":40}],20:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":32,"./Serialiser":39}],23:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":32}],25:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;
return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],27:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b["export"],e=b["import"],d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g["export"],c=g["import"],b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":32}],29:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i=a("./Shared");g=function(){this.init.apply(this,arguments)},g.prototype.init=function(a){var b=this;b._core=a,b.rootPath("/fdb")},i.addModule("NodeApiClient",g),i.mixin(g.prototype,"Mixin.Common"),i.mixin(g.prototype,"Mixin.Events"),i.mixin(g.prototype,"Mixin.ChainReactor"),d=i.modules.Core,e=d.prototype.init,f=i.modules.Collection,h=i.overload,i.synthesize(g.prototype,"rootPath"),g.prototype.server=function(a,b){return void 0!==a?("/"===a.substr(a.length-1,1)&&(a=a.substr(0,a.length-1)),void 0!==b?this._server=a+":"+b:this._server=a,this._host=a,this._port=b,this):void 0!==b?{host:this._host,port:this._port,url:this._server}:this._server},g.prototype.http=function(a,b,c,d,e){var f,g,h,i=this,j=new XMLHttpRequest;switch(a=a.toUpperCase(),j.onreadystatechange=function(){4===j.readyState&&(200===j.status?j.responseText?e(!1,i.jParse(j.responseText)):e(!1,{}):204===j.status?e(!1,{}):(e(j.status,j.responseText),i.emit("httpError",j.status,j.responseText)))},a){case"GET":case"DELETE":case"HEAD":this._sessionData&&(c=void 0!==c?c:{},c[this._sessionData.key]=this._sessionData.obj),f=b+(void 0!==c?"?"+i.jStringify(c):""),h=null;break;case"POST":case"PUT":case"PATCH":this._sessionData&&(g={},g[this._sessionData.key]=this._sessionData.obj),f=b+(void 0!==g?"?"+i.jStringify(g):""),h=void 0!==c?i.jStringify(c):null;break;default:return!1}return j.open(a,f,!0),j.setRequestHeader("Content-Type","application/json;charset=UTF-8"),j.send(h),this},g.prototype.head=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("HEAD",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.get=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("GET",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.put=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("PUT",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.post=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("POST",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.patch=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("PATCH",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.postPatch=function(a,b,c,d,e){var f=this;this.head(a+"/"+b,void 0,{},function(g,h){return g?404===g?f.http("POST",f.server()+f._rootPath+a,c,d,e):void e(g,c):f.http("PATCH",f.server()+f._rootPath+a+"/"+b,c,d,e)})},g.prototype["delete"]=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("DELETE",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.session=function(a,b){return void 0!==a&&void 0!==b?(this._sessionData={key:a,obj:b},this):this._sessionData},g.prototype.sync=function(a,b,c,d,e){var f,g,h,j=this,k="",l=!0;this.debug()&&console.log(this.logIdentifier()+" Connecting to API server "+this.server()+this._rootPath+b),g=this.server()+this._rootPath+b+"/_sync",this._sessionData&&(h=h||{},this._sessionData.key?h[this._sessionData.key]=this._sessionData.obj:i.mixin(h,this._sessionData.obj)),c&&(h=h||{},h.$query=c),d&&(h=h||{},void 0===d.$initialData&&(d.$initialData=!0),h.$options=d),h&&(k=this.jStringify(h),g+="?"+k),f=new EventSource(g),a.__apiConnection=f,f.addEventListener("open",function(c){(!d||d&&d.$initialData)&&j.get(b,h,function(b,c){b||a.upsert(c)})},!1),f.addEventListener("error",function(b){2===f.readyState&&a.unSync(),l&&(l=!1,e(b))},!1),f.addEventListener("insert",function(b){var c=j.jParse(b.data);a.insert(c.dataSet)},!1),f.addEventListener("update",function(b){var c=j.jParse(b.data);a.update(c.query,c.update)},!1),f.addEventListener("remove",function(b){var c=j.jParse(b.data);a.remove(c.query)},!1),e&&f.addEventListener("connected",function(a){l&&(l=!1,e(!1))},!1)},f.prototype.sync=new h({"function":function(a){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),null,null,a)},"string, function":function(a,b){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,null,null,b)},"object, function":function(a,b){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),a,null,b)},"string, string, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,null,null,c)},"string, object, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,b,null,c)},"string, string, object, function":function(a,b,c,d){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,c,null,d)},"object, object, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),a,b,c)},"string, object, object, function":function(a,b,c,d){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,b,c,d)},"string, string, object, object, function":function(a,b,c,d,e){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,c,d,e)},$main:function(a,b,c,d){var e=this;if(!this._db||!this._db._core)throw this.logIdentifier()+" Cannot sync for an anonymous collection! (Collection must be attached to a database)";this.unSync(),this._db._core.api.sync(this,a,b,c,d),this.on("drop",function(){e.unSync()})}}),f.prototype.unSync=function(){return this.__apiConnection?(2!==this.__apiConnection.readyState&&this.__apiConnection.close(),delete this.__apiConnection,!0):!1},f.prototype.http=new h({"string, function":function(a,b){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+this.name(),void 0,void 0,{},b)},$main:function(a,b,c,d,e,f){if(this._db&&this._db._core)return this._db._core.api.http("GET",this._db._core.api.server()+this._rootPath+b,{$query:c,$options:d},e,f);throw this.logIdentifier()+" Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)"}}),f.prototype.autoHttp=new h({"string, function":function(a,b){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+this.name(),void 0,void 0,{},b)},"string, string, function":function(a,b,c){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+b,void 0,void 0,{},c)},"string, string, string, function":function(a,b,c,d){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,void 0,void 0,{},d)},"string, string, string, object, function":function(a,b,c,d,e){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,d,void 0,{},e)},"string, string, string, object, object, function":function(a,b,c,d,e,f){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,d,e,{},f)},$main:function(a,b,c,d,e,f){var g=this;if(this._db&&this._db._core)return this._db._core.api.http("GET",this._db._core.api.server()+this._db._core.api._rootPath+b,{$query:c,$options:d},e,function(b,c){var d;if(!b&&c)switch(a){case"GET":g.insert(c);break;case"POST":c.inserted&&c.inserted.length&&g.insert(c.inserted);break;case"PUT":case"PATCH":if(c instanceof Array)for(d=0;d<c.length;d++)g.updateById(c[d]._id,{$overwrite:c[d]});else g.updateById(c._id,{$overwrite:c});break;case"DELETE":g.remove(c)}f(b,c)});throw this.logIdentifier()+" Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)"}}),d.prototype.init=function(){e.apply(this,arguments),this.api=new g(this)},i.finishModule("NodeApiClient"),b.exports=g},{"./Shared":40}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":34,"./Shared":40}],32:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],33:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":7,"./Document":11,"./Shared":40}],34:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":40}],35:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){b?c(b):o.setItem(a,d).then(function(a){
c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,async:43,localforage:78}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":40,pako:79}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":40,"crypto-js":52}],38:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":40}],39:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],40:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.749",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":20,"./Mixin.ChainReactor":21,"./Mixin.Common":22,"./Mixin.Constants":23,"./Mixin.Events":24,"./Mixin.Matching":25,"./Mixin.Sorting":26,"./Mixin.Tags":27,"./Mixin.Triggers":28,"./Mixin.Updating":29,"./Overload":32}],41:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],42:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return"setData"!==g&&"insert"!==g&&"update"!==g&&"remove"!==g?!1:(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,c||d||e?(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),f.dataArr.length||f.removeArr.length?(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0):!0):!1)},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(){this._from.update.apply(this._from,arguments)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh(),void 0!==e&&this.emit("queryChange",e)},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this._querySettings.query},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor,this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.emit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":32,"./ReactorIO":38,"./Shared":40}],43:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){for(;!j.paused&&g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null);
},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){s.unshift(a)}function f(a){var b=p(s,a);b>=0&&s.splice(b,1)}function g(){j--,k(s.slice(0),function(a){a()})}"function"==typeof arguments[1]&&(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=!1,s=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(t,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](s,l))}if(!q){for(var j,k=N(a[d])?a[d]:[a[d]],s=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,q=!0,c(a,e)}else l[d]=b,K.setImmediate(g)}),t=k.slice(0,k.length-1),u=t.length;u--;){if(!(j=a[t[u]]))throw new Error("Has nonexistent dependency in "+t.join(", "));if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](s,l)):e(i)}})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c.apply(null,[null].concat(f))});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={},f=Object.prototype.hasOwnProperty;b=b||e;var g=r(function(e){var g=e.pop(),h=b.apply(null,e);f.call(c,h)?K.setImmediate(function(){g.apply(null,c[h])}):f.call(d,h)?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([r(function(a){c[h]=a;var b=d[h];delete d[h];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return g.memo=c,g.unmemoized=a,g},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:95}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":46}],46:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],47:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2,l=j|k;g[h>>>2]|=l<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":46}],48:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":46}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":46,"./hmac":51,"./sha1":70}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":45,"./core":46}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":46}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51,"./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":46}],54:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":46}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":45,"./core":46}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":45,"./core":46}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":45,"./core":46}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":45,"./core":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":45,"./core":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":45,"./core":46}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":45,"./core":46}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":45,"./core":46}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":45,"./core":46}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){
var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":45,"./core":46}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":46,"./hmac":51,"./sha1":70}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":46}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":46}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":46,"./sha256":72}],72:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":46}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":46,"./x64-core":77}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":46,"./x64-core":77}],76:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS);
}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":46}],78:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0;var e=function(a){function b(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b={};return b[h.INDEXEDDB]=!!function(){try{var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB;return"undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent)?!1:b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),b[h.WEBSQL]=!!function(){try{return a.openDatabase}catch(b){return!1}}(),b[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),b}(a),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function a(b){d(this,a),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return a.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},a.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},a.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},a.prototype.supports=function(a){return!!l[a]},a.prototype._extend=function(a){e(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<j.length;a++)b(this,j[a])},a.prototype.createInstance=function(b){return new a(b)},a}();return new n}("undefined"!=typeof window?window:self);b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c=function(a){function b(b,c){b=b||[],c=c||{};try{return new Blob(b,c)}catch(d){if("TypeError"!==d.name)throw d;for(var e=a.BlobBuilder||a.MSBlobBuilder||a.MozBlobBuilder||a.WebKitBlobBuilder,f=new e,g=0;g<b.length;g+=1)f.append(b[g]);return f.getBlob(c.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(a){return new Promise(function(c,e){var f=b([""],{type:"image/png"}),g=a.transaction([D],"readwrite");g.objectStore(D).put(f,"key"),g.oncomplete=function(){var b=a.transaction([D],"readwrite"),f=b.objectStore(D).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}},g.onerror=g.onabort=e})["catch"](function(){return!1})}function f(a){return"boolean"==typeof B?Promise.resolve(B):e(a).then(function(a){return B=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(a){var d=c(atob(a.data));return b([d],{type:a.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){var b=this,c=b._initReady().then(function(){var a=C[b._dbInfo.name];return a&&a.dbReady?a.dbReady:void 0});return c.then(a,a),c}function k(a){var b=C[a.name],c={};c.promise=new Promise(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function l(a){var b=C[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function m(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];C||(C={});var f=C[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},C[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=j);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady()["catch"](b))}var k=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,n(d)}).then(function(a){return d.db=a,q(d,c._defaultConfig.version)?o(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<k.length;b++){var e=k[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function n(a){return p(a,!1)}function o(a){return p(a,!0)}function p(b,c){return new Promise(function(d,e){if(b.db){if(!c)return d(b.db);k(b),b.db.close()}var f=[b.name];c&&f.push(b.version);var g=A.open.apply(A,f);c&&(g.onupgradeneeded=function(c){var d=g.result;try{d.createObjectStore(b.storeName),c.oldVersion<=1&&d.createObjectStore(D)}catch(e){if("ConstraintError"!==e.name)throw e;a.console.warn('The database "'+b.name+'" has been upgraded from version '+c.oldVersion+" to version "+c.newVersion+', but the storage "'+b.storeName+'" already exists.')}}),g.onerror=function(){e(g.error)},g.onsuccess=function(){d(g.result),l(b)}})}function q(b,c){if(!b.db)return!0;var d=!b.db.objectStoreNames.contains(b.storeName),e=b.version<b.db.version,f=b.version>b.db.version;if(e&&(b.version!==c&&a.console.warn('The database "'+b.name+"\" can't be downgraded from version "+b.db.version+" to version "+b.version+"."),b.version=b.db.version),f||d){if(d){var g=b.db.version+1;g>b.version&&(b.version=g)}return!0}return!1}function r(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(b);g.onsuccess=function(){var b=g.result;void 0===b&&(b=null),i(b)&&(b=h(b)),a(b)},g.onerror=function(){c(g.error)}})["catch"](c)});return z(e,c),e}function s(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return z(d,b),d}function t(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var h=new Promise(function(a,d){var h;e.ready().then(function(){return h=e._dbInfo,c instanceof Blob?f(h.db).then(function(a){return a?c:g(c)}):c}).then(function(c){var e=h.db.transaction(h.storeName,"readwrite"),f=e.objectStore(h.storeName);null===c&&(c=void 0),e.oncomplete=function(){void 0===c&&(c=null),a(c)},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;d(a)};var g=f.put(c,b)})["catch"](d)});return z(h,d),h}function u(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](b);f.oncomplete=function(){a()},f.onerror=function(){c(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;c(a)}})["catch"](c)});return z(e,c),e}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return z(c,a),c}function w(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return z(c,a),c}function x(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return z(d,b),d}function y(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return z(c,a),c}function z(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var A=A||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB;if(A){var B,C,D="local-forage-detect-blob-support",E={_driver:"asyncStorage",_initStorage:m,iterate:s,getItem:r,setItem:t,removeItem:u,clear:v,length:w,key:x,keys:y};return E}}("undefined"!=typeof window?window:self);b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=function(a){function b(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=m.length-1;c>=0;c--){var d=m.key(c);0===d.indexOf(a)&&m.removeItem(d)}});return l(c,a),c}function e(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=d.ready().then(function(){var a=d._dbInfo,c=m.getItem(a.keyPrefix+b);return c&&(c=a.serializer.deserialize(c)),c});return l(e,c),e}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=m.length,g=1,h=0;f>h;h++){var i=m.key(h);if(0===i.indexOf(d)){var j=m.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=m.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=m.length,d=[],e=0;c>e;e++)0===m.key(e).indexOf(a.keyPrefix)&&d.push(m.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=d.ready().then(function(){var a=d._dbInfo;m.removeItem(a.keyPrefix+b)});return l(e,c),e}function k(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var f=e.ready().then(function(){void 0===c&&(c=null);var a=c;return new Promise(function(d,f){var g=e._dbInfo;g.serializer.serialize(c,function(c,e){if(e)f(e);else try{m.setItem(g.keyPrefix+b,c),d(a)}catch(h){"QuotaExceededError"!==h.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==h.name||f(h),f(h)}})})});return l(f,d),f}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=null;try{if(!(a.localStorage&&"setItem"in a.localStorage))return;m=a.localStorage}catch(n){return}var o={_driver:"localStorageWrapper",_initStorage:b,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};return o}("undefined"!=typeof window?window:self);b["default"]=d,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c=function(a){function b(b,c){b=b||[],c=c||{};try{return new Blob(b,c)}catch(d){if("TypeError"!==d.name)throw d;for(var e=a.BlobBuilder||a.MSBlobBuilder||a.MozBlobBuilder||a.WebKitBlobBuilder,f=new e,g=0;g<b.length;g+=1)f.append(b[g]);return f.getBlob(c.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(a){if(a.substring(0,k)!==j)return JSON.parse(a);var c,d=a.substring(w),f=a.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return b([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};return x}("undefined"!=typeof window?window:self);b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=function(a){function b(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(a,c){try{d.db=m(d.name,String(d.version),d.description,d.size)}catch(e){return c(e)}d.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,a()},function(a,b){c(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo;e.db.transaction(function(d){d.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[b],function(b,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),a(d)},function(a,b){c(b)})})})["catch"](c)});return l(e,c),e}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var f=new Promise(function(a,d){e.ready().then(function(){void 0===c&&(c=null);var f=c,g=e._dbInfo;g.serializer.serialize(c,function(c,e){e?d(e):g.db.transaction(function(e){e.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[b,c],function(){a(f)},function(a,b){d(b)})},function(a){a.code===a.QUOTA_ERR&&d(a)})})})["catch"](d)});return l(f,d),f}function g(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo;e.db.transaction(function(d){d.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[b],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(e,c),e}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=a.openDatabase;if(m){var n={_driver:"webSQLStorage",_initStorage:b,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};return n}}("undefined"!=typeof window?window:self);b["default"]=d,a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:95}],79:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":80,"./lib/inflate":81,"./lib/utils/common":82,"./lib/zlib/constants":85}],80:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);b.header&&h.deflateSetHeader(this.strm,b.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d===r?(this.onEnd(p),e.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":82,"./utils/strings":83,"./zlib/deflate":87,"./zlib/messages":92,"./zlib/zstream":94}],81:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l=this.strm,m=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?l.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new h.Buf8(m),l.next_out=0,l.avail_out=m),c=g.inflate(l,j.Z_NO_FLUSH),c===j.Z_BUF_ERROR&&o===!0&&(c=j.Z_OK,o=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&c!==j.Z_STREAM_END&&(0!==l.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(l.output,l.next_out),f=l.next_out-e,k=i.buf2string(l.output,e),l.next_out=f,l.avail_out=m-f,f&&h.arraySet(l.output,l.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),
this.onEnd(c),this.ended=!0,c===j.Z_OK):d===j.Z_SYNC_FLUSH?(this.onEnd(j.Z_OK),l.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":82,"./utils/strings":83,"./zlib/constants":85,"./zlib/gzheader":88,"./zlib/inflate":90,"./zlib/messages":92,"./zlib/zstream":94}],82:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],83:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":82}],84:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],85:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],86:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],87:[function(a,b,c){"use strict";function d(a,b){return a.msg=H[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(D.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){E._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,D.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=F(a.adler,b,e,c):2===a.state.wrap&&(a.adler=G(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ka?a.strstart-(a.w_size-ka):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ja,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ja-(m-f),f=m-ja,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ka)){D.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ia)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ia-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ia)););}while(a.lookahead<ka&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===I)return ta;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ta;if(a.strstart-a.block_start>=a.w_size-ka&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ta:ta}function o(a,b){for(var c,d;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c)),a.match_length>=ia)if(d=E._tr_tally(a,a.strstart-a.match_start,a.match_length-ia),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ia){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function p(a,b){for(var c,d,e;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ia-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===T||a.match_length===ia&&a.strstart-a.match_start>4096)&&(a.match_length=ia-1)),a.prev_length>=ia&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ia,d=E._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ia),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ia-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ta}else if(a.match_available){if(d=E._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ta}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=E._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ja){if(m(a),a.lookahead<=ja&&b===I)return ta;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ia&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ja;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ja-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ia?(c=E._tr_tally(a,1,a.match_length-ia),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===I)return ta;break}if(a.match_length=0,c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=C[a.level].max_lazy,a.good_match=C[a.level].good_length,a.nice_match=C[a.level].nice_length,a.max_chain_length=C[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ia-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new D.Buf16(2*ga),this.dyn_dtree=new D.Buf16(2*(2*ea+1)),this.bl_tree=new D.Buf16(2*(2*fa+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new D.Buf16(ha+1),this.heap=new D.Buf16(2*da+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new D.Buf16(2*da+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Y,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?ma:ra,a.adler=2===b.wrap?0:1,b.last_flush=I,E._tr_init(b),N):d(a,P)}function w(a){var b=v(a);return b===N&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?P:(a.state.gzhead=b,N):P}function y(a,b,c,e,f,g){if(!a)return P;var h=1;if(b===S&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>$||c!==Z||8>e||e>15||0>b||b>9||0>g||g>W)return d(a,P);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ia-1)/ia),i.window=new D.Buf8(2*i.w_size),i.head=new D.Buf16(i.hash_size),i.prev=new D.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new D.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,Z,_,aa,X)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>M||0>b)return a?d(a,P):P;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===sa&&b!==L)return d(a,0===a.avail_out?R:P);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===ma)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=G(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=na):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,xa),h.status=ra);else{var m=Z+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=U||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=la),m+=31-m%31,h.status=ra,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===na)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=qa)}else h.status=qa;if(h.status===qa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=ra)):h.status=ra),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,N}else if(0===a.avail_in&&e(b)<=e(c)&&b!==L)return d(a,R);if(h.status===sa&&0!==a.avail_in)return d(a,R);if(0!==a.avail_in||0!==h.lookahead||b!==I&&h.status!==sa){var o=h.strategy===U?r(h,b):h.strategy===V?q(h,b):C[h.level].func(h,b);if(o!==va&&o!==wa||(h.status=sa),o===ta||o===va)return 0===a.avail_out&&(h.last_flush=-1),N;if(o===ua&&(b===J?E._tr_align(h):b!==M&&(E._tr_stored_block(h,0,0,!1),b===K&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,N}return b!==L?N:h.wrap<=0?O:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?N:O)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa?d(a,P):(a.state=null,b===ra?d(a,Q):N)):P}var C,D=a("../utils/common"),E=a("./trees"),F=a("./adler32"),G=a("./crc32"),H=a("./messages"),I=0,J=1,K=3,L=4,M=5,N=0,O=1,P=-2,Q=-3,R=-5,S=-1,T=1,U=2,V=3,W=4,X=0,Y=2,Z=8,$=9,_=15,aa=8,ba=29,ca=256,da=ca+1+ba,ea=30,fa=19,ga=2*da+1,ha=15,ia=3,ja=258,ka=ja+ia+1,la=32,ma=42,na=69,oa=73,pa=91,qa=103,ra=113,sa=666,ta=1,ua=2,va=3,wa=4,xa=3;C=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":82,"./adler32":84,"./crc32":86,"./messages":92,"./trees":93}],88:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],89:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],90:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":82,"./adler32":84,"./crc32":86,"./inffast":89,"./inftrees":91}],91:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){
var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":82}],92:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],93:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return 256>a?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;W>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;V>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;W>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;Q-1>d;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;16>d;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;T>d;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;W>=b;b++)g[b]=0;for(a=0;143>=a;)ga[2*a+1]=8,a++,g[8]++;for(;255>=a;)ga[2*a+1]=9,a++,g[9]++;for(;279>=a;)ga[2*a+1]=7,a++,g[7]++;for(;287>=a;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;T>a;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;S>b;b++)a.dyn_ltree[2*b]=0;for(b=0;T>b;b++)a.dyn_dtree[2*b]=0;for(b=0;U>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):10>=h?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;c>=d;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(l>h){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):10>=h?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;d>e;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;R>b;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":82}],94:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],95:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}]},{},[1]); |
gh-page/src/index.js | metodiobetsanov/metodiobetsanov.github.io | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
src/website/app/demos/Text/Text/bestPractices.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Text from '../../../../../library/Text';
import type { BestPractices } from '../../../pages/ComponentDoc/types';
const bestPractices: BestPractices = [
{
type: 'do',
description: `Use a
[logical order](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements#Usage_notes)
for the headings in your app.`,
example: (
<div>
<Text as="h1">Heading 1</Text>
<Text>
This is a paragraph. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Quisque molestie eros at nisl rhoncus, et condimentum
dui elementum.
</Text>
<Text as="h2">Heading 2</Text>
<Text>
This is a paragraph. Praesent gravida metus at scelerisque ultrices.
Suspendisse at facilisis massa.
</Text>
</div>
)
},
{
type: 'do',
description: `Use the prose \`appearance\` for long blocks of text content,
to improve the reading experience.`,
example: (
<div>
<Text as="h1">Title</Text>
<Text appearance="prose">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
molestie eros at nisl rhoncus, et condimentum dui elementum. Praesent
gravida metus at scelerisque ultrices. Suspendisse at facilisis massa.
Integer eleifend eleifend nibh posuere interdum. Sed eu nisl eu lectus
condimentum ultricies id et sapien.
</Text>
<Text appearance="prose">
Mauris vulputate justo nec velit fringilla, sed convallis elit
hendrerit. Sed at viverra nibh. Maecenas pharetra turpis tempor velit
viverra, ac commodo elit iaculis. Sed finibus ultricies nisl non
dapibus. Nunc ut ullamcorper nulla, sit amet tempus turpis.
</Text>
</div>
)
},
{
type: 'do',
description: `Use the mouse \`appearance\` for brief blocks of content when
you need to conserve space or display minor information.`,
example: (
<div>
<Text appearance="mouse">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
molestie eros at nisl rhoncus, et condimentum dui elementum. Praesent
gravida metus at scelerisque ultrices.
</Text>
<Text appearance="mouse">
Suspendisse at facilisis massa. Integer eleifend eleifend nibh posuere
interdum. Sed eu nisl eu lectus condimentum ultricies id et sapien.
</Text>
</div>
)
},
{
type: 'dont',
description: `Don't use font weight in place of semantic meaning. Use a
heading \`element\` or a 'strong' \`element\` instead.`,
example: (
<div>
<Text fontWeight="extraBold">Not a real heading</Text>
<Text>
This is a paragraph. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Quisque molestie eros at nisl rhoncus, et condimentum
dui elementum.
</Text>
</div>
)
}
];
export default bestPractices;
|
ajax/libs/glamorous/3.9.2/glamorous.umd.tiny.min.js | him2him2/cdnjs | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("glamor")):"function"==typeof define&&define.amd?define(["react","glamor"],t):e.glamorous=t(e.React,e.Glamor)}(this,function(e,t){"use strict";function r(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").toString().split(" ").reduce(function(e,r){if(0===r.indexOf("css-")){var n=r.slice("css-".length),o=t.styleSheet.registered[n].style;e.glamorStyles.push(o)}else e.glamorlessClassName=(e.glamorlessClassName+" "+r).trim();return e},{glamorlessClassName:"",glamorStyles:[]})}function n(e,n,o,s){for(var a=e.slice(),i=a.length;i--;)"function"==typeof a[i]&&(a[i]=a[i](n,s));var c=r(n.className),l=c.glamorStyles;return(c.glamorlessClassName+" "+t.css.apply(void 0,y(a).concat(y(l),[o])).toString()).trim()}function o(e){var t=e.css,r=void 0===t?{}:t;e.theme,e.className,e.innerRef,e.glam;return{toForward:m(e,["css","theme","className","innerRef","glam"]),cssOverrides:r}}var s="default"in e?e.default:e,a=void 0;if("15.5"===s.version.slice(0,4))try{a=require("prop-types")}catch(e){}a=a||s.PropTypes;var i="__glamorous__",c=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),u=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},p=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},m=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r},h=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},y=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)};return function(t){function r(e){var t=e.comp,r=e.styles,n=e.rootEl,s=e.forwardProps,a=e.displayName,i=t.comp?t.comp:t;return{styles:t.styles?t.styles.concat(r):r,comp:i,rootEl:n||i,forwardProps:s,displayName:a||"glamorous("+o(t)+")"}}function o(e){return"string"==typeof e?e:e.displayName||e.name||"unknown"}return function(o){function m(){for(var m=arguments.length,y=Array(m),b=0;b<m;b++)y[b]=arguments[b];var O=function(e){function r(){var e,t,n,o;c(this,r);for(var s=arguments.length,a=Array(s),i=0;i<s;i++)a[i]=arguments[i];return t=n=h(this,(e=r.__proto__||Object.getPrototypeOf(r)).call.apply(e,[this].concat(a))),n.state={theme:null},n.setTheme=function(e){return n.setState({theme:e})},o=t,h(n,o)}return p(r,e),l(r,[{key:"componentWillMount",value:function(){var e=this.props.theme;this.context[i]?this.setTheme(e||this.context[i].getState()):this.setTheme(e||{})}},{key:"componentWillReceiveProps",value:function(e){this.props.theme!==e.theme&&this.setTheme(e.theme)}},{key:"componentDidMount",value:function(){this.context[i]&&!this.props.theme&&(this.unsubscribe=this.context[i].subscribe(this.setTheme))}},{key:"componentWillUnmount",value:function(){this.unsubscribe&&this.unsubscribe()}},{key:"render",value:function(){var e=this.props,o=t(e,r),a=o.toForward,i=o.cssOverrides,c=this.state.theme,l=n(r.styles,e,i,c);return s.createElement(r.comp,f({ref:e.innerRef},a,{className:l}))}}]),r}(e.Component);return O.propTypes={className:a.string,cssOverrides:a.object,theme:a.object,innerRef:a.func,glam:a.object},O.contextTypes=u({},i,a.object),Object.assign(O,r({comp:o,styles:y,rootEl:v,forwardProps:g,displayName:d})),O}var y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},v=y.rootEl,d=y.displayName,b=y.forwardProps,g=void 0===b?[]:b;return m}}(o)});
//# sourceMappingURL=glamorous.umd.tiny.min.js.map
|
app/components/Footer/Footer.js | jmparsons/react-tyro | import React from 'react';
import css from 'react-css-modules';
import styles from './Footer.sss';
const Footer = () => (
<div>
<div styleName="content">© 2016 JMParsons</div>
</div>
);
export default css(Footer, styles);
|
static/js/jquery-ui-1.9.2.custom/js/jquery-1.8.3.js | gareve/pi-libras-del-mal | /*!
* jQuery JavaScript Library v1.8.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
consoles/my-joy-instances/src/components/instances/__tests__/list.spec.js | yldio/joyent-portal | import React from 'react';
import renderer from 'react-test-renderer';
import 'jest-styled-components';
import { Table, TableTbody } from 'joyent-ui-toolkit';
import InstanceList, { Item } from '../list';
import Theme from '@mocks/theme';
it('renders <Item /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Table>
<TableTbody>
<Item />
</TableTbody>
</Table>
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Item mutating /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Table>
<TableTbody>
<Item mutating />
</TableTbody>
</Table>
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Item allowedActions /> without throwing', () => {
const allowedActions = {
start: true,
stop: true
};
expect(
renderer
.create(
<Theme>
<Table>
<TableTbody>
<Item allowedActions={allowedActions} />
</TableTbody>
</Table>
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Item {...item} /> without throwing', () => {
const item = {
id: 'id',
name: 'name',
state: 'PROVISIONING'
};
expect(
renderer
.create(
<Theme>
<Table>
<TableTbody>
<Item {...item} />
</TableTbody>
</Table>
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <InstanceList /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<InstanceList />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <InstanceList sortBy /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<InstanceList sortBy="state" />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <InstanceList sortBy sortOrder /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<InstanceList sortBy="state" sortOrder="asc" />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <InstanceList submitting /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<InstanceList submitting />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <InstanceList allSelected /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<InstanceList allSelected />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <InstanceList>{children}</InstanceList> without throwing', () => {
expect(
renderer
.create(
<Theme>
<InstanceList>
<span>children</span>
</InstanceList>
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
|
examples/with-create-react-app/src/components/Add/Add.js | lwhitlock/grow-tracker | import React, { Component } from 'react';
import fire from '../../fire';
import Button from 'react-md/lib/Buttons/Button';
import Dialog from 'react-md/lib/Dialogs';
import Slider from 'react-md/lib/Sliders';
const today = new Date().toJSON();
class Add extends Component {
constructor(props) {
super(props);
this.state = { visible: false, temp: 78, humidity: 60, date: {today}};
this._updateTemp = this._updateTemp.bind(this);
this._updateHumidity = this._updateHumidity.bind(this);
}
_updateTemp(temp) {
this.setState({ temp });
}
_updateHumidity(humidity) {
this.setState({ humidity });
}
addDataPoint(e){
console.log(this.state.date.today)
fire.database().ref('grow/1/recordings').push({
humidity: this.state.humidity,
temperature: this.state.temp,
date: this.state.date.today
});
this._closeDialog();
}
render() {
return (
<div>
<Button
id="add"
floating
secondary
fixed
onClick={this._openDialog}
>add
</Button>
<Dialog
id="recordings"
{...this.state}
title="Add Data"
onHide={this._closeDialog}
modal
aria-label="New Event"
visible={this.state.visible}
actions={[{
onClick: this._closeDialog,
primary: true,
label: 'Cancel',
}, {
onClick: this.addDataPoint.bind(this),
primary: true,
label: 'Save',
}]}
>
<Slider
id="temperature"
label="Temperature"
leftIcon={<span className="md-slider-ind">T</span>}
defaultValue={this.state.temp}
value={this.state.temp}
onChange={this._updateTemp}
max={110}
editable
/>
<Slider
id="humidity"
label="Humidity"
leftIcon={<span className="md-slider-ind">R</span>}
defaultValue={this.state.humidity}
value={this.state.humidity}
onChange={this._updateHumidity}
max={100}
editable
/>
</Dialog>
</div>
)
}
}
export default Add
|
front/js/hooks/use-timestamp-provider.js | giannisp/rails-react-boilerplate | /**
* @file TimestampProvider hook.
*/
import { useState } from 'react';
import axios from 'axios';
import getLogger from '../utils/logger';
const log = getLogger('TimestampProvider');
const useTimestampProvider = () => {
const [timestamp, setTimestamp] = useState(null);
const fetchTimestamp = async () => {
try {
const res = await axios.get('/home/timestamp');
setTimestamp(res.data.timestamp);
} catch (error) {
log.error(error);
}
};
return [timestamp, fetchTimestamp];
};
export default useTimestampProvider;
|
form.js | julianocomg/react-native-form | /**
* @author Juliano Castilho <julianocomg@gmail.com>
*/
import React from 'react'
import {View} from 'react-native'
import serialize from './serialize'
class Form extends React.Component {
/**
* @param {Object} props
*/
constructor(props) {
super(props)
this.fields = {}
this.formFields = {};
}
/**
* @private
* @param {String} id
* @param {String} name
* @param {String} value
*/
_persistFieldValue(id, name, value) {
this.fields[id] = {name, value}
}
/**
* @returns {Object}
*/
getValues() {
let fieldsArray = []
Object.keys(this.fields).map((id, index) => {
fieldsArray[index] = this.fields[id]
})
return serialize(fieldsArray)
}
/**
* @private
* @param {String} id
* @param {String} name
* @param {String} ref
*/
_persistFieldRef(id, name, value) {
this.formFields[id] = {name, value}
}
/**
* @returns {Object}
*/
getRefs() {
let fieldsArray = []
Object.keys(this.formFields).map((id, index) => {
var tempRef = Object.assign({}, this.formFields[id])
var _refs = this.refs
// value 其实就是 ref 参数的名字 // value actually is 'ref'
tempRef.name = tempRef.value // 这里其实只用value // here just same as the value
tempRef.value = _refs[tempRef.value] // 这里获得对应的ref // here get the ref
fieldsArray[index] = tempRef
})
return serialize(fieldsArray)
}
/**
* @returns {Object}
*/
_getAllowedFormFieldTypes() {
return {
...this.props.customFields,
'TextInput': {
defaultValue: '',
valueProp: 'defaultValue',
callbackProp: 'onChangeText'
},
'Switch': {
controlled: true,
valueProp: 'value',
callbackProp: 'onValueChange'
},
'SliderIOS': {
valueProp: 'value',
callbackProp: 'onSlidingComplete'
},
'Slider': {
valueProp: 'value',
callbackProp: 'onSlidingComplete'
},
'Picker': {
controlled: true,
valueProp: 'selectedValue',
callbackProp: 'onValueChange'
},
'PickerIOS': {
controlled: true,
valueProp: 'selectedValue',
callbackProp: 'onValueChange'
},
'DatePickerIOS': {
controlled: true,
valueProp: 'date',
callbackProp: 'onDateChange'
}
}
}
/**
* @return [ReactComponent]
*/
_createFormFields(elements) {
const allowedFieldTypes = this._getAllowedFormFieldTypes()
return React.Children.map(elements, (element, fieldIndex) => {
if (typeof element !== 'object' || element === null) {
return element
}
const fieldType = element.props.type
const fieldName = element.props.name
const allowedField = allowedFieldTypes[fieldType]
const isValidField = !!(allowedField && fieldName)
const fieldId = fieldName + element.key
let props = {}
if (fieldName) {
// set refs
if (!this.formFields[fieldId]) {
this._persistFieldRef(
fieldId,
fieldName,
(element.ref || element.props.name) || fieldName
)
}
props.ref = this.formFields[fieldId].value;
};
// binding values changed
if (! isValidField) {
if (fieldType == 'Accordion') {
return React.cloneElement(element, {
...props,
children: this._createFormFields(element.props.content)
})
} else {
return React.cloneElement(element, {
...props,
children: this._createFormFields(element.props.children)
})
}
}
props[allowedField.callbackProp] = value => {
this._persistFieldValue(
fieldId,
fieldName,
value
)
if (allowedField.controlled) {
this.forceUpdate()
}
const proxyCallback = element.props[allowedField.callbackProp]
if (typeof proxyCallback === 'function') {
proxyCallback(value)
}
}
if (!this.fields[fieldId]) {
this._persistFieldValue(
fieldId,
fieldName,
(element.props[allowedField.valueProp] || element.props.value) || allowedField.defaultValue
)
}
if (allowedField.controlled) {
props[allowedField.valueProp] = this.fields[fieldId].value
}
return React.cloneElement(element, {
...props,
children: this._createFormFields(element.props.children)
})
})
}
/**
* @returns {ReactComponent}
*/
render() {
return (
<View {...this.props}>
{this._createFormFields(this.props.children)}
</View>
)
}
}
/**
* @type {Object}
*/
Form.defaultProps = {
customFields: {}
}
export default Form
|
frontend/src/components/frame/components/Search.js | jf248/scrape-the-plate | import React from 'react';
import * as PowerPlug from 'lib/react-powerplug';
import { RoutePush } from 'controllers/route-push';
import SearchPres from './SearchPres';
Search.defaultProps = {
query: '',
};
function Search(props) {
const { query, ...rest } = props;
const renderFunc = ({ state, setState }, { push }) => {
const value = state.query;
const onChange = event => setState({ query: event.target.value });
const onSubmit = () => push(`/search/${state.query}/`);
const onBlur = () => setState({ query });
return <SearchPres {...{ onSubmit, value, onChange, onBlur, ...rest }} />;
};
return (
/* eslint-disable react/jsx-key */
<PowerPlug.Compose
components={[
<PowerPlug.State initial={{ query }} enableReinitialize />,
<RoutePush />,
]}
render={renderFunc}
/>
/* eslint-enable react/jsx-key */
);
}
export default Search;
|
server/sonar-web/src/main/js/apps/settings/components/inputs/__tests__/MultiValueInput-test.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { shallow } from 'enzyme';
import MultiValueInput from '../MultiValueInput';
import PrimitiveInput from '../PrimitiveInput';
import { click } from '../../../../../helpers/testUtils';
const definition = { multiValues: true };
const assertValues = (inputs, values) => {
values.forEach((value, index) => {
const input = inputs.at(index);
expect(input.prop('value')).toBe(value);
});
};
it('should render one value', () => {
const multiValueInput = shallow(
<MultiValueInput setting={{ definition }} value={['foo']} onChange={jest.fn()} />
);
const stringInputs = multiValueInput.find(PrimitiveInput);
expect(stringInputs.length).toBe(1 + 1);
assertValues(stringInputs, ['foo', '']);
});
it('should render several values', () => {
const multiValueInput = shallow(
<MultiValueInput setting={{ definition }} value={['foo', 'bar', 'baz']} onChange={jest.fn()} />
);
const stringInputs = multiValueInput.find(PrimitiveInput);
expect(stringInputs.length).toBe(3 + 1);
assertValues(stringInputs, ['foo', 'bar', 'baz', '']);
});
it('should remove value', () => {
const onChange = jest.fn();
const multiValueInput = shallow(
<MultiValueInput setting={{ definition }} value={['foo', 'bar', 'baz']} onChange={onChange} />
);
click(multiValueInput.find('.js-remove-value').at(1));
expect(onChange).toBeCalledWith(['foo', 'baz']);
});
it('should change existing value', () => {
const onChange = jest.fn();
const multiValueInput = shallow(
<MultiValueInput setting={{ definition }} value={['foo', 'bar', 'baz']} onChange={onChange} />
);
multiValueInput.find(PrimitiveInput).at(1).prop('onChange')('qux');
expect(onChange).toBeCalledWith(['foo', 'qux', 'baz']);
});
it('should add new value', () => {
const onChange = jest.fn();
const multiValueInput = shallow(
<MultiValueInput setting={{ definition }} value={['foo']} onChange={onChange} />
);
multiValueInput.find(PrimitiveInput).at(1).prop('onChange')('bar');
expect(onChange).toBeCalledWith(['foo', 'bar']);
});
|
src/server.js | cheshire137/hue-steamer | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
import assets from './assets';
import { port } from './config';
import Config from './config.json';
import db from 'sqlite';
const hue = require('node-hue-api');
const server = global.server = express();
async function getBridge(id) {
if (typeof id === 'undefined') {
return await db.get('SELECT * FROM bridges ' +
'ORDER BY id DESC LIMIT 1');
}
return await db.get('SELECT * FROM bridges WHERE id = ?', id);
}
async function getHueApi(id) {
const connection = await getBridge(id);
return new hue.HueApi(connection.ip, connection.user);
}
function sendBridgeDetails(connection, res) {
const api = new hue.HueApi(connection.ip, connection.user);
api.config().then((bridge) => {
res.json({ connection, bridge });
}).fail((err) => {
res.status(400).json({ error: err, connection });
}).done();
}
function setLightState(api, id, state, res) {
api.setLightState(id, state).then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
}
function setGroupLightState(api, id, state, res) {
api.setGroupLightState(id, state).then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
}
async function saveBridge(ip, user) {
let bridge = await db.get('SELECT * FROM bridges ' +
'WHERE ip = ? AND user = ?', ip, user);
if (typeof bridge === 'object') {
await db.run('UPDATE bridges SET user = ? WHERE ip = ?', user, ip);
bridge = await getBridge(bridge.id);
} else {
await db.run('INSERT INTO bridges (user, ip) VALUES (?, ?)', user, ip);
bridge = await getBridge();
}
return bridge;
}
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
server.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin',
Config[process.env.NODE_ENV].clientUri);
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
next();
});
server.get('/bridge', async (req, res) => {
const result = await db.get('SELECT COUNT(*) AS count FROM bridges');
if (result.count < 1) {
res.status(400).json({ error: 'There are no bridges.' });
return;
}
const connection = await getBridge();
sendBridgeDetails(connection, res);
});
server.get('/bridges/discover', async (req, res) => {
const timeout = 2000; // 2 seconds
hue.nupnpSearch(timeout).then((bridges) => {
res.json(bridges);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.get('/bridges/:id', async (req, res) => {
const connection = await getBridge(req.params.id);
sendBridgeDetails(connection, res);
});
server.post('/bridges', async (req, res) => {
const ip = req.query.ip;
if (typeof ip !== 'string' || ip.length < 1) {
res.status(400).
json({ error: 'Must provide Hue Bridge IP address in ip param' });
return;
}
const user = req.query.user;
if (typeof user !== 'string' || user.length < 1) {
res.status(400).
json({ error: 'Must provide Hue Bridge user in user param' });
return;
}
const bridge = await saveBridge(ip, user);
sendBridgeDetails(bridge, res);
});
server.post('/users', async (req, res) => {
const ip = req.query.ip;
if (typeof ip !== 'string' || ip.length < 1) {
res.status(400).
json({ error: 'Must provide Hue Bridge IP address in ip param' });
return;
}
const userDescription = req.query.user;
if (typeof userDescription !== 'string' || userDescription.length < 1) {
res.status(400).
json({
error: 'Must provide Hue Bridge user description in user param',
});
return;
}
const api = new hue.HueApi();
api.registerUser(ip, userDescription).then((user) => {
const bridge = saveBridge(ip, user);
sendBridgeDetails(bridge, res);
}).fail((err) => {
res.status(400).json({ error: err.message });
}).done();
});
server.get('/schedules', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.schedules().then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.get('/scenes', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.scenes().then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.get('/scene/:id', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.scene(req.params.id).then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.get('/groups', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.groups().then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.post('/groups', async (req, res) => {
let name = req.query.name;
if (typeof name !== 'string') {
res.status(400).json({ error: 'Must pass group name in name param' });
return;
}
name = name.trim();
if (name.length < 1) {
res.status(400).json({
error: 'Must pass group name at least 1 character long',
});
return;
}
let lightIDs = req.query.ids;
if (typeof lightIDs !== 'string') {
res.status(400).json({
error: 'Must pass comma-separated list of light IDs in ids param',
});
return;
}
lightIDs = lightIDs.split(',');
const api = await getHueApi(req.query.connectionID);
api.createGroup(name, lightIDs).then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.get('/group/:id', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.getGroup(req.params.id).then((group) => {
res.json(group);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.delete('/group/:id', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.deleteGroup(req.params.id).then((group) => {
res.json(group);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.put('/group/:id', async (req, res) => {
let name = req.query.name;
if (typeof name !== 'string') {
res.status(400).json({ error: 'Must pass group name in name param' });
return;
}
name = name.trim();
if (name.length < 1) {
res.status(400).json({
error: 'Must pass group name at least 1 character long',
});
return;
}
let lightIDs = req.query.ids;
if (typeof lightIDs !== 'string') {
res.status(400).json({
error: 'Must pass comma-separated list of light IDs in ids param',
});
return;
}
lightIDs = lightIDs.split(',');
const api = await getHueApi(req.query.connectionID);
api.updateGroup(req.params.id, name, lightIDs).then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.get('/light/:id', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
api.lightStatus(req.params.id).then((result) => {
res.json(result);
}).fail((err) => {
res.status(400).json(err);
}).done();
});
server.post('/light/:id/on', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
const state = hue.lightState.create().on();
setLightState(api, req.params.id, state, res);
});
server.post('/light/:id/off', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
const state = hue.lightState.create().off();
setLightState(api, req.params.id, state, res);
});
server.post('/group/:id/on', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
const state = hue.lightState.create().on();
setGroupLightState(api, req.params.id, state, res);
});
server.post('/group/:id/off', async (req, res) => {
const api = await getHueApi(req.query.connectionID);
const state = hue.lightState.create().off();
setGroupLightState(api, req.params.id, state, res);
});
server.post('/light/:id/color', async (req, res) => {
const x = req.query.x;
const y = req.query.y;
if (typeof x !== 'string') {
res.status(400).send('{"error": "Must provide x color in x param"}');
return;
}
if (typeof y !== 'string') {
res.status(400).send('{"error": "Must provide y color in y param"}');
return;
}
const api = await getHueApi(req.query.connectionID);
const state = hue.lightState.create().on().xy(x, y);
setLightState(api, req.params.id, state, res);
});
server.post('/group/:id/color', async (req, res) => {
const x = req.query.x;
const y = req.query.y;
if (typeof x !== 'string') {
res.status(400).send('{"error": "Must provide x color in x param"}');
return;
}
if (typeof y !== 'string') {
res.status(400).send('{"error": "Must provide y color in y param"}');
return;
}
const api = await getHueApi(req.query.connectionID);
const state = hue.lightState.create().on().xy(x, y);
setGroupLightState(api, req.params.id, state, res);
});
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };
const css = [];
const context = {
insertCss: styles => css.push(styles._getCss()),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
const dbName = Config[process.env.NODE_ENV].database || ':memory:';
console.log('Working with database ' + dbName);
db.open(dbName, { verbose: true }).
then(() => {
server.listen(port, () => {
/* eslint-disable no-console */
console.log(`The server is running at http://localhost:${port}/`);
});
}).catch(err => console.error(err));
|
app/routes.js | anorudes/redux-easy-boilerplate | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import asyncComponent from './utils/asyncComponent'; /* for async page, show loading component */
import Root from './containers/Root';
import Posts from './containers/Posts';
import About from './components/About';
export default (
<Route path="/" component={Root}>
<IndexRoute component={Posts} />
{ /* async component */}
<Route path="/async-example" getComponent={(location, callback) =>
__CLIENT__
? asyncComponent(require.ensure([], require => callback('', require('./components/AsyncExample').default), 'async-example'))
: callback('', require('./components/AsyncExample').default)
} />
<Route path="/posts" component={Posts} />
<Route path="/about" component={About} />
</Route>
);
|
site/server.js | pablolmiranda/fluxible | /**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import path from 'path';
import express from 'express';
import favicon from 'serve-favicon';
import serialize from 'serialize-javascript';
import { navigateAction } from 'fluxible-router';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import csrf from 'csurf';
import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import app from './app';
import HtmlComponent from './components/Html.jsx';
import assets from './utils/assets';
import DocsService from './services/docs';
import SearchService from './services/search';
import { createElementWithContext } from 'fluxible-addons-react';
import redirects from './configs/redirects';
const htmlComponent = React.createFactory(HtmlComponent);
const server = express();
server.set('state namespace', 'App');
server.use(favicon(path.join(__dirname, '/assets/images/favicon.ico')));
server.use('/public', express['static'](path.join(__dirname, '/build')));
server.use(cookieParser());
server.use(bodyParser.json());
server.use(csrf({ cookie: true }));
// Get access to the fetchr plugin instance
const fetchrPlugin = app.getPlugin('FetchrPlugin');
// Register our services
fetchrPlugin.registerService(DocsService);
fetchrPlugin.registerService(SearchService);
// Set up the fetchr middleware
server.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());
// Set up redirects for old urls
Object.keys(redirects).forEach((from) => {
let to = redirects[from];
server.use(from, (req, res) => {
res.redirect(301, to);
});
});
// Render the app
function renderApp(res, context) {
const appElement = createElementWithContext(context);
const renderedApp = renderToString(appElement);
const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
const doctype = '<!DOCTYPE html>';
const componentContext = context.getComponentContext();
const html = renderToStaticMarkup(htmlComponent({
assets: assets,
context: componentContext,
state: exposed,
markup: renderedApp
}));
res.send(doctype + html);
}
// Every other request gets the app bootstrap
server.use(function (req, res, next) {
const context = app.createContext({
req: req, // The fetchr plugin depends on this
xhrContext: {
_csrf: req.csrfToken() // Make sure all XHR requests have the CSRF token
}
});
context.executeAction(navigateAction, { url: req.url }, function (err) {
if (err) {
if (err.statusCode === 404) {
return next();
}
return next(err);
}
renderApp(res, context);
});
});
const port = process.env.PORT || 3000;
server.listen(port);
console.log('Listening on port ' + port);
|
src/svg-icons/image/leak-add.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLeakAdd = (props) => (
<SvgIcon {...props}>
<path d="M6 3H3v3c1.66 0 3-1.34 3-3zm8 0h-2c0 4.97-4.03 9-9 9v2c6.08 0 11-4.93 11-11zm-4 0H8c0 2.76-2.24 5-5 5v2c3.87 0 7-3.13 7-7zm0 18h2c0-4.97 4.03-9 9-9v-2c-6.07 0-11 4.93-11 11zm8 0h3v-3c-1.66 0-3 1.34-3 3zm-4 0h2c0-2.76 2.24-5 5-5v-2c-3.87 0-7 3.13-7 7z"/>
</SvgIcon>
);
ImageLeakAdd = pure(ImageLeakAdd);
ImageLeakAdd.displayName = 'ImageLeakAdd';
ImageLeakAdd.muiName = 'SvgIcon';
export default ImageLeakAdd;
|
extra/AsterickSVG.js | martinjackson/reactjs-meetup-validation | import React from 'react';
import _ from 'lodash';
// <Asterick fill='red' />
class Asterick extends React.Component {
constructor(props) {
super(props);
}
render(){
var sz = { width: '1.68em', height: '1.68em' };
var st = sz; // _.assign(sz, {float: 'right'});
var bor = _.assign(sz, {borderStyle: 'solid'});
return <div style={bor}>
<svg style={st}>
<path fill={this.props.fill}
d="M 0,14.355469 2.2460938,7.421875 C 7.4218645,9.2448552 11.181626,10.82363 13.525391,12.158203 12.906885,6.2663426 12.581365,2.2136123 12.548828,0 l 7.080078,0 c -0.09768,3.2227258 -0.472027,7.2591801 -1.123047,12.109375 3.35284,-1.692646 7.193982,-3.2551444 11.523438,-4.6875 l 2.246094,6.933594 c -4.134146,1.367244 -8.186877,2.278702 -12.158204,2.734375 1.985652,1.725314 4.785129,4.801483 8.398438,9.228515 L 22.65625,30.46875 C 20.768205,27.89718 18.53839,24.397835 15.966797,19.970703 13.557926,24.560595 11.442043,28.059941 9.6191406,30.46875 L 3.8574219,26.318359 C 7.6334528,21.663463 10.335273,18.587294 11.962891,17.089844 7.763661,16.276098 3.7760348,15.364641 0,14.355469"
id="path3063" />
</svg>
</div>
}
}
export default Asterick
|
src/redux-todo/components/Header.spec.js | SodhanaLibrary/react-examples | import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Header from './Header'
import TodoTextInput from './TodoTextInput'
const setup = () => {
const props = {
addTodo: jest.fn()
}
const renderer = TestUtils.createRenderer()
renderer.render(<Header {...props} />)
const output = renderer.getRenderOutput()
return {
props: props,
output: output,
renderer: renderer
}
}
describe('components', () => {
describe('Header', () => {
it('should render correctly', () => {
const { output } = setup()
expect(output.type).toBe('header')
expect(output.props.className).toBe('header')
const [ h1, input ] = output.props.children
expect(h1.type).toBe('h1')
expect(h1.props.children).toBe('todos')
expect(input.type).toBe(TodoTextInput)
expect(input.props.newTodo).toBe(true)
expect(input.props.placeholder).toBe('What needs to be done?')
})
it('should call addTodo if length of text is greater than 0', () => {
const { output, props } = setup()
const input = output.props.children[1]
input.props.onSave('')
expect(props.addTodo).not.toBeCalled()
input.props.onSave('Use Redux')
expect(props.addTodo).toBeCalled()
})
})
})
|
src/svg-icons/action/settings-cell.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsCell = (props) => (
<SvgIcon {...props}>
<path d="M7 24h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM16 .01L8 0C6.9 0 6 .9 6 2v16c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V2c0-1.1-.9-1.99-2-1.99zM16 16H8V4h8v12z"/>
</SvgIcon>
);
ActionSettingsCell = pure(ActionSettingsCell);
ActionSettingsCell.displayName = 'ActionSettingsCell';
ActionSettingsCell.muiName = 'SvgIcon';
export default ActionSettingsCell;
|
tests/components/Header/Header.spec.js | chenyang0424/initial-project | import React from 'react'
import { Header } from 'components/Header/Header'
import { IndexLink, Link } from 'react-router'
import { shallow } from 'enzyme'
describe('(Component) Header', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Header />)
})
it('Renders a welcome message', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.match(/React Redux Starter Kit/)
})
describe('Navigation links...', () => {
it('Should render a Link to Home route', () => {
expect(_wrapper.contains(
<IndexLink activeClassName='route--active' to='/'>
Home
</IndexLink>
)).to.be.true
})
it('Should render a Link to Counter route', () => {
expect(_wrapper.contains(
<Link activeClassName='route--active' to='/counter'>
Counter
</Link>
)).to.be.true
})
})
})
|
pages/catalogs.js | sgmap/inspire | import React from 'react'
import PropTypes from 'prop-types'
import {flowRight} from 'lodash'
import getConfig from 'next/config'
import {_get} from '../lib/fetch'
import {sortByScore} from '../lib/catalog'
import attachI18n from '../components/hoc/attach-i18n'
import withErrors from '../components/hoc/with-errors'
import Page from '../components/page'
import Meta from '../components/meta'
import Content from '../components/content'
import Container from '../components/container'
import CatalogPreview from '../components/catalog-preview'
const {publicRuntimeConfig: {
GEODATA_API_URL
}} = getConfig()
class CatalogsPage extends React.Component {
static propTypes = {
catalogs: PropTypes.arrayOf(PropTypes.shape({
_id: PropTypes.string.isRequired
})).isRequired,
t: PropTypes.func.isRequired,
tReady: PropTypes.bool.isRequired
}
static async getInitialProps() {
const catalogs = await _get(`${GEODATA_API_URL}/catalogs`)
return {
catalogs
}
}
render() {
const {catalogs, t, tReady} = this.props
const sorted = sortByScore(catalogs)
return (
<Page ready={tReady}>
{() => (
<React.Fragment>
<Meta title={t('list.title')} />
<Content clouds>
<Container fluid>
<h1>{t('list.title')}</h1>
<section>
{sorted.map(catalog => (
<div key={catalog._id}>
<CatalogPreview catalog={catalog} />
</div>
))}
</section>
</Container>
</Content>
<style jsx>{`
h1 {
color: #fff;
font-size: 2.2em;
font-weight: 500;
margin: 0.5em 0 1em;
text-align: center;
}
section {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
div {
width: 360px;
margin: 10px;
@media (max-width: 551px) {
width: 100%;
margin: 10px 0;
}
}
`}</style>
</React.Fragment>
)}
</Page>
)
}
}
export default flowRight(
attachI18n('catalogs'),
withErrors
)(CatalogsPage)
|
docs/src/pages/components/dialogs/CustomizedDialogs.js | allanalexandre/material-ui | import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import Typography from '@material-ui/core/Typography';
const styles = theme => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
const DialogTitle = withStyles(styles)(props => {
const { children, classes, onClose } = props;
return (
<MuiDialogTitle disableTypography className={classes.root}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton aria-label="Close" className={classes.closeButton} onClick={onClose}>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles(theme => ({
root: {
padding: theme.spacing(2),
},
}))(MuiDialogContent);
const DialogActions = withStyles(theme => ({
root: {
margin: 0,
padding: theme.spacing(1),
},
}))(MuiDialogActions);
class CustomizedDialogs extends React.Component {
state = {
open: false,
};
handleClickOpen = () => {
this.setState({
open: true,
});
};
handleClose = () => {
this.setState({ open: false });
};
render() {
return (
<div>
<Button variant="outlined" color="secondary" onClick={this.handleClickOpen}>
Open dialog
</Button>
<Dialog
onClose={this.handleClose}
aria-labelledby="customized-dialog-title"
open={this.state.open}
>
<DialogTitle id="customized-dialog-title" onClose={this.handleClose}>
Modal title
</DialogTitle>
<DialogContent dividers>
<Typography gutterBottom>
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac
facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum
at eros.
</Typography>
<Typography gutterBottom>
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis
lacus vel augue laoreet rutrum faucibus dolor auctor.
</Typography>
<Typography gutterBottom>
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel
scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus
auctor fringilla.
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Save changes
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
export default CustomizedDialogs;
|
ajax/libs/forerunnerdb/1.3.674/fdb-core.js | pombredanne/cdnjs | (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(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":25,"./Shared":28}],3:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback(); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - rob@irrelon.com
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],8:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":25,"./Shared":28}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":28}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":23,"./Shared":28}],13:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],14:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":24,"./Serialiser":27}],16:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],17:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":24}],18:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":24}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":25,"./Shared":28}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":28}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":28}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.674',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
|
node_modules/react-native/local-cli/templates/HelloNavigation/views/chat/ChatScreen.js | joan17cast/Enigma | 'use strict';
import React, { Component } from 'react';
import {
ActivityIndicator,
Button,
ListView,
StyleSheet,
Text,
TextInput,
View,
} from 'react-native';
import KeyboardSpacer from '../../components/KeyboardSpacer';
import Backend from '../../lib/Backend';
export default class ChatScreen extends Component {
static navigationOptions = {
title: (navigation) => `Chat with ${navigation.state.params.name}`,
}
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
messages: [],
dataSource: ds,
myMessage: '',
isLoading: true,
};
}
async componentDidMount() {
let chat;
try {
chat = await Backend.fetchChat(this.props.navigation.state.params.name);
} catch (err) {
// Here we would handle the fact the request failed, e.g.
// set state to display "Messages could not be loaded".
// We should also check network connection first before making any
// network requests - maybe we're offline? See React Native's NetInfo
// module.
this.setState({
isLoading: false,
});
return;
}
this.setState((prevState) => ({
messages: chat.messages,
dataSource: prevState.dataSource.cloneWithRows(chat.messages),
isLoading: false,
}));
}
onAddMessage = async () => {
// Optimistically update the UI
this.addMessageLocal();
// Send the request
try {
await Backend.sendMessage({
name: this.props.navigation.state.params.name,
// TODO Is reading state like this outside of setState OK?
// Can it contain a stale value?
message: this.state.myMessage,
});
} catch (err) {
// Here we would handle the request failure, e.g. call setState
// to display a visual hint showing the message could not be sent.
}
}
addMessageLocal = () => {
this.setState((prevState) => {
if (!prevState.myMessage) {
return prevState;
}
const messages = [
...prevState.messages, {
name: 'Me',
text: prevState.myMessage,
}
];
return {
messages: messages,
dataSource: prevState.dataSource.cloneWithRows(messages),
myMessage: '',
}
});
this.textInput.clear();
}
onMyMessageChange = (event) => {
this.setState({myMessage: event.nativeEvent.text});
}
renderRow = (message) => (
<View style={styles.bubble}>
<Text style={styles.name}>{message.name}</Text>
<Text>{message.text}</Text>
</View>
)
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
onLayout={this.scrollToBottom}
/>
<View style={styles.composer}>
<TextInput
ref={(textInput) => { this.textInput = textInput; }}
style={styles.textInput}
placeholder="Type a message..."
text={this.state.myMessage}
onSubmitEditing={this.onAddMessage}
onChange={this.onMyMessageChange}
/>
{this.state.myMessage !== '' && (
<Button
title="Send"
onPress={this.onAddMessage}
/>
)}
</View>
<KeyboardSpacer />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 8,
backgroundColor: 'white',
},
listView: {
flex: 1,
alignSelf: 'stretch',
},
bubble: {
alignSelf: 'flex-end',
backgroundColor: '#d6f3fc',
padding: 12,
borderRadius: 4,
marginBottom: 4,
},
name: {
fontWeight: 'bold',
},
composer: {
flexDirection: 'row',
alignItems: 'center',
height: 36,
},
textInput: {
flex: 1,
borderColor: '#ddd',
borderWidth: 1,
padding: 4,
height: 30,
fontSize: 13,
marginRight: 8,
}
});
|
packages/react-ui-core/src/Carousel/__tests__/CarouselNavigation-test.js | rentpath/react-ui | import React from 'react'
import renderer from 'react-test-renderer'
import { shallow } from 'enzyme'
import theme from './mocks/theme'
import ThemedCarouselNavigation from '../CarouselNavigation'
const CarouselNavigation = ThemedCarouselNavigation.WrappedComponent
const items = [
<div key="1">Test 1</div>,
<div key="2">Test 2</div>,
<div key="3">Test 3</div>,
<div key="4">Test 4</div>,
]
describe('Carousel Navigation', () => {
it('applies a theme classname and adds direction', () => {
const wrapper = shallow(<CarouselNavigation theme={theme} direction="previous" />)
const className = wrapper.prop('className')
expect(className).toEqual('CarouselNavigation-previous')
})
it('renders passed children', () => {
const snap = renderer
.create(
<CarouselNavigation
theme={theme}
direction="next"
>
{items}
</CarouselNavigation>
).toJSON()
expect(snap).toMatchSnapshot()
})
it('applies a data-tid with direction', () => {
const wrapper = shallow(<CarouselNavigation theme={theme} direction="next" />)
const dataTid = wrapper.prop('data-tid')
expect(dataTid).toEqual('carousel-navigation-next')
})
it('allows props to be passed through', () => {
const onClick = jest.fn()
const wrapper = shallow(<CarouselNavigation theme={theme} onClick={onClick} />)
expect(wrapper.prop('onClick')).toEqual(onClick)
})
})
|
node_modules/_antd@2.13.4@antd/es/mention/index.js | ligangwolai/blog | import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import RcMention, { Nav, toString, toEditorState, getMentions } from 'rc-editor-mention';
import classNames from 'classnames';
import shallowequal from 'shallowequal';
import Icon from '../icon';
var Mention = function (_React$Component) {
_inherits(Mention, _React$Component);
function Mention(props) {
_classCallCheck(this, Mention);
var _this = _possibleConstructorReturn(this, (Mention.__proto__ || Object.getPrototypeOf(Mention)).call(this, props));
_this.onSearchChange = function (value, prefix) {
if (_this.props.onSearchChange) {
return _this.props.onSearchChange(value, prefix);
}
return _this.defaultSearchChange(value);
};
_this.onChange = function (editorState) {
if (_this.props.onChange) {
_this.props.onChange(editorState);
}
};
_this.onFocus = function (ev) {
_this.setState({
focus: true
});
if (_this.props.onFocus) {
_this.props.onFocus(ev);
}
};
_this.onBlur = function (ev) {
_this.setState({
focus: false
});
if (_this.props.onBlur) {
_this.props.onBlur(ev);
}
};
_this.focus = function () {
_this.mentionEle._editor.focus();
};
_this.mentionRef = function (ele) {
_this.mentionEle = ele;
};
_this.state = {
suggestions: props.suggestions,
focus: false
};
return _this;
}
_createClass(Mention, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var suggestions = nextProps.suggestions;
if (!shallowequal(suggestions, this.props.suggestions)) {
this.setState({
suggestions: suggestions
});
}
}
}, {
key: 'defaultSearchChange',
value: function defaultSearchChange(value) {
var searchValue = value.toLowerCase();
var filteredSuggestions = (this.props.suggestions || []).filter(function (suggestion) {
if (suggestion.type && suggestion.type === Nav) {
return suggestion.props.value ? suggestion.props.value.toLowerCase().indexOf(searchValue) !== -1 : true;
}
return suggestion.toLowerCase().indexOf(searchValue) !== -1;
});
this.setState({
suggestions: filteredSuggestions
});
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
_props$className = _props.className,
className = _props$className === undefined ? '' : _props$className,
prefixCls = _props.prefixCls,
loading = _props.loading;
var _state = this.state,
suggestions = _state.suggestions,
focus = _state.focus;
var cls = classNames(className, _defineProperty({}, prefixCls + '-active', focus));
var notFoundContent = loading ? React.createElement(Icon, { type: 'loading' }) : this.props.notFoundContent;
return React.createElement(RcMention, _extends({}, this.props, { className: cls, ref: this.mentionRef, onSearchChange: this.onSearchChange, onChange: this.onChange, onFocus: this.onFocus, onBlur: this.onBlur, suggestions: suggestions, notFoundContent: notFoundContent }));
}
}]);
return Mention;
}(React.Component);
export default Mention;
Mention.getMentions = getMentions;
Mention.defaultProps = {
prefixCls: 'ant-mention',
notFoundContent: '无匹配结果,轻敲空格完成输入',
loading: false,
multiLines: false
};
Mention.Nav = Nav;
Mention.toString = toString;
Mention.toContentState = toEditorState;
Mention.toEditorState = function (text) {
console.warn('Mention.toEditorState is deprecated. Use toContentState instead.');
return toEditorState(text);
}; |
src/components/userComponents/sampleForm.js | toffee7/ReactStarterComponents | import React, { Component } from 'react';
import GenericInputPicker from '../commonComponents/formComponents/genericInputPicker';
import Toggle from '../commonComponents/formComponents/toggle';
import GenericSelect from '../commonComponents/formComponents/genericSelect';
export default class SampleForm extends Component {
constructor(props) {
super(props);
this.handleTimeChange = this.handleTimeChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
}
handleDateChange(v) {
console.log("Inside Date callback" + v);
}
handleTextChange(v) {
console.log("Inside Text callback" + v);
}
handleTimeChange(v) {
console.log("Inside Time callback" + v);
}
render() {
return (
<div className="container">
<GenericInputPicker inputType={"time"} label={"Time"} onValueChange={this.handleTimeChange}/>
<GenericInputPicker inputType={"date"} label={"Date"} onValueChange={this.handleDateChange}/>
<GenericInputPicker inputType={"text"} label={"Text"} onValueChange={this.handleTextChange}/>
<Toggle />
<Toggle />
<GenericSelect currentValue={[{label: "Apple", value: "Apple"}]} />
<GenericSelect currentValue={[{label: "Google", value: "Apple"}]} />
</div>
);
}
} |
app/react/src/client/preview/error_display.js | bigassdragon/storybook | import PropTypes from 'prop-types';
import React from 'react';
const mainStyle = {
position: 'fixed',
top: 0,
bottom: 0,
left: 0,
right: 0,
padding: 20,
backgroundColor: 'rgb(187, 49, 49)',
color: '#FFF',
WebkitFontSmoothing: 'antialiased',
};
const headingStyle = {
fontSize: 20,
fontWeight: 600,
letterSpacing: 0.2,
margin: '10px 0',
fontFamily: `
-apple-system, ".SFNSText-Regular", "San Francisco", Roboto, "Segoe UI",
"Helvetica Neue", "Lucida Grande", sans-serif
`,
};
const codeStyle = {
fontSize: 14,
width: '100vw',
overflow: 'auto',
};
const ErrorDisplay = ({ error }) => (
<div style={mainStyle}>
<div style={headingStyle}>{error.message}</div>
<pre style={codeStyle}>
<code>
{error.stack}
</code>
</pre>
</div>
);
ErrorDisplay.propTypes = {
error: PropTypes.object.isRequired,
};
export default ErrorDisplay;
|
main.js | zedd45/react-static-todos | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './core/store';
import Homepage from './pages/home';
const container = document.getElementById('container');
ReactDOM.render(<Provider store={store}><Homepage /></Provider>, container);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./routes.json', () => {
routes = require('./routes.json'); // eslint-disable-line global-require
render(history.getCurrentLocation());
});
}
|
src/components/footer.js | paulckennedy/KennedyChemistryRocks | import React from 'react';
export default (props) => {
return (
<div>
<footer className="hg_footer">
<div className="contactus">
<h3>Tracy Kennedy MS.</h3>
<div clasclassNames="address">
<h1 className="bigOne"></h1>
<ul id="address">
<li><i className="fa fa-road"></i> Carthage High School</li>
<li>#1 Bulldog Drive</li>
<li>Carthage, Texas 75633</li>
</ul>
</div>
<div className="content">
<pre id="object"></pre>
</div>
<div clclassNameass="contacttypes">
<ul id="contactinfo">
<li><i className="fa fa-envelope-o"></i> Email: tkennedy@carthageisd.org</li>
<li><i className="fa fa-phone"></i> Phone: 903-693-2552</li>
<li>Conference: 4th Period</li>
<li>Room: D5</li>
</ul>
</div>
</div>
</footer>
</div>
);
} |
src/components/LoginForm.js | cernanb/personal-chef-react-app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Form, Segment } from 'semantic-ui-react';
class LoginForm extends Component {
state = {
email: '',
password: '',
};
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
const { onSubmit } = this.props;
const { email, password } = this.state;
return (
<Form
size="large"
onSubmit={e => {
e.preventDefault();
onSubmit(this.state);
}}
>
<Segment stacked>
<Form.Input
fluid
onChange={this.onChange}
icon="user"
name="email"
iconPosition="left"
placeholder="E-mail address"
value={email}
/>
<Form.Input
name="password"
onChange={this.onChange}
fluid
icon="lock"
iconPosition="left"
placeholder="Password"
type="password"
value={password}
/>
<Button fluid size="large">
Login
</Button>
</Segment>
</Form>
);
}
}
LoginForm.propTypes = {
onSubmit: PropTypes.func,
};
export default LoginForm;
|
server/game/cards/14-FotS/LynCorbray.js | cryogen/throneteki | const DrawCard = require('../../drawcard');
const GameActions = require('../../GameActions');
class LynCorbray extends DrawCard {
setupCardAbilities() {
this.reaction({
when: {
onChallengeInitiated: event => event.challenge.isMatch({ initiatedAgainstPlayer: this.controller, challengeType: 'power' }) && this.allowGameAction('stand')
},
message: '{player} uses {source} to stand {source}',
handler: context => {
this.game.resolveGameAction(
GameActions.standCard({ card: this }),
context
);
}
});
}
}
LynCorbray.code = '14039';
module.exports = LynCorbray;
|
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js | senolakkas/react-native-minesweeper | import _transformLib from 'transform-lib';
const _components = {
Foo: {
displayName: 'Foo'
}
};
const _transformLib2 = _transformLib({
filename: '%FIXTURE_PATH%',
components: _components,
locals: [],
imports: []
});
function _wrapComponent(id) {
return function (Component) {
return _transformLib2(Component, id);
};
}
import React, { Component } from 'react';
const Foo = _wrapComponent('Foo')(class Foo extends Component {
render() {}
});
|
packages/cf-component-icon/src/reactsvgs/Bolt.js | jroyal/cf-ui | import React from 'react';
import PropTypes from 'prop-types';
const Bolt = ({ className, label }) => (
<svg
className={className}
aria-label={label}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
>
<polygon points="14.345 6.413 10.379 6.413 11.966 0.068 1.655 9.587 5.621 9.587 4.034 15.932 14.345 6.413" />
</svg>
);
Bolt.propTypes = {
className: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
};
export default Bolt;
|
native-base-theme/components/TabContainer.js | auto-flourish/ios | import { Platform } from 'react-native';
import variable from './../variables/platform';
export default (variables = variable) => {
const platformStyle = variables.platformStyle;
const platform = variables.platform;
const tabContainerTheme = {
elevation: 3,
height: 50,
flexDirection: 'row',
shadowColor: (platformStyle==='material') ? '#000' : undefined,
shadowOffset: (platformStyle==='material') ? {width: 0, height: 2} : undefined,
shadowOpacity: (platformStyle==='material') ? 0.2 : undefined,
shadowRadius: (platformStyle==='material') ? 1.2 : undefined,
justifyContent: 'space-around',
borderBottomWidth: (Platform.OS=='ios') ? variables.borderWidth : 0,
borderColor: variables.topTabBarBorderColor,
};
return tabContainerTheme;
};
|
lib/components/Login.js | mlimberg/Digidex | import React from 'react';
const Login = ({ authorize, setUser, text, id }) => {
return (
<div>
<button className='button'
id={id + '-btn'}
onClick={()=> {
authorize().then((fromFirebase) => setUser(fromFirebase));
}}>
{text}
</button>
</div>
)
}
export default Login
|
src/components/decoline_list.js | lizarraldeignacio/personal-website | import React, { Component } from 'react';
import DecolineItem from './decoline_item';
import _ from 'lodash';
import { firebaseConnect } from 'react-redux-firebase';
/**
DecolineList list of Decoline elements
Params:
elements: The elements that the list will contain
path: The path of the firebase database of the list
itemIconRemove: The icon of the remove action of each element
auth: A flag that indicates if the user is authenticated or not
**/
class DecolineList extends Component {
constructor(props) {
super(props);
}
remove(title) {
const key = _.findKey(this.props.elements,
(item) => {return title == item["title"]});
this.props.firebase.remove(`${this.props.path}/${key}`);
}
renderList() {
return (
_.map(this.props.elements, element => {
return (
<DecolineItem
key = {element["title"]}
title = {element["title"]}
description = {element["description"]}
itemIconRemove = {this.props.itemIconRemove}
remove = {this.remove.bind(this)}
auth = {this.props.auth}
/>
);
})
);
}
render() {
return (
<div className="o-grid">
{this.props.elements && this.renderList.bind(this)()}
</div>
);
}
}
export default firebaseConnect()(DecolineList);
|
examples/04 Sortable/Simple/Container.js | Reggino/react-dnd | import React, { Component } from 'react';
import update from 'react/lib/update';
import Card from './Card';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
const style = {
width: 400
};
@DragDropContext(HTML5Backend)
export default class Container extends Component {
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
cards: [{
id: 1,
text: 'Write a cool JS library'
}, {
id: 2,
text: 'Make it generic enough'
}, {
id: 3,
text: 'Write README'
}, {
id: 4,
text: 'Create some examples'
}, {
id: 5,
text: 'Spam in Twitter and IRC to promote it'
}, {
id: 6,
text: '???'
}, {
id: 7,
text: 'PROFIT'
}]
};
}
moveCard(id, afterId) {
const { cards } = this.state;
const card = cards.filter(c => c.id === id)[0];
const afterCard = cards.filter(c => c.id === afterId)[0];
const cardIndex = cards.indexOf(card);
const afterIndex = cards.indexOf(afterCard);
this.setState(update(this.state, {
cards: {
$splice: [
[cardIndex, 1],
[afterIndex, 0, card]
]
}
}));
}
render() {
const { cards } = this.state;
return (
<div style={style}>
{cards.map(card => {
return (
<Card key={card.id}
id={card.id}
text={card.text}
moveCard={this.moveCard} />
);
})}
</div>
);
}
} |
node_modules/react-icons/io/ios-snowy.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const IoIosSnowy = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m29.7 24.8c0.3 0.1 0.4 0.5 0.2 0.8s-0.5 0.4-0.8 0.3l-2.3-1.4c-0.2 0.7-0.2 1.3 0 1.9 0.1 0.3-0.2 0.7-0.5 0.8s-0.7-0.2-0.8-0.5c-0.1-0.9-0.2-1.9 0.1-2.8l-5-2.8v5.7c0.9 0.2 1.7 0.6 2.4 1.2 0.3 0.3 0.4 0.7 0.1 0.9s-0.6 0.3-0.8 0.1c-0.5-0.4-1-0.8-1.7-1v2.6c0 0.3-0.3 0.6-0.6 0.6s-0.6-0.3-0.6-0.6v-2.6c-0.6 0.2-1.2 0.6-1.7 1-0.2 0.2-0.6 0.1-0.8-0.1s-0.3-0.6 0-0.9c0.7-0.6 1.5-1 2.5-1.2v-5.7l-5.1 2.8c0.3 0.9 0.3 1.8 0.2 2.7-0.1 0.3-0.4 0.7-0.7 0.6s-0.7-0.5-0.6-0.8c0.2-0.6 0.2-1.2 0-1.9l-2.3 1.4c-0.3 0.1-0.7 0-0.8-0.3s-0.1-0.7 0.2-0.8l2.3-1.3c-0.5-0.5-1-0.8-1.7-1-0.3-0.1-0.4-0.5-0.4-0.8 0.2-0.3 0.5-0.5 0.8-0.4 1 0.3 1.7 0.9 2.4 1.5l5.1-2.8-5.1-2.9c-0.7 0.7-1.4 1.2-2.4 1.5-0.3 0.1-0.7 0-0.8-0.3s0.1-0.8 0.4-0.9c0.7-0.2 1.2-0.4 1.7-0.9l-2.3-1.3c-0.3-0.1-0.4-0.5-0.2-0.8s0.5-0.4 0.8-0.3l2.3 1.3c0.2-0.6 0.2-1.2 0-1.8-0.1-0.3 0.2-0.7 0.6-0.8s0.6 0.2 0.7 0.5c0.1 0.9 0 1.9-0.2 2.8l5.1 2.8v-5.7c-1-0.2-1.8-0.6-2.5-1.2-0.3-0.3-0.3-0.7 0-0.9s0.6-0.3 0.8-0.1c0.5 0.4 1.1 0.8 1.7 1v-2.6c0-0.3 0.3-0.6 0.6-0.6s0.6 0.3 0.6 0.6v2.6c0.7-0.2 1.2-0.6 1.7-1 0.2-0.2 0.6-0.1 0.8 0.1s0.2 0.6-0.1 0.9c-0.7 0.6-1.5 1-2.4 1.2v5.7l5-2.8c-0.2-0.9-0.3-1.9-0.1-2.8 0-0.3 0.4-0.6 0.8-0.5s0.5 0.5 0.4 0.8c-0.1 0.6-0.1 1.2 0.1 1.8l2.3-1.3c0.3-0.1 0.7 0 0.8 0.3s0.1 0.7-0.2 0.8l-2.3 1.3c0.5 0.4 1 0.8 1.7 1 0.3 0.1 0.4 0.5 0.4 0.8s-0.5 0.4-0.8 0.4c-1-0.3-1.8-0.8-2.4-1.5l-5 2.8 5 2.8c0.6-0.6 1.4-1.2 2.4-1.5 0.3-0.1 0.7 0.1 0.8 0.4s-0.1 0.7-0.4 0.8c-0.7 0.2-1.2 0.5-1.7 1z"/></g>
</Icon>
)
export default IoIosSnowy
|
ajax/libs/react-router/0.11.5/react-router.min.js | Olical/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){var LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:position?window.scrollTo(position.x,position.y):window.scrollTo(0,0)}}};module.exports=ImitateBrowserBehavior},{"../actions/LocationActions":1}],3:[function(_dereq_,module){var ScrollToTopBehavior={updateScrollPosition:function(){window.scrollTo(0,0)}};module.exports=ScrollToTopBehavior},{}],4:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),PropTypes=_dereq_("../utils/PropTypes"),DefaultRoute=React.createClass({displayName:"DefaultRoute",mixins:[FakeNode],propTypes:{name:React.PropTypes.string,path:PropTypes.falsy,handler:React.PropTypes.func.isRequired}});module.exports=DefaultRoute},{"../mixins/FakeNode":14,"../utils/PropTypes":25}],5:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,classSet=_dereq_("react/lib/cx"),assign=_dereq_("react/lib/Object.assign"),Navigation=_dereq_("../mixins/Navigation"),State=_dereq_("../mixins/State"),Link=React.createClass({displayName:"Link",mixins:[Navigation,State],propTypes:{activeClassName:React.PropTypes.string.isRequired,to:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(event){var clickResult,allowTransition=!0;this.props.onClick&&(clickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((clickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var classNames={};return this.props.className&&(classNames[this.props.className]=!0),this.isActive(this.props.to,this.props.params,this.props.query)&&(classNames[this.props.activeClassName]=!0),classSet(classNames)},render:function(){var props=assign({},this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/Navigation":15,"../mixins/State":19,"react/lib/Object.assign":40,"react/lib/cx":41}],6:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),PropTypes=_dereq_("../utils/PropTypes"),NotFoundRoute=React.createClass({displayName:"NotFoundRoute",mixins:[FakeNode],propTypes:{name:React.PropTypes.string,path:PropTypes.falsy,handler:React.PropTypes.func.isRequired}});module.exports=NotFoundRoute},{"../mixins/FakeNode":14,"../utils/PropTypes":25}],7:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),PropTypes=_dereq_("../utils/PropTypes"),Redirect=React.createClass({displayName:"Redirect",mixins:[FakeNode],propTypes:{path:React.PropTypes.string,from:React.PropTypes.string,to:React.PropTypes.string,handler:PropTypes.falsy}});module.exports=Redirect},{"../mixins/FakeNode":14,"../utils/PropTypes":25}],8:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,FakeNode=_dereq_("../mixins/FakeNode"),Route=React.createClass({displayName:"Route",mixins:[FakeNode],propTypes:{name:React.PropTypes.string,path:React.PropTypes.string,handler:React.PropTypes.func.isRequired,ignoreScrollBehavior:React.PropTypes.bool}});module.exports=Route},{"../mixins/FakeNode":14}],9:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,RouteHandlerMixin=_dereq_("../mixins/RouteHandler"),RouteHandler=React.createClass({displayName:"RouteHandler",mixins:[RouteHandlerMixin],getDefaultProps:function(){return{ref:"__routeHandler__"}},render:function(){return this.getRouteHandler()}});module.exports=RouteHandler},{"../mixins/RouteHandler":17}],10:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.RouteHandler=_dereq_("./components/RouteHandler"),exports.HashLocation=_dereq_("./locations/HashLocation"),exports.HistoryLocation=_dereq_("./locations/HistoryLocation"),exports.RefreshLocation=_dereq_("./locations/RefreshLocation"),exports.ImitateBrowserBehavior=_dereq_("./behaviors/ImitateBrowserBehavior"),exports.ScrollToTopBehavior=_dereq_("./behaviors/ScrollToTopBehavior"),exports.Navigation=_dereq_("./mixins/Navigation"),exports.State=_dereq_("./mixins/State"),exports.create=_dereq_("./utils/createRouter"),exports.run=_dereq_("./utils/runRouter"),exports.History=_dereq_("./utils/History")},{"./behaviors/ImitateBrowserBehavior":2,"./behaviors/ScrollToTopBehavior":3,"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/RouteHandler":9,"./locations/HashLocation":11,"./locations/HistoryLocation":12,"./locations/RefreshLocation":13,"./mixins/Navigation":15,"./mixins/State":19,"./utils/History":22,"./utils/createRouter":28,"./utils/runRouter":32}],11:[function(_dereq_,module){function getHashPath(){return Path.decode(window.location.href.split("#")[1]||"")}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function notifyChange(type){type===LocationActions.PUSH&&(History.length+=1);var change={path:getHashPath(),type:type};_changeListeners.forEach(function(listener){listener(change)})}function onHashChange(){ensureSlash()&&(notifyChange(_actionType||LocationActions.POP),_actionType=null)}var _actionType,LocationActions=_dereq_("../actions/LocationActions"),History=_dereq_("../utils/History"),Path=_dereq_("../utils/Path"),_changeListeners=[],_isListening=!1,HashLocation={addChangeListener:function(listener){_changeListeners.push(listener),ensureSlash(),_isListening||(window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange),_isListening=!0)},removeChangeListener:function(listener){for(var i=0,l=_changeListeners.length;l>i;i++)if(_changeListeners[i]===listener){_changeListeners.splice(i,1);break}window.removeEventListener?window.removeEventListener("hashchange",onHashChange,!1):window.removeEvent("onhashchange",onHashChange),0===_changeListeners.length&&(_isListening=!1)},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=Path.encode(path)},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(window.location.pathname+"#"+Path.encode(path))},pop:function(){_actionType=LocationActions.POP,History.back()},getCurrentPath:getHashPath,toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../utils/History":22,"../utils/Path":23}],12:[function(_dereq_,module){function getWindowPath(){return Path.decode(window.location.pathname+window.location.search)}function notifyChange(type){var change={path:getWindowPath(),type:type};_changeListeners.forEach(function(listener){listener(change)})}function onPopState(){notifyChange(LocationActions.POP)}var LocationActions=_dereq_("../actions/LocationActions"),History=_dereq_("../utils/History"),Path=_dereq_("../utils/Path"),_changeListeners=[],_isListening=!1,HistoryLocation={addChangeListener:function(listener){_changeListeners.push(listener),_isListening||(window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState),_isListening=!0)},removeChangeListener:function(listener){for(var i=0,l=_changeListeners.length;l>i;i++)if(_changeListeners[i]===listener){_changeListeners.splice(i,1);break}window.addEventListener?window.removeEventListener("popstate",onPopState):window.removeEvent("popstate",onPopState),0===_changeListeners.length&&(_isListening=!1)},push:function(path){window.history.pushState({path:path},"",Path.encode(path)),History.length+=1,notifyChange(LocationActions.PUSH)},replace:function(path){window.history.replaceState({path:path},"",Path.encode(path)),notifyChange(LocationActions.REPLACE)},pop:function(){History.back()},getCurrentPath:getWindowPath,toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../utils/History":22,"../utils/Path":23}],13:[function(_dereq_,module){var HistoryLocation=_dereq_("./HistoryLocation"),History=_dereq_("../utils/History"),Path=_dereq_("../utils/Path"),RefreshLocation={push:function(path){window.location=Path.encode(path)},replace:function(path){window.location.replace(Path.encode(path))},pop:History.back,getCurrentPath:HistoryLocation.getCurrentPath,toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../utils/History":22,"../utils/Path":23,"./HistoryLocation":12}],14:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),FakeNode={render:function(){invariant(!1,"%s elements should not be rendered",this.constructor.displayName)}};module.exports=FakeNode},{"react/lib/invariant":43}],15:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Navigation={contextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},makePath:function(to,params,query){return this.context.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.makeHref(to,params,query)},transitionTo:function(to,params,query){this.context.transitionTo(to,params,query)},replaceWith:function(to,params,query){this.context.replaceWith(to,params,query)},goBack:function(){this.context.goBack()}};module.exports=Navigation},{}],16:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,NavigationContext={childContextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},getChildContext:function(){return{makePath:this.constructor.makePath,makeHref:this.constructor.makeHref,transitionTo:this.constructor.transitionTo,replaceWith:this.constructor.replaceWith,goBack:this.constructor.goBack}}};module.exports=NavigationContext},{}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null;module.exports={contextTypes:{getRouteAtDepth:React.PropTypes.func.isRequired,getRouteComponents:React.PropTypes.func.isRequired,routeHandlers:React.PropTypes.array.isRequired},childContextTypes:{routeHandlers:React.PropTypes.array.isRequired},getChildContext:function(){return{routeHandlers:this.context.routeHandlers.concat([this])}},getRouteDepth:function(){return this.context.routeHandlers.length-1},componentDidMount:function(){this._updateRouteComponent()},componentDidUpdate:function(){this._updateRouteComponent()},_updateRouteComponent:function(){var depth=this.getRouteDepth(),components=this.context.getRouteComponents();components[depth]=this.refs[this.props.ref||"__routeHandler__"]},getRouteHandler:function(props){var route=this.context.getRouteAtDepth(this.getRouteDepth());return route?React.createElement(route.handler,props||this.props):null}}},{}],18:[function(_dereq_,module){function shouldUpdateScroll(state,prevState){if(!prevState)return!0;if(state.pathname===prevState.pathname)return!1;var routes=state.routes,prevRoutes=prevState.routes,sharedAncestorRoutes=routes.filter(function(route){return-1!==prevRoutes.indexOf(route)});return!sharedAncestorRoutes.some(function(route){return route.ignoreScrollBehavior})}var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,getWindowScrollPosition=_dereq_("../utils/getWindowScrollPosition"),Scrolling={statics:{recordScrollPosition:function(path){this.scrollHistory||(this.scrollHistory={}),this.scrollHistory[path]=getWindowScrollPosition()},getScrollPosition:function(path){return this.scrollHistory||(this.scrollHistory={}),this.scrollHistory[path]||null}},componentWillMount:function(){invariant(null==this.getScrollBehavior()||canUseDOM,"Cannot use scroll behavior without a DOM")},componentDidMount:function(){this._updateScroll()},componentDidUpdate:function(prevProps,prevState){this._updateScroll(prevState)},_updateScroll:function(prevState){if(shouldUpdateScroll(this.state,prevState)){var scrollBehavior=this.getScrollBehavior();scrollBehavior&&scrollBehavior.updateScrollPosition(this.constructor.getScrollPosition(this.state.path),this.state.action)}}};module.exports=Scrolling},{"../utils/getWindowScrollPosition":30,"react/lib/ExecutionEnvironment":39,"react/lib/invariant":43}],19:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,State={contextTypes:{getCurrentPath:React.PropTypes.func.isRequired,getCurrentRoutes:React.PropTypes.func.isRequired,getCurrentPathname:React.PropTypes.func.isRequired,getCurrentParams:React.PropTypes.func.isRequired,getCurrentQuery:React.PropTypes.func.isRequired,isActive:React.PropTypes.func.isRequired},getPath:function(){return this.context.getCurrentPath()},getRoutes:function(){return this.context.getCurrentRoutes()},getPathname:function(){return this.context.getCurrentPathname()},getParams:function(){return this.context.getCurrentParams()},getQuery:function(){return this.context.getCurrentQuery()},isActive:function(to,params,query){return this.context.isActive(to,params,query)}};module.exports=State},{}],20:[function(_dereq_,module){function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,assign=_dereq_("react/lib/Object.assign"),Path=_dereq_("../utils/Path"),StateContext={getCurrentPath:function(){return this.state.path},getCurrentRoutes:function(){return this.state.routes.slice(0)},getCurrentPathname:function(){return this.state.pathname},getCurrentParams:function(){return assign({},this.state.params)},getCurrentQuery:function(){return assign({},this.state.query)},isActive:function(to,params,query){return Path.isAbsolute(to)?to===this.state.path:routeIsActive(this.state.routes,to)&¶msAreActive(this.state.params,params)&&(null==query||queryIsActive(this.state.query,query))},childContextTypes:{getCurrentPath:React.PropTypes.func.isRequired,getCurrentRoutes:React.PropTypes.func.isRequired,getCurrentPathname:React.PropTypes.func.isRequired,getCurrentParams:React.PropTypes.func.isRequired,getCurrentQuery:React.PropTypes.func.isRequired,isActive:React.PropTypes.func.isRequired},getChildContext:function(){return{getCurrentPath:this.getCurrentPath,getCurrentRoutes:this.getCurrentRoutes,getCurrentPathname:this.getCurrentPathname,getCurrentParams:this.getCurrentParams,getCurrentQuery:this.getCurrentQuery,isActive:this.isActive}}};module.exports=StateContext},{"../utils/Path":23,"react/lib/Object.assign":40}],21:[function(_dereq_,module){function Cancellation(){}module.exports=Cancellation},{}],22:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,History={back:function(){invariant(canUseDOM,"Cannot use History.back without a DOM"),History.length-=1,window.history.back()},length:1};module.exports=History},{"react/lib/ExecutionEnvironment":39,"react/lib/invariant":43}],23:[function(_dereq_,module){function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramCompileMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramCompileMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,paramInjectMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g,paramInjectTrailingSlashMatcher=/\/\/\?|\/\?/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={decode:function(path){return decodeURI(path.replace(/\+/g," "))},encode:function(path){return encodeURI(path).replace(/%20/g,"+")},extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=path.match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramInjectMatcher,function(match,paramName){if(paramName=paramName||"splat","?"!==paramName.slice(-1))invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');else if(paramName=paramName.slice(0,-1),null==params[paramName])return"";var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],segment}).replace(paramInjectTrailingSlashMatcher,"/")},extractQuery:function(path){var match=path.match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path},isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:34,"qs/lib/utils":38,"react/lib/invariant":43}],24:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":45}],25:[function(_dereq_,module){var PropTypes={falsy:function(props,propName,componentName){return props[propName]?new Error("<"+componentName+'> may not have a "'+propName+'" prop'):void 0}};module.exports=PropTypes},{}],26:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],27:[function(_dereq_,module){function runHooks(hooks,callback){var promise;try{promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function runTransitionFromHooks(transition,routes,components,callback){components=reversedArray(components);var hooks=reversedArray(routes).map(function(route,index){return function(){var handler=route.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,components[index]);var promise=transition._promise;return transition._promise=null,promise}});runHooks(hooks,callback)}function runTransitionToHooks(transition,routes,params,query,callback){var hooks=routes.map(function(route){return function(){var handler=route.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,params,query);var promise=transition._promise;return transition._promise=null,promise}});runHooks(hooks,callback)}function Transition(path,retry){this.path=path,this.abortReason=null,this.isAborted=!1,this.retry=retry.bind(this),this._promise=null}var assign=_dereq_("react/lib/Object.assign"),reversedArray=_dereq_("./reversedArray"),Redirect=_dereq_("./Redirect"),Promise=_dereq_("./Promise");assign(Transition.prototype,{abort:function(reason){this.isAborted||(this.abortReason=reason,this.isAborted=!0)},redirect:function(to,params,query){this.abort(new Redirect(to,params,query))},wait:function(value){this._promise=Promise.resolve(value)},from:function(routes,components,callback){return runTransitionFromHooks(this,routes,components,callback)},to:function(routes,params,query,callback){return runTransitionToHooks(this,routes,params,query,callback)}}),module.exports=Transition},{"./Promise":24,"./Redirect":26,"./reversedArray":31,"react/lib/Object.assign":40}],28:[function(_dereq_,module){function defaultErrorHandler(error){throw error}function defaultAbortHandler(abortReason,location){if("string"==typeof location)throw new Error("Unhandled aborted transition! Reason: "+abortReason);abortReason instanceof Cancellation||(abortReason instanceof Redirect?location.replace(this.makePath(abortReason.to,abortReason.params,abortReason.query)):location.pop())}function findMatch(pathname,routes,defaultRoute,notFoundRoute){for(var match,route,params,i=0,len=routes.length;len>i;++i){if(route=routes[i],match=findMatch(pathname,route.childRoutes,route.defaultRoute,route.notFoundRoute),null!=match)return match.routes.unshift(route),match;if(params=Path.extractParams(route.path,pathname))return createMatch(route,params)}return defaultRoute&&(params=Path.extractParams(defaultRoute.path,pathname))?createMatch(defaultRoute,params):notFoundRoute&&(params=Path.extractParams(notFoundRoute.path,pathname))?createMatch(notFoundRoute,params):match}function createMatch(route,params){return{routes:[route],params:params}}function hasMatch(routes,route,prevParams,nextParams){return routes.some(function(r){if(r!==route)return!1;for(var paramName,paramNames=route.paramNames,i=0,len=paramNames.length;len>i;++i)if(paramName=paramNames[i],nextParams[paramName]!==prevParams[paramName])return!1;return!0})}function createRouter(options){function updateState(){state=nextState,nextState={}}options=options||{},"function"==typeof options?options={routes:options}:Array.isArray(options)&&(options={routes:options});var routes=[],namedRoutes={},components=[],location=options.location||DEFAULT_LOCATION,scrollBehavior=options.scrollBehavior||DEFAULT_SCROLL_BEHAVIOR,onError=options.onError||defaultErrorHandler,onAbort=options.onAbort||defaultAbortHandler,state={},nextState={},pendingTransition=null;location!==HistoryLocation||supportsHistory()||(location=RefreshLocation);var router=React.createClass({displayName:"Router",mixins:[NavigationContext,StateContext,Scrolling],statics:{defaultRoute:null,notFoundRoute:null,addRoutes:function(children){routes.push.apply(routes,createRoutesFromChildren(children,this,namedRoutes))},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var route=namedRoutes[to];invariant(route,'Unable to find <Route name="%s">',to),path=route.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return location===HashLocation?"#"+path:path},transitionTo:function(to,params,query){invariant("string"!=typeof location,"You cannot use transitionTo with a static location");var path=this.makePath(to,params,query);pendingTransition?location.replace(path):location.push(path)},replaceWith:function(to,params,query){invariant("string"!=typeof location,"You cannot use replaceWith with a static location"),location.replace(this.makePath(to,params,query))},goBack:function(){return invariant("string"!=typeof location,"You cannot use goBack with a static location"),History.length>1?(location.pop(),!0):(warning(!1,"goBack() was ignored because there is no router history"),!1)},match:function(pathname){return findMatch(pathname,routes,this.defaultRoute,this.notFoundRoute)||null},dispatch:function(path,action,callback){pendingTransition&&(pendingTransition.abort(new Cancellation),pendingTransition=null);var prevPath=state.path;if(prevPath!==path){prevPath&&action!==LocationActions.REPLACE&&this.recordScrollPosition(prevPath);var pathname=Path.withoutQuery(path),match=this.match(pathname);warning(null!=match,'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your routes',path,path),null==match&&(match={});var fromRoutes,toRoutes,prevRoutes=state.routes||[],prevParams=state.params||{},nextRoutes=match.routes||[],nextParams=match.params||{},nextQuery=Path.extractQuery(path)||{};if(prevRoutes.length?(fromRoutes=prevRoutes.filter(function(route){return!hasMatch(nextRoutes,route,prevParams,nextParams)}),toRoutes=nextRoutes.filter(function(route){return!hasMatch(prevRoutes,route,prevParams,nextParams)})):(fromRoutes=[],toRoutes=nextRoutes),!toRoutes.length&&!fromRoutes.length){var currentRoute=state.routes[state.routes.length-1];fromRoutes=[currentRoute],toRoutes=[currentRoute]}var transition=new Transition(path,this.replaceWith.bind(this,path));pendingTransition=transition,transition.from(fromRoutes,components,function(error){return error||transition.isAborted?callback.call(router,error,transition):void transition.to(toRoutes,nextParams,nextQuery,function(error){return error||transition.isAborted?callback.call(router,error,transition):(nextState.path=path,nextState.action=action,nextState.pathname=pathname,nextState.routes=nextRoutes,nextState.params=nextParams,nextState.query=nextQuery,void callback.call(router,null,transition))})})}},run:function(callback){var dispatchHandler=function(error,transition){pendingTransition=null,error?onError.call(router,error):transition.isAborted?onAbort.call(router,transition.abortReason,location):callback.call(router,router,nextState)};if("string"==typeof location)warning(!canUseDOM||!1,"You should not use a static location in a DOM environment because the router will not be kept in sync with the current URL"),router.dispatch(location,null,dispatchHandler);else{invariant(canUseDOM,"You cannot use %s in a non-DOM environment",location);var changeListener=function(change){router.dispatch(change.path,change.type,dispatchHandler)};location.addChangeListener&&location.addChangeListener(changeListener),router.dispatch(location.getCurrentPath(),null,dispatchHandler)}},teardown:function(){location.removeChangeListener(this.changeListener)}},propTypes:{children:PropTypes.falsy},getLocation:function(){return location},getScrollBehavior:function(){return scrollBehavior},getRouteAtDepth:function(depth){var routes=this.state.routes;return routes&&routes[depth]},getRouteComponents:function(){return components},getInitialState:function(){return updateState(),state},componentWillReceiveProps:function(){updateState(),this.setState(state)},componentWillUnmount:function(){router.teardown()},render:function(){return this.getRouteAtDepth(0)?React.createElement(RouteHandler,this.props):null},childContextTypes:{getRouteAtDepth:React.PropTypes.func.isRequired,getRouteComponents:React.PropTypes.func.isRequired,routeHandlers:React.PropTypes.array.isRequired},getChildContext:function(){return{getRouteComponents:this.getRouteComponents,getRouteAtDepth:this.getRouteAtDepth,routeHandlers:[this]}}});return options.routes&&router.addRoutes(options.routes),router}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,ImitateBrowserBehavior=_dereq_("../behaviors/ImitateBrowserBehavior"),RouteHandler=_dereq_("../components/RouteHandler"),LocationActions=_dereq_("../actions/LocationActions"),HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),RefreshLocation=_dereq_("../locations/RefreshLocation"),NavigationContext=_dereq_("../mixins/NavigationContext"),StateContext=_dereq_("../mixins/StateContext"),Scrolling=_dereq_("../mixins/Scrolling"),createRoutesFromChildren=_dereq_("./createRoutesFromChildren"),supportsHistory=_dereq_("./supportsHistory"),Transition=_dereq_("./Transition"),PropTypes=_dereq_("./PropTypes"),Redirect=_dereq_("./Redirect"),History=_dereq_("./History"),Cancellation=_dereq_("./Cancellation"),Path=_dereq_("./Path"),DEFAULT_LOCATION=canUseDOM?HashLocation:"/",DEFAULT_SCROLL_BEHAVIOR=canUseDOM?ImitateBrowserBehavior:null;module.exports=createRouter},{"../actions/LocationActions":1,"../behaviors/ImitateBrowserBehavior":2,"../components/RouteHandler":9,"../locations/HashLocation":11,"../locations/HistoryLocation":12,"../locations/RefreshLocation":13,"../mixins/NavigationContext":16,"../mixins/Scrolling":18,"../mixins/StateContext":20,"./Cancellation":21,"./History":22,"./Path":23,"./PropTypes":25,"./Redirect":26,"./Transition":27,"./createRoutesFromChildren":29,"./supportsHistory":33,"react/lib/ExecutionEnvironment":39,"react/lib/invariant":43,"react/lib/warning":44}],29:[function(_dereq_,module){function createRedirectHandler(to,_params,_query){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,_params||params,_query||query)}},render:function(){return null}})}function checkPropTypes(componentName,propTypes,props){for(var propName in propTypes)if(propTypes.hasOwnProperty(propName)){var error=propTypes[propName](props,propName,componentName);error instanceof Error&&warning(!1,error.message)}}function createRoute(element,parentRoute,namedRoutes){var type=element.type,props=element.props,componentName=type&&type.displayName||"UnknownComponent";invariant(-1!==CONFIG_ELEMENT_TYPES.indexOf(type),'Unrecognized route configuration element "<%s>"',componentName),type.propTypes&&checkPropTypes(componentName,type.propTypes,props);var route={name:props.name};props.ignoreScrollBehavior&&(route.ignoreScrollBehavior=!0),type===Redirect.type?(route.handler=createRedirectHandler(props.to,props.params,props.query),props.path=props.path||props.from||"*"):route.handler=props.handler;var parentPath=parentRoute&&parentRoute.path||"/";
if((props.path||props.name)&&type!==DefaultRoute.type&&type!==NotFoundRoute.type){var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),route.path=Path.normalize(path)}else route.path=parentPath,type===NotFoundRoute.type&&(route.path+="*");return route.paramNames=Path.extractParamNames(route.path),parentRoute&&Array.isArray(parentRoute.paramNames)&&parentRoute.paramNames.forEach(function(paramName){invariant(-1!==route.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',route.path,paramName,parentRoute.path)}),props.name&&(invariant(null==namedRoutes[props.name],'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route),type===NotFoundRoute.type?(invariant(parentRoute,"<NotFoundRoute> must have a parent <Route>"),invariant(null==parentRoute.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),parentRoute.notFoundRoute=route,null):type===DefaultRoute.type?(invariant(parentRoute,"<DefaultRoute> must have a parent <Route>"),invariant(null==parentRoute.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),parentRoute.defaultRoute=route,null):(route.childRoutes=createRoutesFromChildren(props.children,route,namedRoutes),route)}function createRoutesFromChildren(children,parentRoute,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=createRoute(child,parentRoute,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),DefaultRoute=_dereq_("../components/DefaultRoute"),NotFoundRoute=_dereq_("../components/NotFoundRoute"),Redirect=_dereq_("../components/Redirect"),Route=_dereq_("../components/Route"),Path=_dereq_("./Path"),CONFIG_ELEMENT_TYPES=[DefaultRoute.type,NotFoundRoute.type,Redirect.type,Route.type];module.exports=createRoutesFromChildren},{"../components/DefaultRoute":4,"../components/NotFoundRoute":6,"../components/Redirect":7,"../components/Route":8,"./Path":23,"react/lib/invariant":43,"react/lib/warning":44}],30:[function(_dereq_,module){function getWindowScrollPosition(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}}var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM;module.exports=getWindowScrollPosition},{"react/lib/ExecutionEnvironment":39,"react/lib/invariant":43}],31:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],32:[function(_dereq_,module){function runRouter(routes,location,callback){"function"==typeof location&&(callback=location,location=null);var router=createRouter({routes:routes,location:location});return router.run(callback),router}var createRouter=_dereq_("./createRouter");module.exports=runRouter},{"./createRouter":28}],33:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")||-1!==ua.indexOf("Windows Phone")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],34:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":35}],35:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse");module.exports={stringify:Stringify,parse:Parse}},{"./parse":36,"./stringify":37}],36:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":38}],37:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":38}],38:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],39:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],40:[function(_dereq_,module){function assign(target){if(null==target)throw new TypeError("Object.assign target cannot be null or undefined");for(var to=Object(target),hasOwnProperty=Object.prototype.hasOwnProperty,nextIndex=1;nextIndex<arguments.length;nextIndex++){var nextSource=arguments[nextIndex];if(null!=nextSource){var from=Object(nextSource);for(var key in from)hasOwnProperty.call(from,key)&&(to[key]=from[key])}}return to}module.exports=assign},{}],41:[function(_dereq_,module){function cx(classNames){return"object"==typeof classNames?Object.keys(classNames).filter(function(className){return classNames[className]}).join(" "):Array.prototype.join.call(arguments," ")}module.exports=cx},{}],42:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}emptyFunction.thatReturns=makeEmptyFunction,emptyFunction.thatReturnsFalse=makeEmptyFunction(!1),emptyFunction.thatReturnsTrue=makeEmptyFunction(!0),emptyFunction.thatReturnsNull=makeEmptyFunction(null),emptyFunction.thatReturnsThis=function(){return this},emptyFunction.thatReturnsArgument=function(arg){return arg},module.exports=emptyFunction},{}],43:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)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],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],44:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":42}],45:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":47,"./async":48,"./makePromise":49}],46:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],47:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":46}],48:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],49:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state();if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to)},Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[10])(10)}); |
examples/shared-root/app.js | amsardesai/react-router | import React from 'react';
import HashHistory from 'react-router/lib/HashHistory';
import { Router, Route, Link } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
<p>
This illustrates how routes can share UI w/o sharing the url,
when routes have no path, they never match themselves but their
children can, allowing "/signin" and "/forgot-password" to both
be render in the <code>SignedOut</code> component.
</p>
<ol>
<li><Link to="/home">Home</Link></li>
<li><Link to="/signin">Sign in</Link></li>
<li><Link to="/forgot-password">Forgot Password</Link></li>
</ol>
{this.props.children}
</div>
);
}
});
var SignedIn = React.createClass({
render() {
return (
<div>
<h2>Signed In</h2>
{this.props.children}
</div>
);
}
});
var Home = React.createClass({
render() {
return (
<h3>Welcome home!</h3>
);
}
});
var SignedOut = React.createClass({
render() {
return (
<div>
<h2>Signed Out</h2>
{this.props.children}
</div>
);
}
});
var SignIn = React.createClass({
render() {
return (
<h3>Please sign in.</h3>
);
}
});
var ForgotPassword = React.createClass({
render() {
return (
<h3>Forgot your password?</h3>
);
}
});
React.render((
<Router history={new HashHistory}>
<Route path="/" component={App}>
<Route component={SignedOut}>
<Route path="signin" component={SignIn}/>
<Route path="forgot-password" component={ForgotPassword}/>
</Route>
<Route component={SignedIn}>
<Route path="home" component={Home}/>
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
eventkit_cloud/ui/static/ui/app/containers/loginContainer.js | terranodo/eventkit-cloud | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { withTheme } from '@material-ui/core/styles';
import axios from 'axios';
import Button from '@material-ui/core/Button';
import { login } from '../actions/userActions';
export class Form extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.getErrorMessage = this.getErrorMessage.bind(this);
this.state = {
username: '',
password: '',
buttonDisabled: true,
loginForm: false,
oauthName: '',
};
}
componentDidMount() {
this.checkAuthEndpoint();
this.checkOAuthEndpoint();
}
onChange(event) {
this.setState({ [event.target.name]: event.target.value }, () => {
if (!this.state.username || !this.state.password) {
if (!this.state.buttonDisabled) {
this.setState({ buttonDisabled: true });
}
} else if (this.state.buttonDisabled) {
this.setState({ buttonDisabled: false });
}
});
}
getErrorMessage() {
if (!this.props.error) {
return '';
}
const { statusCode, authType } = { ...this.props.error };
if (statusCode === 401) {
if (authType === 'auth') {
return 'Username or Password incorrect.';
}
return 'Authentication failed. Please try again or contact an administrator.';
}
return 'An unknown error occurred. Please contact an administrator.';
}
checkAuthEndpoint() {
return axios.get('/auth').then(() => {
this.setState({ loginForm: true });
}).catch(() => {
});
}
checkOAuthEndpoint() {
return axios.get('/oauth', { params: { query: 'name' } }).then((response) => {
this.setState({ oauthName: response.data.name });
}).catch(() => {
});
}
handleSubmit(event) {
event.preventDefault();
this.props.handleLogin(this.state, (this.props.location ? this.props.location.search : ''));
}
handleOAuth(event) {
event.preventDefault();
window.location.assign('/oauth');
}
render() {
const { colors } = this.props.theme.eventkit;
const styles = {
form: {
verticalAlign: 'middle',
margin: '0 auto',
maxWidth: 300,
},
heading: {
width: '100%',
fontSize: '20px',
fontWeight: 'bold',
color: colors.white,
margin: '15px auto 0px auto',
},
input: {
borderRadius: '0px',
outline: 'none',
border: 'none',
backgroundColor: `${colors.secondary}33`,
fontSize: '16px',
width: '100%',
height: '45px',
color: colors.white,
margin: '0px auto 15px auto',
padding: '10px',
},
};
let loginForm = '';
let oauthButton = '';
if (this.state.loginForm) {
loginForm = (
<form onSubmit={this.handleSubmit} onChange={this.onChange} style={styles.form}>
<div style={styles.heading}>Enter Login Information</div>
<input
id="username"
name="username"
placeholder="Username"
style={styles.input}
type="text"
maxLength="150"
/>
<input
id="password"
name="password"
placeholder="Password"
onChange={this.onChange}
style={styles.input}
type="password"
maxLength="256"
/>
<Button
style={{ margin: '30px auto', width: '150px' }}
type="submit"
name="submit"
color="primary"
variant="contained"
disabled={this.state.buttonDisabled}
>
Login
</Button>
</form>
);
}
if (this.state.oauthName) {
if (!this.state.loginForm) {
oauthButton = (
<div className="qa-LoginForm-oauth">
<div style={{ margin: '40px auto', fontSize: '24px', color: colors.white }}>
<strong>Welcome to EventKit</strong>
</div>
<Button
style={{ margin: '40px auto', minWidth: '150px' }}
variant="contained"
color="primary"
onClick={this.handleOAuth}
>
{`Login with ${this.state.oauthName}`}
</Button>
</div>
);
} else {
oauthButton = (
<span
role="button"
tabIndex={0}
style={{ color: colors.primary, cursor: 'pointer', margin: '15px auto' }}
onClick={this.handleOAuth}
onKeyPress={this.handleOAuth}
className="qa-LoginForm-oauth"
>
<strong>Or, login with {this.state.oauthName}</strong>
</span>
);
}
}
return (
<div style={{ verticalAlign: 'middle', textAlign: 'center', marginTop: '30px' }}>
{this.props.error
&& (
<div style={{ color: colors.warning }}>
{this.getErrorMessage()}
</div>
)}
{loginForm}
{oauthButton}
{!loginForm && !oauthButton
? (
<div style={{ color: colors.white, marginTop: '150px' }}>
No login methods available, please contact an administrator
</div>
)
: null}
</div>
);
}
}
Form.propTypes = {
handleLogin: PropTypes.func.isRequired,
location: PropTypes.shape({
search: PropTypes.object,
}).isRequired,
theme: PropTypes.object.isRequired,
error: PropTypes.object.isRequired,
};
function mapDispatchToProps(dispatch) {
return {
handleLogin: (params, query) => {
dispatch(login(params, query));
},
};
}
function mapStateToProps(state) {
return {
error: state.user.status.error,
};
}
export default withTheme(connect(mapStateToProps, mapDispatchToProps)(Form));
|
js/jquery-1.11.0.min.js | kevteg/sistemasoperativosUNET | /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n}); |
react/features/base/react/components/native/Link.js | parisjulien/arkadin-jitsimeet | import React, { Component } from 'react';
import { Linking } from 'react-native';
import Text from './Text';
/**
* Implements a (hyper)link to a URL in the fashion of the HTML anchor element
* and its href attribute.
*/
export default class Link extends Component {
/**
* {@code Link} component's property types.
*
* @static
*/
static propTypes = {
/**
* The children to be displayed within this Link.
*/
children: React.PropTypes.node,
/**
* Notifies that this Link failed to open the URL associated with it.
*/
onLinkingOpenURLRejected: React.PropTypes.func,
/**
* The CSS style to be applied to this Link for the purposes of display.
*/
style: React.PropTypes.object,
/**
* The URL to be opened when this Link is clicked/pressed.
*/
url: React.PropTypes.string
};
/**
* Initializes a new Link instance.
*
* @param {Object} props - Component properties.
*/
constructor(props) {
super(props);
// Bind event handlers so they are only bound once for every instance.
this._onPress = this._onPress.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
return (
<Text
onPress = { this._onPress }
style = { this.props.style }>
{ this.props.children }
</Text>
);
}
/**
* Notifies this instance that Linking failed to open the associated URL.
*
* @param {any} reason - The rejection reason.
* @private
* @returns {void}
*/
_onLinkingOpenURLRejected(reason) {
const onRejected = this.props.onLinkingOpenURLRejected;
onRejected && onRejected(reason);
}
/**
* Handles press on this Link. Opens the URL associated with this Link.
*
* @private
* @returns {void}
*/
_onPress() {
Linking.openURL(this.props.url)
.catch(reason => this._onLinkingOpenURLRejected(reason));
}
}
|
tiletemplate/tests/js/templates/kissy.js | blademainer/pandao.github.io | /*
Copyright 2012, KISSY UI Library v1.20
MIT Licensed
build time: Feb 8 17:28
*/
/*
* a seed where KISSY grows up from , KISS Yeah !
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
(function (S, undefined) {
/**
* @namespace KISSY
*/
var host = this,
meta = {
/**
* Copies all the properties of s to r.
* @param deep {boolean} whether recursive mix if encounter object
* @return {Object} the augmented object
*/
mix:function (r, s, ov, wl, deep) {
if (!s || !r) {
return r;
}
if (ov === undefined) {
ov = true;
}
var i, p, len;
if (wl && (len = wl.length)) {
for (i = 0; i < len; i++) {
p = wl[i];
if (p in s) {
_mix(p, r, s, ov, deep);
}
}
} else {
for (p in s) {
_mix(p, r, s, ov, deep);
}
}
return r;
}
},
_mix = function (p, r, s, ov, deep) {
if (ov || !(p in r)) {
var target = r[p], src = s[p];
// prevent never-end loop
if (target === src) {
return;
}
// 来源是数组和对象,并且要求深度 mix
if (deep && src && (S.isArray(src) || S.isPlainObject(src))) {
// 目标值为对象或数组,直接 mix
// 否则 新建一个和源值类型一样的空数组/对象,递归 mix
var clone = target && (S.isArray(target) || S.isPlainObject(target)) ?
target :
(S.isArray(src) ? [] : {});
r[p] = S.mix(clone, src, ov, undefined, true);
} else if (src !== undefined) {
r[p] = s[p];
}
}
},
// If KISSY is already defined, the existing KISSY object will not
// be overwritten so that defined namespaces are preserved.
seed = (host && host[S]) || {},
guid = 0,
EMPTY = '';
// The host of runtime environment. specify by user's seed or <this>,
// compatibled for '<this> is null' in unknown engine.
host = seed.__HOST || (seed.__HOST = host || {});
// shortcut and meta for seed.
// override previous kissy
S = host[S] = meta.mix(seed, meta);
S.mix(S, {
configs:{},
// S.app() with these members.
__APP_MEMBERS:['namespace'],
__APP_INIT_METHODS:['__init'],
/**
* The version of the library.
* @type {String}
*/
version:'1.20',
buildTime:'20120208172832',
/**
* Returns a new object containing all of the properties of
* all the supplied objects. The properties from later objects
* will overwrite those in earlier objects. Passing in a
* single object will create a shallow copy of it.
* @return {Object} the new merged object
*/
merge:function () {
var o = {}, i, l = arguments.length;
for (i = 0; i < l; i++) {
S.mix(o, arguments[i]);
}
return o;
},
/**
* Applies prototype properties from the supplier to the receiver.
* @return {Object} the augmented object
*/
augment:function (/*r, s1, s2, ..., ov, wl*/) {
var args = S.makeArray(arguments),
len = args.length - 2,
r = args[0],
ov = args[len],
wl = args[len + 1],
i = 1;
if (!S.isArray(wl)) {
ov = wl;
wl = undefined;
len++;
}
if (!S.isBoolean(ov)) {
ov = undefined;
len++;
}
for (; i < len; i++) {
S.mix(r.prototype, args[i].prototype || args[i], ov, wl);
}
return r;
},
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
* @param r {Function} the object to modify
* @param s {Function} the object to inherit
* @param px {Object} prototype properties to add/override
* @param {Object} [sx] static properties to add/override
* @return r {Object}
*/
extend:function (r, s, px, sx) {
if (!s || !r) {
return r;
}
var create = Object.create ?
function (proto, c) {
return Object.create(proto, {
constructor:{
value:c
}
});
} :
function (proto, c) {
function F() {
}
F.prototype = proto;
var o = new F();
o.constructor = c;
return o;
},
sp = s.prototype,
rp;
// add prototype chain
rp = create(sp, r);
r.prototype = S.mix(rp, r.prototype);
r.superclass = create(sp, s);
// add prototype overrides
if (px) {
S.mix(rp, px);
}
// add object overrides
if (sx) {
S.mix(r, sx);
}
return r;
},
/****************************************************************************************
* The KISSY System Framework *
****************************************************************************************/
/**
* Initializes KISSY
*/
__init:function () {
this.Config = this.Config || {};
this.Env = this.Env || {};
// NOTICE: '@DEBUG@' will replace with '' when compressing.
// So, if loading source file, debug is on by default.
// If loading min version, debug is turned off automatically.
this.Config.debug = '@DEBUG@';
},
/**
* Returns the namespace specified and creates it if it doesn't exist. Be careful
* when naming packages. Reserved words may work in some browsers and not others.
* <code>
* S.namespace('KISSY.app'); // returns KISSY.app
* S.namespace('app.Shop'); // returns KISSY.app.Shop
* S.namespace('TB.app.Shop', true); // returns TB.app.Shop
* </code>
* @return {Object} A reference to the last namespace object created
*/
namespace:function () {
var args = S.makeArray(arguments),
l = args.length,
o = null, i, j, p,
global = (args[l - 1] === true && l--);
for (i = 0; i < l; i++) {
p = (EMPTY + args[i]).split('.');
o = global ? host : this;
for (j = (host[p[0]] === o) ? 1 : 0; j < p.length; ++j) {
o = o[p[j]] = o[p[j]] || { };
}
}
return o;
},
/**
* create app based on KISSY.
* @param name {String} the app name
* @param sx {Object} static properties to add/override
* <code>
* S.app('TB');
* TB.namespace('app'); // returns TB.app
* </code>
* @return {Object} A reference to the app global object
*/
app:function (name, sx) {
var isStr = S.isString(name),
O = isStr ? host[name] || {} : name,
i = 0,
len = S.__APP_INIT_METHODS.length;
S.mix(O, this, true, S.__APP_MEMBERS);
for (; i < len; i++) {
S[S.__APP_INIT_METHODS[i]].call(O);
}
S.mix(O, S.isFunction(sx) ? sx() : sx);
isStr && (host[name] = O);
return O;
},
config:function (c) {
var configs, cfg, r;
for (var p in c) {
if (c.hasOwnProperty(p)) {
if ((configs = this['configs']) &&
(cfg = configs[p])) {
r = cfg(c[p]);
}
}
}
return r;
},
/**
* Prints debug info.
* @param msg {String} the message to log.
* @param {String} [cat] the log category for the message. Default
* categories are "info", "warn", "error", "time" etc.
* @param {String} [src] the source of the the message (opt)
*/
log:function (msg, cat, src) {
if (S.Config.debug) {
if (src) {
msg = src + ': ' + msg;
}
if (host['console'] !== undefined && console.log) {
console[cat && console[cat] ? cat : 'log'](msg);
}
}
},
/**
* Throws error message.
*/
error:function (msg) {
if (S.Config.debug) {
throw msg;
}
},
/*
* Generate a global unique id.
* @param {String} [pre] guid prefix
* @return {String} the guid
*/
guid:function (pre) {
return (pre || EMPTY) + guid++;
}
});
S.__init();
return S;
})('KISSY', undefined);
/**
* @module lang
* @author lifesinger@gmail.com,yiminghe@gmail.com
* @description this code can run in any ecmascript compliant environment
*/
(function (S, undefined) {
var host = S.__HOST,
TRUE = true,
FALSE = false,
OP = Object.prototype,
toString = OP.toString,
hasOwnProperty = OP.hasOwnProperty,
AP = Array.prototype,
indexOf = AP.indexOf,
lastIndexOf = AP.lastIndexOf,
filter = AP.filter,
every = AP.every,
some = AP.some,
//reduce = AP.reduce,
trim = String.prototype.trim,
map = AP.map,
EMPTY = '',
HEX_BASE = 16,
CLONE_MARKER = '__~ks_cloned',
COMPARE_MARKER = '__~ks_compared',
STAMP_MARKER = '__~ks_stamped',
RE_TRIM = /^[\s\xa0]+|[\s\xa0]+$/g,
encode = encodeURIComponent,
decode = decodeURIComponent,
SEP = '&',
EQ = '=',
// [[Class]] -> type pairs
class2type = {},
// http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
htmlEntities = {
'&':'&',
'>':'>',
'<':'<',
'`':'`',
'/':'/',
'"':'"',
''':"'"
},
reverseEntities = {},
escapeReg,
unEscapeReg,
// - # $ ^ * ( ) + [ ] { } | \ , . ?
escapeRegExp = /[\-#$\^*()+\[\]{}|\\,.?\s]/g;
(function () {
for (var k in htmlEntities) {
if (htmlEntities.hasOwnProperty(k)) {
reverseEntities[htmlEntities[k]] = k;
}
}
})();
function getEscapeReg() {
if (escapeReg) {
return escapeReg
}
var str = EMPTY;
S.each(htmlEntities, function (entity) {
str += entity + '|';
});
str = str.slice(0, -1);
return escapeReg = new RegExp(str, "g");
}
function getUnEscapeReg() {
if (unEscapeReg) {
return unEscapeReg
}
var str = EMPTY;
S.each(reverseEntities, function (entity) {
str += entity + '|';
});
str += '&#(\\d{1,5});';
return unEscapeReg = new RegExp(str, "g");
}
function isValidParamValue(val) {
var t = typeof val;
// If the type of val is null, undefined, number, string, boolean, return true.
return nullOrUndefined(val) || (t !== 'object' && t !== 'function');
}
S.mix(S, {
/**
* stamp a object by guid
* @return guid associated with this object
*/
stamp:function (o, readOnly, marker) {
if (!o) {
return o
}
marker = marker || STAMP_MARKER;
var guid = o[marker];
if (guid) {
return guid;
} else if (!readOnly) {
try {
guid = o[marker] = S.guid(marker);
}
catch (e) {
guid = undefined;
}
}
return guid;
},
noop:function () {
},
/**
* Determine the internal JavaScript [[Class]] of an object.
*/
type:function (o) {
return nullOrUndefined(o) ?
String(o) :
class2type[toString.call(o)] || 'object';
},
isNullOrUndefined:nullOrUndefined,
isNull:function (o) {
return o === null;
},
isUndefined:function (o) {
return o === undefined;
},
/**
* Checks to see if an object is empty.
*/
isEmptyObject:function (o) {
for (var p in o) {
if (p !== undefined) {
return FALSE;
}
}
return TRUE;
},
/**
* Checks to see if an object is a plain object (created using "{}"
* or "new Object()" or "new FunctionClass()").
* Ref: http://lifesinger.org/blog/2010/12/thinking-of-isplainobject/
*/
isPlainObject:function (o) {
/**
* note by yiminghe
* isPlainObject(node=document.getElementById("xx")) -> false
* toString.call(node) : ie678 == '[object Object]',other =='[object HTMLElement]'
* 'isPrototypeOf' in node : ie678 === false ,other === true
*/
return o && toString.call(o) === '[object Object]' && 'isPrototypeOf' in o;
},
/**
* 两个目标是否内容相同
*
* @param a 比较目标1
* @param b 比较目标2
* @param [mismatchKeys] internal use
* @param [mismatchValues] internal use
*/
equals:function (a, b, /*internal use*/mismatchKeys, /*internal use*/mismatchValues) {
// inspired by jasmine
mismatchKeys = mismatchKeys || [];
mismatchValues = mismatchValues || [];
if (a === b) {
return TRUE;
}
if (a === undefined || a === null || b === undefined || b === null) {
// need type coercion
return nullOrUndefined(a) && nullOrUndefined(b);
}
if (a instanceof Date && b instanceof Date) {
return a.getTime() == b.getTime();
}
if (S.isString(a) && S.isString(b)) {
return (a == b);
}
if (S.isNumber(a) && S.isNumber(b)) {
return (a == b);
}
if (typeof a === "object" && typeof b === "object") {
return compareObjects(a, b, mismatchKeys, mismatchValues);
}
// Straight check
return (a === b);
},
/**
* Creates a deep copy of a plain object or array. Others are returned untouched.
* 稍微改改就和规范一样了 :)
* @param input
* @param {Function} filter filter function
* @refer http://www.w3.org/TR/html5/common-dom-interfaces.html#safe-passing-of-structured-data
*/
clone:function (input, filter) {
// Let memory be an association list of pairs of objects,
// initially empty. This is used to handle duplicate references.
// In each pair of objects, one is called the source object
// and the other the destination object.
var memory = {},
ret = cloneInternal(input, filter, memory);
S.each(memory, function (v) {
// 清理在源对象上做的标记
v = v.input;
if (v[CLONE_MARKER]) {
try {
delete v[CLONE_MARKER];
} catch (e) {
S.log("delete CLONE_MARKER error : ");
v[CLONE_MARKER] = undefined;
}
}
});
memory = null;
return ret;
},
/**
* Removes the whitespace from the beginning and end of a string.
*/
trim:trim ?
function (str) {
return nullOrUndefined(str) ? EMPTY : trim.call(str);
} :
function (str) {
return nullOrUndefined(str) ? EMPTY : str.toString().replace(RE_TRIM, EMPTY);
},
/**
* Substitutes keywords in a string using an object/array.
* Removes undefined keywords and ignores escaped keywords.
*/
substitute:function (str, o, regexp) {
if (!S.isString(str)
|| !S.isPlainObject(o)) {
return str;
}
return str.replace(regexp || /\\?\{([^{}]+)\}/g, function (match, name) {
if (match.charAt(0) === '\\') {
return match.slice(1);
}
return (o[name] === undefined) ? EMPTY : o[name];
});
},
/**
* Executes the supplied function on each item in the array.
* @param object {Object} the object to iterate
* @param fn {Function} the function to execute on each item. The function
* receives three arguments: the value, the index, the full array.
* @param {Object} [context]
*/
each:function (object, fn, context) {
if (object) {
var key,
val,
i = 0,
length = object && object.length,
isObj = length === undefined || S.type(object) === 'function';
context = context || host;
if (isObj) {
for (key in object) {
// can not use hasOwnProperty
if (fn.call(context, object[key], key, object) === FALSE) {
break;
}
}
} else {
for (val = object[0];
i < length && fn.call(context, val, i, object) !== FALSE; val = object[++i]) {
}
}
}
return object;
},
/**
* Search for a specified value within an array.
*/
indexOf:indexOf ?
function (item, arr) {
return indexOf.call(arr, item);
} :
function (item, arr) {
for (var i = 0, len = arr.length; i < len; ++i) {
if (arr[i] === item) {
return i;
}
}
return -1;
},
/**
* Returns the index of the last item in the array
* that contains the specified value, -1 if the
* value isn't found.
*/
lastIndexOf:(lastIndexOf) ?
function (item, arr) {
return lastIndexOf.call(arr, item);
} :
function (item, arr) {
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] === item) {
break;
}
}
return i;
},
/**
* Returns a copy of the array with the duplicate entries removed
* @param a {Array} the array to find the subset of uniques for
* @param override {Boolean}
* if override is true, S.unique([a, b, a]) => [b, a]
* if override is false, S.unique([a, b, a]) => [a, b]
* @return {Array} a copy of the array with duplicate entries removed
*/
unique:function (a, override) {
var b = a.slice();
if (override) {
b.reverse();
}
var i = 0,
n,
item;
while (i < b.length) {
item = b[i];
while ((n = S.lastIndexOf(item, b)) !== i) {
b.splice(n, 1);
}
i += 1;
}
if (override) {
b.reverse();
}
return b;
},
/**
* Search for a specified value index within an array.
*/
inArray:function (item, arr) {
return S.indexOf(item, arr) > -1;
},
/**
* Executes the supplied function on each item in the array.
* Returns a new array containing the items that the supplied
* function returned true for.
* @param arr {Array} the array to iterate
* @param fn {Function} the function to execute on each item
* @param context {Object} optional context object
* @return {Array} The items on which the supplied function
* returned true. If no items matched an empty array is
* returned.
*/
filter:filter ?
function (arr, fn, context) {
return filter.call(arr, fn, context || this);
} :
function (arr, fn, context) {
var ret = [];
S.each(arr, function (item, i, arr) {
if (fn.call(context || this, item, i, arr)) {
ret.push(item);
}
});
return ret;
},
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
map:map ?
function (arr, fn, context) {
return map.call(arr, fn, context || this);
} :
function (arr, fn, context) {
var len = arr.length,
res = new Array(len);
for (var i = 0; i < len; i++) {
var el = S.isString(arr) ? arr.charAt(i) : arr[i];
if (el
||
//ie<9 in invalid when typeof arr == string
i in arr) {
res[i] = fn.call(context || this, el, i, arr);
}
}
return res;
},
/**
* @refer https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/reduce
*/
reduce:/*
NaN ?
reduce ? function(arr, callback, initialValue) {
return arr.reduce(callback, initialValue);
} : */function (arr, callback, initialValue) {
var len = arr.length;
if (typeof callback !== "function") {
throw new TypeError("callback is not function!");
}
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length == 2) {
throw new TypeError("arguments invalid");
}
var k = 0;
var accumulator;
if (arguments.length >= 3) {
accumulator = arguments[2];
}
else {
do {
if (k in arr) {
accumulator = arr[k++];
break;
}
// if array contains no values, no initial value to return
k += 1;
if (k >= len) {
throw new TypeError();
}
}
while (TRUE);
}
while (k < len) {
if (k in arr) {
accumulator = callback.call(undefined, accumulator, arr[k], k, arr);
}
k++;
}
return accumulator;
},
every:every ?
function (arr, fn, context) {
return every.call(arr, fn, context || this);
} :
function (arr, fn, context) {
var len = arr && arr.length || 0;
for (var i = 0; i < len; i++) {
if (i in arr && !fn.call(context, arr[i], i, arr)) {
return FALSE;
}
}
return TRUE;
},
some:some ?
function (arr, fn, context) {
return some.call(arr, fn, context || this);
} :
function (arr, fn, context) {
var len = arr && arr.length || 0;
for (var i = 0; i < len; i++) {
if (i in arr && fn.call(context, arr[i], i, arr)) {
return TRUE;
}
}
return FALSE;
},
/**
* it is not same with native bind
* @refer https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
*/
bind:function (fn, obj) {
var slice = [].slice,
args = slice.call(arguments, 2),
fNOP = function () {
},
bound = function () {
return fn.apply(this instanceof fNOP ? this : obj,
args.concat(slice.call(arguments)));
};
fNOP.prototype = fn.prototype;
bound.prototype = new fNOP();
return bound;
},
/**
* Gets current date in milliseconds.
* @refer https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now
* http://j-query.blogspot.com/2011/02/timing-ecmascript-5-datenow-function.html
* http://kangax.github.com/es5-compat-table/
*/
now:Date.now || function () {
return +new Date();
},
/**
* frequently used in taobao cookie about nick
*/
fromUnicode:function (str) {
return str.replace(/\\u([a-f\d]{4})/ig, function (m, u) {
return String.fromCharCode(parseInt(u, HEX_BASE));
});
},
/**
* escape string to html
* @refer http://yiminghe.javaeye.com/blog/788929
* http://wonko.com/post/html-escaping
* @param str {string} text2html show
*/
escapeHTML:function (str) {
return str.replace(getEscapeReg(), function (m) {
return reverseEntities[m];
});
},
escapeRegExp:function (str) {
return str.replace(escapeRegExp, '\\$&');
},
/**
* unescape html to string
* @param str {string} html2text
*/
unEscapeHTML:function (str) {
return str.replace(getUnEscapeReg(), function (m, n) {
return htmlEntities[m] || String.fromCharCode(+n);
});
},
/**
* Converts object to a true array.
* @param o {object|Array} array like object or array
* @return {Array}
*/
makeArray:function (o) {
if (nullOrUndefined(o)) {
return [];
}
if (S.isArray(o)) {
return o;
}
// The strings and functions also have 'length'
if (typeof o.length !== 'number' || S.isString(o) || S.isFunction(o)) {
return [o];
}
var ret = [];
for (var i = 0, l = o.length; i < l; i++) {
ret[i] = o[i];
}
return ret;
},
/**
* Creates a serialized string of an array or object.
* @return {String}
* <code>
* {foo: 1, bar: 2} // -> 'foo=1&bar=2'
* {foo: 1, bar: [2, 3]} // -> 'foo=1&bar=2&bar=3'
* {foo: '', bar: 2} // -> 'foo=&bar=2'
* {foo: undefined, bar: 2} // -> 'foo=undefined&bar=2'
* {foo: true, bar: 2} // -> 'foo=true&bar=2'
* </code>
*/
param:function (o, sep, eq, arr) {
if (!S.isPlainObject(o)) {
return EMPTY;
}
sep = sep || SEP;
eq = eq || EQ;
if (S.isUndefined(arr)) {
arr = TRUE;
}
var buf = [], key, val;
for (key in o) {
if (o.hasOwnProperty(key)) {
val = o[key];
key = encode(key);
// val is valid non-array value
if (isValidParamValue(val)) {
buf.push(key, eq, encode(val + EMPTY), sep);
}
// val is not empty array
else if (S.isArray(val) && val.length) {
for (var i = 0, len = val.length; i < len; ++i) {
if (isValidParamValue(val[i])) {
buf.push(key,
(arr ? encode("[]") : EMPTY),
eq, encode(val[i] + EMPTY), sep);
}
}
}
// ignore other cases, including empty array, Function, RegExp, Date etc.
}
}
buf.pop();
return buf.join(EMPTY);
},
/**
* Parses a URI-like query string and returns an object composed of parameter/value pairs.
* <code>
* 'section=blog&id=45' // -> {section: 'blog', id: '45'}
* 'section=blog&tag=js&tag=doc' // -> {section: 'blog', tag: ['js', 'doc']}
* 'tag=ruby%20on%20rails' // -> {tag: 'ruby on rails'}
* 'id=45&raw' // -> {id: '45', raw: ''}
* </code>
*/
unparam:function (str, sep, eq) {
if (typeof str !== 'string'
|| (str = S.trim(str)).length === 0) {
return {};
}
sep = sep || SEP;
eq = eq || EQ;
var ret = {},
pairs = str.split(sep),
pair, key, val,
i = 0, len = pairs.length;
for (; i < len; ++i) {
pair = pairs[i].split(eq);
key = decode(pair[0]);
try {
val = decode(pair[1] || EMPTY);
} catch (e) {
S.log(e + "decodeURIComponent error : " + pair[1], "error");
val = pair[1] || EMPTY;
}
if (S.endsWith(key, "[]")) {
key = key.substring(0, key.length - 2);
}
if (hasOwnProperty.call(ret, key)) {
if (S.isArray(ret[key])) {
ret[key].push(val);
} else {
ret[key] = [ret[key], val];
}
} else {
ret[key] = val;
}
}
return ret;
},
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @param fn {Function|String} the function to execute or the name of the method in
* the 'o' object to execute.
* @param when {Number} the number of milliseconds to wait until the fn is executed.
* @param periodic {Boolean} if true, executes continuously at supplied interval
* until canceled.
* @param context {Object} the context object.
* @param [data] that is provided to the function. This accepts either a single
* item or an array. If an array is provided, the function is executed with
* one parameter for each array item. If you need to pass a single array
* parameter, it needs to be wrapped in an array [myarray].
* @return {Object} a timer object. Call the cancel() method on this object to stop
* the timer.
*/
later:function (fn, when, periodic, context, data) {
when = when || 0;
var m = fn,
d = S.makeArray(data),
f,
r;
if (S.isString(fn)) {
m = context[fn];
}
if (!m) {
S.error('method undefined');
}
f = function () {
m.apply(context, d);
};
r = (periodic) ? setInterval(f, when) : setTimeout(f, when);
return {
id:r,
interval:periodic,
cancel:function () {
if (this.interval) {
clearInterval(r);
} else {
clearTimeout(r);
}
}
};
},
startsWith:function (str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
},
endsWith:function (str, suffix) {
var ind = str.length - suffix.length;
return ind >= 0 && str.indexOf(suffix, ind) == ind;
},
/**
* Based on YUI3
* Throttles a call to a method based on the time between calls.
* @param {function} fn The function call to throttle.
* @param {object} context ontext fn to run
* @param {Number} ms The number of milliseconds to throttle the method call.
* Passing a -1 will disable the throttle. Defaults to 150.
* @return {function} Returns a wrapped function that calls fn throttled.
*/
throttle:function (fn, ms, context) {
ms = ms || 150;
if (ms === -1) {
return (function () {
fn.apply(context || this, arguments);
});
}
var last = S.now();
return (function () {
var now = S.now();
if (now - last > ms) {
last = now;
fn.apply(context || this, arguments);
}
});
},
/**
* buffers a call between a fixed time
* @param {function} fn
* @param {object} [context]
* @param {Number} ms
*/
buffer:function (fn, ms, context) {
ms = ms || 150;
if (ms === -1) {
return (function () {
fn.apply(context || this, arguments);
});
}
var bufferTimer = null;
function f() {
f.stop();
bufferTimer = S.later(fn, ms, FALSE, context || this);
}
f.stop = function () {
if (bufferTimer) {
bufferTimer.cancel();
bufferTimer = 0;
}
};
return f;
}
});
// for idea ..... auto-hint
S.mix(S, {
isBoolean:isValidParamValue,
isNumber:isValidParamValue,
isString:isValidParamValue,
isFunction:isValidParamValue,
isArray:isValidParamValue,
isDate:isValidParamValue,
isRegExp:isValidParamValue,
isObject:isValidParamValue
});
S.each('Boolean Number String Function Array Date RegExp Object'.split(' '),
function (name, lc) {
// populate the class2type map
class2type['[object ' + name + ']'] = (lc = name.toLowerCase());
// add isBoolean/isNumber/...
S['is' + name] = function (o) {
return S.type(o) == lc;
}
});
function nullOrUndefined(o) {
return S.isNull(o) || S.isUndefined(o);
}
function cloneInternal(input, f, memory) {
var destination = input,
isArray,
isPlainObject,
k,
stamp;
if (!input) {
return destination;
}
// If input is the source object of a pair of objects in memory,
// then return the destination object in that pair of objects .
// and abort these steps.
if (input[CLONE_MARKER]) {
// 对应的克隆后对象
return memory[input[CLONE_MARKER]].destination;
} else if (typeof input === "object") {
// 引用类型要先记录
var constructor = input.constructor;
if (S.inArray(constructor, [Boolean, String, Number, Date, RegExp])) {
destination = new constructor(input.valueOf());
}
// ImageData , File, Blob , FileList .. etc
else if (isArray = S.isArray(input)) {
destination = f ? S.filter(input, f) : input.concat();
} else if (isPlainObject = S.isPlainObject(input)) {
destination = {};
}
// Add a mapping from input (the source object)
// to output (the destination object) to memory.
// 做标记
input[CLONE_MARKER] = (stamp = S.guid());
// 存储源对象以及克隆后的对象
memory[stamp] = {destination:destination, input:input};
}
// If input is an Array object or an Object object,
// then, for each enumerable property in input,
// add a new property to output having the same name,
// and having a value created from invoking the internal structured cloning algorithm recursively
// with the value of the property as the "input" argument and memory as the "memory" argument.
// The order of the properties in the input and output objects must be the same.
// clone it
if (isArray) {
for (var i = 0; i < destination.length; i++) {
destination[i] = cloneInternal(destination[i], f, memory);
}
} else if (isPlainObject) {
for (k in input) {
if (input.hasOwnProperty(k)) {
if (k !== CLONE_MARKER &&
(!f || (f.call(input, input[k], k, input) !== FALSE))) {
destination[k] = cloneInternal(input[k], f, memory);
}
}
}
}
return destination;
}
function compareObjects(a, b, mismatchKeys, mismatchValues) {
// 两个比较过了,无需再比较,防止循环比较
if (a[COMPARE_MARKER] === b && b[COMPARE_MARKER] === a) {
return TRUE;
}
a[COMPARE_MARKER] = b;
b[COMPARE_MARKER] = a;
var hasKey = function (obj, keyName) {
return (obj !== null && obj !== undefined) && obj[keyName] !== undefined;
};
for (var property in b) {
if (b.hasOwnProperty(property)) {
if (!hasKey(a, property) && hasKey(b, property)) {
mismatchKeys.push("expected has key '" + property + "', but missing from actual.");
}
}
}
for (property in a) {
if (a.hasOwnProperty(property)) {
if (!hasKey(b, property) && hasKey(a, property)) {
mismatchKeys.push("expected missing key '" + property + "', but present in actual.");
}
}
}
for (property in b) {
if (b.hasOwnProperty(property)) {
if (property == COMPARE_MARKER) {
continue;
}
if (!S.equals(a[property], b[property], mismatchKeys, mismatchValues)) {
mismatchValues.push("'" + property + "' was '" + (b[property] ? (b[property].toString()) : b[property])
+ "' in expected, but was '" +
(a[property] ? (a[property].toString()) : a[property]) + "' in actual.");
}
}
}
if (S.isArray(a) && S.isArray(b) && a.length != b.length) {
mismatchValues.push("arrays were not the same length");
}
delete a[COMPARE_MARKER];
delete b[COMPARE_MARKER];
return (mismatchKeys.length === 0 && mismatchValues.length === 0);
}
})(KISSY, undefined);
/**
* setup data structure for kissy loader
* @author yiminghe@gmail.com
*/
(function(S){
if("require" in this) {
return;
}
S.__loader={};
S.__loaderUtils={};
S.__loaderData={};
})(KISSY);/**
* map mechanism
* @author yiminghe@gmail.com
*/
(function (S, loader) {
if ("require" in this) {
return;
}
/**
* modify current module path
* @param rules
* @example
* [
* [/(.+-)min(.js(\?t=\d+)?)$/,"$1$2"],
* [/(.+-)min(.js(\?t=\d+)?)$/,function(_,m1,m2){
* return m1+m2;
* }]
* ]
*/
S.configs.map = function (rules) {
S.Config.mappedRules = (S.Config.mappedRules || []).concat(rules);
};
S.mix(loader, {
__getMappedPath:function (path) {
var __mappedRules = S.Config.mappedRules || [];
for (var i = 0; i < __mappedRules.length; i++) {
var m, rule = __mappedRules[i];
if (m = path.match(rule[0])) {
return path.replace(rule[0], rule[1]);
}
}
return path;
}
});
})(KISSY, KISSY.__loader);/**
* combine mechanism
* @author yiminghe@gmail.com
*/
(function (S, loader) {
if ("require" in this) {
return;
}
var combines;
/**
* compress 'from module' to 'to module'
* {
* core:['dom','ua','event','node','json','ajax','anim','base','cookie']
* }
*/
combines = S.configs.combines = function (from, to) {
var cs;
if (S.isObject(from)) {
S.each(from, function (v, k) {
S.each(v, function (v2) {
combines(v2, k);
});
});
return;
}
cs = S.Config.combines = S.Config.combines || {};
if (to) {
cs[from] = to;
} else {
return cs[from] || from;
}
};
S.mix(loader, {
__getCombinedMod:function (modName) {
var cs;
cs = S.Config.combines = S.Config.combines || {};
return cs[modName] || modName;
}
});
})(KISSY, KISSY.__loader);/**
* status constants
* @author yiminghe@gmail.com
*/
(function(S, data) {
if ("require" in this) {
return;
}
// 脚本(loadQueue)/模块(mod) 公用状态
S.mix(data, {
"INIT":0,
"LOADING" : 1,
"LOADED" : 2,
"ERROR" : 3,
// 模块特有
"ATTACHED" : 4
});
})(KISSY, KISSY.__loaderData);/**
* utils for kissy loader
* @author yiminghe@gmail.com
*/
(function(S, loader, utils) {
if ("require" in this) {
return;
}
var ua = navigator.userAgent,doc = document;
S.mix(utils, {
docHead:function() {
return doc.getElementsByTagName('head')[0] || doc.documentElement;
},
isWebKit:!!ua.match(/AppleWebKit/),
IE : !!ua.match(/MSIE/),
isCss:function(url) {
return /\.css(?:\?|$)/i.test(url);
},
isLinkNode:function(n) {
return n.nodeName.toLowerCase() == 'link';
},
/**
* resolve relative part of path
* x/../y/z -> y/z
* x/./y/z -> x/y/z
* @param path uri path
* @return {string} resolved path
* @description similar to path.normalize in nodejs
*/
normalizePath:function(path) {
var paths = path.split("/"),
re = [],
p;
for (var i = 0; i < paths.length; i++) {
p = paths[i];
if (p == ".") {
} else if (p == "..") {
re.pop();
} else {
re.push(p);
}
}
return re.join("/");
},
/**
* 根据当前模块以及依赖模块的相对路径,得到依赖模块的绝对路径
* @param moduleName 当前模块
* @param depName 依赖模块
* @return {string|Array} 依赖模块的绝对路径
* @description similar to path.resolve in nodejs
*/
normalDepModuleName:function normalDepModuleName(moduleName, depName) {
if (!depName) {
return depName;
}
if (S.isArray(depName)) {
for (var i = 0; i < depName.length; i++) {
depName[i] = normalDepModuleName(moduleName, depName[i]);
}
return depName;
}
if (startsWith(depName, "../") || startsWith(depName, "./")) {
var anchor = "",index;
// x/y/z -> x/y/
if ((index = moduleName.lastIndexOf("/")) != -1) {
anchor = moduleName.substring(0, index + 1);
}
return normalizePath(anchor + depName);
} else if (depName.indexOf("./") != -1
|| depName.indexOf("../") != -1) {
return normalizePath(depName);
} else {
return depName;
}
},
//去除后缀名,要考虑时间戳?
removePostfix:function (path) {
return path.replace(/(-min)?\.js[^/]*$/i, "");
},
/**
* 路径正则化,不能是相对地址
* 相对地址则转换成相对页面的绝对地址
* 用途:
* package path 相对地址则相对于当前页面获取绝对地址
*/
normalBasePath:function (path) {
path = S.trim(path);
// path 为空时,不能变成 "/"
if (path && path.charAt(path.length - 1) != '/') {
path += "/";
}
/**
* 一定要正则化,防止出现 ../ 等相对路径
* 考虑本地路径
*/
if (!path.match(/^(http(s)?)|(file):/i)
&& !startsWith(path, "/")) {
path = loader.__pagePath + path;
}
return normalizePath(path);
},
/**
* 相对路径文件名转换为绝对路径
* @param path
*/
absoluteFilePath:function(path) {
path = utils.normalBasePath(path);
return path.substring(0, path.length - 1);
},
//http://wiki.commonjs.org/wiki/Packages/Mappings/A
//如果模块名以 / 结尾,自动加 index
indexMapping:function (names) {
for (var i = 0; i < names.length; i++) {
if (names[i].match(/\/$/)) {
names[i] += "index";
}
}
return names;
}
});
var startsWith = S.startsWith,normalizePath = utils.normalizePath;
})(KISSY, KISSY.__loader, KISSY.__loaderUtils);/**
* script/css load across browser
* @author yiminghe@gmail.com
*/
(function(S, utils) {
if ("require" in this) {
return;
}
var CSS_POLL_INTERVAL = 30,
/**
* central poll for link node
*/
timer = 0,
monitors = {
/**
* node.id:[callback]
*/
};
function startCssTimer() {
if (!timer) {
S.log("start css polling");
cssPoll();
}
}
// single thread is ok
function cssPoll() {
for (var url in monitors) {
var callbacks = monitors[url],
node = callbacks.node,
loaded = 0;
if (utils.isWebKit) {
if (node['sheet']) {
S.log("webkit loaded : " + url);
loaded = 1;
}
} else if (node['sheet']) {
try {
var cssRules;
if (cssRules = node['sheet'].cssRules) {
S.log('firefox ' + cssRules + ' loaded : ' + url);
loaded = 1;
}
} catch(ex) {
// S.log('firefox ' + ex.name + ' ' + ex.code + ' ' + url);
// if (ex.name === 'NS_ERROR_DOM_SECURITY_ERR') {
if (ex.code === 1000) {
S.log('firefox ' + ex.name + ' loaded : ' + url);
loaded = 1;
}
}
}
if (loaded) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(node);
}
delete monitors[url];
}
}
if (S.isEmptyObject(monitors)) {
timer = 0;
S.log("end css polling");
} else {
timer = setTimeout(cssPoll, CSS_POLL_INTERVAL);
}
}
S.mix(utils, {
scriptOnload:document.addEventListener ?
function(node, callback) {
if (utils.isLinkNode(node)) {
return utils.styleOnload(node, callback);
}
node.addEventListener('load', callback, false);
} :
function(node, callback) {
if (utils.isLinkNode(node)) {
return utils.styleOnload(node, callback);
}
var oldCallback = node.onreadystatechange;
node.onreadystatechange = function() {
var rs = node.readyState;
if (/loaded|complete/i.test(rs)) {
node.onreadystatechange = null;
oldCallback && oldCallback();
callback.call(this);
}
};
},
/**
* monitor css onload across browsers
* 暂时不考虑如何判断失败,如 404 等
* @refer
* - firefox 不可行(结论4错误):
* - http://yearofmoo.com/2011/03/cross-browser-stylesheet-preloading/
* - 全浏览器兼容
* - http://lifesinger.org/lab/2011/load-js-css/css-preload.html
* - 其他
* - http://www.zachleat.com/web/load-css-dynamically/
*/
styleOnload:window.attachEvent ?
// ie/opera
function(node, callback) {
// whether to detach using function wrapper?
function t() {
node.detachEvent('onload', t);
S.log('ie/opera loaded : ' + node.href);
callback.call(node);
}
node.attachEvent('onload', t);
} :
// refer : http://lifesinger.org/lab/2011/load-js-css/css-preload.html
// 暂时不考虑如何判断失败,如 404 等
function(node, callback) {
var href = node.href,arr;
arr = monitors[href] = monitors[href] || [];
arr.node = node;
arr.push(callback);
startCssTimer();
}
});
})(KISSY, KISSY.__loaderUtils);/**
* getScript support for css and js callback after load
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
(function(S, utils) {
if ("require" in this) {
return;
}
var MILLISECONDS_OF_SECOND = 1000,
scriptOnload = utils.scriptOnload;
S.mix(S, {
/**
* load a css file from server using http get ,after css file load ,execute success callback
* @param url css file url
* @param success callback
* @param charset
*/
getStyle:function(url, success, charset) {
var doc = document,
head = utils.docHead(),
node = doc.createElement('link'),
config = success;
if (S.isPlainObject(config)) {
success = config.success;
charset = config.charset;
}
node.href = url;
node.rel = 'stylesheet';
if (charset) {
node.charset = charset;
}
if (success) {
utils.scriptOnload(node, success);
}
head.appendChild(node);
return node;
},
/**
* Load a JavaScript/Css file from the server using a GET HTTP request, then execute it.
* <code>
* getScript(url, success, charset);
* or
* getScript(url, {
* charset: string
* success: fn,
* error: fn,
* timeout: number
* });
* </code>
*/
getScript:function(url, success, charset) {
if (utils.isCss(url)) {
return S.getStyle(url, success, charset);
}
var doc = document,
head = doc.head || doc.getElementsByTagName("head")[0],
node = doc.createElement('script'),
config = success,
error,
timeout,
timer;
if (S.isPlainObject(config)) {
success = config.success;
error = config.error;
timeout = config.timeout;
charset = config.charset;
}
function clearTimer() {
if (timer) {
timer.cancel();
timer = undefined;
}
}
node.src = url;
node.async = true;
if (charset) {
node.charset = charset;
}
if (success || error) {
scriptOnload(node, function() {
clearTimer();
S.isFunction(success) && success.call(node);
});
if (S.isFunction(error)) {
//标准浏览器
if (doc.addEventListener) {
node.addEventListener("error", function() {
clearTimer();
error.call(node);
}, false);
}
timer = S.later(function() {
timer = undefined;
error();
}, (timeout || this.Config.timeout) * MILLISECONDS_OF_SECOND);
}
}
head.insertBefore(node, head.firstChild);
return node;
}
});
})(KISSY, KISSY.__loaderUtils);/**
* add module definition
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
(function(S, loader, utils, data) {
if ("require" in this) {
return;
}
var IE = utils.IE,
ATTACHED = data.ATTACHED,
mix = S.mix;
mix(loader, {
/**
* Registers a module.
* @param name {String} module name
* @param def {Function|Object} entry point into the module that is used to bind module to KISSY
* @param config {Object}
* <code>
* KISSY.add('module-name', function(S){ }, {requires: ['mod1']});
* </code>
* <code>
* KISSY.add({
* 'mod-name': {
* fullpath: 'url',
* requires: ['mod1','mod2']
* }
* });
* </code>
* @return {KISSY}
*/
add: function(name, def, config) {
var self = this,
mods = self.Env.mods,
o;
// S.add(name, config) => S.add( { name: config } )
if (S.isString(name)
&& !config
&& S.isPlainObject(def)) {
o = {};
o[name] = def;
name = o;
}
// S.add( { name: config } )
if (S.isPlainObject(name)) {
S.each(name, function(v, k) {
v.name = k;
if (mods[k]) {
// 保留之前添加的配置
mix(v, mods[k], false);
}
});
mix(mods, name);
return self;
}
// S.add(name[, fn[, config]])
if (S.isString(name)) {
var host;
if (config && ( host = config.host )) {
var hostMod = mods[host];
if (!hostMod) {
S.log("module " + host + " can not be found !", "error");
//S.error("module " + host + " can not be found !");
return self;
}
if (self.__isAttached(host)) {
def.call(self, self);
} else {
//该 host 模块纯虚!
hostMod.fns = hostMod.fns || [];
hostMod.fns.push(def);
}
return self;
}
self.__registerModule(name, def, config);
//显示指定 add 不 attach
if (config && config['attach'] === false) {
return self;
}
// 和 1.1.7 以前版本保持兼容,不得已而为之
var mod = mods[name];
var requires = utils.normalDepModuleName(name, mod.requires);
if (self.__isAttached(requires)) {
//S.log(mod.name + " is attached when add !");
self.__attachMod(mod);
}
//调试用,为什么不在 add 时 attach
else if (this.Config.debug && !mod) {
var i,modNames;
i = (modNames = S.makeArray(requires)).length - 1;
for (; i >= 0; i--) {
var requireName = modNames[i];
var requireMod = mods[requireName] || {};
if (requireMod.status !== ATTACHED) {
S.log(mod.name + " not attached when added : depends " + requireName);
}
}
}
return self;
}
// S.add(fn,config);
if (S.isFunction(name)) {
config = def;
def = name;
if (IE) {
/*
Kris Zyp
2010年10月21日, 上午11时34分
We actually had some discussions off-list, as it turns out the required
technique is a little different than described in this thread. Briefly,
to identify anonymous modules from scripts:
* In non-IE browsers, the onload event is sufficient, it always fires
immediately after the script is executed.
* In IE, if the script is in the cache, it actually executes *during*
the DOM insertion of the script tag, so you can keep track of which
script is being requested in case define() is called during the DOM
insertion.
* In IE, if the script is not in the cache, when define() is called you
can iterate through the script tags and the currently executing one will
have a script.readyState == "interactive"
See RequireJS source code if you need more hints.
Anyway, the bottom line from a spec perspective is that it is
implemented, it works, and it is possible. Hope that helps.
Kris
*/
// http://groups.google.com/group/commonjs/browse_thread/thread/5a3358ece35e688e/43145ceccfb1dc02#43145ceccfb1dc02
// use onload to get module name is not right in ie
name = self.__findModuleNameByInteractive();
S.log("old_ie get modname by interactive : " + name);
self.__registerModule(name, def, config);
self.__startLoadModuleName = null;
self.__startLoadTime = 0;
} else {
// 其他浏览器 onload 时,关联模块名与模块定义
self.__currentModule = {
def:def,
config:config
};
}
return self;
}
S.log("invalid format for KISSY.add !", "error");
return self;
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderUtils, KISSY.__loaderData);
/**
* @refer
* - https://github.com/amdjs/amdjs-api/wiki/AMD
**//**
* build full path from relative path and base path
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
(function (S, loader, utils, data) {
if ("require" in this) {
return;
}
S.mix(loader, {
__buildPath:function (mod, base) {
var self = this,
Config = self.Config;
base = base || Config.base;
build("fullpath", "path");
if (mod["cssfullpath"] !== data.LOADED) {
build("cssfullpath", "csspath");
}
function build(fullpath, path) {
if (!mod[fullpath] && mod[path]) {
//如果是 ./ 或 ../ 则相对当前模块路径
mod[path] = utils.normalDepModuleName(mod.name, mod[path]);
mod[fullpath] = base + mod[path];
}
// debug 模式下,加载非 min 版
if (mod[fullpath] && Config.debug) {
mod[fullpath] = mod[fullpath].replace(/-min/ig, "");
}
//刷新客户端缓存,加时间戳 tag
if (mod[fullpath]
&& !(mod[fullpath].match(/\?t=/))
&& mod.tag) {
mod[fullpath] += "?t=" + mod.tag;
}
if (mod[fullpath]) {
mod[fullpath] = self.__getMappedPath(mod[fullpath]);
}
}
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderUtils, KISSY.__loaderData);/**
* logic for config.global , mainly for kissy.editor
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
(function(S, loader) {
if ("require" in this) {
return;
}
S.mix(loader, {
// 按需从 global 迁移模块定义到当前 loader 实例,并根据 global 设置 fullpath
__mixMod: function(name, global) {
// 从 __mixMods 调用过来时,可能本实例没有该模块的数据结构
var self = this,
mods = self.Env.mods,
gMods = global.Env.mods,
mod = mods[name] || {},
status = mod.status;
if (gMods[name]) {
S.mix(mod, S.clone(gMods[name]));
// status 属于实例,当有值时,不能被覆盖。
// 1. 只有没有初始值时,才从 global 上继承
// 2. 初始值为 0 时,也从 global 上继承
// 其他都保存自己的状态
if (status) {
mod.status = status;
}
}
// 来自 global 的 mod, path 也应该基于 global
self.__buildPath(mod, global.Config.base);
mods[name] = mod;
}
});
})(KISSY, KISSY.__loader);/**
* for ie ,find current executive script ,then infer module name
* @author yiminghe@gmail.com
*/
(function (S, loader, utils) {
if ("require" in this) {
return;
}
S.mix(loader, {
//ie 特有,找到当前正在交互的脚本,根据脚本名确定模块名
// 如果找不到,返回发送前那个脚本
__findModuleNameByInteractive:function () {
var self = this,
scripts = document.getElementsByTagName("script"),
re,
script;
for (var i = 0; i < scripts.length; i++) {
script = scripts[i];
if (script.readyState == "interactive") {
re = script;
break;
}
}
if (!re) {
// sometimes when read module file from cache , interactive status is not triggered
// module code is executed right after inserting into dom
// i has to preserve module name before insert module script into dom , then get it back here
S.log("can not find interactive script,time diff : " + (+new Date() - self.__startLoadTime), "error");
S.log("old_ie get modname from cache : " + self.__startLoadModuleName);
return self.__startLoadModuleName;
//S.error("找不到 interactive 状态的 script");
}
// src 必定是绝对路径
// or re.hasAttribute ? re.src : re.getAttribute('src', 4);
// http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx
var src = utils.absoluteFilePath(re.src);
// S.log("interactive src :" + src);
// 注意:模块名不包含后缀名以及参数,所以去除
// 系统模块去除系统路径
// 需要 base norm , 防止 base 被指定为相对路径
self.Config.base = utils.normalBasePath(self.Config.base);
if (src.lastIndexOf(self.Config.base, 0)
=== 0) {
return utils.removePostfix(src.substring(self.Config.base.length));
}
var packages = self.Config.packages;
//外部模块去除包路径,得到模块名
for (var p in packages) {
if (packages.hasOwnProperty(p)) {
var p_path = packages[p].path;
if (packages.hasOwnProperty(p) &&
src.lastIndexOf(p_path, 0) === 0) {
return utils.removePostfix(src.substring(p_path.length));
}
}
}
S.log("interactive script does not have package config :" + src, "error");
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderUtils);/**
* load a single mod (js or css)
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
(function(S, loader, utils, data) {
if ("require" in this) {
return;
}
var IE = utils.IE,
LOADING = data.LOADING,
LOADED = data.LOADED,
ERROR = data.ERROR,
ATTACHED = data.ATTACHED;
S.mix(loader, {
/**
* Load a single module.
*/
__load: function(mod, callback, cfg) {
var self = this,
url = mod['fullpath'],
isCss = utils.isCss(url),
// 这个是全局的,防止多实例对同一模块的重复下载
loadQueque = S.Env._loadQueue,
status = loadQueque[url],
node = status;
mod.status = mod.status || 0;
// 可能已经由其它模块触发加载
if (mod.status < LOADING && status) {
// 该模块是否已经载入到 global ?
mod.status = status === LOADED ? LOADED : LOADING;
}
// 1.20 兼容 1.1x 处理:加载 cssfullpath 配置的 css 文件
// 仅发出请求,不做任何其它处理
if (S.isString(mod["cssfullpath"])) {
S.getScript(mod["cssfullpath"]);
mod["cssfullpath"] = mod.csspath = LOADED;
}
if (mod.status < LOADING && url) {
mod.status = LOADING;
if (IE && !isCss) {
self.__startLoadModuleName = mod.name;
self.__startLoadTime = Number(+new Date());
}
node = S.getScript(url, {
success: function() {
if (isCss) {
} else {
//载入 css 不需要这步了
//标准浏览器下:外部脚本执行后立即触发该脚本的 load 事件,ie9 还是不行
if (self.__currentModule) {
S.log("standard browser get modname after load : " + mod.name);
self.__registerModule(mod.name, self.__currentModule.def,
self.__currentModule.config);
self.__currentModule = null;
}
// 模块载入后,如果需要也要混入对应 global 上模块定义
mixGlobal();
if (mod.fns && mod.fns.length > 0) {
} else {
_modError();
}
}
if (mod.status != ERROR) {
S.log(mod.name + ' is loaded.', 'info');
}
_scriptOnComplete();
},
error: function() {
_modError();
_scriptOnComplete();
},
charset: mod.charset
});
loadQueque[url] = node;
}
// 已经在加载中,需要添加回调到 script onload 中
// 注意:没有考虑 error 情形
else if (mod.status === LOADING) {
utils.scriptOnload(node, function() {
// 模块载入后,如果需要也要混入对应 global 上模块定义
mixGlobal();
_scriptOnComplete();
});
}
// 是内嵌代码,或者已经 loaded
else {
// 也要混入对应 global 上模块定义
mixGlobal();
callback();
}
function _modError() {
S.log(mod.name + ' is not loaded! can not find module in path : ' + mod['fullpath'], 'error');
mod.status = ERROR;
}
function mixGlobal() {
// 对于动态下载下来的模块,loaded 后,global 上有可能更新 mods 信息
// 需要同步到 instance 上去
// 注意:要求 mod 对应的文件里,仅修改该 mod 信息
if (cfg.global) {
self.__mixMod(mod.name, cfg.global);
}
}
function _scriptOnComplete() {
loadQueque[url] = LOADED;
if (mod.status !== ERROR) {
// 注意:当多个模块依赖同一个下载中的模块A下,模块A仅需 attach 一次
// 因此要加上下面的 !== 判断,否则会出现重复 attach,
// 比如编辑器里动态加载时,被依赖的模块会重复
if (mod.status !== ATTACHED) {
mod.status = LOADED;
}
callback();
}
}
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderUtils, KISSY.__loaderData);/**
* @module loader
* @author lifesinger@gmail.com,yiminghe@gmail.com,lijing00333@163.com
* @description: constant member and common method holder
*/
(function(S, loader, data) {
if ("require" in this) {
return;
}
var ATTACHED = data.ATTACHED,
mix = S.mix;
mix(loader, {
// 当前页面所在的目录
// http://xx.com/y/z.htm#!/f/g
// ->
// http://xx.com/y/
__pagePath:location.href.replace(location.hash, "").replace(/[^/]*$/i, ""),
//firefox,ie9,chrome 如果add没有模块名,模块定义先暂存这里
__currentModule:null,
//ie6,7,8开始载入脚本的时间
__startLoadTime:0,
//ie6,7,8开始载入脚本对应的模块名
__startLoadModuleName:null,
__isAttached: function(modNames) {
var mods = this.Env.mods,
ret = true;
S.each(modNames, function(name) {
var mod = mods[name];
if (!mod || mod.status !== ATTACHED) {
ret = false;
return ret;
}
});
return ret;
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderData);
/**
* 2011-01-04 chengyu<yiminghe@gmail.com> refactor:
*
* adopt requirejs :
*
* 1. packages(cfg) , cfg :{
* name : 包名,用于指定业务模块前缀
* path: 前缀包名对应的路径
* charset: 该包下所有文件的编码
*
* 2. add(moduleName,function(S,depModule){return function(){}},{requires:["depModuleName"]});
* moduleName add 时可以不写
* depModuleName 可以写相对地址 (./ , ../),相对于 moduleName
*
* 3. S.use(["dom"],function(S,DOM){
* });
* 依赖注入,发生于 add 和 use 时期
*
* 4. add,use 不支持 css loader ,getScript 仍然保留支持
*
* 5. 部分更新模块文件代码 x/y?t=2011 ,加载过程中注意去除事件戳,仅在载入文件时使用
*
* demo : http://lite-ext.googlecode.com/svn/trunk/lite-ext/playground/module_package/index.html
*
* 2011-03-01 yiminghe@gmail.com note:
*
* compatibility
*
* 1. 保持兼容性,不得已而为之
* 支持 { host : }
* 如果 requires 都已经 attached,支持 add 后立即 attach
* 支持 { attach : false } 显示控制 add 时是否 attach
* 支持 { global : Editor } 指明模块来源
*
*
* 2011-05-04 初步拆分文件,tmd 乱了
*/
/**
* package mechanism
* @author yiminghe@gmail.com
*/
(function (S, loader, utils) {
if ("require" in this) {
return;
}
/**
* 包声明
* biz -> .
* 表示遇到 biz/x
* 在当前网页路径找 biz/x.js
*/
S.configs.packages = function (cfgs) {
var ps;
ps = S.Config.packages = S.Config.packages || {};
S.each(cfgs, function (cfg) {
ps[cfg.name] = cfg;
//注意正则化
cfg.path = cfg.path && utils.normalBasePath(cfg.path);
cfg.tag = cfg.tag && encodeURIComponent(cfg.tag);
});
};
S.mix(loader, {
__getPackagePath:function (mod) {
//缓存包路径,未申明的包的模块都到核心模块中找
if (mod.packagepath) {
return mod.packagepath;
}
var self = this,
//一个模块合并到了另一个模块文件中去
modName = S.__getCombinedMod(mod.name),
packages = self.Config.packages || {},
pName = "",
p_def;
for (var p in packages) {
if (packages.hasOwnProperty(p)) {
if (S.startsWith(modName, p) &&
p.length > pName) {
pName = p;
}
}
}
p_def = packages[pName];
mod.charset = p_def && p_def.charset || mod.charset;
if (p_def) {
mod.tag = p_def.tag;
} else {
// kissy 自身组件的事件戳后缀
mod.tag = encodeURIComponent(S.Config.tag || S.buildTime);
}
return mod.packagepath = (p_def && p_def.path) || self.Config.base;
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderUtils);/**
* register module ,associate module name with module factory(definition)
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
(function(S, loader,data) {
if ("require" in this) {
return;
}
var LOADED = data.LOADED,
mix = S.mix;
mix(loader, {
//注册模块,将模块和定义 factory 关联起来
__registerModule:function(name, def, config) {
config = config || {};
var self = this,
mods = self.Env.mods,
mod = mods[name] || {};
// 注意:通过 S.add(name[, fn[, config]]) 注册的代码,无论是页面中的代码,
// 还是 js 文件里的代码,add 执行时,都意味着该模块已经 LOADED
mix(mod, { name: name, status: LOADED });
if (mod.fns && mod.fns.length) {
S.log(name + " is defined more than once");
//S.error(name + " is defined more than once");
}
//支持 host,一个模块多个 add factory
mod.fns = mod.fns || [];
mod.fns.push(def);
mix((mods[name] = mod), config);
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderData);/**
* use and attach mod
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
(function (S, loader, utils, data) {
if ("require" in this) {
return;
}
var LOADED = data.LOADED,
ATTACHED = data.ATTACHED;
S.mix(loader, {
/**
* Start load specific mods, and fire callback when these mods and requires are attached.
* <code>
* S.use('mod-name', callback, config);
* S.use('mod1,mod2', callback, config);
* </code>
*/
use:function (modNames, callback, cfg) {
modNames = modNames.replace(/\s+/g, "").split(',');
utils.indexMapping(modNames);
cfg = cfg || {};
var self = this,
fired;
// 已经全部 attached, 直接执行回调即可
if (self.__isAttached(modNames)) {
var mods = self.__getModules(modNames);
callback && callback.apply(self, mods);
return;
}
// 有尚未 attached 的模块
S.each(modNames, function (modName) {
// 从 name 开始调用,防止不存在模块
self.__attachModByName(modName, function () {
if (!fired &&
self.__isAttached(modNames)) {
fired = true;
var mods = self.__getModules(modNames);
callback && callback.apply(self, mods);
}
}, cfg);
});
return self;
},
__getModules:function (modNames) {
var self = this,
mods = [self];
S.each(modNames, function (modName) {
if (!utils.isCss(modName)) {
mods.push(self.require(modName));
}
});
return mods;
},
/**
* get module's value defined by define function
* @param {string} moduleName
*/
require:function (moduleName) {
var self = this,
mods = self.Env.mods,
mod = mods[moduleName],
re = self['onRequire'] && self['onRequire'](mod);
if (re !== undefined) {
return re;
}
return mod && mod.value;
},
// 加载指定模块名模块,如果不存在定义默认定义为内部模块
__attachModByName:function (modName, callback, cfg) {
var self = this,
mods = self.Env.mods;
var mod = mods[modName];
//没有模块定义
if (!mod) {
// 默认 js/css 名字
// 不指定 .js 默认为 js
// 指定为 css 载入 .css
var componentJsName = self.Config['componentJsName'] ||
function (m) {
var suffix = "js", match;
if (match = m.match(/(.+)\.(js|css)$/i)) {
suffix = match[2];
m = match[1];
}
return m + '-min.' + suffix;
},
path = componentJsName(S.__getCombinedMod(modName));
mod = {
path:path,
charset:'utf-8'
};
//添加模块定义
mods[modName] = mod;
}
mod.name = modName;
if (mod && mod.status === ATTACHED) {
return;
}
// 先从 global 里取
if (cfg.global) {
self.__mixMod(modName, cfg.global);
}
self.__attach(mod, callback, cfg);
},
/**
* Attach a module and all required modules.
*/
__attach:function (mod, callback, cfg) {
var self = this,
r,
rMod,
i,
attached = 0,
mods = self.Env.mods,
//复制一份当前的依赖项出来,防止 add 后修改!
requires = (mod['requires'] || []).concat();
mod['requires'] = requires;
/**
* check cyclic dependency between mods
*/
function cyclicCheck() {
var __allRequires,
myName = mod.name,
r, r2, rmod,
r__allRequires,
requires = mod.requires;
// one mod's all requires mods to run its callback
__allRequires = mod.__allRequires = mod.__allRequires || {};
for (var i = 0; i < requires.length; i++) {
r = requires[i];
rmod = mods[r];
__allRequires[r] = 1;
if (rmod && (r__allRequires = rmod.__allRequires)) {
for (r2 in r__allRequires) {
if (r__allRequires.hasOwnProperty(r2)) {
__allRequires[r2] = 1;
}
}
}
}
if (__allRequires[myName]) {
var t = [];
for (r in __allRequires) {
if (__allRequires.hasOwnProperty(r)) {
t.push(r);
}
}
S.error("find cyclic dependency by mod " + myName + " between mods : " + t.join(","));
}
}
if (S.Config.debug) {
cyclicCheck();
}
// attach all required modules
for (i = 0; i < requires.length; i++) {
r = requires[i] = utils.normalDepModuleName(mod.name, requires[i]);
rMod = mods[r];
if (rMod && rMod.status === ATTACHED) {
//no need
} else {
self.__attachModByName(r, fn, cfg);
}
}
// load and attach this module
self.__buildPath(mod, self.__getPackagePath(mod));
self.__load(mod, function () {
// add 可能改了 config,这里重新取下
mod['requires'] = mod['requires'] || [];
var newRequires = mod['requires'],
needToLoad = [];
//本模块下载成功后串行下载 require
for (i = 0; i < newRequires.length; i++) {
r = newRequires[i] = utils.normalDepModuleName(mod.name, newRequires[i]);
var rMod = mods[r],
inA = S.inArray(r, requires);
//已经处理过了或将要处理
if (rMod &&
rMod.status === ATTACHED
//已经正在处理了
|| inA) {
//no need
} else {
//新增的依赖项
needToLoad.push(r);
}
}
if (needToLoad.length) {
for (i = 0; i < needToLoad.length; i++) {
self.__attachModByName(needToLoad[i], fn, cfg);
}
} else {
fn();
}
}, cfg);
function fn() {
if (!attached &&
self.__isAttached(mod['requires'])) {
if (mod.status === LOADED) {
self.__attachMod(mod);
}
if (mod.status === ATTACHED) {
attached = 1;
callback();
}
}
}
},
__attachMod:function (mod) {
var self = this,
fns = mod.fns;
if (fns) {
S.each(fns, function (fn) {
var value;
if (S.isFunction(fn)) {
value = fn.apply(self, self.__getModules(mod['requires']));
} else {
value = fn;
}
mod.value = mod.value || value;
});
}
mod.status = ATTACHED;
}
});
})(KISSY, KISSY.__loader, KISSY.__loaderUtils, KISSY.__loaderData);/**
* mix loader into S and infer KISSy baseUrl if not set
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
(function (S, loader, utils) {
if ("require" in this) {
return;
}
S.mix(S, loader);
/**
* get base from src
* @param src script source url
* @return base for kissy
* @example:
* http://a.tbcdn.cn/s/kissy/1.1.6/??kissy-min.js,suggest/suggest-pkg-min.js
* http://a.tbcdn.cn/??s/kissy/1.1.6/kissy-min.js,s/kissy/1.1.5/suggest/suggest-pkg-min.js
* http://a.tbcdn.cn/??s/kissy/1.1.6/suggest/suggest-pkg-min.js,s/kissy/1.1.5/kissy-min.js
* http://a.tbcdn.cn/s/kissy/1.1.6/kissy-min.js?t=20101215.js
* @notice: custom combo rules, such as yui3:
* <script src="path/to/kissy" data-combo-prefix="combo?" data-combo-sep="&"></script>
*/
// notice: timestamp
var baseReg = /^(.*)(seed|kissy)(-aio)?(-min)?\.js[^/]*/i,
baseTestReg = /(seed|kissy)(-aio)?(-min)?\.js/i;
function getBaseUrl(script) {
var src = utils.absoluteFilePath(script.src),
prefix = script.getAttribute('data-combo-prefix') || '??',
sep = script.getAttribute('data-combo-sep') || ',',
parts = src.split(sep),
base,
part0 = parts[0],
index = part0.indexOf(prefix);
// no combo
if (index == -1) {
base = src.replace(baseReg, '$1');
} else {
base = part0.substring(0, index);
var part01 = part0.substring(index + 2, part0.length);
// combo first
// notice use match better than test
if (part01.match(baseTestReg)) {
base += part01.replace(baseReg, '$1');
}
// combo after first
else {
S.each(parts, function (part) {
if (part.match(baseTestReg)) {
base += part.replace(baseReg, '$1');
return false;
}
});
}
}
return base;
}
/**
* Initializes loader.
*/
S.__initLoader = function () {
var self = this;
self.Env.mods = self.Env.mods || {}; // all added mods
};
S.Env._loadQueue = {}; // information for loading and loaded mods
S.__initLoader();
(function () {
// get base from current script file path
var scripts = document.getElementsByTagName('script'),
currentScript = scripts[scripts.length - 1],
base = getBaseUrl(currentScript);
S.Config.base = utils.normalBasePath(base);
// the default timeout for getScript
S.Config.timeout = 10;
})();
S.mix(S.configs, {
base:function (base) {
S.Config.base = utils.normalBasePath(base);
},
timeout:function (v) {
S.Config.timeout = v;
},
debug:function (v) {
S.Config.debug = v;
}
});
// for S.app working properly
S.each(loader, function (v, k) {
S.__APP_MEMBERS.push(k);
});
S.__APP_INIT_METHODS.push('__initLoader');
})(KISSY, KISSY.__loader, KISSY.__loaderUtils);/**
* @module web.js
* @author lifesinger@gmail.com,yiminghe@gmail.com
* @description this code can only run at browser environment
*/
(function(S, undefined) {
var win = S.__HOST,
doc = win['document'],
docElem = doc.documentElement,
EMPTY = '',
// Is the DOM ready to be used? Set to true once it occurs.
isReady = false,
// The functions to execute on DOM ready.
readyList = [],
// The number of poll times.
POLL_RETRYS = 500,
// The poll interval in milliseconds.
POLL_INTERVAL = 40,
// #id or id
RE_IDSTR = /^#?([\w-]+)$/,
RE_NOT_WHITE = /\S/;
S.mix(S, {
/**
* A crude way of determining if an object is a window
*/
isWindow: function(o) {
return S.type(o) === 'object'
&& 'setInterval' in o
&& 'document' in o
&& o.document.nodeType == 9;
},
parseXML: function(data) {
var xml;
try {
// Standard
if (window.DOMParser) {
xml = new DOMParser().parseFromString(data, "text/xml");
} else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(data);
}
} catch(e) {
S.log("parseXML error : ");
S.log(e);
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
S.error("Invalid XML: " + data);
}
return xml;
},
/**
* Evalulates a script in a global context.
*/
globalEval: function(data) {
if (data && RE_NOT_WHITE.test(data)) {
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
( window.execScript || function(data) {
window[ "eval" ].call(window, data);
} )(data);
}
},
/**
* Specify a function to execute when the DOM is fully loaded.
* @param fn {Function} A function to execute after the DOM is ready
* <code>
* KISSY.ready(function(S){ });
* </code>
* @return {KISSY}
*/
ready: function(fn) {
// If the DOM is already ready
if (isReady) {
// Execute the function immediately
fn.call(win, this);
} else {
// Remember the function for later
readyList.push(fn);
}
return this;
},
/**
* Executes the supplied callback when the item with the supplied id is found.
* @param id <String> The id of the element, or an array of ids to look for.
* @param fn <Function> What to execute when the element is found.
*/
available: function(id, fn) {
id = (id + EMPTY).match(RE_IDSTR)[1];
if (!id || !S.isFunction(fn)) {
return;
}
var retryCount = 1,
node,
timer = S.later(function() {
if ((node = doc.getElementById(id)) && (fn(node) || 1) ||
++retryCount > POLL_RETRYS) {
timer.cancel();
}
}, POLL_INTERVAL, true);
}
});
/**
* Binds ready events.
*/
function _bindReady() {
var doScroll = docElem.doScroll,
eventType = doScroll ? 'onreadystatechange' : 'DOMContentLoaded',
COMPLETE = 'complete',
fire = function() {
_fireReady();
};
// Catch cases where ready() is called after the
// browser event has already occurred.
if (doc.readyState === COMPLETE) {
return fire();
}
// w3c mode
if (doc.addEventListener) {
function domReady() {
doc.removeEventListener(eventType, domReady, false);
fire();
}
doc.addEventListener(eventType, domReady, false);
// A fallback to window.onload, that will always work
win.addEventListener('load', fire, false);
}
// IE event model is used
else {
function stateChange() {
if (doc.readyState === COMPLETE) {
doc.detachEvent(eventType, stateChange);
fire();
}
}
// ensure firing before onload, maybe late but safe also for iframes
doc.attachEvent(eventType, stateChange);
// A fallback to window.onload, that will always work.
win.attachEvent('onload', fire);
// If IE and not a frame
// continually check to see if the document is ready
var notframe = false;
try {
notframe = (win['frameElement'] === null);
} catch(e) {
S.log("frameElement error : ");
S.log(e);
}
if (doScroll && notframe) {
function readyScroll() {
try {
// Ref: http://javascript.nwbox.com/IEContentLoaded/
doScroll('left');
fire();
} catch(ex) {
//S.log("detect document ready : " + ex);
setTimeout(readyScroll, POLL_INTERVAL);
}
}
readyScroll();
}
}
return 0;
}
/**
* Executes functions bound to ready event.
*/
function _fireReady() {
if (isReady) {
return;
}
// Remember that the DOM is ready
isReady = true;
// If there are functions bound, to execute
if (readyList) {
// Execute all of them
var fn, i = 0;
while (fn = readyList[i++]) {
fn.call(win, S);
}
// Reset the list of functions
readyList = null;
}
}
// If url contains '?ks-debug', debug mode will turn on automatically.
if (location && (location.search || EMPTY).indexOf('ks-debug') !== -1) {
S.Config.debug = true;
}
/**
* bind on start
* in case when you bind but the DOMContentLoaded has triggered
* then you has to wait onload
* worst case no callback at all
*/
_bindReady();
})(KISSY, undefined);
/**
* 声明 kissy 核心中所包含的模块,动态加载时将直接从 core.js 中加载核心模块
* @description: 为了和 1.1.7 及以前版本保持兼容,务实与创新,兼容与革新 !
* @author yiminghe@gmail.com
*/
(function (S) {
S.config({
'combines':{
'core':['dom', 'ua', 'event', 'node', 'json', 'ajax', 'anim', 'base', 'cookie']
}
});
})(KISSY);
/**
combined files :
D:\code\kissy_git\kissy1.2\src\ua\base.js
D:\code\kissy_git\kissy1.2\src\ua\extra.js
D:\code\kissy_git\kissy1.2\src\ua.js
D:\code\kissy_git\kissy1.2\src\dom\base.js
D:\code\kissy_git\kissy1.2\src\dom\attr.js
D:\code\kissy_git\kissy1.2\src\dom\class.js
D:\code\kissy_git\kissy1.2\src\dom\create.js
D:\code\kissy_git\kissy1.2\src\dom\data.js
D:\code\kissy_git\kissy1.2\src\dom\insertion.js
D:\code\kissy_git\kissy1.2\src\dom\offset.js
D:\code\kissy_git\kissy1.2\src\dom\style.js
D:\code\kissy_git\kissy1.2\src\dom\selector.js
D:\code\kissy_git\kissy1.2\src\dom\style-ie.js
D:\code\kissy_git\kissy1.2\src\dom\traversal.js
D:\code\kissy_git\kissy1.2\src\dom.js
D:\code\kissy_git\kissy1.2\src\event\keycodes.js
D:\code\kissy_git\kissy1.2\src\event\object.js
D:\code\kissy_git\kissy1.2\src\event\utils.js
D:\code\kissy_git\kissy1.2\src\event\base.js
D:\code\kissy_git\kissy1.2\src\event\target.js
D:\code\kissy_git\kissy1.2\src\event\focusin.js
D:\code\kissy_git\kissy1.2\src\event\hashchange.js
D:\code\kissy_git\kissy1.2\src\event\valuechange.js
D:\code\kissy_git\kissy1.2\src\event\delegate.js
D:\code\kissy_git\kissy1.2\src\event\mouseenter.js
D:\code\kissy_git\kissy1.2\src\event\submit.js
D:\code\kissy_git\kissy1.2\src\event\change.js
D:\code\kissy_git\kissy1.2\src\event\mousewheel.js
D:\code\kissy_git\kissy1.2\src\event.js
D:\code\kissy_git\kissy1.2\src\node\base.js
D:\code\kissy_git\kissy1.2\src\node\attach.js
D:\code\kissy_git\kissy1.2\src\node\override.js
D:\code\kissy_git\kissy1.2\src\anim\easing.js
D:\code\kissy_git\kissy1.2\src\anim\manager.js
D:\code\kissy_git\kissy1.2\src\anim\fx.js
D:\code\kissy_git\kissy1.2\src\anim\queue.js
D:\code\kissy_git\kissy1.2\src\anim\base.js
D:\code\kissy_git\kissy1.2\src\anim\color.js
D:\code\kissy_git\kissy1.2\src\anim.js
D:\code\kissy_git\kissy1.2\src\node\anim.js
D:\code\kissy_git\kissy1.2\src\node.js
D:\code\kissy_git\kissy1.2\src\json\json2.js
D:\code\kissy_git\kissy1.2\src\json.js
D:\code\kissy_git\kissy1.2\src\ajax\form-serializer.js
D:\code\kissy_git\kissy1.2\src\ajax\xhrobject.js
D:\code\kissy_git\kissy1.2\src\ajax\base.js
D:\code\kissy_git\kissy1.2\src\ajax\xhrbase.js
D:\code\kissy_git\kissy1.2\src\ajax\subdomain.js
D:\code\kissy_git\kissy1.2\src\ajax\xdr.js
D:\code\kissy_git\kissy1.2\src\ajax\xhr.js
D:\code\kissy_git\kissy1.2\src\ajax\script.js
D:\code\kissy_git\kissy1.2\src\ajax\jsonp.js
D:\code\kissy_git\kissy1.2\src\ajax\form.js
D:\code\kissy_git\kissy1.2\src\ajax\iframe-upload.js
D:\code\kissy_git\kissy1.2\src\ajax.js
D:\code\kissy_git\kissy1.2\src\base\attribute.js
D:\code\kissy_git\kissy1.2\src\base\base.js
D:\code\kissy_git\kissy1.2\src\base.js
D:\code\kissy_git\kissy1.2\src\cookie\base.js
D:\code\kissy_git\kissy1.2\src\cookie.js
D:\code\kissy_git\kissy1.2\src\core.js
**/
/**
* @module ua
* @author lifesinger@gmail.com
*/
KISSY.add('ua/base', function() {
var ua = navigator.userAgent,
EMPTY = '', MOBILE = 'mobile',
core = EMPTY, shell = EMPTY, m,
IE_DETECT_RANGE = [6, 9], v, end,
VERSION_PLACEHOLDER = '{{version}}',
IE_DETECT_TPL = '<!--[if IE ' + VERSION_PLACEHOLDER + ']><s></s><![endif]-->',
div = document.createElement('div'), s,
o = {
// browser core type
//webkit: 0,
//trident: 0,
//gecko: 0,
//presto: 0,
// browser type
//chrome: 0,
//safari: 0,
//firefox: 0,
//ie: 0,
//opera: 0
//mobile: '',
//core: '',
//shell: ''
},
numberify = function(s) {
var c = 0;
// convert '1.2.3.4' to 1.234
return parseFloat(s.replace(/\./g, function() {
return (c++ === 0) ? '.' : '';
}));
};
// try to use IE-Conditional-Comment detect IE more accurately
// IE10 doesn't support this method, @ref: http://blogs.msdn.com/b/ie/archive/2011/07/06/html5-parsing-in-ie10.aspx
div.innerHTML = IE_DETECT_TPL.replace(VERSION_PLACEHOLDER, '');
s = div.getElementsByTagName('s');
if (s.length > 0) {
shell = 'ie';
o[core = 'trident'] = 0.1; // Trident detected, look for revision
// Get the Trident's accurate version
if ((m = ua.match(/Trident\/([\d.]*)/)) && m[1]) {
o[core] = numberify(m[1]);
}
// Detect the accurate version
// 注意:
// o.shell = ie, 表示外壳是 ie
// 但 o.ie = 7, 并不代表外壳是 ie7, 还有可能是 ie8 的兼容模式
// 对于 ie8 的兼容模式,还要通过 documentMode 去判断。但此处不能让 o.ie = 8, 否则
// 很多脚本判断会失误。因为 ie8 的兼容模式表现行为和 ie7 相同,而不是和 ie8 相同
for (v = IE_DETECT_RANGE[0],end = IE_DETECT_RANGE[1]; v <= end; v++) {
div.innerHTML = IE_DETECT_TPL.replace(VERSION_PLACEHOLDER, v);
if (s.length > 0) {
o[shell] = v;
break;
}
}
} else {
// WebKit
if ((m = ua.match(/AppleWebKit\/([\d.]*)/)) && m[1]) {
o[core = 'webkit'] = numberify(m[1]);
// Chrome
if ((m = ua.match(/Chrome\/([\d.]*)/)) && m[1]) {
o[shell = 'chrome'] = numberify(m[1]);
}
// Safari
else if ((m = ua.match(/\/([\d.]*) Safari/)) && m[1]) {
o[shell = 'safari'] = numberify(m[1]);
}
// Apple Mobile
if (/ Mobile\//.test(ua)) {
o[MOBILE] = 'apple'; // iPad, iPhone or iPod Touch
}
// Other WebKit Mobile Browsers
else if ((m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/))) {
o[MOBILE] = m[0].toLowerCase(); // Nokia N-series, Android, webOS, ex: NokiaN95
}
}
// NOT WebKit
else {
// Presto
// ref: http://www.useragentstring.com/pages/useragentstring.php
if ((m = ua.match(/Presto\/([\d.]*)/)) && m[1]) {
o[core = 'presto'] = numberify(m[1]);
// Opera
if ((m = ua.match(/Opera\/([\d.]*)/)) && m[1]) {
o[shell = 'opera'] = numberify(m[1]); // Opera detected, look for revision
if ((m = ua.match(/Opera\/.* Version\/([\d.]*)/)) && m[1]) {
o[shell] = numberify(m[1]);
}
// Opera Mini
if ((m = ua.match(/Opera Mini[^;]*/)) && m) {
o[MOBILE] = m[0].toLowerCase(); // ex: Opera Mini/2.0.4509/1316
}
// Opera Mobile
// ex: Opera/9.80 (Windows NT 6.1; Opera Mobi/49; U; en) Presto/2.4.18 Version/10.00
// issue: 由于 Opera Mobile 有 Version/ 字段,可能会与 Opera 混淆,同时对于 Opera Mobile 的版本号也比较混乱
else if ((m = ua.match(/Opera Mobi[^;]*/)) && m) {
o[MOBILE] = m[0];
}
}
// NOT WebKit or Presto
} else {
// MSIE
// 由于最开始已经使用了 IE 条件注释判断,因此落到这里的唯一可能性只有 IE10+
if ((m = ua.match(/MSIE\s([^;]*)/)) && m[1]) {
o[core = 'trident'] = 0.1; // Trident detected, look for revision
o[shell = 'ie'] = numberify(m[1]);
// Get the Trident's accurate version
if ((m = ua.match(/Trident\/([\d.]*)/)) && m[1]) {
o[core] = numberify(m[1]);
}
// NOT WebKit, Presto or IE
} else {
// Gecko
if ((m = ua.match(/Gecko/))) {
o[core = 'gecko'] = 0.1; // Gecko detected, look for revision
if ((m = ua.match(/rv:([\d.]*)/)) && m[1]) {
o[core] = numberify(m[1]);
}
// Firefox
if ((m = ua.match(/Firefox\/([\d.]*)/)) && m[1]) {
o[shell = 'firefox'] = numberify(m[1]);
}
}
}
}
}
}
o.core = core;
o.shell = shell;
o._numberify = numberify;
return o;
});
/**
* NOTES:
*
* 2011.11.08
* - ie < 10 使用条件注释判断内核,更精确 by gonghaocn@gmail.com
*
* 2010.03
* - jQuery, YUI 等类库都推荐用特性探测替代浏览器嗅探。特性探测的好处是能自动适应未来设备和未知设备,比如
* if(document.addEventListener) 假设 IE9 支持标准事件,则代码不用修改,就自适应了“未来浏览器”。
* 对于未知浏览器也是如此。但是,这并不意味着浏览器嗅探就得彻底抛弃。当代码很明确就是针对已知特定浏览器的,
* 同时并非是某个特性探测可以解决时,用浏览器嗅探反而能带来代码的简洁,同时也也不会有什么后患。总之,一切
* 皆权衡。
* - UA.ie && UA.ie < 8 并不意味着浏览器就不是 IE8, 有可能是 IE8 的兼容模式。进一步的判断需要使用 documentMode.
*
* TODO:
* - test mobile
* - 3Q 大战后,360 去掉了 UA 信息中的 360 信息,需采用 res 方法去判断
*
*/
/**
* @module ua-extra
* @author gonghao<gonghao@ghsky.com>
*/
KISSY.add('ua/extra', function(S, UA) {
var ua = navigator.userAgent,
m, external, shell,
o = { },
numberify = UA._numberify;
/**
* 说明:
* @子涯总结的各国产浏览器的判断依据: http://spreadsheets0.google.com/ccc?key=tluod2VGe60_ceDrAaMrfMw&hl=zh_CN#gid=0
* 根据 CNZZ 2009 年度浏览器占用率报告,优化了判断顺序:http://www.tanmi360.com/post/230.htm
* 如果检测出浏览器,但是具体版本号未知用 0.1 作为标识
* 世界之窗 & 360 浏览器,在 3.x 以下的版本都无法通过 UA 或者特性检测进行判断,所以目前只要检测到 UA 关键字就认为起版本号为 3
*/
// 360Browser
if (m = ua.match(/360SE/)) {
o[shell = 'se360'] = 3; // issue: 360Browser 2.x cannot be recognised, so if recognised default set verstion number to 3
}
// Maxthon
else if ((m = ua.match(/Maxthon/)) && (external = window.external)) {
// issue: Maxthon 3.x in IE-Core cannot be recognised and it doesn't have exact version number
// but other maxthon versions all have exact version number
shell = 'maxthon';
try {
o[shell] = numberify(external['max_version']);
} catch(ex) {
o[shell] = 0.1;
}
}
// TT
else if (m = ua.match(/TencentTraveler\s([\d.]*)/)) {
o[shell = 'tt'] = m[1] ? numberify(m[1]) : 0.1;
}
// TheWorld
else if (m = ua.match(/TheWorld/)) {
o[shell = 'theworld'] = 3; // issue: TheWorld 2.x cannot be recognised, so if recognised default set verstion number to 3
}
// Sougou
else if (m = ua.match(/SE\s([\d.]*)/)) {
o[shell = 'sougou'] = m[1] ? numberify(m[1]) : 0.1;
}
// If the browser has shell(no matter IE-core or Webkit-core or others), set the shell key
shell && (o.shell = shell);
S.mix(UA, o);
return UA;
}, {
requires:["ua/base"]
});
KISSY.add("ua", function(S,UA) {
return UA;
}, {
requires:["ua/extra"]
});
/**
* @module dom
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('dom/base', function(S, UA, undefined) {
function nodeTypeIs(node, val) {
return node && node.nodeType === val;
}
var NODE_TYPE = {
/**
* enumeration of dom node type
* @type Number
*/
ELEMENT_NODE : 1,
"ATTRIBUTE_NODE" : 2,
TEXT_NODE:3,
"CDATA_SECTION_NODE" : 4,
"ENTITY_REFERENCE_NODE": 5,
"ENTITY_NODE" : 6,
"PROCESSING_INSTRUCTION_NODE" :7,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9,
"DOCUMENT_TYPE_NODE" : 10,
DOCUMENT_FRAGMENT_NODE : 11,
"NOTATION_NODE" : 12
};
var DOM = {
_isCustomDomain :function (win) {
win = win || window;
var domain = win.document.domain,
hostname = win.location.hostname;
return domain != hostname &&
domain != ( '[' + hostname + ']' ); // IPv6 IP support
},
_genEmptyIframeSrc:function(win) {
win = win || window;
if (UA['ie'] && DOM._isCustomDomain(win)) {
return 'javascript:void(function(){' + encodeURIComponent("" +
"document.open();" +
"document.domain='" +
win.document.domain
+ "';" +
"document.close();") + "}())";
}
},
_NODE_TYPE:NODE_TYPE,
/**
* 是不是 element node
*/
_isElementNode: function(elem) {
return nodeTypeIs(elem, DOM.ELEMENT_NODE);
},
/**
* elem 为 window 时,直接返回
* elem 为 document 时,返回关联的 window
* elem 为 undefined 时,返回当前 window
* 其它值,返回 false
*/
_getWin: function(elem) {
return (elem && ('scrollTo' in elem) && elem['document']) ?
elem :
nodeTypeIs(elem, DOM.DOCUMENT_NODE) ?
elem.defaultView || elem.parentWindow :
(elem === undefined || elem === null) ?
window : false;
},
_nodeTypeIs: nodeTypeIs,
// Ref: http://lifesinger.github.com/lab/2010/nodelist.html
_isNodeList:function(o) {
// 注1:ie 下,有 window.item, typeof node.item 在 ie 不同版本下,返回值不同
// 注2:select 等元素也有 item, 要用 !node.nodeType 排除掉
// 注3:通过 namedItem 来判断不可靠
// 注4:getElementsByTagName 和 querySelectorAll 返回的集合不同
// 注5: 考虑 iframe.contentWindow
return o && !o.nodeType && o.item && !o.setTimeout;
},
_nodeName:function(e, name) {
return e && e.nodeName.toLowerCase() === name.toLowerCase();
}
};
S.mix(DOM, NODE_TYPE);
return DOM;
}, {
requires:['ua']
});
/**
* 2011-08
* - 添加键盘枚举值,方便依赖程序清晰
*/
/**
* @module dom-attr
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('dom/attr', function(S, DOM, UA, undefined) {
var doc = document,
docElement = doc.documentElement,
oldIE = !docElement.hasAttribute,
TEXT = docElement.textContent === undefined ?
'innerText' : 'textContent',
EMPTY = '',
nodeName = DOM._nodeName,
isElementNode = DOM._isElementNode,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rinvalidChar = /:|^on/,
rreturn = /\r/g,
attrFix = {
},
attrFn = {
val: 1,
css: 1,
html: 1,
text: 1,
data: 1,
width: 1,
height: 1,
offset: 1,
scrollTop:1,
scrollLeft:1
},
attrHooks = {
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
tabindex:{
get:function(el) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
var attributeNode = el.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt(attributeNode.value, 10) :
rfocusable.test(el.nodeName) || rclickable.test(el.nodeName) && el.href ?
0 :
undefined;
}
},
// 在标准浏览器下,用 getAttribute 获取 style 值
// IE7- 下,需要用 cssText 来获取
// 统一使用 cssText
style:{
get:function(el) {
return el.style.cssText;
},
set:function(el, val) {
el.style.cssText = val;
}
}
},
propFix = {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
"cellpadding": "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
"contenteditable": "contentEditable"
},
// Hook for boolean attributes
// if bool is false
// - standard browser returns null
// - ie<8 return false
// - so norm to undefined
boolHook = {
get: function(elem, name) {
// 转发到 prop 方法
return DOM.prop(elem, name) ?
// 根据 w3c attribute , true 时返回属性名字符串
name.toLowerCase() :
undefined;
},
set: function(elem, value, name) {
var propName;
if (value === false) {
// Remove boolean attributes when set to false
DOM.removeAttr(elem, name);
} else {
// 直接设置 true,因为这是 bool 类属性
propName = propFix[ name ] || name;
if (propName in elem) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute(name, name.toLowerCase());
}
return name;
}
},
propHooks = {},
// get attribute value from attribute node , only for ie
attrNodeHook = {
},
valHooks = {
option: {
get: function(elem) {
// 当没有设定 value 时,标准浏览器 option.value === option.text
// ie7- 下,没有设定 value 时,option.value === '', 需要用 el.attributes.value 来判断是否有设定 value
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
// 对于 select, 特别是 multiple type, 存在很严重的兼容性问题
get: function(elem) {
var index = elem.selectedIndex,
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if (index < 0) {
return null;
} else if (one) {
return DOM.val(options[index]);
}
// Loop through all the selected options
var ret = [], i = 0, len = options.length;
for (; i < len; ++i) {
if (options[i].selected) {
ret.push(DOM.val(options[i]));
}
}
// Multi-Selects return an array
return ret;
},
set: function(elem, value) {
var values = S.makeArray(value),
opts = elem.options;
S.each(opts, function(opt) {
opt.selected = S.inArray(DOM.val(opt), values);
});
if (!values.length) {
elem.selectedIndex = -1;
}
return values;
}
}};
function isTextNode(elem) {
return DOM._nodeTypeIs(elem, DOM.TEXT_NODE);
}
if (oldIE) {
// get attribute value from attribute node for ie
attrNodeHook = {
get: function(elem, name) {
var ret;
ret = elem.getAttributeNode(name);
// Return undefined if nodeValue is empty string
return ret && ret.nodeValue !== "" ?
ret.nodeValue :
undefined;
},
set: function(elem, value, name) {
// Check form objects in IE (multiple bugs related)
// Only use nodeValue if the attribute node exists on the form
var ret = elem.getAttributeNode(name);
if (ret) {
ret.nodeValue = value;
} else {
try {
var attr = elem.ownerDocument.createAttribute(name);
attr.value = value;
elem.setAttributeNode(attr);
}
catch (e) {
// It's a real failure only if setAttribute also fails.
return elem.setAttribute(name, value, 0);
}
}
}
};
// ie6,7 不区分 attribute 与 property
attrFix = propFix;
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
attrHooks.tabIndex = attrHooks.tabindex;
// fix ie bugs
// 不光是 href, src, 还有 rowspan 等非 mapping 属性,也需要用第 2 个参数来获取原始值
// 注意 colSpan rowSpan 已经由 propFix 转为大写
S.each([ "href", "src", "width", "height","colSpan","rowSpan" ], function(name) {
attrHooks[ name ] = {
get: function(elem) {
var ret = elem.getAttribute(name, 2);
return ret === null ? undefined : ret;
}
};
});
// button 元素的 value 属性和其内容冲突
// <button value='xx'>zzz</button>
valHooks.button = attrHooks.value = attrNodeHook;
}
// Radios and checkboxes getter/setter
S.each([ "radio", "checkbox" ], function(r) {
valHooks[ r ] = {
get: function(elem) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
},
set: function(elem, value) {
if (S.isArray(value)) {
return elem.checked = S.inArray(DOM.val(elem), value);
}
}
};
});
function getProp(elem, name) {
name = propFix[ name ] || name;
var hook = propHooks[ name ];
if (hook && hook.get) {
return hook.get(elem, name);
} else {
return elem[ name ];
}
}
S.mix(DOM, {
/**
* 自定义属性不推荐使用,使用 .data
* @param selector
* @param name
* @param value
*/
prop: function(selector, name, value) {
// suports hash
if (S.isPlainObject(name)) {
for (var k in name) {
DOM.prop(selector, k, name[k]);
}
return;
}
var elems = DOM.query(selector);
// Try to normalize/fix the name
name = propFix[ name ] || name;
var hook = propHooks[ name ];
if (value !== undefined) {
elems.each(function(elem) {
if (hook && hook.set) {
hook.set(elem, value, name);
} else {
elem[ name ] = value;
}
});
} else {
if (elems.length) {
return getProp(elems[0], name);
}
}
},
/**
* 是否其中一个元素包含指定 property
* @param selector
* @param name
*/
hasProp:function(selector, name) {
var elems = DOM.query(selector);
for (var i = 0; i < elems.length; i++) {
var el = elems[i];
if (getProp(el, name) !== undefined) {
return true;
}
}
return false;
},
/**
* 不推荐使用,使用 .data .removeData
* @param selector
* @param name
*/
removeProp:function(selector, name) {
name = propFix[ name ] || name;
DOM.query(selector).each(function(el) {
try {
el[ name ] = undefined;
delete el[ name ];
} catch(e) {
S.log("delete el property error : ");
S.log(e);
}
});
},
/**
* Gets the value of an attribute for the first element in the set of matched elements or
* Sets an attribute for the set of matched elements.
*/
attr:function(selector, name, val, pass) {
/*
Hazards From Caja Note:
- In IE[67], el.setAttribute doesn't work for attributes like
'class' or 'for'. IE[67] expects you to set 'className' or
'htmlFor'. Caja use setAttributeNode solves this problem.
- In IE[67], <input> elements can shadow attributes. If el is a
form that contains an <input> named x, then el.setAttribute(x, y)
will set x's value rather than setting el's attribute. Using
setAttributeNode solves this problem.
- In IE[67], the style attribute can only be modified by setting
el.style.cssText. Neither setAttribute nor setAttributeNode will
work. el.style.cssText isn't bullet-proof, since it can be
shadowed by <input> elements.
- In IE[67], you can never change the type of an <button> element.
setAttribute('type') silently fails, but setAttributeNode
throws an exception. caja : the silent failure. KISSY throws error.
- In IE[67], you can never change the type of an <input> element.
setAttribute('type') throws an exception. We want the exception.
- In IE[67], setAttribute is case-sensitive, unless you pass 0 as a
3rd argument. setAttributeNode is case-insensitive.
- Trying to set an invalid name like ":" is supposed to throw an
error. In IE[678] and Opera 10, it fails without an error.
*/
// suports hash
if (S.isPlainObject(name)) {
pass = val;
for (var k in name) {
DOM.attr(selector, k, name[k], pass);
}
return;
}
if (!(name = S.trim(name))) {
return;
}
// attr functions
if (pass && attrFn[name]) {
return DOM[name](selector, val);
}
// scrollLeft
name = name.toLowerCase();
if (pass && attrFn[name]) {
return DOM[name](selector, val);
}
var els = DOM.query(selector);
if (val === undefined) {
return DOM.__attr(els[0], name);
} else {
els.each(function(el) {
DOM.__attr(el, name, val);
});
}
},
__attr:function(el, name, val) {
if (!isElementNode(el)) {
return;
}
// custom attrs
name = attrFix[name] || name;
var attrNormalizer,
ret;
// browsers index elements by id/name on forms, give priority to attributes.
if (nodeName(el, "form")) {
attrNormalizer = attrNodeHook;
}
else if (rboolean.test(name)) {
attrNormalizer = boolHook;
}
// only old ie?
else if (rinvalidChar.test(name)) {
attrNormalizer = attrNodeHook;
} else {
attrNormalizer = attrHooks[name];
}
// getter
if (val === undefined) {
if (attrNormalizer && attrNormalizer.get) {
return attrNormalizer.get(el, name);
}
ret = el.getAttribute(name);
// standard browser non-existing attribute return null
// ie<8 will return undefined , because it return property
// so norm to undefined
return ret === null ? undefined : ret;
} else {
if (attrNormalizer && attrNormalizer.set) {
attrNormalizer.set(el, val, name);
} else {
// convert the value to a string (all browsers do this but IE)
el.setAttribute(name, EMPTY + val);
}
}
},
/**
* Removes the attribute of the matched elements.
*/
removeAttr: function(selector, name) {
name = name.toLowerCase();
name = attrFix[name] || name;
DOM.query(selector).each(function(el) {
if (isElementNode(el)) {
var propName;
el.removeAttribute(name);
// Set corresponding property to false for boolean attributes
if (rboolean.test(name) && (propName = propFix[ name ] || name) in el) {
el[ propName ] = false;
}
}
});
},
/**
* 是否其中一个元素包含指定属性
*/
hasAttr: oldIE ?
function(selector, name) {
name = name.toLowerCase();
var elems = DOM.query(selector);
// from ppk :http://www.quirksmode.org/dom/w3c_core.html
// IE5-7 doesn't return the value of a style attribute.
// var $attr = el.attributes[name];
for (var i = 0; i < elems.length; i++) {
var el = elems[i];
var $attr = el.getAttributeNode(name);
if ($attr && $attr.specified) {
return true;
}
}
return false;
}
:
function(selector, name) {
var elems = DOM.query(selector);
for (var i = 0; i < elems.length; i++) {
var el = elems[i];
//使用原生实现
if (el.hasAttribute(name)) {
return true;
}
}
return false;
},
/**
* Gets the current value of the first element in the set of matched or
* Sets the value of each element in the set of matched elements.
*/
val : function(selector, value) {
var hook, ret;
//getter
if (value === undefined) {
var elem = DOM.get(selector);
if (elem) {
hook = valHooks[ elem.nodeName.toLowerCase() ] || valHooks[ elem.type ];
if (hook && "get" in hook && (ret = hook.get(elem, "value")) !== undefined) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undefined or number
S.isNullOrUndefined(ret) ? "" : ret;
}
return;
}
DOM.query(selector).each(function(elem) {
if (elem.nodeType !== 1) {
return;
}
var val = value;
// Treat null/undefined as ""; convert numbers to string
if (S.isNullOrUndefined(val)) {
val = "";
} else if (typeof val === "number") {
val += "";
} else if (S.isArray(val)) {
val = S.map(val, function (value) {
return S.isNullOrUndefined(val) ? "" : value + "";
});
}
hook = valHooks[ elem.nodeName.toLowerCase() ] || valHooks[ elem.type ];
// If set returns undefined, fall back to normal setting
if (!hook || !("set" in hook) || hook.set(elem, val, "value") === undefined) {
elem.value = val;
}
});
},
/**
* Gets the text context of the first element in the set of matched elements or
* Sets the text content of the matched elements.
*/
text: function(selector, val) {
// getter
if (val === undefined) {
// supports css selector/Node/NodeList
var el = DOM.get(selector);
// only gets value on supported nodes
if (isElementNode(el)) {
return el[TEXT] || EMPTY;
}
else if (isTextNode(el)) {
return el.nodeValue;
}
return undefined;
}
// setter
else {
DOM.query(selector).each(function(el) {
if (isElementNode(el)) {
el[TEXT] = val;
}
else if (isTextNode(el)) {
el.nodeValue = val;
}
});
}
}
});
return DOM;
}, {
requires:["./base","ua"]
}
);
/**
* NOTES:
* 承玉:2011-06-03
* - 借鉴 jquery 1.6,理清 attribute 与 property
*
* 承玉:2011-01-28
* - 处理 tabindex,顺便重构
*
* 2010.03
* - 在 jquery/support.js 中,special attrs 里还有 maxlength, cellspacing,
* rowspan, colspan, useap, frameboder, 但测试发现,在 Grade-A 级浏览器中
* 并无兼容性问题。
* - 当 colspan/rowspan 属性值设置有误时,ie7- 会自动纠正,和 href 一样,需要传递
* 第 2 个参数来解决。jQuery 未考虑,存在兼容性 bug.
* - jQuery 考虑了未显式设定 tabindex 时引发的兼容问题,kissy 里忽略(太不常用了)
* - jquery/attributes.js: Safari mis-reports the default selected
* property of an option 在 Safari 4 中已修复。
*
*/
/**
* @module dom-class
* @author lifesinger@gmail.com
*/
KISSY.add('dom/class', function(S, DOM, undefined) {
var SPACE = ' ',
REG_SPLIT = /[\.\s]\s*\.?/,
REG_CLASS = /[\n\t]/g;
function norm(elemClass) {
return (SPACE + elemClass + SPACE).replace(REG_CLASS, SPACE);
}
S.mix(DOM, {
__hasClass:function(el, cls) {
var className = el.className;
if (className) {
className = norm(className);
return className.indexOf(SPACE + cls + SPACE) > -1;
} else {
return false;
}
},
/**
* Determine whether any of the matched elements are assigned the given class.
*/
hasClass: function(selector, value) {
return batch(selector, value, function(elem, classNames, cl) {
var elemClass = elem.className;
if (elemClass) {
var className = norm(elemClass),
j = 0,
ret = true;
for (; j < cl; j++) {
if (className.indexOf(SPACE + classNames[j] + SPACE) < 0) {
ret = false;
break;
}
}
if (ret) {
return true;
}
}
}, true);
},
/**
* Adds the specified class(es) to each of the set of matched elements.
*/
addClass: function(selector, value) {
batch(selector, value, function(elem, classNames, cl) {
var elemClass = elem.className;
if (!elemClass) {
elem.className = value;
} else {
var className = norm(elemClass),
setClass = elemClass,
j = 0;
for (; j < cl; j++) {
if (className.indexOf(SPACE + classNames[j] + SPACE) < 0) {
setClass += SPACE + classNames[j];
}
}
elem.className = S.trim(setClass);
}
}, undefined);
},
/**
* Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
*/
removeClass: function(selector, value) {
batch(selector, value, function(elem, classNames, cl) {
var elemClass = elem.className;
if (elemClass) {
if (!cl) {
elem.className = '';
} else {
var className = norm(elemClass),
j = 0,
needle;
for (; j < cl; j++) {
needle = SPACE + classNames[j] + SPACE;
// 一个 cls 有可能多次出现:'link link2 link link3 link'
while (className.indexOf(needle) >= 0) {
className = className.replace(needle, SPACE);
}
}
elem.className = S.trim(className);
}
}
}, undefined);
},
/**
* Replace a class with another class for matched elements.
* If no oldClassName is present, the newClassName is simply added.
*/
replaceClass: function(selector, oldClassName, newClassName) {
DOM.removeClass(selector, oldClassName);
DOM.addClass(selector, newClassName);
},
/**
* Add or remove one or more classes from each element in the set of
* matched elements, depending on either the class's presence or the
* value of the switch argument.
* @param state {Boolean} optional boolean to indicate whether class
* should be added or removed regardless of current state.
*/
toggleClass: function(selector, value, state) {
var isBool = S.isBoolean(state), has;
batch(selector, value, function(elem, classNames, cl) {
var j = 0, className;
for (; j < cl; j++) {
className = classNames[j];
has = isBool ? !state : DOM.hasClass(elem, className);
DOM[has ? 'removeClass' : 'addClass'](elem, className);
}
}, undefined);
}
});
function batch(selector, value, fn, resultIsBool) {
if (!(value = S.trim(value))) {
return resultIsBool ? false : undefined;
}
var elems = DOM.query(selector),
len = elems.length,
tmp = value.split(REG_SPLIT),
elem,
ret;
var classNames = [];
for (var i = 0; i < tmp.length; i++) {
var t = S.trim(tmp[i]);
if (t) {
classNames.push(t);
}
}
for (i = 0; i < len; i++) {
elem = elems[i];
if (DOM._isElementNode(elem)) {
ret = fn(elem, classNames, classNames.length);
if (ret !== undefined) {
return ret;
}
}
}
if (resultIsBool) {
return false;
}
return undefined;
}
return DOM;
}, {
requires:["dom/base"]
});
/**
* NOTES:
* - hasClass/addClass/removeClass 的逻辑和 jQuery 保持一致
* - toggleClass 不支持 value 为 undefined 的情形(jQuery 支持)
*/
/**
* @module dom-create
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
KISSY.add('dom/create', function(S, DOM, UA, undefined) {
var doc = document,
ie = UA['ie'],
nodeTypeIs = DOM._nodeTypeIs,
isElementNode = DOM._isElementNode,
isString = S.isString,
DIV = 'div',
PARENT_NODE = 'parentNode',
DEFAULT_DIV = doc.createElement(DIV),
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
RE_TAG = /<([\w:]+)/,
rleadingWhitespace = /^\s+/,
lostLeadingWhitespace = ie && ie < 9,
rhtml = /<|&#?\w+;/,
RE_SIMPLE_TAG = /^<(\w+)\s*\/?>(?:<\/\1>)?$/;
// help compression
function getElementsByTagName(el, tag) {
return el.getElementsByTagName(tag);
}
function cleanData(els) {
var Event = S.require("event");
if (Event) {
Event.detach(els);
}
DOM.removeData(els);
}
S.mix(DOM, {
/**
* Creates a new HTMLElement using the provided html string.
*/
create: function(html, props, ownerDoc, _trim/*internal*/) {
if (isElementNode(html)
|| nodeTypeIs(html, DOM.TEXT_NODE)) {
return DOM.clone(html);
}
var ret = null;
if (!isString(html)) {
return ret;
}
if (_trim === undefined) {
_trim = true;
}
if (_trim) {
html = S.trim(html);
}
if (!html) {
return ret;
}
var creators = DOM._creators,
holder,
whitespaceMatch,
context = ownerDoc || doc,
m,
tag = DIV,
k,
nodes;
if (!rhtml.test(html)) {
ret = context.createTextNode(html);
}
// 简单 tag, 比如 DOM.create('<p>')
else if ((m = RE_SIMPLE_TAG.exec(html))) {
ret = context.createElement(m[1]);
}
// 复杂情况,比如 DOM.create('<img src="sprite.png" />')
else {
// Fix "XHTML"-style tags in all browsers
html = html.replace(rxhtmlTag, "<$1><" + "/$2>");
if ((m = RE_TAG.exec(html)) && (k = m[1])) {
tag = k.toLowerCase();
}
holder = (creators[tag] || creators[DIV])(html, context);
// ie 把前缀空白吃掉了
if (lostLeadingWhitespace && (whitespaceMatch = html.match(rleadingWhitespace))) {
holder.insertBefore(context.createTextNode(whitespaceMatch[0]), holder.firstChild);
}
nodes = holder.childNodes;
if (nodes.length === 1) {
// return single node, breaking parentNode ref from "fragment"
ret = nodes[0][PARENT_NODE].removeChild(nodes[0]);
}
else if (nodes.length) {
// return multiple nodes as a fragment
ret = nl2frag(nodes, context);
} else {
S.error(html + " : create node error");
}
}
return attachProps(ret, props);
},
_creators: {
div: function(html, ownerDoc) {
var frag = ownerDoc && ownerDoc != doc ? ownerDoc.createElement(DIV) : DEFAULT_DIV;
// html 为 <style></style> 时不行,必须有其他元素?
frag['innerHTML'] = "m<div>" + html + "<" + "/div>";
return frag.lastChild;
}
},
/**
* Gets/Sets the HTML contents of the HTMLElement.
* @param {Boolean} loadScripts (optional) True to look for and process scripts (defaults to false).
* @param {Function} callback (optional) For async script loading you can be notified when the update completes.
*/
html: function(selector, val, loadScripts, callback) {
// supports css selector/Node/NodeList
var els = DOM.query(selector),el = els[0];
if (!el) {
return
}
// getter
if (val === undefined) {
// only gets value on the first of element nodes
if (isElementNode(el)) {
return el['innerHTML'];
} else {
return null;
}
}
// setter
else {
var success = false;
val += "";
// faster
if (! val.match(/<(?:script|style)/i) &&
(!lostLeadingWhitespace || !val.match(rleadingWhitespace)) &&
!creatorsMap[ (val.match(RE_TAG) || ["",""])[1].toLowerCase() ]) {
try {
els.each(function(elem) {
if (isElementNode(elem)) {
cleanData(getElementsByTagName(elem, "*"));
elem.innerHTML = val;
}
});
success = true;
} catch(e) {
// a <= "<a>"
// a.innerHTML='<p>1</p>';
}
}
if (!success) {
val = DOM.create(val, 0, el.ownerDocument, false);
els.each(function(elem) {
if (isElementNode(elem)) {
DOM.empty(elem);
DOM.append(val, elem, loadScripts);
}
});
}
callback && callback();
}
},
/**
* Remove the set of matched elements from the DOM.
* 不要使用 innerHTML='' 来清除元素,可能会造成内存泄露,要使用 DOM.remove()
* @param selector 选择器或元素集合
* @param {Boolean} keepData 删除元素时是否保留其上的数据,用于离线操作,提高性能
*/
remove: function(selector, keepData) {
DOM.query(selector).each(function(el) {
if (!keepData && isElementNode(el)) {
// 清楚数据
var elChildren = getElementsByTagName(el, "*");
cleanData(elChildren);
cleanData(el);
}
if (el.parentNode) {
el.parentNode.removeChild(el);
}
});
},
/**
* clone node across browsers for the first node in selector
* @param selector 选择器或单个元素
* @param {Boolean} withDataAndEvent 复制节点是否包括和源节点同样的数据和事件
* @param {Boolean} deepWithDataAndEvent 复制节点的子孙节点是否包括和源节点子孙节点同样的数据和事件
* @refer https://developer.mozilla.org/En/DOM/Node.cloneNode
* @returns 复制后的节点
*/
clone:function(selector, deep, withDataAndEvent, deepWithDataAndEvent) {
var elem = DOM.get(selector);
if (!elem) {
return null;
}
// TODO
// ie bug :
// 1. ie<9 <script>xx</script> => <script></script>
// 2. ie will execute external script
var clone = elem.cloneNode(deep);
if (isElementNode(elem) ||
nodeTypeIs(elem, DOM.DOCUMENT_FRAGMENT_NODE)) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
if (isElementNode(elem)) {
fixAttributes(elem, clone);
}
if (deep) {
processAll(fixAttributes, elem, clone);
}
}
// runtime 获得事件模块
if (withDataAndEvent) {
cloneWidthDataAndEvent(elem, clone);
if (deep && deepWithDataAndEvent) {
processAll(cloneWidthDataAndEvent, elem, clone);
}
}
return clone;
},
empty:function(selector) {
DOM.query(selector).each(function(el) {
DOM.remove(el.childNodes);
});
},
_nl2frag:nl2frag
});
function processAll(fn, elem, clone) {
if (nodeTypeIs(elem, DOM.DOCUMENT_FRAGMENT_NODE)) {
var eCs = elem.childNodes,
cloneCs = clone.childNodes,
fIndex = 0;
while (eCs[fIndex]) {
if (cloneCs[fIndex]) {
processAll(fn, eCs[fIndex], cloneCs[fIndex]);
}
fIndex++;
}
} else if (isElementNode(elem)) {
var elemChildren = getElementsByTagName(elem, "*"),
cloneChildren = getElementsByTagName(clone, "*"),
cIndex = 0;
while (elemChildren[cIndex]) {
if (cloneChildren[cIndex]) {
fn(elemChildren[cIndex], cloneChildren[cIndex]);
}
cIndex++;
}
}
}
// 克隆除了事件的 data
function cloneWidthDataAndEvent(src, dest) {
var Event = S.require('event');
if (isElementNode(dest) && !DOM.hasData(src)) {
return;
}
var srcData = DOM.data(src);
// 浅克隆,data 也放在克隆节点上
for (var d in srcData) {
DOM.data(dest, d, srcData[d]);
}
// 事件要特殊点
if (Event) {
// _removeData 不需要?刚克隆出来本来就没
Event._removeData(dest);
Event._clone(src, dest);
}
}
// wierd ie cloneNode fix from jq
function fixAttributes(src, dest) {
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if (dest.clearAttributes) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if (dest.mergeAttributes) {
dest.mergeAttributes(src);
}
var nodeName = dest.nodeName.toLowerCase(),
srcChilds = src.childNodes;
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if (nodeName === "object" && !dest.childNodes.length) {
for (var i = 0; i < srcChilds.length; i++) {
dest.appendChild(srcChilds[i].cloneNode(true));
}
// dest.outerHTML = src.outerHTML;
} else if (nodeName === "input" && (src.type === "checkbox" || src.type === "radio")) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if (src.checked) {
dest['defaultChecked'] = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if (dest.value !== src.value) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if (nodeName === "option") {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if (nodeName === "input" || nodeName === "textarea") {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
// 自定义 data 根据参数特殊处理,expando 只是个用于引用的属性
dest.removeAttribute(DOM.__EXPANDO);
}
// 添加成员到元素中
function attachProps(elem, props) {
if (S.isPlainObject(props)) {
if (isElementNode(elem)) {
DOM.attr(elem, props, true);
}
// document fragment
else if (nodeTypeIs(elem, DOM.DOCUMENT_FRAGMENT_NODE)) {
DOM.attr(elem.childNodes, props, true);
}
}
return elem;
}
// 将 nodeList 转换为 fragment
function nl2frag(nodes, ownerDoc) {
var ret = null, i, len;
if (nodes
&& (nodes.push || nodes.item)
&& nodes[0]) {
ownerDoc = ownerDoc || nodes[0].ownerDocument;
ret = ownerDoc.createDocumentFragment();
nodes = S.makeArray(nodes);
for (i = 0,len = nodes.length; i < len; i++) {
ret.appendChild(nodes[i]);
}
}
else {
S.log('Unable to convert ' + nodes + ' to fragment.');
}
return ret;
}
// only for gecko and ie
// 2010-10-22: 发现 chrome 也与 gecko 的处理一致了
//if (ie || UA['gecko'] || UA['webkit']) {
// 定义 creators, 处理浏览器兼容
var creators = DOM._creators,
create = DOM.create,
TABLE_OPEN = '<table>',
TABLE_CLOSE = '<' + '/table>',
RE_TBODY = /(?:\/(?:thead|tfoot|caption|col|colgroup)>)+\s*<tbody/,
creatorsMap = {
option: 'select',
optgroup:'select',
area:'map',
thead:'table',
td: 'tr',
th:'tr',
tr: 'tbody',
tbody: 'table',
tfoot:'table',
caption:'table',
colgroup:'table',
col: 'colgroup',
legend: 'fieldset' // ie 支持,但 gecko 不支持
};
for (var p in creatorsMap) {
(function(tag) {
creators[p] = function(html, ownerDoc) {
return create('<' + tag + '>' + html + '<' + '/' + tag + '>', null, ownerDoc);
}
})(creatorsMap[p]);
}
// IE7- adds TBODY when creating thead/tfoot/caption/col/colgroup elements
if (ie < 8) {
creators.tbody = function(html, ownerDoc) {
var frag = create(TABLE_OPEN + html + TABLE_CLOSE, null, ownerDoc),
tbody = frag.children['tags']('tbody')[0];
if (frag.children.length > 1 && tbody && !RE_TBODY.test(html)) {
tbody[PARENT_NODE].removeChild(tbody); // strip extraneous tbody
}
return frag;
};
}
// fix table elements
S.mix(creators, {
thead: creators.tbody,
tfoot: creators.tbody,
caption: creators.tbody,
colgroup: creators.tbody
});
//}
return DOM;
},
{
requires:["./base","ua"]
});
/**
* 2011-10-13
* empty , html refactor
*
* 2011-08-22
* clone 实现,参考 jq
*
* 2011-08
* remove 需要对子孙节点以及自身清除事件以及自定义 data
* create 修改,支持 <style></style> ie 下直接创建
* TODO: jquery clone ,clean 实现
*
* TODO:
* - 研究 jQuery 的 buildFragment 和 clean
* - 增加 cache, 完善 test cases
* - 支持更多 props
* - remove 时,是否需要移除事件,以避免内存泄漏?需要详细的测试。
*/
/**
* @fileOverview dom-data
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
KISSY.add('dom/data', function (S, DOM, undefined) {
var win = window,
EXPANDO = '_ks_data_' + S.now(), // 让每一份 kissy 的 expando 都不同
dataCache = { }, // 存储 node 节点的 data
winDataCache = { }; // 避免污染全局
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
var noData = {
};
noData['applet'] = 1;
noData['object'] = 1;
noData['embed'] = 1;
var commonOps = {
hasData:function (cache, name) {
if (cache) {
if (name !== undefined) {
if (name in cache) {
return true;
}
} else if (!S.isEmptyObject(cache)) {
return true;
}
}
return false;
}
};
var objectOps = {
hasData:function (ob, name) {
// 只判断当前窗口,iframe 窗口内数据直接放入全局变量
if (ob == win) {
return objectOps.hasData(winDataCache, name);
}
// 直接建立在对象内
var thisCache = ob[EXPANDO];
return commonOps.hasData(thisCache, name);
},
data:function (ob, name, value) {
if (ob == win) {
return objectOps.data(winDataCache, name, value);
}
var cache = ob[EXPANDO];
if (value !== undefined) {
cache = ob[EXPANDO] = ob[EXPANDO] || {};
cache[name] = value;
} else {
if (name !== undefined) {
return cache && cache[name];
} else {
cache = ob[EXPANDO] = ob[EXPANDO] || {};
return cache;
}
}
},
removeData:function (ob, name) {
if (ob == win) {
return objectOps.removeData(winDataCache, name);
}
var cache = ob[EXPANDO];
if (name !== undefined) {
delete cache[name];
if (S.isEmptyObject(cache)) {
objectOps.removeData(ob);
}
} else {
try {
// ob maybe window in iframe
// ie will throw error
delete ob[EXPANDO];
} catch (e) {
ob[EXPANDO] = undefined;
}
}
}
};
var domOps = {
hasData:function (elem, name) {
var key = elem[EXPANDO];
if (!key) {
return false;
}
var thisCache = dataCache[key];
return commonOps.hasData(thisCache, name);
},
data:function (elem, name, value) {
if (noData[elem.nodeName.toLowerCase()]) {
return undefined;
}
var key = elem[EXPANDO], cache;
if (!key) {
// 根本不用附加属性
if (name !== undefined &&
value === undefined) {
return undefined;
}
// 节点上关联键值也可以
key = elem[EXPANDO] = S.guid();
}
cache = dataCache[key];
if (value !== undefined) {
// 需要新建
cache = dataCache[key] = dataCache[key] || {};
cache[name] = value;
} else {
if (name !== undefined) {
return cache && cache[name];
} else {
// 需要新建
cache = dataCache[key] = dataCache[key] || {};
return cache;
}
}
},
removeData:function (elem, name) {
var key = elem[EXPANDO], cache;
if (!key) {
return;
}
cache = dataCache[key];
if (name !== undefined) {
delete cache[name];
if (S.isEmptyObject(cache)) {
domOps.removeData(elem);
}
} else {
delete dataCache[key];
try {
delete elem[EXPANDO];
} catch (e) {
elem[EXPANDO] = undefined;
//S.log("delete expando error : ");
//S.log(e);
}
if (elem.removeAttribute) {
elem.removeAttribute(EXPANDO);
}
}
}
};
S.mix(DOM,
/**
* @lends DOM
*/
{
__EXPANDO:EXPANDO,
/**
* whether any node has data
* @param {HTMLElement[]|String} selector 选择器或节点数组
* @param {String} name 数据键名
* @returns {boolean} 节点是否有关联数据键名的值
*/
hasData:function (selector, name) {
var ret = false, elems = DOM.query(selector);
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (checkIsNode(elem)) {
ret = domOps.hasData(elem, name);
} else {
ret = objectOps.hasData(elem, name);
}
if (ret) {
return ret;
}
}
return ret;
},
/**
* Store arbitrary data associated with the matched elements.
* @param {HTMLElement[]|String} selector 选择器或节点数组
* @param {String} [name] 数据键名
* @param {String} [data] 数据键值
* @returns 当不设置 data,设置 name 那么返回: 节点是否有关联数据键名的值
* 当不设置 data, name 那么返回: 节点的存储空间对象
* 当设置 data, name 那么进行设置操作,返回 undefined
*/
data:function (selector, name, data) {
// suports hash
if (S.isPlainObject(name)) {
for (var k in name) {
DOM.data(selector, k, name[k]);
}
return undefined;
}
// getter
if (data === undefined) {
var elem = DOM.get(selector);
if (checkIsNode(elem)) {
return domOps.data(elem, name, data);
} else if (elem) {
return objectOps.data(elem, name, data);
}
}
// setter
else {
DOM.query(selector).each(function (elem) {
if (checkIsNode(elem)) {
domOps.data(elem, name, data);
} else {
objectOps.data(elem, name, data);
}
});
}
return undefined;
},
/**
* Remove a previously-stored piece of data.
* @param {HTMLElement[]|String} selector 选择器或节点数组
* @param {String} [name] 数据键名,不设置时删除关联节点的所有键值对
*/
removeData:function (selector, name) {
DOM.query(selector).each(function (elem) {
if (checkIsNode(elem)) {
domOps.removeData(elem, name);
} else {
objectOps.removeData(elem, name);
}
});
}
});
function checkIsNode(elem) {
// note : 普通对象不要定义 nodeType 这种特殊属性!
return elem && elem.nodeType;
}
return DOM;
}, {
requires:["./base"]
});
/**
* 承玉:2011-05-31
* - 分层 ,节点和普通对象分开处理
**/
/**
* @module dom-insertion
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('dom/insertion', function(S, UA, DOM) {
var PARENT_NODE = 'parentNode',
rformEls = /^(?:button|input|object|select|textarea)$/i,
nodeName = DOM._nodeName,
makeArray = S.makeArray,
_isElementNode = DOM._isElementNode,
NEXT_SIBLING = 'nextSibling';
/**
ie 6,7 lose checked status when append to dom
var c=S.all("<input />");
c.attr("type","radio");
c.attr("checked",true);
S.all("#t").append(c);
alert(c[0].checked);
*/
function fixChecked(ret) {
for (var i = 0; i < ret.length; i++) {
var el = ret[i];
if (el.nodeType == DOM.DOCUMENT_FRAGMENT_NODE) {
fixChecked(el.childNodes);
} else if (nodeName(el, "input")) {
fixCheckedInternal(el);
} else if (_isElementNode(el)) {
var cs = el.getElementsByTagName("input");
for (var j = 0; j < cs.length; j++) {
fixChecked(cs[j]);
}
}
}
}
function fixCheckedInternal(el) {
if (el.type === "checkbox" || el.type === "radio") {
// after insert , in ie6/7 checked is decided by defaultChecked !
el.defaultChecked = el.checked;
}
}
var rscriptType = /\/(java|ecma)script/i;
function isJs(el) {
return !el.type || rscriptType.test(el.type);
}
// extract script nodes and execute alone later
function filterScripts(nodes, scripts) {
var ret = [],i,el,nodeName;
for (i = 0; nodes[i]; i++) {
el = nodes[i];
nodeName = el.nodeName.toLowerCase();
if (el.nodeType == DOM.DOCUMENT_FRAGMENT_NODE) {
ret.push.apply(ret, filterScripts(makeArray(el.childNodes), scripts));
} else if (nodeName === "script" && isJs(el)) {
// remove script to make sure ie9 does not invoke when append
if (el.parentNode) {
el.parentNode.removeChild(el)
}
if (scripts) {
scripts.push(el);
}
} else {
if (_isElementNode(el) &&
// ie checkbox getElementsByTagName 后造成 checked 丢失
!rformEls.test(nodeName)) {
var tmp = [],
s,
j,
ss = el.getElementsByTagName("script");
for (j = 0; j < ss.length; j++) {
s = ss[j];
if (isJs(s)) {
tmp.push(s);
}
}
nodes.splice.apply(nodes, [i + 1,0].concat(tmp));
}
ret.push(el);
}
}
return ret;
}
// execute script
function evalScript(el) {
if (el.src) {
S.getScript(el.src);
} else {
var code = S.trim(el.text || el.textContent || el.innerHTML || "");
if (code) {
S.globalEval(code);
}
}
}
// fragment is easier than nodelist
function insertion(newNodes, refNodes, fn, scripts) {
newNodes = DOM.query(newNodes);
if (scripts) {
scripts = [];
}
// filter script nodes ,process script separately if needed
newNodes = filterScripts(newNodes, scripts);
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7
if (UA['ie'] < 8) {
fixChecked(newNodes);
}
refNodes = DOM.query(refNodes);
var newNodesLength = newNodes.length,
refNodesLength = refNodes.length;
if ((!newNodesLength &&
(!scripts || !scripts.length)) ||
!refNodesLength) {
return;
}
// fragment 插入速度快点
var newNode = DOM._nl2frag(newNodes),
clonedNode;
//fragment 一旦插入里面就空了,先复制下
if (refNodesLength > 1) {
clonedNode = DOM.clone(newNode, true);
}
for (var i = 0; i < refNodesLength; i++) {
var refNode = refNodes[i];
if (newNodesLength) {
//refNodes 超过一个,clone
var node = i > 0 ? DOM.clone(clonedNode, true) : newNode;
fn(node, refNode);
}
if (scripts && scripts.length) {
S.each(scripts, evalScript);
}
}
}
// loadScripts default to false to prevent xss
S.mix(DOM, {
/**
* Inserts the new node as the previous sibling of the reference node.
*/
insertBefore: function(newNodes, refNodes, loadScripts) {
insertion(newNodes, refNodes, function(newNode, refNode) {
if (refNode[PARENT_NODE]) {
refNode[PARENT_NODE].insertBefore(newNode, refNode);
}
}, loadScripts);
},
/**
* Inserts the new node as the next sibling of the reference node.
*/
insertAfter: function(newNodes, refNodes, loadScripts) {
insertion(newNodes, refNodes, function(newNode, refNode) {
if (refNode[PARENT_NODE]) {
refNode[PARENT_NODE].insertBefore(newNode, refNode[NEXT_SIBLING]);
}
}, loadScripts);
},
/**
* Inserts the new node as the last child.
*/
appendTo: function(newNodes, parents, loadScripts) {
insertion(newNodes, parents, function(newNode, parent) {
parent.appendChild(newNode);
}, loadScripts);
},
/**
* Inserts the new node as the first child.
*/
prependTo:function(newNodes, parents, loadScripts) {
insertion(newNodes, parents, function(newNode, parent) {
parent.insertBefore(newNode, parent.firstChild);
}, loadScripts);
}
});
var alias = {
"prepend":"prependTo",
"append":"appendTo",
"before":"insertBefore",
"after":"insertAfter"
};
for (var a in alias) {
DOM[a] = DOM[alias[a]];
}
return DOM;
}, {
requires:["ua","./create"]
});
/**
* 2011-05-25
* - 承玉:参考 jquery 处理多对多的情形 :http://api.jquery.com/append/
* DOM.append(".multi1",".multi2");
*
*/
/**
* @module dom-offset
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
KISSY.add('dom/offset', function(S, DOM, UA, undefined) {
var win = window,
doc = document,
isIE = UA['ie'],
docElem = doc.documentElement,
isElementNode = DOM._isElementNode,
nodeTypeIs = DOM._nodeTypeIs,
getWin = DOM._getWin,
CSS1Compat = "CSS1Compat",
compatMode = "compatMode",
isStrict = doc[compatMode] === CSS1Compat,
MAX = Math.max,
PARSEINT = parseInt,
POSITION = 'position',
RELATIVE = 'relative',
DOCUMENT = 'document',
BODY = 'body',
DOC_ELEMENT = 'documentElement',
OWNER_DOCUMENT = 'ownerDocument',
VIEWPORT = 'viewport',
SCROLL = 'scroll',
CLIENT = 'client',
LEFT = 'left',
TOP = 'top',
isNumber = S.isNumber,
SCROLL_LEFT = SCROLL + 'Left',
SCROLL_TOP = SCROLL + 'Top',
GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect';
// ownerDocument 的判断不保证 elem 没有游离在 document 之外(比如 fragment)
// function inDocument(elem) {
// if (!elem) {
// return 0;
// }
// var doc = elem.ownerDocument;
// if (!doc) {
// return 0;
// }
// var html = doc.documentElement;
// if (html === elem) {
// return true;
// }
// else if (DOM.__contains(html, elem)) {
// return true;
// }
// return false;
// }
S.mix(DOM, {
/**
* Gets the current coordinates of the element, relative to the document.
* @param relativeWin The window to measure relative to. If relativeWin
* is not in the ancestor frame chain of the element, we measure relative to
* the top-most window.
*/
offset: function(selector, val, relativeWin) {
// getter
if (val === undefined) {
var elem = DOM.get(selector),ret;
if (elem) {
ret = getOffset(elem, relativeWin);
}
return ret;
}
// setter
DOM.query(selector).each(function(elem) {
setOffset(elem, val);
});
},
/**
* Makes elem visible in the container
* @param elem
* @param container
* @param top
* @param hscroll
* @param {Boolean} auto whether adjust element automatically
* (it only scrollIntoView when element is out of view)
* @refer http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#scrollIntoView
* http://www.sencha.com/deploy/dev/docs/source/Element.scroll-more.html#scrollIntoView
* http://yiminghe.javaeye.com/blog/390732
*/
scrollIntoView: function(elem, container, top, hscroll, auto) {
if (!(elem = DOM.get(elem))) {
return;
}
if (container) {
container = DOM.get(container);
}
if (!container) {
container = elem.ownerDocument;
}
if (auto !== true) {
hscroll = hscroll === undefined ? true : !!hscroll;
top = top === undefined ? true : !!top;
}
// document 归一化到 window
if (nodeTypeIs(container, DOM.DOCUMENT_NODE)) {
container = getWin(container);
}
var isWin = !!getWin(container),
elemOffset = DOM.offset(elem),
eh = DOM.outerHeight(elem),
ew = DOM.outerWidth(elem),
containerOffset,
ch,
cw,
containerScroll,
diffTop,
diffBottom,
win,
winScroll,
ww,
wh;
if (isWin) {
win = container;
wh = DOM.height(win);
ww = DOM.width(win);
winScroll = {
left:DOM.scrollLeft(win),
top:DOM.scrollTop(win)
};
// elem 相对 container 可视视窗的距离
diffTop = {
left: elemOffset[LEFT] - winScroll[LEFT],
top: elemOffset[TOP] - winScroll[TOP]
};
diffBottom = {
left: elemOffset[LEFT] + ew - (winScroll[LEFT] + ww),
top:elemOffset[TOP] + eh - (winScroll[TOP] + wh)
};
containerScroll = winScroll;
}
else {
containerOffset = DOM.offset(container);
ch = container.clientHeight;
cw = container.clientWidth;
containerScroll = {
left:DOM.scrollLeft(container),
top:DOM.scrollTop(container)
};
// elem 相对 container 可视视窗的距离
// 注意边框 , offset 是边框到根节点
diffTop = {
left: elemOffset[LEFT] - containerOffset[LEFT] -
(PARSEINT(DOM.css(container, 'borderLeftWidth')) || 0),
top: elemOffset[TOP] - containerOffset[TOP] -
(PARSEINT(DOM.css(container, 'borderTopWidth')) || 0)
};
diffBottom = {
left: elemOffset[LEFT] + ew -
(containerOffset[LEFT] + cw +
(PARSEINT(DOM.css(container, 'borderRightWidth')) || 0)) ,
top:elemOffset[TOP] + eh -
(containerOffset[TOP] + ch +
(PARSEINT(DOM.css(container, 'borderBottomWidth')) || 0))
};
}
if (diffTop.top < 0 || diffBottom.top > 0) {
// 强制向上
if (top === true) {
DOM.scrollTop(container, containerScroll.top + diffTop.top);
} else if (top === false) {
DOM.scrollTop(container, containerScroll.top + diffBottom.top);
} else {
// 自动调整
if (diffTop.top < 0) {
DOM.scrollTop(container, containerScroll.top + diffTop.top);
} else {
DOM.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
}
if (hscroll) {
if (diffTop.left < 0 || diffBottom.left > 0) {
// 强制向上
if (top === true) {
DOM.scrollLeft(container, containerScroll.left + diffTop.left);
} else if (top === false) {
DOM.scrollLeft(container, containerScroll.left + diffBottom.left);
} else {
// 自动调整
if (diffTop.left < 0) {
DOM.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
DOM.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
}
}
},
/**
* for idea autocomplete
*/
docWidth:0,
docHeight:0,
viewportHeight:0,
viewportWidth:0
});
// http://old.jr.pl/www.quirksmode.org/viewport/compatibility.html
// http://www.quirksmode.org/dom/w3c_cssom.html
// add ScrollLeft/ScrollTop getter/setter methods
S.each(['Left', 'Top'], function(name, i) {
var method = SCROLL + name;
DOM[method] = function(elem, v) {
if (isNumber(elem)) {
return arguments.callee(win, elem);
}
elem = DOM.get(elem);
var ret,
w = getWin(elem),
d;
if (w) {
if (v !== undefined) {
v = parseFloat(v);
// 注意多 windw 情况,不能简单取 win
var left = name == "Left" ? v : DOM.scrollLeft(w),
top = name == "Top" ? v : DOM.scrollTop(w);
w['scrollTo'](left, top);
} else {
//标准
//chrome == body.scrollTop
//firefox/ie9 == documentElement.scrollTop
ret = w[ 'page' + (i ? 'Y' : 'X') + 'Offset'];
if (!isNumber(ret)) {
d = w[DOCUMENT];
//ie6,7,8 standard mode
ret = d[DOC_ELEMENT][method];
if (!isNumber(ret)) {
//quirks mode
ret = d[BODY][method];
}
}
}
} else if (isElementNode(elem)) {
if (v !== undefined) {
elem[method] = parseFloat(v)
} else {
ret = elem[method];
}
}
return ret;
}
});
// add docWidth/Height, viewportWidth/Height getter methods
S.each(['Width', 'Height'], function(name) {
DOM['doc' + name] = function(refWin) {
refWin = DOM.get(refWin);
var w = getWin(refWin),
d = w[DOCUMENT];
return MAX(
//firefox chrome documentElement.scrollHeight< body.scrollHeight
//ie standard mode : documentElement.scrollHeight> body.scrollHeight
d[DOC_ELEMENT][SCROLL + name],
//quirks : documentElement.scrollHeight 最大等于可视窗口多一点?
d[BODY][SCROLL + name],
DOM[VIEWPORT + name](d));
};
DOM[VIEWPORT + name] = function(refWin) {
refWin = DOM.get(refWin);
var prop = CLIENT + name,
win = getWin(refWin),
doc = win[DOCUMENT],
body = doc[BODY],
documentElement = doc[DOC_ELEMENT],
documentElementProp = documentElement[prop];
// 标准模式取 documentElement
// backcompat 取 body
return doc[compatMode] === CSS1Compat
&& documentElementProp ||
body && body[ prop ] || documentElementProp;
// return (prop in w) ?
// // 标准 = documentElement.clientHeight
// w[prop] :
// // ie 标准 documentElement.clientHeight , 在 documentElement.clientHeight 上滚动?
// // ie quirks body.clientHeight: 在 body 上?
// (isStrict ? d[DOC_ELEMENT][CLIENT + name] : d[BODY][CLIENT + name]);
}
});
function getClientPosition(elem) {
var box, x = 0, y = 0,
body = doc.body,
w = getWin(elem[OWNER_DOCUMENT]);
// 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式
if (elem[GET_BOUNDING_CLIENT_RECT]) {
box = elem[GET_BOUNDING_CLIENT_RECT]();
// 注:jQuery 还考虑减去 docElem.clientLeft/clientTop
// 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确
// 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin
x = box[LEFT];
y = box[TOP];
// ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的
// 窗口边框标准是设 documentElement ,quirks 时设置 body
// 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去
// 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置
// 标准 ie 下 docElem.clientTop 就是 border-top
// ie7 html 即窗口边框改变不了。永远为 2
// 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0
var clientTop = isIE && doc['documentMode'] != 9
&& (isStrict ? docElem.clientTop : body.clientTop)
|| 0,
clientLeft = isIE && doc['documentMode'] != 9
&& (isStrict ? docElem.clientLeft : body.clientLeft)
|| 0;
if (1 > 2) {
}
x -= clientLeft;
y -= clientTop;
// iphone/ipad/itouch 下的 Safari 获取 getBoundingClientRect 时,已经加入 scrollTop
if (UA.mobile == 'apple') {
x -= DOM[SCROLL_LEFT](w);
y -= DOM[SCROLL_TOP](w);
}
}
return { left: x, top: y };
}
function getPageOffset(el) {
var pos = getClientPosition(el);
var w = getWin(el[OWNER_DOCUMENT]);
pos.left += DOM[SCROLL_LEFT](w);
pos.top += DOM[SCROLL_TOP](w);
return pos;
}
// 获取 elem 相对 elem.ownerDocument 的坐标
function getOffset(el, relativeWin) {
var position = {left:0,top:0};
// Iterate up the ancestor frame chain, keeping track of the current window
// and the current element in that window.
var currentWin = getWin(el[OWNER_DOCUMENT]);
var currentEl = el;
relativeWin = relativeWin || currentWin;
do {
// if we're at the top window, we want to get the page offset.
// if we're at an inner frame, we only want to get the window position
// so that we can determine the actual page offset in the context of
// the outer window.
var offset = currentWin == relativeWin ?
getPageOffset(currentEl) :
getClientPosition(currentEl);
position.left += offset.left;
position.top += offset.top;
} while (currentWin && currentWin != relativeWin &&
(currentEl = currentWin['frameElement']) &&
(currentWin = currentWin.parent));
return position;
}
// 设置 elem 相对 elem.ownerDocument 的坐标
function setOffset(elem, offset) {
// set position first, in-case top/left are set even on static elem
if (DOM.css(elem, POSITION) === 'static') {
elem.style[POSITION] = RELATIVE;
}
var old = getOffset(elem), ret = { }, current, key;
for (key in offset) {
current = PARSEINT(DOM.css(elem, key), 10) || 0;
ret[key] = current + offset[key] - old[key];
}
DOM.css(elem, ret);
}
return DOM;
}, {
requires:["./base","ua"]
});
/**
* 2011-05-24
* - 承玉:
* - 调整 docWidth , docHeight ,
* viewportHeight , viewportWidth ,scrollLeft,scrollTop 参数,
* 便于放置到 Node 中去,可以完全摆脱 DOM,完全使用 Node
*
*
*
* TODO:
* - 考虑是否实现 jQuery 的 position, offsetParent 等功能
* - 更详细的测试用例(比如:测试 position 为 fixed 的情况)
*/
/**
* @module dom
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('dom/style', function(S, DOM, UA, undefined) {
var doc = document,
docElem = doc.documentElement,
isIE = UA['ie'],
STYLE = 'style',
FLOAT = 'float',
CSS_FLOAT = 'cssFloat',
STYLE_FLOAT = 'styleFloat',
WIDTH = 'width',
HEIGHT = 'height',
AUTO = 'auto',
DISPLAY = 'display',
OLD_DISPLAY = DISPLAY + S.now(),
NONE = 'none',
PARSEINT = parseInt,
RE_NUMPX = /^-?\d+(?:px)?$/i,
cssNumber = {
"fillOpacity": 1,
"fontWeight": 1,
"lineHeight": 1,
"opacity": 1,
"orphans": 1,
"widows": 1,
"zIndex": 1,
"zoom": 1
},
RE_DASH = /-([a-z])/ig,
CAMELCASE_FN = function(all, letter) {
return letter.toUpperCase();
},
// 考虑 ie9 ...
rupper = /([A-Z]|^ms)/g,
EMPTY = '',
DEFAULT_UNIT = 'px',
CUSTOM_STYLES = {},
cssProps = {},
defaultDisplay = {};
// normalize reserved word float alternatives ("cssFloat" or "styleFloat")
if (docElem[STYLE][CSS_FLOAT] !== undefined) {
cssProps[FLOAT] = CSS_FLOAT;
}
else if (docElem[STYLE][STYLE_FLOAT] !== undefined) {
cssProps[FLOAT] = STYLE_FLOAT;
}
function camelCase(name) {
return name.replace(RE_DASH, CAMELCASE_FN);
}
var defaultDisplayDetectIframe,
defaultDisplayDetectIframeDoc;
// modified from jquery : bullet-proof method of getting default display
// fix domain problem in ie>6 , ie6 still access denied
function getDefaultDisplay(tagName) {
var body,
elem;
if (!defaultDisplay[ tagName ]) {
body = doc.body || doc.documentElement;
elem = doc.createElement(tagName);
DOM.prepend(elem, body);
var oldDisplay = DOM.css(elem, "display");
body.removeChild(elem);
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if (oldDisplay === "none" || oldDisplay === "") {
// No iframe to use yet, so create it
if (!defaultDisplayDetectIframe) {
defaultDisplayDetectIframe = doc.createElement("iframe");
defaultDisplayDetectIframe.frameBorder =
defaultDisplayDetectIframe.width =
defaultDisplayDetectIframe.height = 0;
DOM.prepend(defaultDisplayDetectIframe, body);
var iframeSrc;
if (iframeSrc = DOM._genEmptyIframeSrc()) {
defaultDisplayDetectIframe.src = iframeSrc;
}
} else {
DOM.prepend(defaultDisplayDetectIframe, body);
}
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if (!defaultDisplayDetectIframeDoc || !defaultDisplayDetectIframe.createElement) {
try {
defaultDisplayDetectIframeDoc = defaultDisplayDetectIframe.contentWindow.document;
defaultDisplayDetectIframeDoc.write(( doc.compatMode === "CSS1Compat" ? "<!doctype html>" : "" )
+ "<html><head>" +
(UA['ie'] && DOM._isCustomDomain() ?
"<script>document.domain = '" +
doc.domain
+ "';</script>" : "")
+
"</head><body>");
defaultDisplayDetectIframeDoc.close();
} catch(e) {
// ie6 need a breath , such as alert(8) or setTimeout;
// 同时需要同步,所以无解,勉强返回
return "block";
}
}
elem = defaultDisplayDetectIframeDoc.createElement(tagName);
defaultDisplayDetectIframeDoc.body.appendChild(elem);
oldDisplay = DOM.css(elem, "display");
body.removeChild(defaultDisplayDetectIframe);
}
// Store the correct default display
defaultDisplay[ tagName ] = oldDisplay;
}
return defaultDisplay[ tagName ];
}
S.mix(DOM, {
_camelCase:camelCase,
_cssNumber:cssNumber,
_CUSTOM_STYLES: CUSTOM_STYLES,
_cssProps:cssProps,
_getComputedStyle: function(elem, name) {
var val = "",
computedStyle = {},
d = elem.ownerDocument;
name = name.replace(rupper, "-$1").toLowerCase();
// https://github.com/kissyteam/kissy/issues/61
if (computedStyle = d.defaultView.getComputedStyle(elem, null)) {
val = computedStyle.getPropertyValue(name) || computedStyle[name];
}
// 还没有加入到 document,就取行内
if (val == "" && !DOM.__contains(d.documentElement, elem)) {
name = cssProps[name] || name;
val = elem[STYLE][name];
}
return val;
},
/**
* Get and set the style property on a DOM Node
*/
style:function(selector, name, val) {
// suports hash
if (S.isPlainObject(name)) {
for (var k in name) {
DOM.style(selector, k, name[k]);
}
return;
}
if (val === undefined) {
var elem = DOM.get(selector),ret = '';
if (elem) {
ret = style(elem, name, val);
}
return ret;
} else {
DOM.query(selector).each(function(elem) {
style(elem, name, val);
});
}
},
/**
* (Gets computed style) or (sets styles) on the matches elements.
*/
css: function(selector, name, val) {
// suports hash
if (S.isPlainObject(name)) {
for (var k in name) {
DOM.css(selector, k, name[k]);
}
return;
}
name = camelCase(name);
var hook = CUSTOM_STYLES[name];
// getter
if (val === undefined) {
// supports css selector/Node/NodeList
var elem = DOM.get(selector), ret = '';
if (elem) {
// If a hook was provided get the computed value from there
if (hook && "get" in hook && (ret = hook.get(elem, true)) !== undefined) {
} else {
ret = DOM._getComputedStyle(elem, name);
}
}
return ret === undefined ? '' : ret;
}
// setter
else {
DOM.style(selector, name, val);
}
},
/**
* Show the matched elements.
*/
show: function(selector) {
DOM.query(selector).each(function(elem) {
elem[STYLE][DISPLAY] = DOM.data(elem, OLD_DISPLAY) || EMPTY;
// 可能元素还处于隐藏状态,比如 css 里设置了 display: none
if (DOM.css(elem, DISPLAY) === NONE) {
var tagName = elem.tagName.toLowerCase(),
old = getDefaultDisplay(tagName);
DOM.data(elem, OLD_DISPLAY, old);
elem[STYLE][DISPLAY] = old;
}
});
},
/**
* Hide the matched elements.
*/
hide: function(selector) {
DOM.query(selector).each(function(elem) {
var style = elem[STYLE], old = style[DISPLAY];
if (old !== NONE) {
if (old) {
DOM.data(elem, OLD_DISPLAY, old);
}
style[DISPLAY] = NONE;
}
});
},
/**
* Display or hide the matched elements.
*/
toggle: function(selector) {
DOM.query(selector).each(function(elem) {
if (DOM.css(elem, DISPLAY) === NONE) {
DOM.show(elem);
} else {
DOM.hide(elem);
}
});
},
/**
* Creates a stylesheet from a text blob of rules.
* These rules will be wrapped in a STYLE tag and appended to the HEAD of the document.
* @param {String} cssText The text containing the css rules
* @param {String} id An id to add to the stylesheet for later removal
*/
addStyleSheet: function(refWin, cssText, id) {
if (S.isString(refWin)) {
id = cssText;
cssText = refWin;
refWin = window;
}
refWin = DOM.get(refWin);
var win = DOM._getWin(refWin),doc = win.document;
var elem;
if (id && (id = id.replace('#', EMPTY))) {
elem = DOM.get('#' + id, doc);
}
// 仅添加一次,不重复添加
if (elem) {
return;
}
elem = DOM.create('<style>', { id: id }, doc);
// 先添加到 DOM 树中,再给 cssText 赋值,否则 css hack 会失效
DOM.get('head', doc).appendChild(elem);
if (elem.styleSheet) { // IE
elem.styleSheet.cssText = cssText;
} else { // W3C
elem.appendChild(doc.createTextNode(cssText));
}
},
unselectable:function(selector) {
DOM.query(selector).each(function(elem) {
if (UA['gecko']) {
elem[STYLE]['MozUserSelect'] = 'none';
}
else if (UA['webkit']) {
elem[STYLE]['KhtmlUserSelect'] = 'none';
} else {
if (UA['ie'] || UA['opera']) {
var e,i = 0,
els = elem.getElementsByTagName("*");
elem.setAttribute("unselectable", 'on');
while (( e = els[ i++ ] )) {
switch (e.tagName.toLowerCase()) {
case 'iframe' :
case 'textarea' :
case 'input' :
case 'select' :
/* Ignore the above tags */
break;
default :
e.setAttribute("unselectable", 'on');
}
}
}
}
});
},
innerWidth:0,
innerHeight:0,
outerWidth:0,
outerHeight:0,
width:0,
height:0
});
function capital(str) {
return str.charAt(0).toUpperCase() + str.substring(1);
}
S.each([WIDTH,HEIGHT], function(name) {
DOM["inner" + capital(name)] = function(selector) {
var el = DOM.get(selector);
if (el) {
return getWH(el, name, "padding");
} else {
return null;
}
};
DOM["outer" + capital(name)] = function(selector, includeMargin) {
var el = DOM.get(selector);
if (el) {
return getWH(el, name, includeMargin ? "margin" : "border");
} else {
return null;
}
};
DOM[name] = function(selector, val) {
var ret = DOM.css(selector, name, val);
if (ret) {
ret = parseFloat(ret);
}
return ret;
};
});
var cssShow = { position: "absolute", visibility: "hidden", display: "block" };
/**
* css height,width 永远都是计算值
*/
S.each(["height", "width"], function(name) {
CUSTOM_STYLES[ name ] = {
get: function(elem, computed) {
var val;
if (computed) {
if (elem.offsetWidth !== 0) {
val = getWH(elem, name);
} else {
swap(elem, cssShow, function() {
val = getWH(elem, name);
});
}
return val + "px";
}
},
set: function(elem, value) {
if (RE_NUMPX.test(value)) {
value = parseFloat(value);
if (value >= 0) {
return value + "px";
}
} else {
return value;
}
}
};
});
S.each(["left", "top"], function(name) {
CUSTOM_STYLES[ name ] = {
get: function(elem, computed) {
if (computed) {
var val = DOM._getComputedStyle(elem, name),offset;
// 1. 当没有设置 style.left 时,getComputedStyle 在不同浏览器下,返回值不同
// 比如:firefox 返回 0, webkit/ie 返回 auto
// 2. style.left 设置为百分比时,返回值为百分比
// 对于第一种情况,如果是 relative 元素,值为 0. 如果是 absolute 元素,值为 offsetLeft - marginLeft
// 对于第二种情况,大部分类库都未做处理,属于“明之而不 fix”的保留 bug
if (val === AUTO) {
val = 0;
if (S.inArray(DOM.css(elem, 'position'), ['absolute','fixed'])) {
offset = elem[name === 'left' ? 'offsetLeft' : 'offsetTop'];
// old-ie 下,elem.offsetLeft 包含 offsetParent 的 border 宽度,需要减掉
if (isIE && document['documentMode'] != 9 || UA['opera']) {
// 类似 offset ie 下的边框处理
// 如果 offsetParent 为 html ,需要减去默认 2 px == documentElement.clientTop
// 否则减去 borderTop 其实也是 clientTop
// http://msdn.microsoft.com/en-us/library/aa752288%28v=vs.85%29.aspx
// ie<9 注意有时候 elem.offsetParent 为 null ...
// 比如 DOM.append(DOM.create("<div class='position:absolute'></div>"),document.body)
offset -= elem.offsetParent && elem.offsetParent['client' + (name == 'left' ? 'Left' : 'Top')]
|| 0;
}
val = offset - (PARSEINT(DOM.css(elem, 'margin-' + name)) || 0);
}
val += "px";
}
return val;
}
}
};
});
function swap(elem, options, callback) {
var old = {};
// Remember the old values, and insert the new ones
for (var name in options) {
old[ name ] = elem[STYLE][ name ];
elem[STYLE][ name ] = options[ name ];
}
callback.call(elem);
// Revert the old values
for (name in options) {
elem[STYLE][ name ] = old[ name ];
}
}
function style(elem, name, val) {
var style;
if (elem.nodeType === 3 || elem.nodeType === 8 || !(style = elem[STYLE])) {
return undefined;
}
name = camelCase(name);
var ret,hook = CUSTOM_STYLES[name];
name = cssProps[name] || name;
// setter
if (val !== undefined) {
// normalize unsetting
if (val === null || val === EMPTY) {
val = EMPTY;
}
// number values may need a unit
else if (!isNaN(Number(val)) && !cssNumber[name]) {
val += DEFAULT_UNIT;
}
if (hook && hook.set) {
val = hook.set(elem, val);
}
if (val !== undefined) {
// ie 无效值报错
try {
elem[STYLE][name] = val;
} catch(e) {
S.log("css set error :" + e);
}
}
return undefined;
}
//getter
else {
// If a hook was provided get the non-computed value from there
if (hook && "get" in hook && (ret = hook.get(elem, false)) !== undefined) {
} else {
// Otherwise just get the value from the style object
ret = style[ name ];
}
return ret === undefined ? "" : ret;
}
}
/**
* 得到元素的大小信息
* @param elem
* @param name
* @param {String} extra "padding" : (css width) + padding
* "border" : (css width) + padding + border
* "margin" : (css width) + padding + border + margin
*/
function getWH(elem, name, extra) {
if (S.isWindow(elem)) {
return name == WIDTH ? DOM.viewportWidth(elem) : DOM.viewportHeight(elem);
} else if (elem.nodeType == 9) {
return name == WIDTH ? DOM.docWidth(elem) : DOM.docHeight(elem);
}
var which = name === WIDTH ? ['Left', 'Right'] : ['Top', 'Bottom'],
val = name === WIDTH ? elem.offsetWidth : elem.offsetHeight;
if (val > 0) {
if (extra !== "border") {
S.each(which, function(w) {
if (!extra) {
val -= parseFloat(DOM.css(elem, "padding" + w)) || 0;
}
if (extra === "margin") {
val += parseFloat(DOM.css(elem, extra + w)) || 0;
} else {
val -= parseFloat(DOM.css(elem, "border" + w + "Width")) || 0;
}
});
}
return val
}
// Fall back to computed then uncomputed css if necessary
val = DOM._getComputedStyle(elem, name);
if (val < 0 || S.isNullOrUndefined(val)) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat(val) || 0;
// Add padding, border, margin
if (extra) {
S.each(which, function(w) {
val += parseFloat(DOM.css(elem, "padding" + w)) || 0;
if (extra !== "padding") {
val += parseFloat(DOM.css(elem, "border" + w + "Width")) || 0;
}
if (extra === "margin") {
val += parseFloat(DOM.css(elem, extra + w)) || 0;
}
});
}
return val;
}
return DOM;
}, {
requires:["dom/base","ua"]
});
/**
*
* 2011-08-19
* - 调整结构,减少耦合
* - fix css("height") == auto
*
* NOTES:
* - Opera 下,color 默认返回 #XXYYZZ, 非 rgb(). 目前 jQuery 等类库均忽略此差异,KISSY 也忽略。
* - Safari 低版本,transparent 会返回为 rgba(0, 0, 0, 0), 考虑低版本才有此 bug, 亦忽略。
*
*
* - getComputedStyle 在 webkit 下,会舍弃小数部分,ie 下会四舍五入,gecko 下直接输出 float 值。
*
* - color: blue 继承值,getComputedStyle, 在 ie 下返回 blue, opera 返回 #0000ff, 其它浏览器
* 返回 rgb(0, 0, 255)
*
* - 总之:要使得返回值完全一致是不大可能的,jQuery/ExtJS/KISSY 未“追求完美”。YUI3 做了部分完美处理,但
* 依旧存在浏览器差异。
*/
/**
* @module selector
* @author lifesinger@gmail.com , yiminghe@gmail.com
*/
KISSY.add('dom/selector', function(S, DOM, undefined) {
var doc = document,
filter = S.filter,
require = function(selector) {
return S.require(selector);
},
isArray = S.isArray,
makeArray = S.makeArray,
isNodeList = DOM._isNodeList,
nodeName = DOM._nodeName,
push = Array.prototype.push,
SPACE = ' ',
COMMA = ',',
trim = S.trim,
ANY = '*',
REG_ID = /^#[\w-]+$/,
REG_QUERY = /^(?:#([\w-]+))?\s*([\w-]+|\*)?\.?([\w-]+)?$/;
/**
* Retrieves an Array of HTMLElement based on the given CSS selector.
* @param {String|Array} selector
* @param {String|Array<HTMLElement>|NodeList} context find elements matching selector under context
* @return {Array} The array of found HTMLElement
*/
function query(selector, context) {
var ret,
i,
isSelectorString = typeof selector === 'string',
// optimize common usage
contexts = context === undefined ? [doc] : tuneContext(context);
if (isSelectorString) {
selector = trim(selector);
if (contexts.length == 1 && selector) {
ret = quickFindBySelectorStr(selector, contexts[0]);
}
}
if (!ret) {
ret = [];
if (selector) {
for (i = 0; i < contexts.length; i++) {
push.apply(ret, queryByContexts(selector, contexts[i]));
}
//必要时去重排序
if (ret.length > 1 &&
// multiple contexts
(contexts.length > 1 ||
(isSelectorString &&
// multiple selector
selector.indexOf(COMMA) > -1))) {
unique(ret);
}
}
}
// attach each method
ret.each = function(f) {
var self = this,el,i;
for (i = 0; i < self.length; i++) {
el = self[i];
if (f(el, i) === false) {
break;
}
}
};
return ret;
}
function queryByContexts(selector, context) {
var ret = [],
isSelectorString = typeof selector === 'string';
if (isSelectorString && selector.match(REG_QUERY) ||
!isSelectorString) {
// 简单选择器自己处理
ret = queryBySimple(selector, context);
}
// 如果选择器有 , 分开递归一部分一部分来
else if (isSelectorString && selector.indexOf(COMMA) > -1) {
ret = queryBySelectors(selector, context);
}
else {
// 复杂了,交给 sizzle
ret = queryBySizzle(selector, context);
}
return ret;
}
// 交给 sizzle 模块处理
function queryBySizzle(selector, context) {
var ret = [],
sizzle = require("sizzle");
if (sizzle) {
sizzle(selector, context, ret);
} else {
// 原生不支持
error(selector);
}
return ret;
}
// 处理 selector 的每个部分
function queryBySelectors(selector, context) {
var ret = [],
i,
selectors = selector.split(/\s*,\s*/);
for (i = 0; i < selectors.length; i++) {
push.apply(ret, queryByContexts(selectors[i], context));
}
// 多部分选择器可能得到重复结果
return ret;
}
function quickFindBySelectorStr(selector, context) {
var ret,t,match,id,tag,cls;
// selector 为 #id 是最常见的情况,特殊优化处理
if (REG_ID.test(selector)) {
t = getElementById(selector.slice(1), context);
if (t) {
// #id 无效时,返回空数组
ret = [t];
} else {
ret = [];
}
}
// selector 为支持列表中的其它 6 种
else {
match = REG_QUERY.exec(selector);
if (match) {
// 获取匹配出的信息
id = match[1];
tag = match[2];
cls = match[3];
// 空白前只能有 id ,取出来作为 context
context = (id ? getElementById(id, context) : context);
if (context) {
// #id .cls | #id tag.cls | .cls | tag.cls | #id.cls
if (cls) {
if (!id || selector.indexOf(SPACE) != -1) { // 排除 #id.cls
ret = [].concat(getElementsByClassName(cls, tag, context));
}
// 处理 #id.cls
else {
t = getElementById(id, context);
if (t && hasClass(t, cls)) {
ret = [t];
}
}
}
// #id tag | tag
else if (tag) { // 排除空白字符串
ret = getElementsByTagName(tag, context);
}
}
ret = ret || [];
}
}
return ret;
}
// 最简单情况了,单个选择器部分,单个上下文
function queryBySimple(selector, context) {
var ret,
isSelectorString = typeof selector === 'string';
if (isSelectorString) {
ret = quickFindBySelectorStr(selector, context) || [];
}
// 传入的 selector 是 NodeList 或已是 Array
else if (selector && (isArray(selector) || isNodeList(selector))) {
// 只能包含在 context 里面
ret = filter(selector, function(s) {
return testByContext(s, context);
});
}
// 传入的 selector 是 HTMLNode 查看约束
// 否则 window/document,原样返回
else if (selector && testByContext(selector, context)) {
ret = [selector];
}
return ret;
}
function testByContext(element, context) {
if (!element) {
return false;
}
// 防止 element 节点还没添加到 document ,但是也可以获取到 query(element) => [element]
// document 的上下文一律放行
// context == doc 意味着没有提供第二个参数,到这里只是想单纯包装原生节点,则不检测
if (context == doc) {
return true;
}
// 节点受上下文约束
return DOM.__contains(context, element);
}
var unique;
(function() {
var sortOrder,
t,
hasDuplicate,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
// 排序去重
unique = function (elements) {
if (sortOrder) {
hasDuplicate = baseHasDuplicate;
elements.sort(sortOrder);
if (hasDuplicate) {
var i = 1,len = elements.length;
while (i < len) {
if (elements[i] === elements[ i - 1 ]) {
elements.splice(i, 1);
} else {
i++;
}
}
}
}
return elements;
};
// 貌似除了 ie 都有了...
if (doc.documentElement.compareDocumentPosition) {
sortOrder = t = function(a, b) {
if (a == b) {
hasDuplicate = true;
return 0;
}
if (!a.compareDocumentPosition || !b.compareDocumentPosition) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = t = function(a, b) {
// The nodes are identical, we can exit early
if (a == b) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if (a.sourceIndex && b.sourceIndex) {
return a.sourceIndex - b.sourceIndex;
}
};
}
})();
// 调整 context 为合理值
function tuneContext(context) {
// context 为 undefined 是最常见的情况,优先考虑
if (context === undefined) {
return [doc];
}
// 其他直接使用 query
return query(context, undefined);
}
// query #id
function getElementById(id, context) {
var doc = context,
el;
if (context.nodeType !== DOM.DOCUMENT_NODE) {
doc = context.ownerDocument;
}
el = doc.getElementById(id);
if (el && el.id === id) {
// optimize for common usage
}
else if (el && el.parentNode) {
// ie opera confuse name with id
// https://github.com/kissyteam/kissy/issues/67
// 不能直接 el.id ,否则 input shadow form attribute
if (DOM.__attr(el, "id") !== id) {
// 直接在 context 下的所有节点找
el = DOM.filter(ANY, "#" + id, context)[0] || null;
}
// ie 特殊情况下以及指明在 context 下找了,不需要再判断
// 如果指定了 context node , 还要判断 id 是否处于 context 内
else if (!testByContext(el, context)) {
el = null;
}
} else {
el = null;
}
return el;
}
// query tag
function getElementsByTagName(tag, context) {
return context && makeArray(context.getElementsByTagName(tag)) || [];
}
(function() {
// Check to see if the browser returns only elements
// when doing getElementsByTagName('*')
// Create a fake element
var div = doc.createElement('div');
div.appendChild(doc.createComment(''));
// Make sure no comments are found
if (div.getElementsByTagName(ANY).length > 0) {
getElementsByTagName = function(tag, context) {
var ret = makeArray(context.getElementsByTagName(tag));
if (tag === ANY) {
var t = [], i = 0,node;
while ((node = ret[i++])) {
// Filter out possible comments
if (node.nodeType === 1) {
t.push(node);
}
}
ret = t;
}
return ret;
};
}
})();
// query .cls
var getElementsByClassName = doc.getElementsByClassName ? function(cls, tag, context) {
// query("#id1 xx","#id2")
// #id2 内没有 #id1 , context 为 null , 这里防御下
if (!context) {
return [];
}
var els = context.getElementsByClassName(cls),
ret,
i = 0,
len = els.length,
el;
if (tag && tag !== ANY) {
ret = [];
for (; i < len; ++i) {
el = els[i];
if (nodeName(el, tag)) {
ret.push(el);
}
}
} else {
ret = makeArray(els);
}
return ret;
} : ( doc.querySelectorAll ? function(cls, tag, context) {
// ie8 return staticNodeList 对象,[].concat 会形成 [ staticNodeList ] ,手动转化为普通数组
return context && makeArray(context.querySelectorAll((tag ? tag : '') + '.' + cls)) || [];
} : function(cls, tag, context) {
if (!context) {
return [];
}
var els = context.getElementsByTagName(tag || ANY),
ret = [],
i = 0,
len = els.length,
el;
for (; i < len; ++i) {
el = els[i];
if (hasClass(el, cls)) {
ret.push(el);
}
}
return ret;
});
function hasClass(el, cls) {
return DOM.__hasClass(el, cls);
}
// throw exception
function error(msg) {
S.error('Unsupported selector: ' + msg);
}
S.mix(DOM, {
query: query,
get: function(selector, context) {
return query(selector, context)[0] || null;
},
unique:unique,
/**
* Filters an array of elements to only include matches of a filter.
* @param filter selector or fn
*/
filter: function(selector, filter, context) {
var elems = query(selector, context),
sizzle = require("sizzle"),
match,
tag,
id,
cls,
ret = [];
// 默认仅支持最简单的 tag.cls 或 #id 形式
if (typeof filter === 'string' &&
(filter = trim(filter)) &&
(match = REG_QUERY.exec(filter))) {
id = match[1];
tag = match[2];
cls = match[3];
if (!id) {
filter = function(elem) {
var tagRe = true,clsRe = true;
// 指定 tag 才进行判断
if (tag) {
tagRe = nodeName(elem, tag);
}
// 指定 cls 才进行判断
if (cls) {
clsRe = hasClass(elem, cls);
}
return clsRe && tagRe;
}
} else if (id && !tag && !cls) {
filter = function(elem) {
return DOM.__attr(elem, "id") === id;
};
}
}
if (S.isFunction(filter)) {
ret = S.filter(elems, filter);
}
// 其它复杂 filter, 采用外部选择器
else if (filter && sizzle) {
ret = sizzle.matches(filter, elems);
}
// filter 为空或不支持的 selector
else {
error(filter);
}
return ret;
},
/**
* Returns true if the passed element(s) match the passed filter
*/
test: function(selector, filter, context) {
var elements = query(selector, context);
return elements.length && (DOM.filter(elements, filter, context).length === elements.length);
}
});
return DOM;
}, {
requires:["./base"]
});
/**
* NOTES:
*
* 2011.08.02
* - 利用 sizzle 重构选择器
* - 1.1.6 修正,原来 context 只支持 #id 以及 document
* 1.2 context 支持任意,和 selector 格式一致
* - 简单选择器也和 jquery 保持一致 DOM.query("xx","yy") 支持
* - context 不提供则为当前 document ,否则通过 query 递归取得
* - 保证选择出来的节点(除了 document window)都是位于 context 范围内
*
*
* 2010.01
* - 对 reg exec 的结果(id, tag, className)做 cache, 发现对性能影响很小,去掉。
* - getElementById 使用频率最高,使用直达通道优化。
* - getElementsByClassName 性能优于 querySelectorAll, 但 IE 系列不支持。
* - instanceof 对性能有影响。
* - 内部方法的参数,比如 cls, context 等的异常情况,已经在 query 方法中有保证,无需冗余“防卫”。
* - query 方法中的条件判断考虑了“频率优先”原则。最有可能出现的情况放在前面。
* - Array 的 push 方法可以用 j++ 来替代,性能有提升。
* - 返回值策略和 Sizzle 一致,正常时,返回数组;其它所有情况,返回空数组。
*
* - 从压缩角度考虑,还可以将 getElmentsByTagName 和 getElementsByClassName 定义为常量,
* 不过感觉这样做太“压缩控”,还是保留不替换的好。
*
* - 调整 getElementsByClassName 的降级写法,性能最差的放最后。
*
* 2010.02
* - 添加对分组选择器的支持(主要参考 Sizzle 的代码,代去除了对非 Grade A 级浏览器的支持)
*
* 2010.03
* - 基于原生 dom 的两个 api: S.query 返回数组; S.get 返回第一个。
* 基于 Node 的 api: S.one, 在 Node 中实现。
* 基于 NodeList 的 api: S.all, 在 NodeList 中实现。
* 通过 api 的分层,同时满足初级用户和高级用户的需求。
*
* 2010.05
* - 去掉给 S.query 返回值默认添加的 each 方法,保持纯净。
* - 对于不支持的 selector, 采用外部耦合进来的 Selector.
*
* 2010.06
* - 增加 filter 和 test 方法
*
* 2010.07
* - 取消对 , 分组的支持,group 直接用 Sizzle
*
* 2010.08
* - 给 S.query 的结果 attach each 方法
*
* 2011.05
* - 承玉:恢复对简单分组支持
*
* Ref: http://ejohn.org/blog/selectors-that-people-actually-use/
* 考虑 2/8 原则,仅支持以下选择器:
* #id
* tag
* .cls
* #id tag
* #id .cls
* tag.cls
* #id tag.cls
* 注 1:REG_QUERY 还会匹配 #id.cls
* 注 2:tag 可以为 * 字符
* 注 3: 支持 , 号分组
*
*
* Bugs:
* - S.query('#test-data *') 等带 * 号的选择器,在 IE6 下返回的值不对。jQuery 等类库也有此 bug, 诡异。
*
* References:
* - http://ejohn.org/blog/selectors-that-people-actually-use/
* - http://ejohn.org/blog/thoughts-on-queryselectorall/
* - MDC: querySelector, querySelectorAll, getElementsByClassName
* - Sizzle: http://github.com/jeresig/sizzle
* - MINI: http://james.padolsey.com/javascript/mini/
* - Peppy: http://jamesdonaghue.com/?p=40
* - Sly: http://github.com/digitarald/sly
* - XPath, TreeWalker:http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1529640.html
*
* - http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
* - http://www.quirksmode.org/dom/getElementsByTagNames.html
* - http://ejohn.org/blog/comparing-document-position/
* - http://github.com/jeresig/sizzle/blob/master/sizzle.js
*/
/**
* @module dom
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
KISSY.add('dom/style-ie', function(S, DOM, UA, Style) {
var HUNDRED = 100;
// only for ie
if (!UA['ie']) {
return DOM;
}
var doc = document,
docElem = doc.documentElement,
OPACITY = 'opacity',
STYLE = 'style',
FILTER = "filter",
CURRENT_STYLE = 'currentStyle',
RUNTIME_STYLE = 'runtimeStyle',
LEFT = 'left',
PX = 'px',
CUSTOM_STYLES = Style._CUSTOM_STYLES,
RE_NUMPX = /^-?\d+(?:px)?$/i,
RE_NUM = /^-?\d/,
ropacity = /opacity=([^)]*)/,
ralpha = /alpha\([^)]*\)/i;
// use alpha filter for IE opacity
try {
if (S.isNullOrUndefined(docElem.style[OPACITY])) {
CUSTOM_STYLES[OPACITY] = {
get: function(elem, computed) {
// 没有设置过 opacity 时会报错,这时返回 1 即可
// 如果该节点没有添加到 dom ,取不到 filters 结构
// val = elem[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY];
return ropacity.test((
computed && elem[CURRENT_STYLE] ?
elem[CURRENT_STYLE][FILTER] :
elem[STYLE][FILTER]) || "") ?
( parseFloat(RegExp.$1) / HUNDRED ) + "" :
computed ? "1" : "";
},
set: function(elem, val) {
val = parseFloat(val);
var style = elem[STYLE],
currentStyle = elem[CURRENT_STYLE],
opacity = isNaN(val) ? "" : "alpha(" + OPACITY + "=" + val * HUNDRED + ")",
filter = S.trim(currentStyle && currentStyle[FILTER] || style[FILTER] || "");
// ie has layout
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute
if (val >= 1 && S.trim(filter.replace(ralpha, "")) === "") {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute(FILTER);
// if there there is no filter style applied in a css rule, we are done
if (currentStyle && !currentStyle[FILTER]) {
return;
}
}
// otherwise, set new filter values
// 如果 >=1 就不设,就不能覆盖外部样式表定义的样式,一定要设
style.filter = ralpha.test(filter) ?
filter.replace(ralpha, opacity) :
filter + (filter ? ", " : "") + opacity;
}
};
}
}
catch(ex) {
S.log('IE filters ActiveX is disabled. ex = ' + ex);
}
/**
* border fix
* ie 不设置数值,则 computed style 不返回数值,只返回 thick? medium ...
* (default is "medium")
*/
var IE8 = UA['ie'] == 8,
BORDER_MAP = {
},
BORDERS = ["","Top","Left","Right","Bottom"];
BORDER_MAP['thin'] = IE8 ? '1px' : '2px';
BORDER_MAP['medium'] = IE8 ? '3px' : '4px';
BORDER_MAP['thick'] = IE8 ? '5px' : '6px';
S.each(BORDERS, function(b) {
var name = "border" + b + "Width",
styleName = "border" + b + "Style";
CUSTOM_STYLES[name] = {
get: function(elem, computed) {
// 只有需要计算样式的时候才转换,否则取原值
var currentStyle = computed ? elem[CURRENT_STYLE] : 0,
current = currentStyle && String(currentStyle[name]) || undefined;
// look up keywords if a border exists
if (current && current.indexOf("px") < 0) {
// 边框没有隐藏
if (BORDER_MAP[current] && currentStyle[styleName] !== "none") {
current = BORDER_MAP[current];
} else {
// otherwise no border
current = 0;
}
}
return current;
}
};
});
// getComputedStyle for IE
if (!(doc.defaultView || { }).getComputedStyle && docElem[CURRENT_STYLE]) {
DOM._getComputedStyle = function(elem, name) {
name = DOM._cssProps[name] || name;
var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];
// 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值
// 一开始就处理了! CUSTOM_STYLE["height"],CUSTOM_STYLE["width"] ,cssHook 解决@2011-08-19
// 在 ie 下不对,需要直接用 offset 方式
// borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ((!RE_NUMPX.test(ret) && RE_NUM.test(ret))) {
// Remember the original values
var style = elem[STYLE],
left = style[LEFT],
rsLeft = elem[RUNTIME_STYLE] && elem[RUNTIME_STYLE][LEFT];
// Put in the new values to get a computed value out
if (rsLeft) {
elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];
}
style[LEFT] = name === 'fontSize' ? '1em' : (ret || 0);
ret = style['pixelLeft'] + PX;
// Revert the changed values
style[LEFT] = left;
if (rsLeft) {
elem[RUNTIME_STYLE][LEFT] = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
return DOM;
},
{
requires:["./base","ua","./style"]
}
);
/**
* NOTES:
* 承玉: 2011.05.19 opacity in ie
* - 如果节点是动态创建,设置opacity,没有加到 dom 前,取不到 opacity 值
* - 兼容:border-width 值,ie 下有可能返回 medium/thin/thick 等值,其它浏览器返回 px 值。
*
* - opacity 的实现,参考自 jquery
*
*/
/**
* @module dom-traversal
* @author lifesinger@gmail.com,yiminghe@gmail.com
*/
KISSY.add('dom/traversal', function(S, DOM, undefined) {
var isElementNode = DOM._isElementNode,
CONTAIN_MASK = 16;
S.mix(DOM, {
closest:function(selector, filter, context) {
return nth(selector, filter, 'parentNode', function(elem) {
return elem.nodeType != DOM.DOCUMENT_FRAGMENT_NODE;
}, context, true);
},
/**
* Gets the parent node of the first matched element.
*/
parent: function(selector, filter, context) {
return nth(selector, filter, 'parentNode', function(elem) {
return elem.nodeType != DOM.DOCUMENT_FRAGMENT_NODE;
}, context);
},
first:function(selector, filter) {
var elem = DOM.get(selector);
return nth(elem && elem.firstChild, filter, 'nextSibling',
undefined, undefined, true);
},
last:function(selector, filter) {
var elem = DOM.get(selector);
return nth(elem && elem.lastChild, filter, 'previousSibling',
undefined, undefined, true);
},
/**
* Gets the following sibling of the first matched element.
*/
next: function(selector, filter) {
return nth(selector, filter, 'nextSibling', undefined);
},
/**
* Gets the preceding sibling of the first matched element.
*/
prev: function(selector, filter) {
return nth(selector, filter, 'previousSibling', undefined);
},
/**
* Gets the siblings of the first matched element.
*/
siblings: function(selector, filter) {
return getSiblings(selector, filter, true);
},
/**
* Gets the children of the first matched element.
*/
children: function(selector, filter) {
return getSiblings(selector, filter, undefined);
},
__contains:document.documentElement.contains ?
function(a, b) {
if (a.nodeType == DOM.TEXT_NODE) {
return false;
}
var precondition;
if (b.nodeType == DOM.TEXT_NODE) {
b = b.parentNode;
// a 和 b父亲相等也就是返回 true
precondition = true;
} else if (b.nodeType == DOM.DOCUMENT_NODE) {
// b === document
// 没有任何元素能包含 document
return false;
} else {
// a 和 b 相等返回 false
precondition = a !== b;
}
// !a.contains => a===document
// 注意原生 contains 判断时 a===b 也返回 true
return precondition && (a.contains ? a.contains(b) : true);
} : (
document.documentElement.compareDocumentPosition ?
function(a, b) {
return !!(a.compareDocumentPosition(b) & CONTAIN_MASK);
} :
// it can not be true , pathetic browser
0
),
/**
* Check to see if a DOM node is within another DOM node.
*/
contains:
function(a, b) {
a = DOM.get(a);
b = DOM.get(b);
if (a && b) {
return DOM.__contains(a, b);
}
},
equals:function(n1, n2) {
n1 = DOM.query(n1);
n2 = DOM.query(n2);
if (n1.length != n2.length) {
return false;
}
for (var i = n1.length; i >= 0; i--) {
if (n1[i] != n2[i]) {
return false;
}
}
return true;
}
});
// 获取元素 elem 在 direction 方向上满足 filter 的第一个元素
// filter 可为 number, selector, fn array ,为数组时返回多个
// direction 可为 parentNode, nextSibling, previousSibling
// context : 到某个阶段不再查找直接返回
function nth(elem, filter, direction, extraFilter, context, includeSef) {
if (!(elem = DOM.get(elem))) {
return null;
}
if (filter === 0) {
return elem;
}
if (!includeSef) {
elem = elem[direction];
}
if (!elem) {
return null;
}
context = (context && DOM.get(context)) || null;
if (filter === undefined) {
// 默认取 1
filter = 1;
}
var ret = [],
isArray = S.isArray(filter),
fi,
flen;
if (S.isNumber(filter)) {
fi = 0;
flen = filter;
filter = function() {
return ++fi === flen;
};
}
// 概念统一,都是 context 上下文,只过滤子孙节点,自己不管
while (elem && elem != context) {
if (isElementNode(elem)
&& testFilter(elem, filter)
&& (!extraFilter || extraFilter(elem))) {
ret.push(elem);
if (!isArray) {
break;
}
}
elem = elem[direction];
}
return isArray ? ret : ret[0] || null;
}
function testFilter(elem, filter) {
if (!filter) {
return true;
}
if (S.isArray(filter)) {
for (var i = 0; i < filter.length; i++) {
if (DOM.test(elem, filter[i])) {
return true;
}
}
} else if (DOM.test(elem, filter)) {
return true;
}
return false;
}
// 获取元素 elem 的 siblings, 不包括自身
function getSiblings(selector, filter, parent) {
var ret = [],
elem = DOM.get(selector),
j,
parentNode = elem,
next;
if (elem && parent) {
parentNode = elem.parentNode;
}
if (parentNode) {
for (j = 0,next = parentNode.firstChild;
next;
next = next.nextSibling) {
if (isElementNode(next)
&& next !== elem
&& (!filter || DOM.test(next, filter))) {
ret[j++] = next;
}
}
}
return ret;
}
return DOM;
}, {
requires:["./base"]
});
/**
* 2011-08
* - 添加 closest , first ,last 完全摆脱原生属性
*
* NOTES:
* - jquery does not return null ,it only returns empty array , but kissy does.
*
* - api 的设计上,没有跟随 jQuery. 一是为了和其他 api 一致,保持 first-all 原则。二是
* 遵循 8/2 原则,用尽可能少的代码满足用户最常用的功能。
*
*/
KISSY.add("dom", function(S,DOM) {
return DOM;
}, {
requires:["dom/attr",
"dom/class",
"dom/create",
"dom/data",
"dom/insertion",
"dom/offset",
"dom/style",
"dom/selector",
"dom/style-ie",
"dom/traversal"]
});
/**
* @fileOverview some keycodes definition and utils from closure-library
* @author yiminghe@gmail.com
*/
KISSY.add("event/keycodes", function() {
var KeyCodes = {
MAC_ENTER: 3,
BACKSPACE: 8,
TAB: 9,
NUM_CENTER: 12, // NUMLOCK on FF/Safari Mac
ENTER: 13,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAUSE: 19,
CAPS_LOCK: 20,
ESC: 27,
SPACE: 32,
PAGE_UP: 33, // also NUM_NORTH_EAST
PAGE_DOWN: 34, // also NUM_SOUTH_EAST
END: 35, // also NUM_SOUTH_WEST
HOME: 36, // also NUM_NORTH_WEST
LEFT: 37, // also NUM_WEST
UP: 38, // also NUM_NORTH
RIGHT: 39, // also NUM_EAST
DOWN: 40, // also NUM_SOUTH
PRINT_SCREEN: 44,
INSERT: 45, // also NUM_INSERT
DELETE: 46, // also NUM_DELETE
ZERO: 48,
ONE: 49,
TWO: 50,
THREE: 51,
FOUR: 52,
FIVE: 53,
SIX: 54,
SEVEN: 55,
EIGHT: 56,
NINE: 57,
QUESTION_MARK: 63, // needs localization
A: 65,
B: 66,
C: 67,
D: 68,
E: 69,
F: 70,
G: 71,
H: 72,
I: 73,
J: 74,
K: 75,
L: 76,
M: 77,
N: 78,
O: 79,
P: 80,
Q: 81,
R: 82,
S: 83,
T: 84,
U: 85,
V: 86,
W: 87,
X: 88,
Y: 89,
Z: 90,
META: 91, // WIN_KEY_LEFT
WIN_KEY_RIGHT: 92,
CONTEXT_MENU: 93,
NUM_ZERO: 96,
NUM_ONE: 97,
NUM_TWO: 98,
NUM_THREE: 99,
NUM_FOUR: 100,
NUM_FIVE: 101,
NUM_SIX: 102,
NUM_SEVEN: 103,
NUM_EIGHT: 104,
NUM_NINE: 105,
NUM_MULTIPLY: 106,
NUM_PLUS: 107,
NUM_MINUS: 109,
NUM_PERIOD: 110,
NUM_DIVISION: 111,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
NUMLOCK: 144,
SEMICOLON: 186, // needs localization
DASH: 189, // needs localization
EQUALS: 187, // needs localization
COMMA: 188, // needs localization
PERIOD: 190, // needs localization
SLASH: 191, // needs localization
APOSTROPHE: 192, // needs localization
SINGLE_QUOTE: 222, // needs localization
OPEN_SQUARE_BRACKET: 219, // needs localization
BACKSLASH: 220, // needs localization
CLOSE_SQUARE_BRACKET: 221, // needs localization
WIN_KEY: 224,
MAC_FF_META: 224, // Firefox (Gecko) fires this for the meta key instead of 91
WIN_IME: 229
};
KeyCodes.isTextModifyingKeyEvent = function(e) {
if (e.altKey && !e.ctrlKey ||
e.metaKey ||
// Function keys don't generate text
e.keyCode >= KeyCodes.F1 &&
e.keyCode <= KeyCodes.F12) {
return false;
}
// The following keys are quite harmless, even in combination with
// CTRL, ALT or SHIFT.
switch (e.keyCode) {
case KeyCodes.ALT:
case KeyCodes.CAPS_LOCK:
case KeyCodes.CONTEXT_MENU:
case KeyCodes.CTRL:
case KeyCodes.DOWN:
case KeyCodes.END:
case KeyCodes.ESC:
case KeyCodes.HOME:
case KeyCodes.INSERT:
case KeyCodes.LEFT:
case KeyCodes.MAC_FF_META:
case KeyCodes.META:
case KeyCodes.NUMLOCK:
case KeyCodes.NUM_CENTER:
case KeyCodes.PAGE_DOWN:
case KeyCodes.PAGE_UP:
case KeyCodes.PAUSE:
case KeyCodes.PHANTOM:
case KeyCodes.PRINT_SCREEN:
case KeyCodes.RIGHT:
case KeyCodes.SHIFT:
case KeyCodes.UP:
case KeyCodes.WIN_KEY:
case KeyCodes.WIN_KEY_RIGHT:
return false;
default:
return true;
}
};
KeyCodes.isCharacterKey = function(keyCode) {
if (keyCode >= KeyCodes.ZERO &&
keyCode <= KeyCodes.NINE) {
return true;
}
if (keyCode >= KeyCodes.NUM_ZERO &&
keyCode <= KeyCodes.NUM_MULTIPLY) {
return true;
}
if (keyCode >= KeyCodes.A &&
keyCode <= KeyCodes.Z) {
return true;
}
// Safari sends zero key code for non-latin characters.
if (goog.userAgent.WEBKIT && keyCode == 0) {
return true;
}
switch (keyCode) {
case KeyCodes.SPACE:
case KeyCodes.QUESTION_MARK:
case KeyCodes.NUM_PLUS:
case KeyCodes.NUM_MINUS:
case KeyCodes.NUM_PERIOD:
case KeyCodes.NUM_DIVISION:
case KeyCodes.SEMICOLON:
case KeyCodes.DASH:
case KeyCodes.EQUALS:
case KeyCodes.COMMA:
case KeyCodes.PERIOD:
case KeyCodes.SLASH:
case KeyCodes.APOSTROPHE:
case KeyCodes.SINGLE_QUOTE:
case KeyCodes.OPEN_SQUARE_BRACKET:
case KeyCodes.BACKSLASH:
case KeyCodes.CLOSE_SQUARE_BRACKET:
return true;
default:
return false;
}
};
return KeyCodes;
});
/**
* @module EventObject
* @author lifesinger@gmail.com
*/
KISSY.add('event/object', function(S, undefined) {
var doc = document,
props = ('altKey attrChange attrName bubbles button cancelable ' +
'charCode clientX clientY ctrlKey currentTarget data detail ' +
'eventPhase fromElement handler keyCode metaKey ' +
'newValue offsetX offsetY originalTarget pageX pageY prevValue ' +
'relatedNode relatedTarget screenX screenY shiftKey srcElement ' +
'target toElement view wheelDelta which axis').split(' ');
/**
* KISSY's event system normalizes the event object according to
* W3C standards. The event object is guaranteed to be passed to
* the event handler. Most properties from the original event are
* copied over and normalized to the new event object.
*/
function EventObject(currentTarget, domEvent, type) {
var self = this;
self.currentTarget = currentTarget;
self.originalEvent = domEvent || { };
if (domEvent) { // html element
self.type = domEvent.type;
self._fix();
}
else { // custom
self.type = type;
self.target = currentTarget;
}
// bug fix: in _fix() method, ie maybe reset currentTarget to undefined.
self.currentTarget = currentTarget;
self.fixed = true;
}
S.augment(EventObject, {
_fix: function() {
var self = this,
originalEvent = self.originalEvent,
l = props.length, prop,
ct = self.currentTarget,
ownerDoc = (ct.nodeType === 9) ? ct : (ct.ownerDocument || doc); // support iframe
// clone properties of the original event object
while (l) {
prop = props[--l];
self[prop] = originalEvent[prop];
}
// fix target property, if necessary
if (!self.target) {
self.target = self.srcElement || doc; // srcElement might not be defined either
}
// check if target is a textnode (safari)
if (self.target.nodeType === 3) {
self.target = self.target.parentNode;
}
// add relatedTarget, if necessary
if (!self.relatedTarget && self.fromElement) {
self.relatedTarget = (self.fromElement === self.target) ? self.toElement : self.fromElement;
}
// calculate pageX/Y if missing and clientX/Y available
if (self.pageX === undefined && self.clientX !== undefined) {
var docEl = ownerDoc.documentElement, bd = ownerDoc.body;
self.pageX = self.clientX + (docEl && docEl.scrollLeft || bd && bd.scrollLeft || 0) - (docEl && docEl.clientLeft || bd && bd.clientLeft || 0);
self.pageY = self.clientY + (docEl && docEl.scrollTop || bd && bd.scrollTop || 0) - (docEl && docEl.clientTop || bd && bd.clientTop || 0);
}
// add which for key events
if (self.which === undefined) {
self.which = (self.charCode === undefined) ? self.keyCode : self.charCode;
}
// add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if (self.metaKey === undefined) {
self.metaKey = self.ctrlKey;
}
// add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if (!self.which && self.button !== undefined) {
self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : ( self.button & 4 ? 2 : 0)));
}
},
/**
* Prevents the event's default behavior
*/
preventDefault: function() {
var e = this.originalEvent;
// if preventDefault exists run it on the original event
if (e.preventDefault) {
e.preventDefault();
}
// otherwise set the returnValue property of the original event to false (IE)
else {
e.returnValue = false;
}
this.isDefaultPrevented = true;
},
/**
* Stops the propagation to the next bubble target
*/
stopPropagation: function() {
var e = this.originalEvent;
// if stopPropagation exists run it on the original event
if (e.stopPropagation) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
else {
e.cancelBubble = true;
}
this.isPropagationStopped = true;
},
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
*/
stopImmediatePropagation: function() {
var self = this;
self.isImmediatePropagationStopped = true;
// fixed 1.2
// call stopPropagation implicitly
self.stopPropagation();
},
/**
* Stops the event propagation and prevents the default
* event behavior.
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
halt: function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
}
});
if (1 > 2) {
alert(S.cancelBubble);
}
return EventObject;
});
/**
* NOTES:
*
* 2010.04
* - http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
*
* TODO:
* - pageX, clientX, scrollLeft, clientLeft 的详细测试
*/
/**
* utils for event
* @author yiminghe@gmail.com
*/
KISSY.add("event/utils", function(S, DOM) {
/**
* whether two event listens are the same
* @param h1 已有的 handler 描述
* @param h2 用户提供的 handler 描述
*/
function isIdenticalHandler(h1, h2, el) {
var scope1 = h1.scope || el,
ret = 1,
d1,
d2,
scope2 = h2.scope || el;
if (h1.fn !== h2.fn
|| scope1 !== scope2) {
ret = 0;
} else if ((d1 = h1.data) !== (d2 = h2.data)) {
// undelgate 不能 remove 普通 on 的 handler
// remove 不能 remove delegate 的 handler
if (!d1 && d2
|| d1 && !d2
) {
ret = 0;
} else if (d1 && d2) {
if (!d1.equals || !d2.equals) {
S.error("no equals in data");
} else if (!d1.equals(d2,el)) {
ret = 0;
}
}
}
return ret;
}
function isValidTarget(target) {
// 3 - is text node
// 8 - is comment node
return target &&
target.nodeType !== DOM.TEXT_NODE &&
target.nodeType !== DOM.COMMENT_NODE;
}
function batchForType(obj, methodName, targets, types) {
// on(target, 'click focus', fn)
if (types && types.indexOf(" ") > 0) {
var args = S.makeArray(arguments);
S.each(types.split(/\s+/), function(type) {
var args2 = [].concat(args);
args2.splice(0, 4, targets, type);
obj[methodName].apply(obj, args2);
});
return true;
}
return 0;
}
function splitAndRun(type, fn) {
S.each(type.split(/\s+/), fn);
}
var doc = document,
simpleAdd = doc.addEventListener ?
function(el, type, fn, capture) {
if (el.addEventListener) {
el.addEventListener(type, fn, !!capture);
}
} :
function(el, type, fn) {
if (el.attachEvent) {
el.attachEvent('on' + type, fn);
}
},
simpleRemove = doc.removeEventListener ?
function(el, type, fn, capture) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, !!capture);
}
} :
function(el, type, fn) {
if (el.detachEvent) {
el.detachEvent('on' + type, fn);
}
};
return {
splitAndRun:splitAndRun,
batchForType:batchForType,
isValidTarget:isValidTarget,
isIdenticalHandler:isIdenticalHandler,
simpleAdd:simpleAdd,
simpleRemove:simpleRemove
};
}, {
requires:['dom']
});
/**
* scalable event framework for kissy (refer DOM3 Events)
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('event/base', function(S, DOM, EventObject, Utils, undefined) {
var isValidTarget = Utils.isValidTarget,
isIdenticalHandler = Utils.isIdenticalHandler,
batchForType = Utils.batchForType,
simpleRemove = Utils.simpleRemove,
simpleAdd = Utils.simpleAdd,
splitAndRun = Utils.splitAndRun,
nodeName = DOM._nodeName,
makeArray = S.makeArray,
each = S.each,
trim = S.trim,
// 记录手工 fire(domElement,type) 时的 type
// 再在浏览器通知的系统 eventHandler 中检查
// 如果相同,那么证明已经 fire 过了,不要再次触发了
Event_Triggered = "",
TRIGGERED_NONE = "trigger-none-" + S.now(),
EVENT_SPECIAL = {},
// 事件存储位置 key
// { handler: eventHandler, events: {type:[{scope:scope,fn:fn}]} } }
EVENT_GUID = 'ksEventTargetId' + S.now();
/**
* @name Event
* @namespace
*/
var Event = {
_clone:function(src, dest) {
if (dest.nodeType !== DOM.ELEMENT_NODE ||
!Event._hasData(src)) {
return;
}
var eventDesc = Event._data(src),
events = eventDesc.events;
each(events, function(handlers, type) {
each(handlers, function(handler) {
// scope undefined 时不能写死在 handlers 中,否则不能保证 clone 时的 this
Event.on(dest, type, handler.fn, handler.scope, handler.data);
});
});
},
_hasData:function(elem) {
return DOM.hasData(elem, EVENT_GUID);
},
_data:function(elem) {
var args = makeArray(arguments);
args.splice(1, 0, EVENT_GUID);
return DOM.data.apply(DOM, args);
},
_removeData:function(elem) {
var args = makeArray(arguments);
args.splice(1, 0, EVENT_GUID);
return DOM.removeData.apply(DOM, args);
},
// such as: { 'mouseenter' : { setup:fn ,tearDown:fn} }
special: EVENT_SPECIAL,
// single type , single target , fixed native
__add:function(isNativeTarget, target, type, fn, scope, data) {
var eventDesc;
// 不是有效的 target 或 参数不对
if (!target ||
!S.isFunction(fn) ||
(isNativeTarget && !isValidTarget(target))) {
return;
}
// 获取事件描述
eventDesc = Event._data(target);
if (!eventDesc) {
Event._data(target, eventDesc = {});
}
//事件 listeners , similar to eventListeners in DOM3 Events
var events = eventDesc.events = eventDesc.events || {},
handlers = events[type] = events[type] || [],
handleObj = {
fn: fn,
scope: scope,
data:data
},
eventHandler = eventDesc.handler;
// 该元素没有 handler ,并且该元素是 dom 节点时才需要注册 dom 事件
if (!eventHandler) {
eventHandler = eventDesc.handler = function(event, data) {
// 是经过 fire 手动调用而浏览器同步触发导致的,就不要再次触发了,
// 已经在 fire 中 bubble 过一次了
if (event && event.type == Event_Triggered) {
return;
}
var currentTarget = eventHandler.target;
if (!event || !event.fixed) {
event = new EventObject(currentTarget, event);
}
var type = event.type;
if (S.isPlainObject(data)) {
S.mix(event, data);
}
// protect type
if (type) {
event.type = type;
}
return _handle(currentTarget, event);
};
// as for native dom event , this represents currentTarget !
eventHandler.target = target;
}
for (var i = handlers.length - 1; i >= 0; --i) {
/**
* If multiple identical EventListeners are registered on the same EventTarget
* with the same parameters the duplicate instances are discarded.
* They do not cause the EventListener to be called twice
* and since they are discarded
* they do not need to be removed with the removeEventListener method.
*/
if (isIdenticalHandler(handlers[i], handleObj, target)) {
return;
}
}
if (isNativeTarget) {
addDomEvent(target, type, eventHandler, handlers, handleObj);
//nullify to prevent memory leak in ie ?
target = null;
}
// 增加 listener
handlers.push(handleObj);
},
/**
* Adds an event listener.similar to addEventListener in DOM3 Events
* @param targets KISSY selector
* @param type {String} The type of event to append.
* @param fn {Function} The event handler/listener.
* @param scope {Object} (optional) The scope (this reference) in which the handler function is executed.
*/
add: function(targets, type, fn, scope /* optional */, data/*internal usage*/) {
type = trim(type);
// data : 附加在回调后面的数据,delegate 检查使用
// remove 时 data 相等(指向同一对象或者定义了 equals 比较函数)
if (batchForType(Event, 'add', targets, type, fn, scope, data)) {
return targets;
}
DOM.query(targets).each(function(target) {
Event.__add(true, target, type, fn, scope, data);
});
return targets;
},
// single target, single type, fixed native
__remove:function(isNativeTarget, target, type, fn, scope, data) {
if (
!target ||
(isNativeTarget && !isValidTarget(target))
) {
return;
}
var eventDesc = Event._data(target),
events = eventDesc && eventDesc.events,
handlers,
len,
i,
j,
t,
special = (isNativeTarget && EVENT_SPECIAL[type]) || { };
if (!events) {
return;
}
// remove all types of event
if (!type) {
for (type in events) {
Event.__remove(isNativeTarget, target, type);
}
return;
}
if ((handlers = events[type])) {
len = handlers.length;
// 移除 fn
if (fn && len) {
var currentHandler = {
data:data,
fn:fn,
scope:scope
},handler;
for (i = 0,j = 0,t = []; i < len; ++i) {
handler = handlers[i];
// 注意顺序,用户提供的 handler 在第二个参数
if (!isIdenticalHandler(handler, currentHandler, target)) {
t[j++] = handler;
} else if (special.remove) {
special.remove.call(target, handler);
}
}
events[type] = t;
len = t.length;
}
// remove(el, type) or fn 已移除光
if (fn === undefined || len === 0) {
// dom node need to detach handler from dom node
if (isNativeTarget &&
(!special['tearDown'] ||
special['tearDown'].call(target) === false)) {
simpleRemove(target, type, eventDesc.handler);
}
// remove target's single event description
delete events[type];
}
}
// remove target's all events description
if (S.isEmptyObject(events)) {
eventDesc.handler.target = null;
delete eventDesc.handler;
delete eventDesc.events;
Event._removeData(target);
}
},
/**
* Detach an event or set of events from an element. similar to removeEventListener in DOM3 Events
* @param targets KISSY selector
* @param type {String} The type of event to append.
* @param fn {Function} The event handler/listener.
* @param scope {Object} (optional) The scope (this reference) in which the handler function is executed.
*/
remove: function(targets, type /* optional */, fn /* optional */, scope /* optional */, data/*internal usage*/) {
type = trim(type);
if (batchForType(Event, 'remove', targets, type, fn, scope)) {
return targets;
}
DOM.query(targets).each(function(target) {
Event.__remove(true, target, type, fn, scope, data);
});
return targets;
},
_handle:_handle,
/**
* fire event , simulate bubble in browser. similar to dispatchEvent in DOM3 Events
* @return boolean The return value of fire/dispatchEvent indicates
* whether any of the listeners which handled the event called preventDefault.
* If preventDefault was called the value is false, else the value is true.
*/
fire: function(targets, eventType, eventData, onlyHandlers) {
var ret = true;
eventType = trim(eventType);
if (eventType.indexOf(" ") > -1) {
splitAndRun(eventType, function(t) {
ret = Event.fire(targets, t, eventData, onlyHandlers) && ret;
});
return ret;
}
// custom event firing moved to target.js
eventData = eventData || {};
// protect event type
eventData.type = eventType;
DOM.query(targets).each(function(target) {
ret = fireDOMEvent(target, eventType, eventData, onlyHandlers) && ret;
});
return ret;
}
};
// for compatibility
Event['__getListeners'] = getListeners
// shorthand
Event.on = Event.add;
Event.detach = Event.remove;
function getListeners(target, type) {
var events = getEvents(target) || {};
return events[type] || [];
}
function _handle(target, event) {
/* As some listeners may remove themselves from the
event, the original array length is dynamic. So,
let's make a copy of all listeners, so we are
sure we'll call all of them.*/
/**
* DOM3 Events: EventListenerList objects in the DOM are live. ??
*/
var listeners = getListeners(target, event.type).slice(0),
ret,
gRet,
i = 0,
len = listeners.length,
listener;
for (; i < len; ++i) {
listener = listeners[i];
// 传入附件参数data,目前用于委托
// scope undefined 时不能写死在 listener 中,否则不能保证 clone 时的 this
ret = listener.fn.call(listener.scope || target,
event, listener.data);
// 和 jQuery 逻辑保持一致
if (ret !== undefined) {
// 有一个 false,最终结果就是 false
// 否则等于最后一个返回值
if (gRet !== false) {
gRet = ret;
}
// return false 等价 preventDefault + stopProgation
if (ret === false) {
event.halt();
}
}
if (event.isImmediatePropagationStopped) {
break;
}
}
// fire 时判断如果 preventDefault,则返回 false 否则返回 true
// 这里返回值意义不同
return gRet;
}
function getEvents(target) {
// 获取事件描述
var eventDesc = Event._data(target);
return eventDesc && eventDesc.events;
}
/**
* dom node need eventHandler attached to dom node
*/
function addDomEvent(target, type, eventHandler, handlers, handleObj) {
var special = EVENT_SPECIAL[type] || {};
// 第一次注册该事件,dom 节点才需要注册 dom 事件
if (!handlers.length &&
(!special.setup || special.setup.call(target) === false)) {
simpleAdd(target, type, eventHandler)
}
if (special.add) {
special.add.call(target, handleObj);
}
}
/**
* fire dom event from bottom to up , emulate dispatchEvent in DOM3 Events
* @return boolean The return value of dispatchEvent indicates
* whether any of the listeners which handled the event called preventDefault.
* If preventDefault was called the value is false, else the value is true.
*/
function fireDOMEvent(target, eventType, eventData, onlyHandlers) {
if (!isValidTarget(target)) {
return false;
}
var event,
ret = true;
if (eventData instanceof EventObject) {
event = eventData;
} else {
event = new EventObject(target, undefined, eventType);
S.mix(event, eventData);
}
/*
The target of the event is the EventTarget on which dispatchEvent is called.
*/
// TODO: protect target , but incompatible
// event.target=target;
// protect type
event.type = eventType;
// 只运行自己的绑定函数,不冒泡也不触发默认行为
if (onlyHandlers) {
event.halt();
}
var cur = target,
ontype = "on" + eventType;
//bubble up dom tree
do{
event.currentTarget = cur;
_handle(cur, event);
// Trigger an inline bound script
if (cur[ ontype ] &&
cur[ ontype ].call(cur) === false) {
event.preventDefault();
}
// Bubble up to document, then to window
cur = cur.parentNode ||
cur.ownerDocument ||
cur === target.ownerDocument && window;
} while (cur && !event.isPropagationStopped);
if (!event.isDefaultPrevented) {
if (!(eventType === "click" &&
nodeName(target, "a"))) {
var old;
try {
if (ontype && target[ eventType ]) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = target[ ontype ];
if (old) {
target[ ontype ] = null;
}
// 记录当前 trigger 触发
Event_Triggered = eventType;
// 只触发默认事件,而不要执行绑定的用户回调
// 同步触发
target[ eventType ]();
}
} catch (ieError) {
S.log("trigger action error : ");
S.log(ieError);
}
if (old) {
target[ ontype ] = old;
}
Event_Triggered = TRIGGERED_NONE;
}
} else {
ret = false;
}
return ret;
}
return Event;
}, {
requires:["dom","./object","./utils"]
});
/**
* 2011-11-24
* - 自定义事件和 dom 事件操作彻底分离
* - TODO: group event from DOM3 Event
*
* 2011-06-07
* - refer : http://www.w3.org/TR/2001/WD-DOM-Level-3-Events-20010823/events.html
* - 重构
* - eventHandler 一个元素一个而不是一个元素一个事件一个,节省内存
* - 减少闭包使用,prevent ie 内存泄露?
* - 增加 fire ,模拟冒泡处理 dom 事件
*/
/**
* @module EventTarget
* @author yiminghe@gmail.com
*/
KISSY.add('event/target', function(S, Event, EventObject, Utils, undefined) {
var KS_PUBLISH = "__~ks_publish",
trim = S.trim,
splitAndRun = Utils.splitAndRun,
KS_BUBBLE_TARGETS = "__~ks_bubble_targets",
ALL_EVENT = "*";
function getCustomEvent(self, type, eventData) {
if (eventData instanceof EventObject) {
// set currentTarget in the process of bubbling
eventData.currentTarget = self;
return eventData;
}
var customEvent = new EventObject(self, undefined, type);
if (S.isPlainObject(eventData)) {
S.mix(customEvent, eventData);
}
// protect type
customEvent.type = type;
return customEvent
}
function getEventPublishObj(self) {
self[KS_PUBLISH] = self[KS_PUBLISH] || {};
return self[KS_PUBLISH];
}
function getBubbleTargetsObj(self) {
self[KS_BUBBLE_TARGETS] = self[KS_BUBBLE_TARGETS] || {};
return self[KS_BUBBLE_TARGETS];
}
function isBubblable(self, eventType) {
var publish = getEventPublishObj(self);
return publish[eventType] && publish[eventType].bubbles || publish[ALL_EVENT] && publish[ALL_EVENT].bubbles
}
function attach(method) {
return function(type, fn, scope) {
var self = this;
type = trim(type);
splitAndRun(type, function(t) {
Event["__" + method](false, self, t, fn, scope);
});
return self; // chain
};
}
/**
* 提供事件发布和订阅机制
* @name Target
* @memberOf Event
*/
var Target =
/**
* @lends Event.Target
*/
{
/**
* 触发事件
* @param {String} type 事件名
* @param {Object} eventData 事件附加信息对象
* @returns 如果一个 listener 返回false,则返回 false ,否则返回最后一个 listener 的值.
*/
fire: function(type, eventData) {
var self = this,
ret,
r2,
customEvent;
type = trim(type);
if (type.indexOf(" ") > 0) {
splitAndRun(type, function(t) {
r2 = self.fire(t, eventData);
if (r2 === false) {
ret = false;
}
});
return ret;
}
customEvent = getCustomEvent(self, type, eventData);
ret = Event._handle(self, customEvent);
if (!customEvent.isPropagationStopped &&
isBubblable(self, type)) {
r2 = self.bubble(type, customEvent);
// false 优先返回
if (ret !== false) {
ret = r2;
}
}
return ret
},
/**
* defined event config
* @param type
* @param cfg
* example { bubbles: true}
* default bubbles: false
*/
publish: function(type, cfg) {
var self = this,
publish = getEventPublishObj(self);
type = trim(type);
if (type) {
publish[type] = cfg;
}
},
/**
* bubble event to its targets
* @param type
* @param eventData
*/
bubble: function(type, eventData) {
var self = this,
ret,
targets = getBubbleTargetsObj(self);
S.each(targets, function(t) {
var r2 = t.fire(type, eventData);
if (ret !== false) {
ret = r2;
}
});
return ret;
},
/**
* add target which bubblable event bubbles towards
* @param target another EventTarget instance
*/
addTarget: function(target) {
var self = this,
targets = getBubbleTargetsObj(self);
targets[S.stamp(target)] = target;
},
removeTarget:function(target) {
var self = this,
targets = getBubbleTargetsObj(self);
delete targets[S.stamp(target)];
},
/**
* 监听事件
* @param {String} type 事件名
* @param {Function} fn 事件处理器
* @param {Object} scope 事件处理器内的 this 值,默认当前实例
* @returns 当前实例
*/
on: attach("add")
};
/**
* 取消监听事件
* @param {String} type 事件名
* @param {Function} fn 事件处理器
* @param {Object} scope 事件处理器内的 this 值,默认当前实例
* @returns 当前实例
*/
Target.detach = attach("remove");
return Target;
}, {
/*
实际上只需要 dom/data ,但是不要跨模块引用另一模块的子模块,
否则会导致build打包文件 dom 和 dom-data 重复载入
*/
requires:["./base",'./object','./utils']
});
/**
* yiminghe:2011-10-17
* - implement bubble for custom event
**/
/**
* @module event-focusin
* @author yiminghe@gmail.com
*/
KISSY.add('event/focusin', function(S, UA, Event) {
// 让非 IE 浏览器支持 focusin/focusout
if (!UA['ie']) {
S.each([
{ name: 'focusin', fix: 'focus' },
{ name: 'focusout', fix: 'blur' }
], function(o) {
var attaches = 0;
Event.special[o.name] = {
// 统一在 document 上 capture focus/blur 事件,然后模拟冒泡 fire 出来
// 达到和 focusin 一样的效果 focusin -> focus
// refer: http://yiminghe.iteye.com/blog/813255
setup: function() {
if (attaches++ === 0) {
document.addEventListener(o.fix, handler, true);
}
},
tearDown:function() {
if (--attaches === 0) {
document.removeEventListener(o.fix, handler, true);
}
}
};
function handler(event) {
var target = event.target;
return Event.fire(target, o.name);
}
});
}
return Event;
}, {
requires:["ua","./base"]
});
/**
* 承玉:2011-06-07
* - refactor to jquery , 更加合理的模拟冒泡顺序,子元素先出触发,父元素后触发
*
* NOTES:
* - webkit 和 opera 已支持 DOMFocusIn/DOMFocusOut 事件,但上面的写法已经能达到预期效果,暂时不考虑原生支持。
*/
/**
* @module event-hashchange
* @author yiminghe@gmail.com , xiaomacji@gmail.com
*/
KISSY.add('event/hashchange', function(S, Event, DOM, UA) {
var doc = document,
docMode = doc['documentMode'],
ie = docMode || UA['ie'],
HASH_CHANGE = 'hashchange';
// ie8 支持 hashchange
// 但IE8以上切换浏览器模式到IE7(兼容模式),会导致 'onhashchange' in window === true,但是不触发事件
// 1. 不支持 hashchange 事件,支持 hash 导航(opera??):定时器监控
// 2. 不支持 hashchange 事件,不支持 hash 导航(ie67) : iframe + 定时器
if ((!( 'on' + HASH_CHANGE in window)) || ie && ie < 8) {
function getIframeDoc(iframe) {
return iframe.contentWindow.document;
}
var POLL_INTERVAL = 50,
win = window,
IFRAME_TEMPLATE = "<html><head><title>" + (doc.title || "") +
" - {hash}</title>{head}</head><body>{hash}</body></html>",
getHash = function() {
// 不能 location.hash
// http://xx.com/#yy?z=1
// ie6 => location.hash = #yy
// 其他浏览器 => location.hash = #yy?z=1
var url = location.href;
return '#' + url.replace(/^[^#]*#?(.*)$/, '$1');
},
timer,
// 用于定时器检测,上次定时器记录的 hash 值
lastHash,
poll = function () {
var hash = getHash();
if (hash !== lastHash) {
// S.log("poll success :" + hash + " :" + lastHash);
// 通知完调用者 hashchange 事件前设置 lastHash
lastHash = hash;
// ie<8 同步 : hashChange -> onIframeLoad
hashChange(hash);
}
timer = setTimeout(poll, POLL_INTERVAL);
},
hashChange = ie && ie < 8 ? function(hash) {
// S.log("set iframe html :" + hash);
var html = S.substitute(IFRAME_TEMPLATE, {
hash: hash,
// 一定要加哦
head:DOM._isCustomDomain() ? "<script>document.domain = '" +
doc.domain
+ "';</script>" : ""
}),
iframeDoc = getIframeDoc(iframe);
try {
// 写入历史 hash
iframeDoc.open();
// 取时要用 innerText !!
// 否则取 innerHtml 会因为 escapeHtml 导置 body.innerHTMl != hash
iframeDoc.write(html);
iframeDoc.close();
// 立刻同步调用 onIframeLoad !!!!
} catch (e) {
// S.log('doc write error : ', 'error');
// S.log(e, 'error');
}
} : function () {
notifyHashChange();
},
notifyHashChange = function () {
// S.log("hash changed : " + getHash());
Event.fire(win, HASH_CHANGE);
},
setup = function () {
if (!timer) {
poll();
}
},
tearDown = function () {
timer && clearTimeout(timer);
timer = 0;
},
iframe;
// ie6, 7, 覆盖一些function
if (ie < 8) {
/**
* 前进后退 : start -> notifyHashChange
* 直接输入 : poll -> hashChange -> start
* iframe 内容和 url 同步
*/
setup = function() {
if (!iframe) {
var iframeSrc = DOM._genEmptyIframeSrc();
//http://www.paciellogroup.com/blog/?p=604
iframe = DOM.create('<iframe ' +
(iframeSrc ? 'src="' + iframeSrc + '"' : '') +
' style="display: none" ' +
'height="0" ' +
'width="0" ' +
'tabindex="-1" ' +
'title="empty"/>');
// Append the iframe to the documentElement rather than the body.
// Keeping it outside the body prevents scrolling on the initial
// page load
DOM.prepend(iframe, doc.documentElement);
// init,第一次触发,以后都是 onIframeLoad
Event.add(iframe, "load", function() {
Event.remove(iframe, "load");
// Update the iframe with the initial location hash, if any. This
// will create an initial history entry that the user can return to
// after the state has changed.
hashChange(getHash());
Event.add(iframe, "load", onIframeLoad);
poll();
});
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function() {
try {
if (event.propertyName === 'title') {
getIframeDoc(iframe).title =
doc.title + " - " + getHash();
}
} catch(e) {
}
};
/**
* 前进后退 : onIframeLoad -> 触发
* 直接输入 : timer -> hashChange -> onIframeLoad -> 触发
* 触发统一在 start(load)
* iframe 内容和 url 同步
*/
function onIframeLoad() {
// S.log('iframe start load..');
// 2011.11.02 note: 不能用 innerHtml 会自动转义!!
// #/x?z=1&y=2 => #/x?z=1&y=2
var c = S.trim(getIframeDoc(iframe).body.innerText),
ch = getHash();
// 后退时不等
// 定时器调用 hashChange() 修改 iframe 同步调用过来的(手动改变 location)则相等
if (c != ch) {
S.log("set loc hash :" + c);
location.hash = c;
// 使lasthash为 iframe 历史, 不然重新写iframe,
// 会导致最新状态(丢失前进状态)
// 后退则立即触发 hashchange,
// 并更新定时器记录的上个 hash 值
lastHash = c;
}
notifyHashChange();
}
}
};
tearDown = function() {
timer && clearTimeout(timer);
timer = 0;
Event.detach(iframe);
DOM.remove(iframe);
iframe = 0;
};
}
Event.special[HASH_CHANGE] = {
setup: function() {
if (this !== win) {
return;
}
// 第一次启动 hashchange 时取一下,不能类库载入后立即取
// 防止类库嵌入后,手动修改过 hash,
lastHash = getHash();
// 不用注册 dom 事件
setup();
},
tearDown: function() {
if (this !== win) {
return;
}
tearDown();
}
};
}
}, {
requires:["./base","dom","ua"]
});
/**
* 已知 bug :
* - ie67 有时后退后取得的 location.hash 不和地址栏一致,导致必须后退两次才能触发 hashchange
*
* v1 : 2010-12-29
* v1.1: 支持非IE,但不支持onhashchange事件的浏览器(例如低版本的firefox、safari)
* refer : http://yiminghe.javaeye.com/blog/377867
* https://github.com/cowboy/jquery-hashchange
*/
/**
* inspired by yui3 :
*
* Synthetic event that fires when the <code>value</code> property of an input
* field or textarea changes as a result of a keystroke, mouse operation, or
* input method editor (IME) input event.
*
* Unlike the <code>onchange</code> event, this event fires when the value
* actually changes and not when the element loses focus. This event also
* reports IME and multi-stroke input more reliably than <code>oninput</code> or
* the various key events across browsers.
*
* @author yiminghe@gmail.com
*/
KISSY.add('event/valuechange', function (S, Event, DOM) {
var VALUE_CHANGE = "valuechange",
nodeName = DOM._nodeName,
KEY = "event/valuechange",
HISTORY_KEY = KEY + "/history",
POLL_KEY = KEY + "/poll",
interval = 50;
function stopPoll(target) {
DOM.removeData(target, HISTORY_KEY);
if (DOM.hasData(target, POLL_KEY)) {
var poll = DOM.data(target, POLL_KEY);
clearTimeout(poll);
DOM.removeData(target, POLL_KEY);
}
}
function stopPollHandler(ev) {
var target = ev.target;
stopPoll(target);
}
function startPoll(target) {
if (DOM.hasData(target, POLL_KEY)) return;
DOM.data(target, POLL_KEY, setTimeout(function () {
var v = target.value, h = DOM.data(target, HISTORY_KEY);
if (v !== h) {
// 只触发自己绑定的 handler
Event.fire(target, VALUE_CHANGE, {
prevVal:h,
newVal:v
}, true);
DOM.data(target, HISTORY_KEY, v);
}
DOM.data(target, POLL_KEY, setTimeout(arguments.callee, interval));
}, interval));
}
function startPollHandler(ev) {
var target = ev.target;
// when focus ,record its current value immediately
if (ev.type == "focus") {
DOM.data(target, HISTORY_KEY, target.value);
}
startPoll(target);
}
function monitor(target) {
unmonitored(target);
Event.on(target, "blur", stopPollHandler);
Event.on(target, "mousedown keyup keydown focus", startPollHandler);
}
function unmonitored(target) {
stopPoll(target);
Event.remove(target, "blur", stopPollHandler);
Event.remove(target, "mousedown keyup keydown focus", startPollHandler);
}
Event.special[VALUE_CHANGE] = {
setup:function () {
var target = this;
if (nodeName(target, "input")
|| nodeName(target, "textarea")) {
monitor(target);
}
},
tearDown:function () {
var target = this;
unmonitored(target);
}
};
return Event;
}, {
requires:["./base", "dom"]
});
/**
* kissy delegate for event module
* @author yiminghe@gmail.com
*/
KISSY.add("event/delegate", function(S, DOM, Event, Utils) {
var batchForType = Utils.batchForType,
delegateMap = {
"focus":{
type:"focusin"
},
"blur":{
type:"focusout"
},
"mouseenter":{
type:"mouseover",
handler:mouseHandler
},
"mouseleave":{
type:"mouseout",
handler:mouseHandler
}
};
S.mix(Event, {
delegate:function(targets, type, selector, fn, scope) {
if (batchForType(Event, 'delegate', targets, type, selector, fn, scope)) {
return targets;
}
DOM.query(targets).each(function(target) {
var preType = type,handler = delegateHandler;
if (delegateMap[type]) {
type = delegateMap[preType].type;
handler = delegateMap[preType].handler || handler;
}
Event.on(target, type, handler, target, {
fn:fn,
selector:selector,
preType:preType,
scope:scope,
equals:equals
});
});
return targets;
},
undelegate:function(targets, type, selector, fn, scope) {
if (batchForType(Event, 'undelegate', targets, type, selector, fn, scope)) {
return targets;
}
DOM.query(targets).each(function(target) {
var preType = type,
handler = delegateHandler;
if (delegateMap[type]) {
type = delegateMap[preType].type;
handler = delegateMap[preType].handler || handler;
}
Event.remove(target, type, handler, target, {
fn:fn,
selector:selector,
preType:preType,
scope:scope,
equals:equals
});
});
return targets;
}
});
// 比较函数,两个 delegate 描述对象比较
// 注意顺序: 已有data 和 用户提供的 data 比较
function equals(d, el) {
// 用户不提供 fn selector 那么肯定成功
if (d.fn === undefined && d.selector === undefined) {
return true;
}
// 用户不提供 fn 则只比较 selector
else if (d.fn === undefined) {
return this.selector == d.selector;
} else {
var scope = this.scope || el,
dScope = d.scope || el;
return this.fn == d.fn && this.selector == d.selector && scope == dScope;
}
}
// 根据 selector ,从事件源得到对应节点
function delegateHandler(event, data) {
var delegateTarget = this,
target = event.target,
invokeds = DOM.closest(target, [data.selector], delegateTarget);
// 找到了符合 selector 的元素,可能并不是事件源
return invokes.call(delegateTarget, invokeds, event, data);
}
// mouseenter/leave 特殊处理
function mouseHandler(event, data) {
var delegateTarget = this,
ret,
target = event.target,
relatedTarget = event.relatedTarget;
// 恢复为用户想要的 mouseenter/leave 类型
event.type = data.preType;
// mouseenter/leave 不会冒泡,只选择最近一个
target = DOM.closest(target, data.selector, delegateTarget);
if (target) {
if (target !== relatedTarget &&
(!relatedTarget || !DOM.contains(target, relatedTarget))
) {
var currentTarget = event.currentTarget;
event.currentTarget = target;
ret = data.fn.call(data.scope || delegateTarget, event);
event.currentTarget = currentTarget;
}
}
return ret;
}
function invokes(invokeds, event, data) {
var self = this;
if (invokeds) {
// 保护 currentTarget
// 否则 fire 影响 delegated listener 之后正常的 listener 事件
var currentTarget = event.currentTarget;
for (var i = 0; i < invokeds.length; i++) {
event.currentTarget = invokeds[i];
var ret = data.fn.call(data.scope || self, event);
// delegate 的 handler 操作事件和根元素本身操作事件效果一致
if (ret === false) {
event.halt();
}
if (event.isPropagationStopped) {
break;
}
}
event.currentTarget = currentTarget;
}
}
return Event;
}, {
requires:["dom","./base","./utils"]
});
/**
* focusin/out 的特殊之处 , delegate 只能在容器上注册 focusin/out ,
* 1.其实非 ie 都是注册 focus capture=true,然后注册到 focusin 对应 handlers
* 1.1 当 Event.fire("focus"),没有 focus 对应的 handlers 数组,然后调用元素 focus 方法,
* focusin.js 调用 Event.fire("focusin") 进而执行 focusin 对应的 handlers 数组
* 1.2 当调用 Event.fire("focusin"),直接执行 focusin 对应的 handlers 数组,但不会真正聚焦
*
* 2.ie 直接注册 focusin , focusin handlers 也有对应用户回调
* 2.1 当 Event.fire("focus") , 同 1.1
* 2.2 当 Event.fire("focusin"),直接执行 focusin 对应的 handlers 数组,但不会真正聚焦
*
* mouseenter/leave delegate 特殊处理, mouseenter 没有冒泡的概念,只能替换为 mouseover/out
*
* form submit 事件 ie<9 不会冒泡
*
**/
/**
* @module event-mouseenter
* @author lifesinger@gmail.com , yiminghe@gmail.com
*/
KISSY.add('event/mouseenter', function(S, Event, DOM, UA) {
if (!UA['ie']) {
S.each([
{ name: 'mouseenter', fix: 'mouseover' },
{ name: 'mouseleave', fix: 'mouseout' }
], function(o) {
// 元素内触发的 mouseover/out 不能算 mouseenter/leave
function withinElement(event) {
var self = this,
parent = event.relatedTarget;
// 设置用户实际注册的事件名,触发该事件所对应的 listener 数组
event.type = o.name;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Chrome does something similar, the parentNode property
// can be accessed but is null.
if (parent && parent !== document && !parent.parentNode) {
return;
}
// 在自身外边就触发
if (parent !== self &&
// self==document , parent==null
(!parent || !DOM.contains(self, parent))
) {
// handle event if we actually just moused on to a non sub-element
Event._handle(self, event);
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) {
S.log("withinElement error : ", "error");
S.log(e, "error");
}
}
Event.special[o.name] = {
// 第一次 mouseenter 时注册下
// 以后都直接放到 listener 数组里, 由 mouseover 读取触发
setup: function() {
Event.add(this, o.fix, withinElement);
},
//当 listener 数组为空时,也清掉 mouseover 注册,不再读取
tearDown:function() {
Event.remove(this, o.fix, withinElement);
}
}
});
}
return Event;
}, {
requires:["./base","dom","ua"]
});
/**
* 承玉:2011-06-07
* - 根据新结构,调整 mouseenter 兼容处理
* - fire('mouseenter') 可以的,直接执行 mouseenter 的 handlers 用户回调数组
*
*
* TODO:
* - ie6 下,原生的 mouseenter/leave 貌似也有 bug, 比如 <div><div /><div /><div /></div>
* jQuery 也异常,需要进一步研究
*/
/**
* patch for ie<9 submit : does not bubble !
* @author yiminghe@gmail.com
*/
KISSY.add("event/submit", function(S, UA, Event, DOM) {
var mode = document['documentMode'];
if (UA['ie'] && (UA['ie'] < 9 || (mode && mode < 9))) {
var nodeName = DOM._nodeName;
Event.special['submit'] = {
setup: function() {
var el = this;
// form use native
if (nodeName(el, "form")) {
return false;
}
// lazy add submit for inside forms
// note event order : click/keypress -> submit
// keypoint : find the forms
Event.on(el, "click keypress", detector);
},
tearDown:function() {
var el = this;
// form use native
if (nodeName(el, "form")) {
return false;
}
Event.remove(el, "click keypress", detector);
DOM.query("form", el).each(function(form) {
if (form.__submit__fix) {
form.__submit__fix = 0;
Event.remove(form, "submit", submitBubble);
}
});
}
};
function detector(e) {
var t = e.target,
form = nodeName(t, "input") || nodeName(t, "button") ? t.form : null;
if (form && !form.__submit__fix) {
form.__submit__fix = 1;
Event.on(form, "submit", submitBubble);
}
}
function submitBubble(e) {
var form = this;
if (form.parentNode) {
// simulated bubble for submit
// fire from parentNode. if form.on("submit") , this logic is never run!
Event.fire(form.parentNode, "submit", e);
}
}
}
}, {
requires:["ua","./base","dom"]
});
/**
* modified from jq ,fix submit in ie<9
**/
/**
* change bubble and checkbox/radio fix patch for ie<9
* @author yiminghe@gmail.com
*/
KISSY.add("event/change", function(S, UA, Event, DOM) {
var mode = document['documentMode'];
if (UA['ie'] && (UA['ie'] < 9 || (mode && mode < 9))) {
var rformElems = /^(?:textarea|input|select)$/i;
function isFormElement(n) {
return rformElems.test(n.nodeName);
}
function isCheckBoxOrRadio(el) {
var type = el.type;
return type == "checkbox" || type == "radio";
}
Event.special['change'] = {
setup: function() {
var el = this;
if (isFormElement(el)) {
// checkbox/radio only fires change when blur in ie<9
// so use another technique from jquery
if (isCheckBoxOrRadio(el)) {
// change in ie<9
// change = propertychange -> click
Event.on(el, "propertychange", propertyChange);
Event.on(el, "click", onClick);
} else {
// other form elements use native , do not bubble
return false;
}
} else {
// if bind on parentNode ,lazy bind change event to its form elements
// note event order : beforeactivate -> change
// note 2: checkbox/radio is exceptional
Event.on(el, "beforeactivate", beforeActivate);
}
},
tearDown:function() {
var el = this;
if (isFormElement(el)) {
if (isCheckBoxOrRadio(el)) {
Event.remove(el, "propertychange", propertyChange);
Event.remove(el, "click", onClick);
} else {
return false;
}
} else {
Event.remove(el, "beforeactivate", beforeActivate);
DOM.query("textarea,input,select", el).each(function(fel) {
if (fel.__changeHandler) {
fel.__changeHandler = 0;
Event.remove(fel, "change", changeHandler);
}
});
}
}
};
function propertyChange(e) {
if (e.originalEvent.propertyName == "checked") {
this.__changed = 1;
}
}
function onClick(e) {
if (this.__changed) {
this.__changed = 0;
// fire from itself
Event.fire(this, "change", e);
}
}
function beforeActivate(e) {
var t = e.target;
if (isFormElement(t) && !t.__changeHandler) {
t.__changeHandler = 1;
// lazy bind change
Event.on(t, "change", changeHandler);
}
}
function changeHandler(e) {
var fel = this;
// checkbox/radio already bubble using another technique
if (isCheckBoxOrRadio(fel)) {
return;
}
var p;
if (p = fel.parentNode) {
// fire from parent , itself is handled natively
Event.fire(p, "change", e);
}
}
}
}, {
requires:["ua","./base","dom"]
});
/**
* normalize mousewheel in gecko
* @author yiminghe@gmail.com
*/
KISSY.add("event/mousewheel", function(S, Event, UA, Utils, EventObject) {
var MOUSE_WHEEL = UA.gecko ? 'DOMMouseScroll' : 'mousewheel',
simpleRemove = Utils.simpleRemove,
simpleAdd = Utils.simpleAdd,
mousewheelHandler = "mousewheelHandler";
function handler(e) {
var deltaX,
currentTarget = this,
deltaY,
delta,
detail = e.detail;
if (e.wheelDelta) {
delta = e.wheelDelta / 120;
}
if (e.detail) {
// press control e.detail == 1 else e.detail == 3
delta = -(detail % 3 == 0 ? detail / 3 : detail);
}
// Gecko
if (e.axis !== undefined) {
if (e.axis === e['HORIZONTAL_AXIS']) {
deltaY = 0;
deltaX = -1 * delta;
} else if (e.axis === e['VERTICAL_AXIS']) {
deltaX = 0;
deltaY = delta;
}
}
// Webkit
if (e['wheelDeltaY'] !== undefined) {
deltaY = e['wheelDeltaY'] / 120;
}
if (e['wheelDeltaX'] !== undefined) {
deltaX = -1 * e['wheelDeltaX'] / 120;
}
// 默认 deltaY ( ie )
if (!deltaX && !deltaY) {
deltaY = delta;
}
// can not invoke eventDesc.handler , it will protect type
// but here in firefox , we want to change type really
e = new EventObject(currentTarget, e);
S.mix(e, {
deltaY:deltaY,
delta:delta,
deltaX:deltaX,
type:'mousewheel'
});
return Event._handle(currentTarget, e);
}
Event.special['mousewheel'] = {
setup: function() {
var el = this,
mousewheelHandler,
eventDesc = Event._data(el);
// solve this in ie
mousewheelHandler = eventDesc[mousewheelHandler] = S.bind(handler, el);
simpleAdd(this, MOUSE_WHEEL, mousewheelHandler);
},
tearDown:function() {
var el = this,
mousewheelHandler,
eventDesc = Event._data(el);
mousewheelHandler = eventDesc[mousewheelHandler];
simpleRemove(this, MOUSE_WHEEL, mousewheelHandler);
delete eventDesc[mousewheelHandler];
}
};
}, {
requires:['./base','ua','./utils','./object']
});
/**
note:
not perfect in osx : accelerated scroll
refer:
https://github.com/brandonaaron/jquery-mousewheel/blob/master/jquery.mousewheel.js
http://www.planabc.net/2010/08/12/mousewheel_event_in_javascript/
http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers/5542105#5542105
http://www.javascriptkit.com/javatutors/onmousewheel.shtml
http://www.adomas.org/javascript-mouse-wheel/
http://plugins.jquery.com/project/mousewheel
http://www.cnblogs.com/aiyuchen/archive/2011/04/19/2020843.html
http://www.w3.org/TR/DOM-Level-3-Events/#events-mousewheelevents
**/
/**
* KISSY Scalable Event Framework
* @author yiminghe@gmail.com
*/
KISSY.add("event", function(S, KeyCodes, Event, Target, Object) {
Event.KeyCodes = KeyCodes;
Event.Target = Target;
Event.Object = Object;
return Event;
}, {
requires:[
"event/keycodes",
"event/base",
"event/target",
"event/object",
"event/focusin",
"event/hashchange",
"event/valuechange",
"event/delegate",
"event/mouseenter",
"event/submit",
"event/change",
"event/mousewheel"
]
});
/**
* definition for node and nodelist
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add("node/base", function(S, DOM, undefined) {
var AP = Array.prototype,
makeArray = S.makeArray,
isNodeList = DOM._isNodeList;
/**
* The NodeList class provides a wrapper for manipulating DOM Node.
* @constructor
*/
function NodeList(html, props, ownerDocument) {
var self = this,
domNode;
if (!(self instanceof NodeList)) {
return new NodeList(html, props, ownerDocument);
}
// handle NodeList(''), NodeList(null), or NodeList(undefined)
if (!html) {
return undefined;
}
else if (S.isString(html)) {
// create from html
domNode = DOM.create(html, props, ownerDocument);
// ('<p>1</p><p>2</p>') 转换为 NodeList
if (domNode.nodeType === DOM.DOCUMENT_FRAGMENT_NODE) { // fragment
AP.push.apply(this, makeArray(domNode.childNodes));
return undefined;
}
}
else if (S.isArray(html) || isNodeList(html)) {
AP.push.apply(this, makeArray(html));
return undefined;
}
else {
// node, document, window
domNode = html;
}
self[0] = domNode;
self.length = 1;
return undefined;
}
S.augment(NodeList, {
/**
* 默认长度为 0
*/
length: 0,
item: function(index) {
var self = this;
if (S.isNumber(index)) {
if (index >= self.length) {
return null;
} else {
return new NodeList(self[index]);
}
} else {
return new NodeList(index);
}
},
add:function(selector, context, index) {
if (S.isNumber(context)) {
index = context;
context = undefined;
}
var list = NodeList.all(selector, context).getDOMNodes(),
ret = new NodeList(this);
if (index === undefined) {
AP.push.apply(ret, list);
} else {
var args = [index,0];
args.push.apply(args, list);
AP.splice.apply(ret, args);
}
return ret;
},
slice:function(start, end) {
return new NodeList(AP.slice.call(this, start, end));
},
/**
* Retrieves the DOMNodes.
*/
getDOMNodes: function() {
return AP.slice.call(this);
},
/**
* Applies the given function to each Node in the NodeList.
* @param fn The function to apply. It receives 3 arguments: the current node instance, the node's index, and the NodeList instance
* @param context An optional context to apply the function with Default context is the current NodeList instance
*/
each: function(fn, context) {
var self = this;
S.each(self, function(n, i) {
n = new NodeList(n);
return fn.call(context || n, n, i, self);
});
return self;
},
/**
* Retrieves the DOMNode.
*/
getDOMNode: function() {
return this[0];
},
/**
* stack sub query
*/
end:function() {
var self = this;
return self.__parent || self;
},
all:function(selector) {
var ret,self = this;
if (self.length > 0) {
ret = NodeList.all(selector, self);
} else {
ret = new NodeList();
}
ret.__parent = self;
return ret;
},
one:function(selector) {
var self = this,all = self.all(selector),
ret = all.length ? all.slice(0, 1) : null;
if (ret) {
ret.__parent = self;
}
return ret;
}
});
S.mix(NodeList, {
/**
* 查找位于上下文中并且符合选择器定义的节点列表或根据 html 生成新节点
* @param {String|HTMLElement[]|NodeList} selector html 字符串或<a href='http://docs.kissyui.com/docs/html/api/core/dom/selector.html'>选择器</a>或节点列表
* @param {String|Array<HTMLElement>|NodeList|HTMLElement|Document} [context] 上下文定义
* @returns {NodeList} 节点列表对象
*/
all:function(selector, context) {
// are we dealing with html string ?
// TextNode 仍需要自己 new Node
if (S.isString(selector)
&& (selector = S.trim(selector))
&& selector.length >= 3
&& S.startsWith(selector, "<")
&& S.endsWith(selector, ">")
) {
if (context) {
if (context.getDOMNode) {
context = context.getDOMNode();
}
if (context.ownerDocument) {
context = context.ownerDocument;
}
}
return new NodeList(selector, undefined, context);
}
return new NodeList(DOM.query(selector, context));
},
one:function(selector, context) {
var all = NodeList.all(selector, context);
return all.length ? all.slice(0, 1) : null;
}
});
S.mix(NodeList, DOM._NODE_TYPE);
return NodeList;
}, {
requires:["dom"]
});
/**
* Notes:
* 2011-05-25
* - 承玉:参考 jquery,只有一个 NodeList 对象,Node 就是 NodeList 的别名
*
* 2010.04
* - each 方法传给 fn 的 this, 在 jQuery 里指向原生对象,这样可以避免性能问题。
* 但从用户角度讲,this 的第一直觉是 $(this), kissy 和 yui3 保持一致,牺牲
* 性能,以易用为首。
* - 有了 each 方法,似乎不再需要 import 所有 dom 方法,意义不大。
* - dom 是低级 api, node 是中级 api, 这是分层的一个原因。还有一个原因是,如果
* 直接在 node 里实现 dom 方法,则不大好将 dom 的方法耦合到 nodelist 里。可
* 以说,技术成本会制约 api 设计。
*/
/**
* import methods from DOM to NodeList.prototype
* @author yiminghe@gmail.com
*/
KISSY.add('node/attach', function(S, DOM, Event, NodeList, undefined) {
var NLP = NodeList.prototype,
makeArray = S.makeArray,
// DOM 添加到 NP 上的方法
// if DOM methods return undefined , Node methods need to transform result to itself
DOM_INCLUDES_NORM = [
"equals",
"contains",
"scrollTop",
"scrollLeft",
"height",
"width",
"innerHeight",
"innerWidth",
"outerHeight",
"outerWidth",
"addStyleSheet",
// "append" will be overridden
"appendTo",
// "prepend" will be overridden
"prependTo",
"insertBefore",
"before",
"after",
"insertAfter",
"test",
"hasClass",
"addClass",
"removeClass",
"replaceClass",
"toggleClass",
"removeAttr",
"hasAttr",
"hasProp",
// anim override
// "show",
// "hide",
// "toggle",
"scrollIntoView",
"remove",
"empty",
"removeData",
"hasData",
"unselectable"
],
// if return array ,need transform to nodelist
DOM_INCLUDES_NORM_NODE_LIST = [
"filter",
"first",
"last",
"parent",
"closest",
"next",
"prev",
"clone",
"siblings",
"children"
],
// if set return this else if get return true value ,no nodelist transform
DOM_INCLUDES_NORM_IF = {
// dom method : set parameter index
"attr":1,
"text":0,
"css":1,
"style":1,
"val":0,
"prop":1,
"offset":0,
"html":0,
"data":1
},
// Event 添加到 NP 上的方法
EVENT_INCLUDES = ["on","detach","fire","delegate","undelegate"];
function accessNorm(fn, self, args) {
args.unshift(self);
var ret = DOM[fn].apply(DOM, args);
if (ret === undefined) {
return self;
}
return ret;
}
function accessNormList(fn, self, args) {
args.unshift(self);
var ret = DOM[fn].apply(DOM, args);
if (ret === undefined) {
return self;
}
else if (ret === null) {
return null;
}
return new NodeList(ret);
}
function accessNormIf(fn, self, index, args) {
// get
if (args[index] === undefined
// 并且第一个参数不是对象,否则可能是批量设置写
&& !S.isObject(args[0])) {
args.unshift(self);
return DOM[fn].apply(DOM, args);
}
// set
return accessNorm(fn, self, args);
}
S.each(DOM_INCLUDES_NORM, function(k) {
NLP[k] = function() {
var args = makeArray(arguments);
return accessNorm(k, this, args);
};
});
S.each(DOM_INCLUDES_NORM_NODE_LIST, function(k) {
NLP[k] = function() {
var args = makeArray(arguments);
return accessNormList(k, this, args);
};
});
S.each(DOM_INCLUDES_NORM_IF, function(index, k) {
NLP[k] = function() {
var args = makeArray(arguments);
return accessNormIf(k, this, index, args);
};
});
S.each(EVENT_INCLUDES, function(k) {
NLP[k] = function() {
var self=this,
args = makeArray(arguments);
args.unshift(self);
Event[k].apply(Event, args);
return self;
}
});
}, {
requires:["dom","event","./base"]
});
/**
* 2011-05-24
* - 承玉:
* - 将 DOM 中的方法包装成 NodeList 方法
* - Node 方法调用参数中的 KISSY NodeList 要转换成第一个 HTML Node
* - 要注意链式调用,如果 DOM 方法返回 undefined (无返回值),则 NodeList 对应方法返回 this
* - 实际上可以完全使用 NodeList 来代替 DOM,不和节点关联的方法如:viewportHeight 等,在 window,document 上调用
* - 存在 window/document 虚节点,通过 S.one(window)/new Node(window) ,S.one(document)/new NodeList(document) 获得
*/
/**
* overrides methods in NodeList.prototype
* @author yiminghe@gmail.com
*/
KISSY.add("node/override", function(S, DOM, Event, NodeList) {
/**
* append(node ,parent) : 参数顺序反过来了
* appendTo(parent,node) : 才是正常
*
*/
S.each(['append', 'prepend','before','after'], function(insertType) {
NodeList.prototype[insertType] = function(html) {
var newNode = html,self = this;
// 创建
if (S.isString(newNode)) {
newNode = DOM.create(newNode);
}
if (newNode) {
DOM[insertType](newNode, self);
}
return self;
};
});
}, {
requires:["dom","event","./base","./attach"]
});
/**
* 2011-05-24
* - 承玉:
* - 重写 NodeList 的某些方法
* - 添加 one ,all ,从当前 NodeList 往下开始选择节点
* - 处理 append ,prepend 和 DOM 的参数实际上是反过来的
* - append/prepend 参数是节点时,如果当前 NodeList 数量 > 1 需要经过 clone,因为同一节点不可能被添加到多个节点中去(NodeList)
*/
/**
* @module anim-easing
*/
KISSY.add('anim/easing', function() {
// Based on Easing Equations (c) 2003 Robert Penner, all rights reserved.
// This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html
// Preview: http://www.robertpenner.com/easing/easing_demo.html
/**
* 和 YUI 的 Easing 相比,S.Easing 进行了归一化处理,参数调整为:
* @param {Number} t Time value used to compute current value 保留 0 =< t <= 1
* @param {Number} b Starting value b = 0
* @param {Number} c Delta between start and end values c = 1
* @param {Number} d Total length of animation d = 1
*/
var PI = Math.PI,
pow = Math.pow,
sin = Math.sin,
BACK_CONST = 1.70158,
Easing = {
swing:function(t) {
return ( -Math.cos(t * PI) / 2 ) + 0.5;
},
/**
* Uniform speed between points.
*/
easeNone: function (t) {
return t;
},
/**
* Begins slowly and accelerates towards end. (quadratic)
*/
easeIn: function (t) {
return t * t;
},
/**
* Begins quickly and decelerates towards end. (quadratic)
*/
easeOut: function (t) {
return ( 2 - t) * t;
},
/**
* Begins slowly and decelerates towards end. (quadratic)
*/
easeBoth: function (t) {
return (t *= 2) < 1 ?
.5 * t * t :
.5 * (1 - (--t) * (t - 2));
},
/**
* Begins slowly and accelerates towards end. (quartic)
*/
easeInStrong: function (t) {
return t * t * t * t;
},
/**
* Begins quickly and decelerates towards end. (quartic)
*/
easeOutStrong: function (t) {
return 1 - (--t) * t * t * t;
},
/**
* Begins slowly and decelerates towards end. (quartic)
*/
easeBothStrong: function (t) {
return (t *= 2) < 1 ?
.5 * t * t * t * t :
.5 * (2 - (t -= 2) * t * t * t);
},
/**
* Snap in elastic effect.
*/
elasticIn: function (t) {
var p = .3, s = p / 4;
if (t === 0 || t === 1) return t;
return -(pow(2, 10 * (t -= 1)) * sin((t - s) * (2 * PI) / p));
},
/**
* Snap out elastic effect.
*/
elasticOut: function (t) {
var p = .3, s = p / 4;
if (t === 0 || t === 1) return t;
return pow(2, -10 * t) * sin((t - s) * (2 * PI) / p) + 1;
},
/**
* Snap both elastic effect.
*/
elasticBoth: function (t) {
var p = .45, s = p / 4;
if (t === 0 || (t *= 2) === 2) return t;
if (t < 1) {
return -.5 * (pow(2, 10 * (t -= 1)) *
sin((t - s) * (2 * PI) / p));
}
return pow(2, -10 * (t -= 1)) *
sin((t - s) * (2 * PI) / p) * .5 + 1;
},
/**
* Backtracks slightly, then reverses direction and moves to end.
*/
backIn: function (t) {
if (t === 1) t -= .001;
return t * t * ((BACK_CONST + 1) * t - BACK_CONST);
},
/**
* Overshoots end, then reverses and comes back to end.
*/
backOut: function (t) {
return (t -= 1) * t * ((BACK_CONST + 1) * t + BACK_CONST) + 1;
},
/**
* Backtracks slightly, then reverses direction, overshoots end,
* then reverses and comes back to end.
*/
backBoth: function (t) {
if ((t *= 2 ) < 1) {
return .5 * (t * t * (((BACK_CONST *= (1.525)) + 1) * t - BACK_CONST));
}
return .5 * ((t -= 2) * t * (((BACK_CONST *= (1.525)) + 1) * t + BACK_CONST) + 2);
},
/**
* Bounce off of start.
*/
bounceIn: function (t) {
return 1 - Easing.bounceOut(1 - t);
},
/**
* Bounces off end.
*/
bounceOut: function (t) {
var s = 7.5625, r;
if (t < (1 / 2.75)) {
r = s * t * t;
}
else if (t < (2 / 2.75)) {
r = s * (t -= (1.5 / 2.75)) * t + .75;
}
else if (t < (2.5 / 2.75)) {
r = s * (t -= (2.25 / 2.75)) * t + .9375;
}
else {
r = s * (t -= (2.625 / 2.75)) * t + .984375;
}
return r;
},
/**
* Bounces off start and end.
*/
bounceBoth: function (t) {
if (t < .5) {
return Easing.bounceIn(t * 2) * .5;
}
return Easing.bounceOut(t * 2 - 1) * .5 + .5;
}
};
Easing.NativeTimeFunction = {
easeNone: 'linear',
ease: 'ease',
easeIn: 'ease-in',
easeOut: 'ease-out',
easeBoth: 'ease-in-out',
// Ref:
// 1. http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag
// 2. http://www.robertpenner.com/easing/easing_demo.html
// 3. assets/cubic-bezier-timing-function.html
// 注:是模拟值,非精确推导值
easeInStrong: 'cubic-bezier(0.9, 0.0, 0.9, 0.5)',
easeOutStrong: 'cubic-bezier(0.1, 0.5, 0.1, 1.0)',
easeBothStrong: 'cubic-bezier(0.9, 0.0, 0.1, 1.0)'
};
return Easing;
});
/**
* TODO:
* - test-easing.html 详细的测试 + 曲线可视化
*
* NOTES:
* - 综合比较 jQuery UI/scripty2/YUI 的 easing 命名,还是觉得 YUI 的对用户
* 最友好。因此这次完全照搬 YUI 的 Easing, 只是代码上做了点压缩优化。
*
*/
/**
* single timer for the whole anim module
* @author yiminghe@gmail.com
*/
KISSY.add("anim/manager", function(S) {
var stamp = S.stamp;
return {
interval:15,
runnings:{},
timer:null,
start:function(anim) {
var self = this,
kv = stamp(anim);
if (self.runnings[kv]) {
return;
}
self.runnings[kv] = anim;
self.startTimer();
},
stop:function(anim) {
this.notRun(anim);
},
notRun:function(anim) {
var self = this,
kv = stamp(anim);
delete self.runnings[kv];
if (S.isEmptyObject(self.runnings)) {
self.stopTimer();
}
},
pause:function(anim) {
this.notRun(anim);
},
resume:function(anim) {
this.start(anim);
},
startTimer:function() {
var self = this;
if (!self.timer) {
self.timer = setTimeout(function() {
if (!self.runFrames()) {
self.timer = 0;
self.startTimer();
} else {
self.stopTimer();
}
}, self.interval);
}
},
stopTimer:function() {
var self = this,
t = self.timer;
if (t) {
clearTimeout(t);
self.timer = 0;
}
},
runFrames:function() {
var self = this,
done = 1,
runnings = self.runnings;
for (var r in runnings) {
if (runnings.hasOwnProperty(r)) {
done = 0;
runnings[r]._frame();
}
}
return done;
}
};
});
/**
* animate on single property
* @author yiminghe@gmail.com
*/
KISSY.add("anim/fx", function(S, DOM, undefined) {
/**
* basic animation about single css property or element attribute
* @param cfg
*/
function Fx(cfg) {
this.load(cfg);
}
S.augment(Fx, {
load:function(cfg) {
var self = this;
S.mix(self, cfg);
self.startTime = S.now();
self.pos = 0;
self.unit = self.unit || "";
},
frame:function(end) {
var self = this,
endFlag = 0,
elapsedTime,
t = S.now();
if (end || t >= self.duration + self.startTime) {
self.pos = 1;
endFlag = 1;
} else {
elapsedTime = t - self.startTime;
self.pos = self.easing(elapsedTime / self.duration);
}
self.update();
return endFlag;
},
/**
* 数值插值函数
* @param {Number} from 源值
* @param {Number} to 目的值
* @param {Number} pos 当前位置,从 easing 得到 0~1
* @return {Number} 当前值
*/
interpolate:function (from, to, pos) {
// 默认只对数字进行 easing
if (S.isNumber(from) &&
S.isNumber(to)) {
return (from + (to - from) * pos).toFixed(3);
} else {
return undefined;
}
},
update:function() {
var self = this,
prop = self.prop,
elem = self.elem,
from = self.from,
to = self.to,
val = self.interpolate(from, to, self.pos);
if (val === undefined) {
// 插值出错,直接设置为最终值
if (!self.finished) {
self.finished = 1;
DOM.css(elem, prop, to);
S.log(self.prop + " update directly ! : " + val + " : " + from + " : " + to);
}
} else {
val += self.unit;
if (isAttr(elem, prop)) {
DOM.attr(elem, prop, val, 1);
} else {
DOM.css(elem, prop, val);
}
}
},
/**
* current value
*/
cur:function() {
var self = this,
prop = self.prop,
elem = self.elem;
if (isAttr(elem, prop)) {
return DOM.attr(elem, prop, undefined, 1);
}
var parsed,
r = DOM.css(elem, prop);
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN(parsed = parseFloat(r)) ?
!r || r === "auto" ? 0 : r
: parsed;
}
});
function isAttr(elem, prop) {
// support scrollTop/Left now!
if ((!elem.style || elem.style[ prop ] == null) &&
DOM.attr(elem, prop, undefined, 1) != null) {
return 1;
}
return 0;
}
Fx.Factories = {};
Fx.getFx = function(cfg) {
var Constructor = Fx.Factories[cfg.prop] || Fx;
return new Constructor(cfg);
};
return Fx;
}, {
requires:['dom']
});
/**
* TODO
* 支持 transform ,ie 使用 matrix
* - http://shawphy.com/2011/01/transformation-matrix-in-front-end.html
* - http://www.cnblogs.com/winter-cn/archive/2010/12/29/1919266.html
* - 标准:http://www.zenelements.com/blog/css3-transform/
* - ie: http://www.useragentman.com/IETransformsTranslator/
* - wiki: http://en.wikipedia.org/wiki/Transformation_matrix
* - jq 插件: http://plugins.jquery.com/project/2d-transform
**/
/**
* queue of anim objects
* @author yiminghe@gmail.com
*/
KISSY.add("anim/queue", function(S, DOM) {
var /*队列集合容器*/
queueCollectionKey = S.guid("ks-queue-" + S.now() + "-"),
/*默认队列*/
queueKey = S.guid("ks-queue-" + S.now() + "-"),
// 当前队列是否有动画正在执行
processing = "...";
function getQueue(elem, name, readOnly) {
name = name || queueKey;
var qu,
quCollection = DOM.data(elem, queueCollectionKey);
if (!quCollection && !readOnly) {
DOM.data(elem, queueCollectionKey, quCollection = {});
}
if (quCollection) {
qu = quCollection[name];
if (!qu && !readOnly) {
qu = quCollection[name] = [];
}
}
return qu;
}
function removeQueue(elem, name) {
name = name || queueKey;
var quCollection = DOM.data(elem, queueCollectionKey);
if (quCollection) {
delete quCollection[name];
}
if (S.isEmptyObject(quCollection)) {
DOM.removeData(elem, queueCollectionKey);
}
}
var q = {
queueCollectionKey:queueCollectionKey,
queue:function(anim) {
var elem = anim.elem,
name = anim.config.queue,
qu = getQueue(elem, name);
qu.push(anim);
if (qu[0] !== processing) {
q.dequeue(anim);
}
return qu;
},
remove:function(anim) {
var elem = anim.elem,
name = anim.config.queue,
qu = getQueue(elem, name, 1),index;
if (qu) {
index = S.indexOf(anim, qu);
if (index > -1) {
qu.splice(index, 1);
}
}
},
removeQueues:function(elem) {
DOM.removeData(elem, queueCollectionKey);
},
removeQueue:removeQueue,
dequeue:function(anim) {
var elem = anim.elem,
name = anim.config.queue,
qu = getQueue(elem, name, 1),
nextAnim = qu && qu.shift();
if (nextAnim == processing) {
nextAnim = qu.shift();
}
if (nextAnim) {
qu.unshift(processing);
nextAnim._runInternal();
} else {
// remove queue data
removeQueue(elem, name);
}
}
};
return q;
}, {
requires:['dom']
});
/**
* animation framework for KISSY
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('anim/base', function(S, DOM, Event, Easing, UA, AM, Fx, Q) {
var camelCase = DOM._camelCase,
_isElementNode = DOM._isElementNode,
specialVals = ["hide","show","toggle"],
// shorthand css properties
SHORT_HANDS = {
border:[
"borderBottomWidth",
"borderLeftWidth",
'borderRightWidth',
// 'borderSpacing', 组合属性?
'borderTopWidth'
],
"borderBottom":["borderBottomWidth"],
"borderLeft":["borderLeftWidth"],
borderTop:["borderTopWidth"],
borderRight:["borderRightWidth"],
font:[
'fontSize',
'fontWeight'
],
margin:[
'marginBottom',
'marginLeft',
'marginRight',
'marginTop'
],
padding:[
'paddingBottom',
'paddingLeft',
'paddingRight',
'paddingTop'
]
},
defaultConfig = {
duration: 1,
easing: 'easeNone'
},
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i;
Anim.SHORT_HANDS = SHORT_HANDS;
/**
* get a anim instance associate
* @param elem 元素或者 window ( window 时只能动画 scrollTop/scrollLeft )
* @param props
* @param duration
* @param easing
* @param callback
*/
function Anim(elem, props, duration, easing, callback) {
var self = this,config;
// ignore non-exist element
if (!(elem = DOM.get(elem))) {
return;
}
// factory or constructor
if (!(self instanceof Anim)) {
return new Anim(elem, props, duration, easing, callback);
}
/**
* the transition properties
*/
if (S.isString(props)) {
props = S.unparam(props, ";", ":");
} else {
// clone to prevent collision within multiple instance
props = S.clone(props);
}
/**
* 驼峰属性名
*/
for (var prop in props) {
var camelProp = camelCase(S.trim(prop));
if (prop != camelProp) {
props[camelProp] = props[prop];
delete props[prop];
}
}
/**
* animation config
*/
if (S.isPlainObject(duration)) {
config = S.clone(duration);
} else {
config = {
duration:parseFloat(duration) || undefined,
easing:easing,
complete:callback
};
}
config = S.merge(defaultConfig, config);
self.config = config;
config.duration *= 1000;
// domEl deprecated!
self.elem = self['domEl'] = elem;
self.props = props;
// 实例属性
self._backupProps = {};
self._fxs = {};
// register callback
self.on("complete", onComplete);
}
function onComplete(e) {
var self = this,
_backupProps = self._backupProps,
config = self.config;
// only recover after complete anim
if (!S.isEmptyObject(_backupProps = self._backupProps)) {
DOM.css(self.elem, _backupProps);
}
if (config.complete) {
config.complete.call(self, e);
}
}
function runInternal() {
var self = this,
config = self.config,
_backupProps = self._backupProps,
elem = self.elem,
hidden,
val,
prop,
specialEasing = (config['specialEasing'] || {}),
fxs = self._fxs,
props = self.props;
// 进入该函数即代表执行(q[0] 已经是 ...)
saveRunning(self);
if (self.fire("start") === false) {
// no need to invoke complete
self.stop(0);
return;
}
if (_isElementNode(elem)) {
hidden = DOM.css(elem, "display") == "none";
for (prop in props) {
val = props[prop];
// 直接结束
if (val == "hide" && hidden || val == 'show' && !hidden) {
// need to invoke complete
self.stop(1);
return;
}
}
}
// 分离 easing
S.each(props, function(val, prop) {
if (!props.hasOwnProperty(prop)) {
return;
}
var easing;
if (S.isArray(val)) {
easing = specialEasing[prop] = val[1];
props[prop] = val[0];
} else {
easing = specialEasing[prop] = (specialEasing[prop] || config.easing);
}
if (S.isString(easing)) {
easing = specialEasing[prop] = Easing[easing];
}
specialEasing[prop] = easing || Easing.easeNone;
});
// 扩展分属性
S.each(SHORT_HANDS, function(shortHands, p) {
var sh,
origin,
val;
if (val = props[p]) {
origin = {};
S.each(shortHands, function(sh) {
// 得到原始分属性之前值
origin[sh] = DOM.css(elem, sh);
specialEasing[sh] = specialEasing[p];
});
DOM.css(elem, p, val);
for (sh in origin) {
// 得到期待的分属性最后值
props[sh] = DOM.css(elem, sh);
// 还原
DOM.css(elem, sh, origin[sh]);
}
// 删除复合属性
delete props[p];
}
});
// 取得单位,并对单个属性构建 Fx 对象
for (prop in props) {
if (!props.hasOwnProperty(prop)) {
continue;
}
val = S.trim(props[prop]);
var to,
from,
propCfg = {
elem:elem,
prop:prop,
duration:config.duration,
easing:specialEasing[prop]
},
fx = Fx.getFx(propCfg);
// hide/show/toggle : special treat!
if (S.inArray(val, specialVals)) {
// backup original value
_backupProps[prop] = DOM.style(elem, prop);
if (val == "toggle") {
val = hidden ? "show" : "hide";
}
if (val == "hide") {
to = 0;
from = fx.cur();
// 执行完后隐藏
_backupProps.display = 'none';
} else {
from = 0;
to = fx.cur();
// prevent flash of content
DOM.css(elem, prop, from);
DOM.show(elem);
}
val = to;
} else {
to = val;
from = fx.cur();
}
val += "";
var unit = "",
parts = val.match(rfxnum);
if (parts) {
to = parseFloat(parts[2]);
unit = parts[3];
// 有单位但单位不是 px
if (unit && unit !== "px") {
DOM.css(elem, prop, val);
from = (to / fx.cur()) * from;
DOM.css(elem, prop, from + unit);
}
// 相对
if (parts[1]) {
to = ( (parts[ 1 ] === "-=" ? -1 : 1) * to ) + from;
}
}
propCfg.from = from;
propCfg.to = to;
propCfg.unit = unit;
fx.load(propCfg);
fxs[prop] = fx;
}
if (_isElementNode(elem) &&
(props.width || props.height)) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
S.mix(_backupProps, {
overflow:DOM.style(elem, "overflow"),
"overflow-x":DOM.style(elem, "overflowX"),
"overflow-y":DOM.style(elem, "overflowY")
});
DOM.css(elem, "overflow", "hidden");
// inline element should has layout/inline-block
if (DOM.css(elem, "display") === "inline" &&
DOM.css(elem, "float") === "none") {
if (UA['ie']) {
DOM.css(elem, "zoom", 1);
} else {
DOM.css(elem, "display", "inline-block");
}
}
}
AM.start(self);
}
S.augment(Anim, Event.Target, {
/**
* @type {boolean} 是否在运行
*/
isRunning:function() {
return isRunning(this);
},
_runInternal:runInternal,
/**
* 开始动画
*/
run: function() {
var self = this,
queueName = self.config.queue;
if (queueName === false) {
runInternal.call(self);
} else {
// 当前动画对象加入队列
Q.queue(self);
}
return self;
},
_frame:function() {
var self = this,
prop,
end = 1,
fxs = self._fxs;
for (prop in fxs) {
if (fxs.hasOwnProperty(prop)) {
end &= fxs[prop].frame();
}
}
if ((self.fire("step") === false) ||
end) {
// complete 事件只在动画到达最后一帧时才触发
self.stop(end);
}
},
stop: function(finish) {
var self = this,
config = self.config,
queueName = config.queue,
prop,
fxs = self._fxs;
// already stopped
if (!self.isRunning()) {
// 从自己的队列中移除
if (queueName !== false) {
Q.remove(self);
}
return;
}
if (finish) {
for (prop in fxs) {
if (fxs.hasOwnProperty(prop)) {
fxs[prop].frame(1);
}
}
self.fire("complete");
}
AM.stop(self);
removeRunning(self);
if (queueName !== false) {
// notify next anim to run in the same queue
Q.dequeue(self);
}
return self;
}
});
var runningKey = S.guid("ks-anim-unqueued-" + S.now() + "-");
function saveRunning(anim) {
var elem = anim.elem,
allRunning = DOM.data(elem, runningKey);
if (!allRunning) {
DOM.data(elem, runningKey, allRunning = {});
}
allRunning[S.stamp(anim)] = anim;
}
function removeRunning(anim) {
var elem = anim.elem,
allRunning = DOM.data(elem, runningKey);
if (allRunning) {
delete allRunning[S.stamp(anim)];
if (S.isEmptyObject(allRunning)) {
DOM.removeData(elem, runningKey);
}
}
}
function isRunning(anim) {
var elem = anim.elem,
allRunning = DOM.data(elem, runningKey);
if (allRunning) {
return !!allRunning[S.stamp(anim)];
}
return 0;
}
/**
* stop all the anims currently running
* @param elem element which anim belongs to
* @param end
* @param clearQueue
*/
Anim.stop = function(elem, end, clearQueue, queueName) {
if (
// default queue
queueName === null ||
// name of specified queue
S.isString(queueName) ||
// anims not belong to any queue
queueName === false
) {
return stopQueue.apply(undefined, arguments);
}
// first stop first anim in queues
if (clearQueue) {
Q.removeQueues(elem);
}
var allRunning = DOM.data(elem, runningKey),
// can not stop in for/in , stop will modified allRunning too
anims = S.merge(allRunning);
for (var k in anims) {
anims[k].stop(end);
}
};
/**
*
* @param elem element which anim belongs to
* @param queueName queue'name if set to false only remove
* @param end
* @param clearQueue
*/
function stopQueue(elem, end, clearQueue, queueName) {
if (clearQueue && queueName !== false) {
Q.removeQueue(elem, queueName);
}
var allRunning = DOM.data(elem, runningKey),
anims = S.merge(allRunning);
for (var k in anims) {
var anim = anims[k];
if (anim.config.queue == queueName) {
anim.stop(end);
}
}
}
/**
* whether elem is running anim
* @param elem
*/
Anim['isRunning'] = function(elem) {
var allRunning = DOM.data(elem, runningKey);
return allRunning && !S.isEmptyObject(allRunning);
};
Anim.Q = Q;
if (SHORT_HANDS) {
}
return Anim;
}, {
requires:["dom","event","./easing","ua","./manager","./fx","./queue"]
});
/**
* 2011-11
* - 重构,抛弃 emile,优化性能,只对需要的属性进行动画
* - 添加 stop/stopQueue/isRunning,支持队列管理
*
* 2011-04
* - 借鉴 yui3 ,中央定时器,否则 ie6 内存泄露?
* - 支持配置 scrollTop/scrollLeft
*
*
* TODO:
* - 效率需要提升,当使用 nativeSupport 时仍做了过多动作
* - opera nativeSupport 存在 bug ,浏览器自身 bug ?
* - 实现 jQuery Effects 的 queue / specialEasing / += / 等特性
*
* NOTES:
* - 与 emile 相比,增加了 borderStyle, 使得 border: 5px solid #ccc 能从无到有,正确显示
* - api 借鉴了 YUI, jQuery 以及 http://www.w3.org/TR/css3-transitions/
* - 代码实现了借鉴了 Emile.js: http://github.com/madrobby/emile *
*/
/**
* special patch for making color gradual change
* @author yiminghe@gmail.com
*/
KISSY.add("anim/color", function(S, DOM, Anim, Fx) {
var HEX_BASE = 16,
floor = Math.floor,
KEYWORDS = {
"black":[0,0,0],
"silver":[192,192,192],
"gray":[128,128,128],
"white":[255,255,255],
"maroon":[128,0,0],
"red":[255,0,0],
"purple":[128,0,128],
"fuchsia":[255,0,255],
"green":[0,128,0],
"lime":[0,255,0],
"olive":[128,128,0],
"yellow":[255,255,0],
"navy":[0,0,128],
"blue":[0,0,255],
"teal":[0,128,128],
"aqua":[0,255,255]
},
re_RGB = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
re_RGBA = /^rgba\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+),\s*([0-9]+)\)$/i,
re_hex = /^#?([0-9A-F]{1,2})([0-9A-F]{1,2})([0-9A-F]{1,2})$/i,
SHORT_HANDS = Anim.SHORT_HANDS,
COLORS = [
'backgroundColor' ,
'borderBottomColor' ,
'borderLeftColor' ,
'borderRightColor' ,
'borderTopColor' ,
'color' ,
'outlineColor'
];
SHORT_HANDS['background'] = ['backgroundColor'];
SHORT_HANDS['borderColor'] = [
'borderBottomColor',
'borderLeftColor',
'borderRightColor',
'borderTopColor'
];
SHORT_HANDS['border'].push(
'borderBottomColor',
'borderLeftColor',
'borderRightColor',
'borderTopColor'
);
SHORT_HANDS['borderBottom'].push(
'borderBottomColor'
);
SHORT_HANDS['borderLeft'].push(
'borderLeftColor'
);
SHORT_HANDS['borderRight'].push(
'borderRightColor'
);
SHORT_HANDS['borderTop'].push(
'borderTopColor'
);
//得到颜色的数值表示,红绿蓝数字数组
function numericColor(val) {
val = (val + "");
var match;
if (match = val.match(re_RGB)) {
return [
parseInt(match[1]),
parseInt(match[2]),
parseInt(match[3])
];
}
else if (match = val.match(re_RGBA)) {
return [
parseInt(match[1]),
parseInt(match[2]),
parseInt(match[3]),
parseInt(match[4])
];
}
else if (match = val.match(re_hex)) {
for (var i = 1; i < match.length; i++) {
if (match[i].length < 2) {
match[i] += match[i];
}
}
return [
parseInt(match[1], HEX_BASE),
parseInt(match[2], HEX_BASE),
parseInt(match[3], HEX_BASE)
];
}
if (KEYWORDS[val = val.toLowerCase()]) {
return KEYWORDS[val];
}
//transparent 或者 颜色字符串返回
S.log("only allow rgb or hex color string : " + val, "warn");
return [255,255,255];
}
function ColorFx() {
ColorFx.superclass.constructor.apply(this, arguments);
}
S.extend(ColorFx, Fx, {
load:function() {
var self = this;
ColorFx.superclass.load.apply(self, arguments);
if (self.from) {
self.from = numericColor(self.from);
}
if (self.to) {
self.to = numericColor(self.to);
}
},
interpolate:function (from, to, pos) {
var interpolate = ColorFx.superclass.interpolate;
if (from.length == 3 && to.length == 3) {
return 'rgb(' + [
floor(interpolate(from[0], to[0], pos)),
floor(interpolate(from[1], to[1], pos)),
floor(interpolate(from[2], to[2], pos))
].join(', ') + ')';
} else if (from.length == 4 || to.length == 4) {
return 'rgba(' + [
floor(interpolate(from[0], to[0], pos)),
floor(interpolate(from[1], to[1], pos)),
floor(interpolate(from[2], to[2], pos)),
// 透明度默认 1
floor(interpolate(from[3] || 1, to[3] || 1, pos))
].join(', ') + ')';
} else {
S.log("anim/color unknown value : " + from);
}
}
});
S.each(COLORS, function(color) {
Fx.Factories[color] = ColorFx;
});
return ColorFx;
}, {
requires:["dom","./base","./fx"]
});
/**
* TODO
* 支持 hsla
* - https://github.com/jquery/jquery-color/blob/master/jquery.color.js
**/
KISSY.add("anim", function(S, Anim,Easing) {
Anim.Easing=Easing;
return Anim;
}, {
requires:["anim/base","anim/easing","anim/color"]
});
/**
* @module anim-node-plugin
* @author yiminghe@gmail.com,
* lifesinger@gmail.com,
* qiaohua@taobao.com,
*
*/
KISSY.add('node/anim', function(S, DOM, Anim, Node, undefined) {
var FX = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
function getFxs(type, num, from) {
var ret = [],
obj = {};
for (var i = from || 0; i < num; i++) {
ret.push.apply(ret, FX[i]);
}
for (i = 0; i < ret.length; i++) {
obj[ret[i]] = type;
}
return obj;
}
S.augment(Node, {
animate:function() {
var self = this,
args = S.makeArray(arguments);
S.each(self, function(elem) {
Anim.apply(undefined, [elem].concat(args)).run();
});
return self;
},
stop:function(end, clearQueue, queue) {
var self = this;
S.each(self, function(elem) {
Anim.stop(elem, end, clearQueue, queue);
});
return self;
},
isRunning:function() {
var self = this;
for (var i = 0; i < self.length; i++) {
if (Anim.isRunning(self[i])) {
return 1;
}
}
return 0;
}
});
S.each({
show: getFxs("show", 3),
hide: getFxs("hide", 3),
toggle:getFxs("toggle", 3),
fadeIn: getFxs("show", 3, 2),
fadeOut: getFxs("hide", 3, 2),
fadeToggle:getFxs("toggle", 3, 2),
slideDown: getFxs("show", 1),
slideUp: getFxs("hide", 1),
slideToggle:getFxs("toggle", 1)
},
function(v, k) {
Node.prototype[k] = function(speed, callback, easing) {
var self = this;
// 没有参数时,调用 DOM 中的对应方法
if (DOM[k] && !speed) {
DOM[k](self);
} else {
S.each(self, function(elem) {
Anim(elem, v, speed, easing || 'easeOut', callback).run();
});
}
return self;
};
});
}, {
requires:["dom","anim","./base"]
});
/**
* 2011-11-10
* - 重写,逻辑放到 Anim 模块,这边只进行转发
*
* 2011-05-17
* - 承玉:添加 stop ,随时停止动画
*
* TODO
* - anim needs queue mechanism ?
*/
KISSY.add("node", function(S, Event, Node) {
Node.KeyCodes = Event.KeyCodes;
return Node;
}, {
requires:[
"event",
"node/base",
"node/attach",
"node/override",
"node/anim"]
});
/*
http://www.JSON.org/json2.js
2010-08-25
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
KISSY.add("json/json2", function(S, UA) {
var win = window,JSON = win.JSON;
// ie 8.0.7600.16315@win7 json 有问题
if (!JSON || UA['ie'] < 9) {
JSON = win.JSON = {};
}
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
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);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
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.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;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
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});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx['lastIndex'] = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
return JSON;
}, {requires:['ua']});
/**
* adapt json2 to kissy
* @author lifesinger@gmail.com
*/
KISSY.add('json', function (S, JSON) {
return {
parse: function(text) {
// 当输入为 undefined / null / '' 时,返回 null
if (S.isNullOrUndefined(text) || text === '') {
return null;
}
return JSON.parse(text);
},
stringify: JSON.stringify
};
}, {
requires:["json/json2"]
});
/**
* form data serialization util
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/form-serializer", function(S, DOM) {
var rselectTextarea = /^(?:select|textarea)/i,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i;
return {
/**
* 序列化表单元素
* @param {String|HTMLElement[]|HTMLElement|Node} forms
*/
serialize:function(forms) {
var elements = [],data = {};
DOM.query(forms).each(function(el) {
// form 取其表单元素集合
// 其他直接取自身
var subs = el.elements ? S.makeArray(el.elements) : [el];
elements.push.apply(elements, subs);
});
// 对表单元素进行过滤,具备有效值的才保留
elements = S.filter(elements, function(el) {
// 有名字
return el.name &&
// 不被禁用
!el.disabled &&
(
// radio,checkbox 被选择了
el.checked ||
// select 或者 textarea
rselectTextarea.test(el.nodeName) ||
// input 类型
rinput.test(el.type)
);
// 这样子才取值
});
S.each(elements, function(el) {
var val = DOM.val(el),vs;
// 字符串换行平台归一化
val = S.map(S.makeArray(val), function(v) {
return v.replace(rCRLF, "\r\n");
});
// 全部搞成数组,防止同名
vs = data[el.name] = data[el.name] || [];
vs.push.apply(vs, val);
});
// 名值键值对序列化,数组元素名字前不加 []
return S.param(data, undefined, undefined, false);
}
};
}, {
requires:['dom']
});
/**
* encapsulation of io object . as transaction object in yui3
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/xhrobject", function(S, Event) {
var OK_CODE = 200,
MULTIPLE_CHOICES = 300,
NOT_MODIFIED = 304,
// get individual response header from responseheader str
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg;
function handleResponseData(xhr) {
// text xml 是否原生转化支持
var text = xhr.responseText,
xml = xhr.responseXML,
c = xhr.config,
cConverts = c.converters,
xConverts = xhr.converters || {},
type,
responseData,
contents = c.contents,
dataType = c.dataType;
// 例如 script 直接是js引擎执行,没有返回值,不需要自己处理初始返回值
// jsonp 时还需要把 script 转换成 json,后面还得自己来
if (text || xml) {
var contentType = xhr.mimeType || xhr.getResponseHeader("Content-Type");
// 去除无用的通用格式
while (dataType[0] == "*") {
dataType.shift();
}
if (!dataType.length) {
// 获取源数据格式,放在第一个
for (type in contents) {
if (contents[type].test(contentType)) {
if (dataType[0] != type) {
dataType.unshift(type);
}
break;
}
}
}
// 服务器端没有告知(并且客户端没有mimetype)默认 text 类型
dataType[0] = dataType[0] || "text";
//获得合适的初始数据
if (dataType[0] == "text" && text !== undefined) {
responseData = text;
}
// 有 xml 值才直接取,否则可能还要从 xml 转
else if (dataType[0] == "xml" && xml !== undefined) {
responseData = xml;
} else {
// 看能否从 text xml 转换到合适数据
S.each(["text","xml"], function(prevType) {
var type = dataType[0],
converter = xConverts[prevType] && xConverts[prevType][type] ||
cConverts[prevType] && cConverts[prevType][type];
if (converter) {
dataType.unshift(prevType);
responseData = prevType == "text" ? text : xml;
return false;
}
});
}
}
var prevType = dataType[0];
// 按照转化链把初始数据转换成我们想要的数据类型
for (var i = 1; i < dataType.length; i++) {
type = dataType[i];
var converter = xConverts[prevType] && xConverts[prevType][type] ||
cConverts[prevType] && cConverts[prevType][type];
if (!converter) {
throw "no covert for " + prevType + " => " + type;
}
responseData = converter(responseData);
prevType = type;
}
xhr.responseData = responseData;
}
function XhrObject(c) {
S.mix(this, {
// 结构化数据,如 json
responseData:null,
config:c || {},
timeoutTimer:null,
responseText:null,
responseXML:null,
responseHeadersString:"",
responseHeaders:null,
requestHeaders:{},
readyState:0,
//internal state
state:0,
statusText:null,
status:0,
transport:null
});
}
S.augment(XhrObject, Event.Target, {
// Caches the header
setRequestHeader: function(name, value) {
this.requestHeaders[ name ] = value;
return this;
},
// Raw string
getAllResponseHeaders: function() {
return this.state === 2 ? this.responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function(key) {
var match;
if (this.state === 2) {
if (!this.responseHeaders) {
this.responseHeaders = {};
while (( match = rheaders.exec(this.responseHeadersString) )) {
this.responseHeaders[ match[1] ] = match[ 2 ];
}
}
match = this.responseHeaders[ key];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function(type) {
if (!this.state) {
this.mimeType = type;
}
return this;
},
// Cancel the request
abort: function(statusText) {
statusText = statusText || "abort";
if (this.transport) {
this.transport.abort(statusText);
}
this.callback(0, statusText);
return this;
},
callback:function(status, statusText) {
//debugger
var xhr = this;
// 只能执行一次,防止重复执行
// 例如完成后,调用 abort
// 到这要么成功,调用success
// 要么失败,调用 error
// 最终都会调用 complete
if (xhr.state == 2) {
return;
}
xhr.state = 2;
xhr.readyState = 4;
var isSuccess;
if (status >= OK_CODE && status < MULTIPLE_CHOICES || status == NOT_MODIFIED) {
if (status == NOT_MODIFIED) {
statusText = "notmodified";
isSuccess = true;
} else {
try {
handleResponseData(xhr);
statusText = "success";
isSuccess = true;
} catch(e) {
statusText = "parsererror : " + e;
}
}
} else {
if (status < 0) {
status = 0;
}
}
xhr.status = status;
xhr.statusText = statusText;
if (isSuccess) {
xhr.fire("success");
} else {
xhr.fire("error");
}
xhr.fire("complete");
xhr.transport = undefined;
}
}
);
return XhrObject;
}, {
requires:["event"]
});
/**
* a scalable client io framework
* @author yiminghe@gmail.com , lijing00333@163.com
*/
KISSY.add("ajax/base", function(S, JSON, Event, XhrObject) {
var rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
rspace = /\s+/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
mirror = function(s) {
return s;
},
HTTP_PORT = 80,
HTTPS_PORT = 443,
rnoContent = /^(?:GET|HEAD)$/,
curLocation,
curLocationParts;
try {
curLocation = location.href;
} catch(e) {
S.log("ajax/base get curLocation error : ");
S.log(e);
// Use the href attribute of an A element
// since IE will modify it given document.location
curLocation = document.createElement("a");
curLocation.href = "";
curLocation = curLocation.href;
}
curLocationParts = rurl.exec(curLocation);
var isLocal = rlocalProtocol.test(curLocationParts[1]),
transports = {},
defaultConfig = {
// isLocal:isLocal,
type:"GET",
// only support utf-8 when post, encoding can not be changed actually
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
async:true,
// whether add []
serializeArray:true,
// whether param data
processData:true,
/*
url:"",
context:null,
// 单位秒!!
timeout: 0,
data: null,
// 可取json | jsonp | script | xml | html | text | null | undefined
dataType: null,
username: null,
password: null,
cache: null,
mimeType:null,
xdr:{
subDomain:{
proxy:'http://xx.t.com/proxy.html'
},
src:''
},
headers: {},
xhrFields:{},
// jsonp script charset
scriptCharset:null,
crossdomain:false,
forceScript:false,
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": "*/*"
},
converters:{
text:{
json:JSON.parse,
html:mirror,
text:mirror,
xml:S.parseXML
}
},
contents:{
xml:/xml/,
html:/html/,
json:/json/
}
};
defaultConfig.converters.html = defaultConfig.converters.text;
function setUpConfig(c) {
// deep mix
c = S.mix(S.clone(defaultConfig), c || {}, undefined, undefined, true);
if (!S.isBoolean(c.crossDomain)) {
var parts = rurl.exec(c.url.toLowerCase());
c.crossDomain = !!( parts &&
( parts[ 1 ] != curLocationParts[ 1 ] || parts[ 2 ] != curLocationParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? HTTP_PORT : HTTPS_PORT ) )
!=
( curLocationParts[ 3 ] || ( curLocationParts[ 1 ] === "http:" ? HTTP_PORT : HTTPS_PORT ) ) )
);
}
if (c.processData && c.data && !S.isString(c.data)) {
// 必须 encodeURIComponent 编码 utf-8
c.data = S.param(c.data, undefined, undefined, c.serializeArray);
}
c.type = c.type.toUpperCase();
c.hasContent = !rnoContent.test(c.type);
if (!c.hasContent) {
if (c.data) {
c.url += ( /\?/.test(c.url) ? "&" : "?" ) + c.data;
}
if (c.cache === false) {
c.url += ( /\?/.test(c.url) ? "&" : "?" ) + "_ksTS=" + (S.now() + "_" + S.guid());
}
}
// 数据类型处理链,一步步将前面的数据类型转化成最后一个
c.dataType = S.trim(c.dataType || "*").split(rspace);
c.context = c.context || c;
return c;
}
function fire(eventType, xhr) {
io.fire(eventType, { ajaxConfig: xhr.config ,xhr:xhr});
}
function handleXhrEvent(e) {
var xhr = this,
c = xhr.config,
type = e.type;
if (this.timeoutTimer) {
clearTimeout(this.timeoutTimer);
}
if (c[type]) {
c[type].call(c.context, xhr.responseData, xhr.statusText, xhr);
}
fire(type, xhr);
}
function io(c) {
if (!c.url) {
return undefined;
}
c = setUpConfig(c);
var xhr = new XhrObject(c);
fire("start", xhr);
var transportContructor = transports[c.dataType[0]] || transports["*"],
transport = new transportContructor(xhr);
xhr.transport = transport;
if (c.contentType) {
xhr.setRequestHeader("Content-Type", c.contentType);
}
var dataType = c.dataType[0],
accepts = c.accepts;
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader(
"Accept",
dataType && accepts[dataType] ?
accepts[ dataType ] + (dataType === "*" ? "" : ", */*; q=0.01" ) :
accepts[ "*" ]
);
// Check for headers option
for (var i in c.headers) {
xhr.setRequestHeader(i, c.headers[ i ]);
}
xhr.on("complete success error", handleXhrEvent);
xhr.readyState = 1;
fire("send", xhr);
// Timeout
if (c.async && c.timeout > 0) {
xhr.timeoutTimer = setTimeout(function() {
xhr.abort("timeout");
}, c.timeout * 1000);
}
try {
// flag as sending
xhr.state = 1;
transport.send();
} catch (e) {
// Propagate exception as error if not done
if (xhr.status < 2) {
xhr.callback(-1, e);
// Simply rethrow otherwise
} else {
S.error(e);
}
}
return xhr;
}
S.mix(io, Event.Target);
S.mix(io, {
isLocal:isLocal,
setupConfig:function(setting) {
S.mix(defaultConfig, setting, undefined, undefined, true);
},
setupTransport:function(name, fn) {
transports[name] = fn;
},
getTransport:function(name) {
return transports[name];
},
getConfig:function() {
return defaultConfig;
}
});
return io;
},
{
requires:["json","event","./xhrobject"]
});
/**
* 借鉴 jquery,优化减少闭包使用
*
* TODO:
* ifModified mode 是否需要?
* 优点:
* 不依赖浏览器处理,ajax 请求浏览不会自动加 If-Modified-Since If-None-Match ??
* 缺点:
* 内存占用
**/
/**
* base for xhr and subdomain
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/xhrbase", function(S, io) {
var OK_CODE = 200,
win = window,
// http://msdn.microsoft.com/en-us/library/cc288060(v=vs.85).aspx
_XDomainRequest = win['XDomainRequest'],
NO_CONTENT_CODE = 204,
NOT_FOUND_CODE = 404,
NO_CONTENT_CODE2 = 1223,
XhrBase = {
proto:{}
};
function createStandardXHR(_, refWin) {
try {
return new (refWin || win)['XMLHttpRequest']();
} catch(e) {
//S.log("createStandardXHR error");
}
return undefined;
}
function createActiveXHR(_, refWin) {
try {
return new (refWin || win)['ActiveXObject']("Microsoft.XMLHTTP");
} catch(e) {
S.log("createActiveXHR error");
}
return undefined;
}
XhrBase.xhr = win.ActiveXObject ? function(crossDomain, refWin) {
if (crossDomain && _XDomainRequest) {
return new _XDomainRequest();
}
// ie7 XMLHttpRequest 不能访问本地文件
return !io.isLocal && createStandardXHR(crossDomain, refWin) || createActiveXHR(crossDomain, refWin);
} : createStandardXHR;
function isInstanceOfXDomainRequest(xhr) {
return _XDomainRequest && (xhr instanceof _XDomainRequest);
}
S.mix(XhrBase.proto, {
sendInternal:function() {
var self = this,
xhrObj = self.xhrObj,
c = xhrObj.config;
var xhr = self.xhr,
xhrFields,
i;
if (c['username']) {
xhr.open(c.type, c.url, c.async, c['username'], c.password)
} else {
xhr.open(c.type, c.url, c.async);
}
if (xhrFields = c['xhrFields']) {
for (i in xhrFields) {
xhr[ i ] = xhrFields[ i ];
}
}
// Override mime type if supported
if (xhrObj.mimeType && xhr.overrideMimeType) {
xhr.overrideMimeType(xhrObj.mimeType);
}
// yui3 and jquery both have
if (!c.crossDomain && !xhrObj.requestHeaders["X-Requested-With"]) {
xhrObj.requestHeaders[ "X-Requested-With" ] = "XMLHttpRequest";
}
try {
// 跨域时,不能设,否则请求变成
// OPTIONS /xhr/r.php HTTP/1.1
if (!c.crossDomain) {
for (i in xhrObj.requestHeaders) {
xhr.setRequestHeader(i, xhrObj.requestHeaders[ i ]);
}
}
} catch(e) {
S.log("setRequestHeader in xhr error : ");
S.log(e);
}
xhr.send(c.hasContent && c.data || null);
if (!c.async || xhr.readyState == 4) {
self._callback();
} else {
// _XDomainRequest 单独的回调机制
if (isInstanceOfXDomainRequest(xhr)) {
xhr.onload = function() {
xhr.readyState = 4;
xhr.status = 200;
self._callback();
};
xhr.onerror = function() {
xhr.readyState = 4;
xhr.status = 500;
self._callback();
};
} else {
xhr.onreadystatechange = function() {
self._callback();
};
}
}
},
// 由 xhrObj.abort 调用,自己不可以调用 xhrObj.abort
abort:function() {
this._callback(0, 1);
},
_callback:function(event, abort) {
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
var self = this,
xhr = self.xhr,
xhrObj = self.xhrObj,
c = xhrObj.config;
//abort or complete
if (abort || xhr.readyState == 4) {
// ie6 ActiveObject 设置不恰当属性导致出错
if (isInstanceOfXDomainRequest(xhr)) {
xhr.onerror = S.noop;
xhr.onload = S.noop;
} else {
// ie6 ActiveObject 只能设置,不能读取这个属性,否则出错!
xhr.onreadystatechange = S.noop;
}
if (abort) {
// 完成以后 abort 不要调用
if (xhr.readyState !== 4) {
xhr.abort();
}
} else {
var status = xhr.status;
// _XDomainRequest 不能获取响应头
if (!isInstanceOfXDomainRequest(xhr)) {
xhrObj.responseHeadersString = xhr.getAllResponseHeaders();
}
var xml = xhr.responseXML;
// Construct response list
if (xml && xml.documentElement /* #4958 */) {
xhrObj.responseXML = xml;
}
xhrObj.responseText = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
var statusText = xhr.statusText;
} catch(e) {
S.log("xhr statustext error : ");
S.log(e);
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if (!status && io.isLocal && !c.crossDomain) {
status = xhrObj.responseText ? OK_CODE : NOT_FOUND_CODE;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if (status === NO_CONTENT_CODE2) {
status = NO_CONTENT_CODE;
}
xhrObj.callback(status, statusText);
}
}
} catch (firefoxAccessException) {
xhr.onreadystatechange = S.noop;
if (!abort) {
xhrObj.callback(-1, firefoxAccessException);
}
}
}
});
return XhrBase;
}, {
requires:['./base']
});
/**
* solve io between sub domains using proxy page
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/subdomain", function(S, XhrBase, Event, DOM) {
var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
PROXY_PAGE = "/sub_domain_proxy.html",
doc = document,
iframeMap = {
// hostname:{iframe: , ready:}
};
function SubDomain(xhrObj) {
var self = this,
c = xhrObj.config;
self.xhrObj = xhrObj;
var m = c.url.match(rurl);
self.__hostname = m[2];
self.__protocol = m[1];
c.crossDomain = false;
}
S.augment(SubDomain, XhrBase.proto, {
send:function() {
var self = this,
c = self.xhrObj.config,
hostname = self.__hostname,
iframe,
iframeDesc = iframeMap[hostname];
var proxy = PROXY_PAGE;
if (c['xdr'] && c['xdr']['subDomain'] && c['xdr']['subDomain'].proxy) {
proxy = c['xdr']['subDomain'].proxy;
}
if (iframeDesc && iframeDesc.ready) {
self.xhr = XhrBase.xhr(0, iframeDesc.iframe.contentWindow);
if (self.xhr) {
self.sendInternal();
} else {
S.error("document.domain not set correctly!");
}
return;
}
if (!iframeDesc) {
iframeDesc = iframeMap[hostname] = {};
iframe = iframeDesc.iframe = document.createElement("iframe");
DOM.css(iframe, {
position:'absolute',
left:'-9999px',
top:'-9999px'
});
DOM.prepend(iframe, doc.body || doc.documentElement);
iframe.src = self.__protocol + "//" + hostname + proxy;
} else {
iframe = iframeDesc.iframe;
}
Event.on(iframe, "load", _onLoad, self);
}
});
function _onLoad() {
var self = this,
hostname = self.__hostname,
iframeDesc = iframeMap[hostname];
iframeDesc.ready = 1;
Event.detach(iframeDesc.iframe, "load", _onLoad, self);
self.send();
}
return SubDomain;
}, {
requires:['./xhrbase','event','dom']
});
/**
* use flash to accomplish cross domain request , usage scenario ? why not jsonp ?
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/xdr", function(S, io, DOM) {
var // current running request instances
maps = {},
ID = "io_swf",
// flash transporter
flash,
doc = document,
// whether create the flash transporter
init = false;
// create the flash transporter
function _swf(uri, _, uid) {
if (init) {
return;
}
init = true;
var o = '<object id="' + ID +
'" type="application/x-shockwave-flash" data="' +
uri + '" width="0" height="0">' +
'<param name="movie" value="' +
uri + '" />' +
'<param name="FlashVars" value="yid=' +
_ + '&uid=' +
uid +
'&host=KISSY.io" />' +
'<param name="allowScriptAccess" value="always" />' +
'</object>',
c = doc.createElement('div');
DOM.prepend(c, doc.body || doc.documentElement);
c.innerHTML = o;
}
function XdrTransport(xhrObj) {
S.log("use flash xdr");
this.xhrObj = xhrObj;
}
S.augment(XdrTransport, {
// rewrite send to support flash xdr
send:function() {
var self = this,
xhrObj = self.xhrObj,
c = xhrObj.config;
var xdr = c['xdr'] || {};
// 不提供则使用 cdn 默认的 flash
_swf(xdr.src || (S.Config.base + "ajax/io.swf"), 1, 1);
// 简便起见,用轮训
if (!flash) {
// S.log("detect xdr flash");
setTimeout(function() {
self.send();
}, 200);
return;
}
self._uid = S.guid();
maps[self._uid] = self;
// ie67 send 出错?
flash.send(c.url, {
id:self._uid,
uid:self._uid,
method:c.type,
data:c.hasContent && c.data || {}
});
},
abort:function() {
flash.abort(this._uid);
},
_xdrResponse:function(e, o) {
// S.log(e);
var self = this,
ret,
xhrObj = self.xhrObj;
// need decodeURI to get real value from flash returned value
xhrObj.responseText = decodeURI(o.c.responseText);
switch (e) {
case 'success':
ret = { status: 200, statusText: "success" };
delete maps[o.id];
break;
case 'abort':
delete maps[o.id];
break;
case 'timeout':
case 'transport error':
case 'failure':
delete maps[o.id];
ret = { status: 500, statusText: e };
break;
}
if (ret) {
xhrObj.callback(ret.status, ret.statusText);
}
}
});
/*called by flash*/
io['applyTo'] = function(_, cmd, args) {
// S.log(cmd + " execute");
var cmds = cmd.split("."),
func = S;
S.each(cmds, function(c) {
func = func[c];
});
func.apply(null, args);
};
// when flash is loaded
io['xdrReady'] = function() {
flash = doc.getElementById(ID);
};
/**
* when response is returned from server
* @param e response status
* @param o internal data
* @param c internal data
*/
io['xdrResponse'] = function(e, o, c) {
var xhr = maps[o.uid];
xhr && xhr._xdrResponse(e, o, c);
};
// export io for flash to call
S.io = io;
return XdrTransport;
}, {
requires:["./base",'dom']
});
/**
* ajax xhr transport class , route subdomain , xdr
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/xhr", function(S, io, XhrBase, SubDomain, XdrTransport) {
var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/;
var _XDomainRequest = window['XDomainRequest'];
var detectXhr = XhrBase.xhr();
if (detectXhr) {
// slice last two pars
// xx.taobao.com => taobao.com
function getMainDomain(host) {
var t = host.split('.');
if (t.length < 2) {
return t.join(".");
} else {
return t.reverse().slice(0, 2).reverse().join('.');
}
}
function XhrTransport(xhrObj) {
var c = xhrObj.config,
xdrCfg = c['xdr'] || {};
if (c.crossDomain) {
var parts = c.url.match(rurl);
// 跨子域
if (getMainDomain(location.hostname) == getMainDomain(parts[2])) {
return new SubDomain(xhrObj);
}
/**
* ie>7 强制使用 flash xdr
*/
if (!("withCredentials" in detectXhr) &&
(String(xdrCfg.use) === "flash" || !_XDomainRequest)) {
return new XdrTransport(xhrObj);
}
}
this.xhrObj = xhrObj;
return undefined;
}
S.augment(XhrTransport, XhrBase.proto, {
send:function() {
var self = this,
xhrObj = self.xhrObj,
c = xhrObj.config;
self.xhr = XhrBase.xhr(c.crossDomain);
self.sendInternal();
}
});
io.setupTransport("*", XhrTransport);
}
return io;
}, {
requires:["./base",'./xhrbase','./subdomain',"./xdr"]
});
/**
* 借鉴 jquery,优化使用原型替代闭包
**/
/**
* script transport for kissy io
* @description: modified version of S.getScript , add abort ability
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/script", function(S, io) {
var doc = document;
var OK_CODE = 200,ERROR_CODE = 500;
io.setupConfig({
accepts:{
script:"text/javascript, " +
"application/javascript, " +
"application/ecmascript, " +
"application/x-ecmascript"
},
contents:{
script:/javascript|ecmascript/
},
converters:{
text:{
// 如果以 xhr+eval 需要下面的,
// 否则直接 script node 不需要,引擎自己执行了,
// 不需要手动 eval
script:function(text) {
S.globalEval(text);
return text;
}
}
}
});
function ScriptTransport(xhrObj) {
// 优先使用 xhr+eval 来执行脚本, ie 下可以探测到(更多)失败状态
if (!xhrObj.config.crossDomain &&
!xhrObj.config['forceScript']) {
return new (io.getTransport("*"))(xhrObj);
}
this.xhrObj = xhrObj;
return 0;
}
S.augment(ScriptTransport, {
send:function() {
var self = this,
script,
xhrObj = this.xhrObj,
c = xhrObj.config,
head = doc['head'] ||
doc.getElementsByTagName("head")[0] ||
doc.documentElement;
self.head = head;
script = doc.createElement("script");
self.script = script;
script.async = "async";
if (c['scriptCharset']) {
script.charset = c['scriptCharset'];
}
script.src = c.url;
script.onerror =
script.onload =
script.onreadystatechange = function(e) {
e = e || window.event;
// firefox onerror 没有 type ?!
self._callback((e.type || "error").toLowerCase());
};
head.insertBefore(script, head.firstChild);
},
_callback:function(event, abort) {
var script = this.script,
xhrObj = this.xhrObj,
head = this.head;
// 防止重复调用,成功后 abort
if (!script) {
return;
}
if (abort ||
!script.readyState ||
/loaded|complete/.test(script.readyState)
|| event == "error"
) {
script['onerror'] = script.onload = script.onreadystatechange = null;
// Remove the script
if (head && script.parentNode) {
// ie 报错载入无效 js
// 怎么 abort ??
// script.src = "#";
head.removeChild(script);
}
this.script = undefined;
this.head = undefined;
// Callback if not abort
if (!abort && event != "error") {
xhrObj.callback(OK_CODE, "success");
}
// 非 ie<9 可以判断出来
else if (event == "error") {
xhrObj.callback(ERROR_CODE, "scripterror");
}
}
},
abort:function() {
this._callback(0, 1);
}
});
io.setupTransport("script", ScriptTransport);
return io;
}, {
requires:['./base','./xhr']
});
/**
* jsonp transport based on script transport
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/jsonp", function(S, io) {
io.setupConfig({
jsonp:"callback",
jsonpCallback:function() {
//不使用 now() ,极端情况下可能重复
return S.guid("jsonp");
}
});
io.on("start", function(e) {
var xhr = e.xhr,c = xhr.config;
if (c.dataType[0] == "jsonp") {
var response,
cJsonpCallback = c.jsonpCallback,
jsonpCallback = S.isFunction(cJsonpCallback) ?
cJsonpCallback() :
cJsonpCallback,
previous = window[ jsonpCallback ];
c.url += ( /\?/.test(c.url) ? "&" : "?" ) + c.jsonp + "=" + jsonpCallback;
// build temporary JSONP function
window[jsonpCallback] = function(r) {
// 使用数组,区别:故意调用了 jsonpCallback(undefined) 与 根本没有调用
// jsonp 返回了数组
if (arguments.length > 1) {
r = S.makeArray(arguments);
}
response = [r];
};
// cleanup whether success or failure
xhr.on("complete", function() {
window[ jsonpCallback ] = previous;
if (previous === undefined) {
try {
delete window[ jsonpCallback ];
} catch(e) {
//S.log("delete window variable error : ");
//S.log(e);
}
} else if (response) {
// after io success handler called
// then call original existed jsonpcallback
previous(response[0]);
}
});
xhr.converters = xhr.converters || {};
xhr.converters.script = xhr.converters.script || {};
// script -> jsonp ,jsonp need to see json not as script
xhr.converters.script.json = function() {
if (!response) {
S.error(" not call jsonpCallback : " + jsonpCallback)
}
return response[0];
};
c.dataType.length = 2;
// 利用 script transport 发送 script 请求
c.dataType[0] = 'script';
c.dataType[1] = 'json';
}
});
return io;
}, {
requires:['./base']
});
KISSY.add("ajax/form", function(S, io, DOM, FormSerializer) {
io.on("start", function(e) {
var xhr = e.xhr,
c = xhr.config;
// serialize form if needed
if (c.form) {
var form = DOM.get(c.form),
enctype = form['encoding'] || form.enctype;
// 上传有其他方法
if (enctype.toLowerCase() != "multipart/form-data") {
// when get need encode
var formParam = FormSerializer.serialize(form);
if (formParam) {
if (c.hasContent) {
// post 加到 data 中
c.data = c.data || "";
if (c.data) {
c.data += "&";
}
c.data += formParam;
} else {
// get 直接加到 url
c.url += ( /\?/.test(c.url) ? "&" : "?" ) + formParam;
}
}
} else {
var d = c.dataType[0];
if (d == "*") {
d = "text";
}
c.dataType.length = 2;
c.dataType[0] = "iframe";
c.dataType[1] = d;
}
}
});
return io;
}, {
requires:['./base',"dom","./form-serializer"]
});
/**
* non-refresh upload file with form by iframe
* @author yiminghe@gmail.com
*/
KISSY.add("ajax/iframe-upload", function(S, DOM, Event, io) {
var doc = document;
var OK_CODE = 200,ERROR_CODE = 500,BREATH_INTERVAL = 30;
// iframe 内的内容就是 body.innerText
io.setupConfig({
converters:{
// iframe 到其他类型的转化和 text 一样
iframe:io.getConfig().converters.text,
text:{
iframe:function(text) {
return text;
}
}}});
function createIframe(xhr) {
var id = S.guid("ajax-iframe");
xhr.iframe = DOM.create("<iframe " +
" id='" + id + "'" +
// need name for target of form
" name='" + id + "'" +
" style='position:absolute;left:-9999px;top:-9999px;'/>");
xhr.iframeId = id;
DOM.prepend(xhr.iframe, doc.body || doc.documentElement);
}
function addDataToForm(data, form, serializeArray) {
data = S.unparam(data);
var ret = [];
for (var d in data) {
var isArray = S.isArray(data[d]),
vs = S.makeArray(data[d]);
// 数组和原生一样对待,创建多个同名输入域
for (var i = 0; i < vs.length; i++) {
var e = doc.createElement("input");
e.type = 'hidden';
e.name = d + (isArray && serializeArray ? "[]" : "");
e.value = vs[i];
DOM.append(e, form);
ret.push(e);
}
}
return ret;
}
function removeFieldsFromData(fields) {
DOM.remove(fields);
}
function IframeTransport(xhr) {
this.xhr = xhr;
}
S.augment(IframeTransport, {
send:function() {
//debugger
var xhr = this.xhr,
c = xhr.config,
fields,
form = DOM.get(c.form);
this.attrs = {
target:DOM.attr(form, "target") || "",
action:DOM.attr(form, "action") || ""
};
this.form = form;
createIframe(xhr);
// set target to iframe to avoid main page refresh
DOM.attr(form, {"target": xhr.iframeId,"action": c.url});
if (c.data) {
fields = addDataToForm(c.data, form, c.serializeArray);
}
this.fields = fields;
var iframe = xhr.iframe;
Event.on(iframe, "load error", this._callback, this);
form.submit();
},
_callback:function(event
//, abort
) {
//debugger
var form = this.form,
xhr = this.xhr,
eventType = event.type,
iframe = xhr.iframe;
// 防止重复调用 , 成功后 abort
if (!iframe) {
return;
}
DOM.attr(form, this.attrs);
if (eventType == "load") {
var iframeDoc = iframe.contentWindow.document;
xhr.responseXML = iframeDoc;
xhr.responseText = DOM.text(iframeDoc.body);
xhr.callback(OK_CODE, "success");
} else if (eventType == 'error') {
xhr.callback(ERROR_CODE, "error");
}
removeFieldsFromData(this.fields);
Event.detach(iframe);
setTimeout(function() {
// firefox will keep loading if not settimeout
DOM.remove(iframe);
}, BREATH_INTERVAL);
// nullify to prevent memory leak?
xhr.iframe = null;
},
abort:function() {
this._callback(0, 1);
}
});
io.setupTransport("iframe", IframeTransport);
return io;
}, {
requires:["dom","event","./base"]
});
KISSY.add("ajax", function(S, serializer, io) {
var undef = undefined;
// some shortcut
S.mix(io, {
/**
* form 序列化
* @param formElement {HTMLFormElement} 将要序列化的 form 元素
*/
serialize:serializer.serialize,
get: function(url, data, callback, dataType, _t) {
// data 参数可省略
if (S.isFunction(data)) {
dataType = callback;
callback = data;
data = undef;
}
return io({
type: _t || "get",
url: url,
data: data,
success: callback,
dataType: dataType
});
},
post: function(url, data, callback, dataType) {
if (S.isFunction(data)) {
dataType = callback;
callback = data;
data = undef;
}
return io.get(url, data, callback, dataType, "post");
},
jsonp: function(url, data, callback) {
if (S.isFunction(data)) {
callback = data;
data = undef;
}
return io.get(url, data, callback, "jsonp");
},
// 和 S.getScript 保持一致
// 更好的 getScript 可以用
/*
io({
dataType:'script'
});
*/
getScript:S.getScript,
getJSON: function(url, data, callback) {
if (S.isFunction(data)) {
callback = data;
data = undef;
}
return io.get(url, data, callback, "json");
},
upload:function(url, form, data, callback, dataType) {
if (S.isFunction(data)) {
dataType = callback;
callback = data;
data = undef;
}
return io({
url:url,
type:'post',
dataType:dataType,
form:form,
data:data,
success:callback
});
}
});
return io;
}, {
requires:[
"ajax/form-serializer",
"ajax/base",
"ajax/xhrobject",
"ajax/xhr",
"ajax/script",
"ajax/jsonp",
"ajax/form",
"ajax/iframe-upload"]
});
/**
* @module Attribute
* @author yiminghe@gmail.com, lifesinger@gmail.com
*/
KISSY.add('base/attribute', function(S, undef) {
// atomic flag
Attribute.INVALID = {};
var INVALID = Attribute.INVALID;
/**
*
* @param host
* @param method
* @return method if fn or host[method]
*/
function normalFn(host, method) {
if (S.isString(method)) {
return host[method];
}
return method;
}
/**
* fire attribute value change
*/
function __fireAttrChange(self, when, name, prevVal, newVal, subAttrName, attrName) {
attrName = attrName || name;
return self.fire(when + capitalFirst(name) + 'Change', {
attrName: attrName,
subAttrName:subAttrName,
prevVal: prevVal,
newVal: newVal
});
}
/**
*
* @param obj
* @param name
* @param create
* @return non-empty property value of obj
*/
function ensureNonEmpty(obj, name, create) {
var ret = obj[name] || {};
if (create) {
obj[name] = ret;
}
return ret;
}
/**
*
* @param self
* @return non-empty attr config holder
*/
function getAttrs(self) {
/**
* attribute meta information
{
attrName: {
getter: function,
setter: function,
// 注意:只能是普通对象以及系统内置类型,而不能是 new Xx(),否则用 valueFn 替代
value: v, // default value
valueFn: function
}
}
*/
return ensureNonEmpty(self, "__attrs", true);
}
/**
*
* @param self
* @return non-empty attr value holder
*/
function getAttrVals(self) {
/**
* attribute value
{
attrName: attrVal
}
*/
return ensureNonEmpty(self, "__attrVals", true);
}
/**
* o, [x,y,z] => o[x][y][z]
* @param o
* @param path
*/
function getValueByPath(o, path) {
for (var i = 0,len = path.length;
o != undef && i < len;
i++) {
o = o[path[i]];
}
return o;
}
/**
* o, [x,y,z], val => o[x][y][z]=val
* @param o
* @param path
* @param val
*/
function setValueByPath(o, path, val) {
var rlen = path.length - 1,
s = o;
if (rlen >= 0) {
for (var i = 0; i < rlen; i++) {
o = o[path[i]];
}
if (o != undef) {
o[path[i]] = val;
} else {
s = undef;
}
}
return s;
}
function setInternal(self, name, value, opts, attrs) {
var ret;
opts = opts || {};
var dot = ".",
path,
subVal,
prevVal,
fullName = name;
if (name.indexOf(dot) !== -1) {
path = name.split(dot);
name = path.shift();
}
prevVal = self.get(name);
if (path) {
subVal = getValueByPath(prevVal, path);
}
// if no change, just return
if (!path && prevVal === value) {
return undefined;
} else if (path && subVal === value) {
return undefined;
}
if (path) {
var tmp = S.clone(prevVal);
setValueByPath(tmp, path, value);
value = tmp;
}
// check before event
if (!opts['silent']) {
if (false === __fireAttrChange(self, 'before', name, prevVal, value, fullName)) {
return false;
}
}
// set it
ret = self.__set(name, value);
if (ret === false) {
return ret;
}
// fire after event
if (!opts['silent']) {
value = getAttrVals(self)[name];
__fireAttrChange(self, 'after', name, prevVal, value, fullName);
if (!attrs) {
__fireAttrChange(self,
'', '*',
[prevVal], [value],
[fullName], [name]);
} else {
attrs.push({
prevVal:prevVal,
newVal:value,
attrName:name,
subAttrName:fullName
});
}
}
return self;
}
/**
* 提供属性管理机制
* @name Attribute
* @class
*/
function Attribute() {
}
S.augment(Attribute, {
/**
* @return un-cloned attr config collections
*/
getAttrs: function() {
return getAttrs(this);
},
/**
* @return un-cloned attr value collections
*/
getAttrVals:function() {
var self = this,
o = {},
a,
attrs = getAttrs(self);
for (a in attrs) {
o[a] = self.get(a);
}
return o;
},
/**
* Adds an attribute with the provided configuration to the host object.
* @param {String} name attrName
* @param {Object} attrConfig The config supports the following properties:
* {
* value: 'the default value', // 最好不要使用自定义类生成的对象,这时使用 valueFn
* valueFn: function //
* setter: function
* getter: function
* }
* @param {boolean} override whether override existing attribute config ,default true
*/
addAttr: function(name, attrConfig, override) {
var self = this,
attrs = getAttrs(self),
cfg = S.clone(attrConfig);
if (!attrs[name]) {
attrs[name] = cfg;
} else {
S.mix(attrs[name], cfg, override);
}
return self;
},
/**
* Configures a group of attributes, and sets initial values.
* @param {Object} attrConfigs An object with attribute name/configuration pairs.
* @param {Object} initialValues user defined initial values
*/
addAttrs: function(attrConfigs, initialValues) {
var self = this;
S.each(attrConfigs, function(attrConfig, name) {
self.addAttr(name, attrConfig);
});
if (initialValues) {
self.set(initialValues);
}
return self;
},
/**
* Checks if the given attribute has been added to the host.
*/
hasAttr: function(name) {
return name && getAttrs(this).hasOwnProperty(name);
},
/**
* Removes an attribute from the host object.
*/
removeAttr: function(name) {
var self = this;
if (self.hasAttr(name)) {
delete getAttrs(self)[name];
delete getAttrVals(self)[name];
}
return self;
},
/**
* Sets the value of an attribute.
*/
set: function(name, value, opts) {
var ret,self = this;
if (S.isPlainObject(name)) {
var all = name;
name = 0;
ret = true;
opts = value;
var attrs = [];
for (name in all) {
ret = setInternal(self, name, all[name], opts, attrs);
if (ret === false) {
break;
}
}
var attrNames = [],
prevVals = [],
newVals = [],
subAttrNames = [];
S.each(attrs, function(attr) {
prevVals.push(attr.prevVal);
newVals.push(attr.newVal);
attrNames.push(attr.attrName);
subAttrNames.push(attr.subAttrName);
});
if (attrNames.length) {
__fireAttrChange(self,
'',
'*',
prevVals,
newVals,
subAttrNames,
attrNames);
}
return ret;
}
return setInternal(self, name, value, opts);
},
/**
* internal use, no event involved, just set.
* @protected overriden by mvc/model
*/
__set: function(name, value) {
var self = this,
setValue,
// if host does not have meta info corresponding to (name,value)
// then register on demand in order to collect all data meta info
// 一定要注册属性元数据,否则其他模块通过 _attrs 不能枚举到所有有效属性
// 因为属性在声明注册前可以直接设置值
attrConfig = ensureNonEmpty(getAttrs(self), name, true),
validator = attrConfig['validator'],
setter = attrConfig['setter'];
// validator check
if (validator = normalFn(self, validator)) {
if (validator.call(self, value, name) === false) {
return false;
}
}
// if setter has effect
if (setter = normalFn(self, setter)) {
setValue = setter.call(self, value, name);
}
if (setValue === INVALID) {
return false;
}
if (setValue !== undef) {
value = setValue;
}
// finally set
getAttrVals(self)[name] = value;
},
/**
* Gets the current value of the attribute.
*/
get: function(name) {
var self = this,
dot = ".",
path,
attrConfig,
getter, ret;
if (name.indexOf(dot) !== -1) {
path = name.split(dot);
name = path.shift();
}
attrConfig = ensureNonEmpty(getAttrs(self), name);
getter = attrConfig['getter'];
// get user-set value or default value
//user-set value takes privilege
ret = name in getAttrVals(self) ?
getAttrVals(self)[name] :
self.__getDefAttrVal(name);
// invoke getter for this attribute
if (getter = normalFn(self, getter)) {
ret = getter.call(self, ret, name);
}
if (path) {
ret = getValueByPath(ret, path);
}
return ret;
},
/**
* get default attribute value from valueFn/value
* @private
* @param name
*/
__getDefAttrVal: function(name) {
var self = this,
attrConfig = ensureNonEmpty(getAttrs(self), name),
valFn,
val;
if ((valFn = normalFn(self, attrConfig.valueFn))) {
val = valFn.call(self);
if (val !== undef) {
attrConfig.value = val;
}
delete attrConfig.valueFn;
getAttrs(self)[name] = attrConfig;
}
return attrConfig.value;
},
/**
* Resets the value of an attribute.just reset what addAttr set (not what invoker set when call new Xx(cfg))
* @param {String} name name of attribute
*/
reset: function (name, opts) {
var self = this;
if (S.isString(name)) {
if (self.hasAttr(name)) {
// if attribute does not have default value, then set to undefined.
return self.set(name, self.__getDefAttrVal(name), opts);
}
else {
return self;
}
}
opts = name;
var attrs = getAttrs(self),
values = {};
// reset all
for (name in attrs) {
values[name] = self.__getDefAttrVal(name);
}
self.set(values, opts);
return self;
}
});
function capitalFirst(s) {
return s.charAt(0).toUpperCase() + s.substring(1);
}
if (undef) {
Attribute.prototype.addAttrs = undef;
}
return Attribute;
});
/**
* 2011-10-18
* get/set sub attribute value ,set("x.y",val) x 最好为 {} ,不要是 new Clz() 出来的
* add validator
*/
/**
* @module Base
* @author yiminghe@gmail.com,lifesinger@gmail.com
*/
KISSY.add('base/base', function (S, Attribute, Event) {
/**
* Base for class-based component
* @name Base
* @extends Event.Target
* @extends Attribute
* @class
*/
function Base(config) {
var c = this.constructor;
// define
while (c) {
addAttrs(this, c['ATTRS']);
c = c.superclass ? c.superclass.constructor : null;
}
// initial
initAttrs(this, config);
}
function addAttrs(host, attrs) {
if (attrs) {
for (var attr in attrs) {
// 子类上的 ATTRS 配置优先
if (attrs.hasOwnProperty(attr)) {
// 父类后加,父类不覆盖子类的相同设置
// 属性对象会 merge a: {y:{getter:fn}}, b:{y:{value:3}}, b extends a => b {y:{value:3}}
host.addAttr(attr, attrs[attr], false);
}
}
}
}
function initAttrs(host, config) {
if (config) {
for (var attr in config) {
if (config.hasOwnProperty(attr)) {
//用户设置会调用 setter/validator 的,但不会触发属性变化事件
host.__set(attr, config[attr]);
}
}
}
}
S.augment(Base, Event.Target, Attribute);
return Base;
}, {
requires:["./attribute","event"]
});
KISSY.add("base", function(S, Base, Attribute) {
Base.Attribute = Attribute;
return Base;
}, {
requires:["base/base","base/attribute"]
});
/**
* @module cookie
* @author lifesinger@gmail.com
*/
KISSY.add('cookie/base', function(S) {
var doc = document,
MILLISECONDS_OF_DAY = 24 * 60 * 60 * 1000,
encode = encodeURIComponent,
decode = decodeURIComponent;
function isNotEmptyString(val) {
return S.isString(val) && val !== '';
}
return {
/**
* 获取 cookie 值
* @return {string} 如果 name 不存在,返回 undefined
*/
get: function(name) {
var ret, m;
if (isNotEmptyString(name)) {
if ((m = String(doc.cookie).match(
new RegExp('(?:^| )' + name + '(?:(?:=([^;]*))|;|$)')))) {
ret = m[1] ? decode(m[1]) : '';
}
}
return ret;
},
set: function(name, val, expires, domain, path, secure) {
var text = String(encode(val)), date = expires;
// 从当前时间开始,多少天后过期
if (typeof date === 'number') {
date = new Date();
date.setTime(date.getTime() + expires * MILLISECONDS_OF_DAY);
}
// expiration date
if (date instanceof Date) {
text += '; expires=' + date.toUTCString();
}
// domain
if (isNotEmptyString(domain)) {
text += '; domain=' + domain;
}
// path
if (isNotEmptyString(path)) {
text += '; path=' + path;
}
// secure
if (secure) {
text += '; secure';
}
//S.log(text);
doc.cookie = name + '=' + text;
},
remove: function(name, domain, path, secure) {
// 置空,并立刻过期
this.set(name, '', -1, domain, path, secure);
}
};
});
/**
* NOTES:
*
* 2010.04
* - get 方法要考虑 ie 下,
* 值为空的 cookie 为 'test3; test3=3; test3tt=2; test1=t1test3; test3', 没有等于号。
* 除了正则获取,还可以 split 字符串的方式来获取。
* - api 设计上,原本想借鉴 jQuery 的简明风格:S.cookie(name, ...), 但考虑到可扩展性,目前
* 独立成静态工具类的方式更优。
*/
KISSY.add("cookie", function(S,C) {
return C;
}, {
requires:["cookie/base"]
});
KISSY.add("core", function(S, UA, DOM, Event, Node, JSON, Ajax, Anim, Base, Cookie) {
var re = {
UA:UA,
DOM:DOM,
Event:Event,
EventTarget:Event.Target,
"EventObject":Event.Object,
Node:Node,
NodeList:Node,
JSON:JSON,
"Ajax":Ajax,
"IO":Ajax,
ajax:Ajax,
io:Ajax,
jsonp:Ajax.jsonp,
Anim:Anim,
Easing:Anim.Easing,
Base:Base,
"Cookie":Cookie,
one:Node.one,
all:Node.all,
get:DOM.get,
query:DOM.query
};
S.mix(S, re);
return re;
}, {
requires:[
"ua",
"dom",
"event",
"node",
"json",
"ajax",
"anim",
"base",
"cookie"
]
});
KISSY.use('core');
|
ajax/libs/quasar-framework/0.15.0-beta.12/quasar.ios.umd.js | extend1994/cdnjs | /*!
* Quasar Framework v0.15.0-beta.11
* (c) 2016-present Razvan Stoenescu
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue')) :
typeof define === 'function' && define.amd ? define(['vue'], factory) :
(global.Quasar = factory(global.Vue));
}(this, (function (Vue) { 'use strict';
Vue = Vue && Vue.hasOwnProperty('default') ? Vue['default'] : Vue;
var version = "0.15.0-beta.11";
function offset (el) {
if (el === window) {
return {top: 0, left: 0}
}
var ref = el.getBoundingClientRect();
var top = ref.top;
var left = ref.left;
return {top: top, left: left}
}
function style (el, property) {
return window.getComputedStyle(el).getPropertyValue(property)
}
function height (el) {
if (el === window) {
return viewport().height
}
return parseFloat(style(el, 'height'))
}
function width (el) {
if (el === window) {
return viewport().width
}
return parseFloat(style(el, 'width'))
}
function css (element, css) {
var style = element.style;
Object.keys(css).forEach(function (prop) {
style[prop] = css[prop];
});
}
function viewport () {
var
e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return {
width: e[a + 'Width'],
height: e[a + 'Height']
}
}
function ready (fn) {
if (typeof fn !== 'function') {
return
}
if (document.readyState === 'complete') {
return fn()
}
document.addEventListener('DOMContentLoaded', fn, false);
}
var prefix = ['-webkit-', '-moz-', '-ms-', '-o-'];
function cssTransform (val) {
var o = {transform: val};
prefix.forEach(function (p) {
o[p + 'transform'] = val;
});
return o
}
var dom = Object.freeze({
offset: offset,
style: style,
height: height,
width: width,
css: css,
viewport: viewport,
ready: ready,
cssTransform: cssTransform
});
/* eslint-disable no-useless-escape */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-mixed-operators */
var isSSR = typeof window === 'undefined';
function getUserAgent () {
return (navigator.userAgent || navigator.vendor || window.opera).toLowerCase()
}
function getMatch (userAgent, platformMatch) {
var match = /(edge)\/([\w.]+)/.exec(userAgent) ||
/(opr)[\/]([\w.]+)/.exec(userAgent) ||
/(vivaldi)[\/]([\w.]+)/.exec(userAgent) ||
/(chrome)[\/]([\w.]+)/.exec(userAgent) ||
/(iemobile)[\/]([\w.]+)/.exec(userAgent) ||
/(version)(applewebkit)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
/(webkit)[\/]([\w.]+).*(version)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
/(webkit)[\/]([\w.]+)/.exec(userAgent) ||
/(opera)(?:.*version|)[\/]([\w.]+)/.exec(userAgent) ||
/(msie) ([\w.]+)/.exec(userAgent) ||
userAgent.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(userAgent) ||
userAgent.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(userAgent) ||
[];
return {
browser: match[5] || match[3] || match[1] || '',
version: match[2] || match[4] || '0',
versionNumber: match[4] || match[2] || '0',
platform: platformMatch[0] || ''
}
}
function getPlatformMatch (userAgent) {
return /(ipad)/.exec(userAgent) ||
/(ipod)/.exec(userAgent) ||
/(windows phone)/.exec(userAgent) ||
/(iphone)/.exec(userAgent) ||
/(kindle)/.exec(userAgent) ||
/(silk)/.exec(userAgent) ||
/(android)/.exec(userAgent) ||
/(win)/.exec(userAgent) ||
/(mac)/.exec(userAgent) ||
/(linux)/.exec(userAgent) ||
/(cros)/.exec(userAgent) ||
/(playbook)/.exec(userAgent) ||
/(bb)/.exec(userAgent) ||
/(blackberry)/.exec(userAgent) ||
[]
}
function getPlatform () {
var
userAgent = getUserAgent(),
platformMatch = getPlatformMatch(userAgent),
matched = getMatch(userAgent, platformMatch),
browser = {};
if (matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.versionNumber, 10);
}
if (matched.platform) {
browser[matched.platform] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if (browser.android || browser.bb || browser.blackberry || browser.ipad || browser.iphone ||
browser.ipod || browser.kindle || browser.playbook || browser.silk || browser['windows phone']) {
browser.mobile = true;
}
// Set iOS if on iPod, iPad or iPhone
if (browser.ipod || browser.ipad || browser.iphone) {
browser.ios = true;
}
if (browser['windows phone']) {
browser.winphone = true;
delete browser['windows phone'];
}
// These are all considered desktop platforms, meaning they run a desktop browser
if (browser.cros || browser.mac || browser.linux || browser.win) {
browser.desktop = true;
}
// Chrome, Opera 15+, Vivaldi and Safari are webkit based browsers
if (browser.chrome || browser.opr || browser.safari || browser.vivaldi) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
if (browser.rv || browser.iemobile) {
matched.browser = 'ie';
browser.ie = true;
}
// Edge is officially known as Microsoft Edge, so rewrite the key to match
if (browser.edge) {
matched.browser = 'edge';
browser.edge = true;
}
// Blackberry browsers are marked as Safari on BlackBerry
if (browser.safari && browser.blackberry || browser.bb) {
matched.browser = 'blackberry';
browser.blackberry = true;
}
// Playbook browsers are marked as Safari on Playbook
if (browser.safari && browser.playbook) {
matched.browser = 'playbook';
browser.playbook = true;
}
// Opera 15+ are identified as opr
if (browser.opr) {
matched.browser = 'opera';
browser.opera = true;
}
// Stock Android browsers are marked as Safari on Android.
if (browser.safari && browser.android) {
matched.browser = 'android';
browser.android = true;
}
// Kindle browsers are marked as Safari on Kindle
if (browser.safari && browser.kindle) {
matched.browser = 'kindle';
browser.kindle = true;
}
// Kindle Silk browsers are marked as Safari on Kindle
if (browser.safari && browser.silk) {
matched.browser = 'silk';
browser.silk = true;
}
if (browser.vivaldi) {
matched.browser = 'vivaldi';
browser.vivaldi = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
if (window && window.process && window.process.versions && window.process.versions.electron) {
browser.electron = true;
}
else if (document.location.href.indexOf('chrome-extension://') === 0) {
browser.chromeExt = true;
}
else if (
window._cordovaNative ||
window.cordova ||
document.location.href.indexOf('http://') === -1
) {
browser.cordova = true;
}
return browser
}
var Platform = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
Platform.is = { ssr: true };
Platform.has = {
touch: false,
webStorage: false
};
Platform.within = { iframe: false };
}
else {
var webStorage;
try {
if (window.localStorage) {
webStorage = true;
}
}
catch (e) {
webStorage = false;
}
Platform.is = getPlatform();
Platform.has = {
touch: (function () { return !!('ontouchstart' in document.documentElement) || window.navigator.msMaxTouchPoints > 0; })(),
webStorage: webStorage
};
Platform.within = {
iframe: window.self !== window.top
};
}
$q.platform = Platform;
}
};
var History = {
__history: [],
add: function () {},
remove: function () {},
__installed: false,
install: function install () {
var this$1 = this;
if (this.__installed || !Platform.is.cordova || isSSR) {
return
}
this.__installed = true;
this.add = function (definition) {
this$1.__history.push(definition);
};
this.remove = function (definition) {
var index = this$1.__history.indexOf(definition);
if (index >= 0) {
this$1.__history.splice(index, 1);
}
};
document.addEventListener('deviceready', function () {
document.addEventListener('backbutton', function () {
if (this$1.__history.length) {
this$1.__history.pop().handler();
}
else {
window.history.back();
}
}, false);
});
}
}
/* eslint-disable no-extend-native, one-var, no-self-compare */
if (!Array.prototype.includes) {
Array.prototype.includes = function (searchEl, startFrom) {
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false
}
var n = parseInt(startFrom, 10) || 0;
var k;
if (n >= 0) {
k = n;
}
else {
k = len + n;
if (k < 0) { k = 0; }
}
var curEl;
while (k < len) {
curEl = O[k];
if (searchEl === curEl ||
(searchEl !== searchEl && curEl !== curEl)) { // NaN !== NaN
return true
}
k++;
}
return false
};
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (str, position) {
position = position || 0;
return this.substr(position, str.length) === str
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (str, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= str.length;
var lastIndex = subjectString.indexOf(str, position);
return lastIndex !== -1 && lastIndex === position
};
}
if (!isSSR && typeof Element.prototype.matches !== 'function') {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.webkitMatchesSelector || function matches (selector) {
var
element = this,
elements = (element.document || element.ownerDocument).querySelectorAll(selector),
index = 0;
while (elements[index] && elements[index] !== element) {
++index;
}
return Boolean(elements[index])
};
}
if (!isSSR && typeof Element.prototype.closest !== 'function') {
Element.prototype.closest = function closest (selector) {
var el = this;
while (el && el.nodeType === 1) {
if (el.matches(selector)) {
return el
}
el = el.parentNode;
}
return null
};
}
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function value (predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined')
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function')
}
var value;
var
list = Object(this),
length = list.length >>> 0,
thisArg = arguments[1];
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value
}
}
return undefined
}
});
}
var langEn = {
lang: 'en-us',
label: {
clear: 'Clear',
ok: 'OK',
cancel: 'Cancel',
close: 'Close',
set: 'Set',
select: 'Select',
reset: 'Reset',
remove: 'Remove',
update: 'Update',
create: 'Create',
search: 'Search',
filter: 'Filter',
refresh: 'Refresh'
},
date: {
days: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
daysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
firstDayOfWeek: 0, // 0-6, 0 - Sunday, 1 Monday, ...
format24h: false
},
pullToRefresh: {
pull: 'Pull down to refresh',
release: 'Release to refresh',
refresh: 'Refreshing...'
},
table: {
noData: 'No data available',
noResults: 'No matching records found',
loader: 'Loading...',
selectedRows: function (rows) { return rows > 0 ? (rows + " row" + (rows === 1 ? '' : 's') + " selected.") : 'No selected rows.'; },
rowsPerPage: 'Rows per page:',
allRows: 'All',
pagination: function (start, end, total) { return (start + "-" + end + " of " + total); },
columns: 'Columns'
},
editor: {
url: 'URL',
bold: 'Bold',
italic: 'Italic',
strikethrough: 'Strikethrough',
underline: 'Underline',
unorderedList: 'Unordered List',
orderedList: 'Ordered List',
subscript: 'Subscript',
superscript: 'Superscript',
hyperlink: 'Hyperlink',
toggleFullscreen: 'Toggle Fullscreen',
quote: 'Quote',
left: 'Left align',
center: 'Center align',
right: 'Right align',
justify: 'Justify align',
print: 'Print',
outdent: 'Decrease indentation',
indent: 'Increase indentation',
removeFormat: 'Remove formatting',
formatting: 'Formatting',
fontSize: 'Font Size',
align: 'Align',
hr: 'Insert Horizontal Rule',
undo: 'Undo',
redo: 'Redo',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
header5: 'Header 5',
header6: 'Header 6',
paragraph: 'Paragraph',
code: 'Code',
size1: 'Very small',
size2: 'A bit small',
size3: 'Normal',
size4: 'Medium-large',
size5: 'Big',
size6: 'Very big',
size7: 'Maximum',
defaultFont: 'Default Font'
},
tree: {
noNodes: 'No nodes available',
noResults: 'No matching nodes found'
}
}
var i18n = {
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
var lang = ref.lang;
if (this.__installed) { return }
this.__installed = true;
this.set = function (lang) {
if ( lang === void 0 ) lang = langEn;
lang.set = this$1.set;
Vue$$1.set($q, 'i18n', lang);
this$1.name = lang.lang;
this$1.lang = lang;
};
this.set(lang);
}
}
var iconMaterial = {
name: 'material',
type: {
positive: 'check_circle',
negative: 'warning',
info: 'info',
warning: 'priority_high'
},
arrow: {
up: 'arrow_upward',
right: 'arrow_forward',
down: 'arrow_downward',
left: 'arrow_back'
},
chevron: {
left: 'chevron_left',
right: 'chevron_right'
},
pullToRefresh: {
arrow: 'arrow_downward',
refresh: 'refresh'
},
search: {
icon: 'search',
clear: 'cancel',
clearInverted: 'clear'
},
carousel: {
left: 'chevron_left',
right: 'chevron_right',
quickNav: 'lens'
},
checkbox: {
checked: {
ios: 'check_circle',
mat: 'check_box'
},
unchecked: {
ios: 'radio_button_unchecked',
mat: 'check_box_outline_blank'
},
indeterminate: {
ios: 'remove_circle_outline',
mat: 'indeterminate_check_box'
}
},
chip: {
close: 'cancel'
},
chipsInput: {
add: 'send'
},
collapsible: {
icon: 'keyboard_arrow_down'
},
datetime: {
arrowLeft: 'chevron_left',
arrowRight: 'chevron_right'
},
editor: {
bold: 'format_bold',
italic: 'format_italic',
strikethrough: 'strikethrough_s',
underline: 'format_underlined',
unorderedList: 'format_list_bulleted',
orderedList: 'format_list_numbered',
subscript: 'vertical_align_bottom',
superscript: 'vertical_align_top',
hyperlink: 'link',
toggleFullscreen: 'fullscreen',
quote: 'format_quote',
left: 'format_align_left',
center: 'format_align_center',
right: 'format_align_right',
justify: 'format_align_justify',
print: 'print',
outdent: 'format_indent_decrease',
indent: 'format_indent_increase',
removeFormat: 'format_clear',
formatting: 'text_format',
fontSize: 'format_size',
align: 'format_align_left',
hr: 'remove',
undo: 'undo',
redo: 'redo',
header: 'format_size',
code: 'code',
size: 'format_size',
font: 'font_download'
},
fab: {
icon: 'add',
activeIcon: 'close'
},
input: {
showPass: 'visibility',
hidePass: 'visibility_off',
showNumber: 'keyboard',
hideNumber: 'keyboard_hide',
clear: 'cancel',
clearInverted: 'clear',
dropdown: 'arrow_drop_down'
},
pagination: {
first: 'first_page',
prev: 'keyboard_arrow_left',
next: 'keyboard_arrow_right',
last: 'last_page'
},
radio: {
checked: {
ios: 'check',
mat: 'radio_button_checked'
},
unchecked: {
ios: '',
mat: 'radio_button_unchecked'
}
},
rating: {
icon: 'grade'
},
stepper: {
done: 'check',
active: 'edit',
error: 'warning'
},
tabs: {
left: 'chevron_left',
right: 'chevron_right'
},
table: {
arrowUp: 'arrow_upward',
warning: 'warning',
prevPage: 'chevron_left',
nextPage: 'chevron_right'
},
tree: {
icon: 'play_arrow'
},
uploader: {
done: 'done',
clear: 'cancel',
clearInverted: 'clear',
add: 'add',
upload: 'cloud_upload',
expand: 'keyboard_arrow_down',
file: 'insert_drive_file'
}
}
var icons = {
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
var iconSet = ref.iconSet;
if (this.__installed) { return }
this.__installed = true;
this.set = function (iconDef) {
if ( iconDef === void 0 ) iconDef = iconMaterial;
iconDef.set = this$1.set;
Vue$$1.set($q, 'icon', iconDef);
this$1.name = iconDef.name;
this$1.def = iconDef;
};
// TODO default ???
this.set(iconSet);
}
}
function addBodyClasses () {
var cls = [
"ios",
Platform.is.desktop ? 'desktop' : 'mobile',
Platform.has.touch ? 'touch' : 'no-touch',
("platform-" + (Platform.is.ios ? 'ios' : 'mat'))
];
Platform.within.iframe && cls.push('within-iframe');
Platform.is.cordova && cls.push('cordova');
Platform.is.electron && cls.push('electron');
document.body.classList.add.apply(document.body.classList, cls);
}
function install (_Vue, opts) {
if ( opts === void 0 ) opts = {};
if (this.__installed) {
return
}
this.__installed = true;
var $q = {
version: version,
theme: "ios"
};
// required plugins
Platform.install({ $q: $q });
History.install();
i18n.install({ $q: $q, Vue: _Vue, lang: opts.i18n });
icons.install({ $q: $q, Vue: _Vue, iconSet: opts.iconSet });
if (!isSSR) {
// inject body classes
ready(addBodyClasses);
}
if (opts.directives) {
Object.keys(opts.directives).forEach(function (key) {
var d = opts.directives[key];
if (d.name !== undefined && !d.name.startsWith('q-')) {
_Vue.directive(d.name, d);
}
});
}
if (opts.components) {
Object.keys(opts.components).forEach(function (key) {
var c = opts.components[key];
if (c.name !== undefined && c.name.startsWith('q-')) {
_Vue.component(c.name, c);
}
});
}
if (opts.plugins) {
Object.keys(opts.plugins).forEach(function (key) {
var p = opts.plugins[key];
if (typeof p.install === 'function') {
p.install({ $q: $q, Vue: _Vue });
}
});
}
_Vue.prototype.$q = $q;
}
var handlers = [];
var EscapeKey = {
__installed: false,
__install: function __install () {
this.__installed = true;
window.addEventListener('keyup', function (evt) {
if (handlers.length === 0) {
return
}
if (evt.which === 27 || evt.keyCode === 27) {
handlers[handlers.length - 1]();
}
});
},
register: function register (handler) {
if (Platform.is.desktop) {
if (!this.__installed) {
this.__install();
}
handlers.push(handler);
}
},
pop: function pop () {
if (Platform.is.desktop) {
handlers.pop();
}
}
}
var toString = Object.prototype.toString;
var hasOwn = Object.prototype.hasOwnProperty;
var class2type = {};
'Boolean Number String Function Array Date RegExp Object'.split(' ').forEach(function (name) {
class2type['[object ' + name + ']'] = name.toLowerCase();
});
function type (obj) {
return obj === null ? String(obj) : class2type[toString.call(obj)] || 'object'
}
function isPlainObject (obj) {
if (!obj || type(obj) !== 'object') {
return false
}
if (obj.constructor &&
!hasOwn.call(obj, 'constructor') &&
!hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) {
return false
}
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key)
}
function extend () {
var arguments$1 = arguments;
var
options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
i = 2;
}
if (Object(target) !== target && type(target) !== 'function') {
target = {};
}
if (length === i) {
target = this;
i--;
}
for (; i < length; i++) {
if ((options = arguments$1[i]) !== null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue
}
if (deep && copy && (isPlainObject(copy) || (copyIsArray = type(copy) === 'array'))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && type(src) === 'array' ? src : [];
}
else {
clone = src && isPlainObject(src) ? src : {};
}
target[name] = extend(deep, clone, copy);
}
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target
}
/* eslint prefer-promise-reject-errors: 0 */
var ModelToggleMixin = {
props: {
value: Boolean
},
data: function data () {
return {
showing: false
}
},
watch: {
value: function value (val) {
var this$1 = this;
if (this.disable && val) {
this.$emit('input', false);
return
}
this.$nextTick(function () {
if (this$1.value !== this$1.showing) {
this$1[val ? 'show' : 'hide']();
}
});
}
},
methods: {
toggle: function toggle (evt) {
return this[this.showing ? 'hide' : 'show'](evt)
},
show: function show (evt) {
var this$1 = this;
if (this.disable || this.showing) {
return this.showPromise || Promise.resolve(evt)
}
if (this.hidePromise) {
this.hidePromiseReject();
}
this.showing = true;
if (this.value === false) {
this.$emit('input', true);
}
if (this.$options.modelToggle === void 0 || this.$options.modelToggle.history) {
this.__historyEntry = {
handler: this.hide
};
History.add(this.__historyEntry);
}
if (!this.__show) {
this.$emit('show');
return Promise.resolve(evt)
}
this.showPromise = new Promise(function (resolve, reject) {
this$1.showPromiseResolve = function () {
this$1.showPromise = null;
this$1.$emit('show');
resolve(evt);
};
this$1.showPromiseReject = function () {
this$1.showPromise = null;
reject(null); // eslint prefer-promise-reject-errors: 0
};
});
this.__show(evt);
return this.showPromise || Promise.resolve(evt)
},
hide: function hide (evt) {
var this$1 = this;
if (this.disable || !this.showing) {
return this.hidePromise || Promise.resolve(evt)
}
if (this.showPromise) {
this.showPromiseReject();
}
this.showing = false;
if (this.value === true) {
this.$emit('input', false);
}
if (this.__historyEntry) {
History.remove(this.__historyEntry);
this.__historyEntry = null;
}
if (!this.__hide) {
this.$emit('hide');
return Promise.resolve()
}
this.hidePromise = new Promise(function (resolve, reject) {
this$1.hidePromiseResolve = function () {
this$1.hidePromise = null;
this$1.$emit('hide');
resolve();
};
this$1.hidePromiseReject = function () {
this$1.hidePromise = null;
reject(null);
};
});
this.__hide(evt);
return this.hidePromise || Promise.resolve(evt)
}
},
beforeDestroy: function beforeDestroy () {
if (this.showing) {
this.showPromise && this.showPromiseReject();
this.hidePromise && this.hidePromiseReject();
this.$emit('input', false);
this.__hide && this.__hide();
}
}
}
var positions = {
top: 'items-start justify-center with-backdrop',
bottom: 'items-end justify-center with-backdrop',
right: 'items-center justify-end with-backdrop',
left: 'items-center justify-start with-backdrop'
};
var positionCSS = {
maxHeight: '80vh',
height: 'auto',
boxShadow: 'none'
};
function additionalCSS (position) {
var css = {};
if (['left', 'right'].includes(position)) {
css.maxWidth = '90vw';
}
{
if (['left', 'top'].includes(position)) {
css.borderTopLeftRadius = 0;
}
if (['right', 'top'].includes(position)) {
css.borderTopRightRadius = 0;
}
if (['left', 'bottom'].includes(position)) {
css.borderBottomLeftRadius = 0;
}
if (['right', 'bottom'].includes(position)) {
css.borderBottomRightRadius = 0;
}
}
return css
}
var openedModalNumber = 0;
var QModal = {
name: 'q-modal',
mixins: [ModelToggleMixin],
provide: function provide () {
return {
__qmodal: true
}
},
props: {
position: {
type: String,
default: '',
validator: function validator (val) {
return val === '' || ['top', 'bottom', 'left', 'right'].includes(val)
}
},
transition: String,
enterClass: String,
leaveClass: String,
positionClasses: {
type: String,
default: 'flex-center'
},
contentClasses: [Object, Array, String],
contentCss: [Object, Array, String],
noBackdropDismiss: {
type: Boolean,
default: false
},
noEscDismiss: {
type: Boolean,
default: false
},
noRouteDismiss: Boolean,
minimized: Boolean,
maximized: Boolean
},
watch: {
$route: function $route () {
if (!this.noRouteDismiss) {
this.hide();
}
}
},
computed: {
modalClasses: function modalClasses () {
var cls = this.position
? positions[this.position]
: this.positionClasses;
if (this.maximized) {
return ['maximized', cls]
}
else if (this.minimized) {
return ['minimized', cls]
}
return cls
},
transitionProps: function transitionProps () {
if (this.position) {
return { name: ("q-modal-" + (this.position)) }
}
if (this.enterClass === void 0 && this.leaveClass === void 0) {
return { name: this.transition || 'q-modal' }
}
return {
enterActiveClass: this.enterClass,
leaveActiveClass: this.leaveClass
}
},
modalCss: function modalCss () {
if (this.position) {
var css = Array.isArray(this.contentCss)
? this.contentCss
: [this.contentCss];
css.unshift(extend(
{},
positionCSS,
additionalCSS(this.position)
));
return css
}
return this.contentCss
}
},
methods: {
__dismiss: function __dismiss () {
var this$1 = this;
if (this.noBackdropDismiss) {
return
}
this.hide().then(function () {
this$1.$emit('dismiss');
});
},
__show: function __show () {
var this$1 = this;
var body = document.body;
body.appendChild(this.$el);
body.classList.add('with-modal');
EscapeKey.register(function () {
if (!this$1.noEscDismiss) {
this$1.hide().then(function () {
this$1.$emit('escape-key');
});
}
});
openedModalNumber++;
var content = this.$refs.content;
content.scrollTop = 0
;['modal-scroll', 'layout-view'].forEach(function (c) {
[].slice.call(content.getElementsByClassName(c)).forEach(function (el) {
el.scrollTop = 0;
});
});
},
__hide: function __hide () {
EscapeKey.pop();
openedModalNumber--;
if (openedModalNumber === 0) {
var body = document.body;
body.classList.remove('with-modal');
}
}
},
mounted: function mounted () {
if (this.value) {
this.show();
}
},
beforeDestroy: function beforeDestroy () {
if (this.$el.parentNode) {
this.$el.parentNode.removeChild(this.$el);
}
},
render: function render (h) {
var this$1 = this;
return h('transition', {
props: this.transitionProps,
on: {
afterEnter: function () {
this$1.showPromise && this$1.showPromiseResolve();
},
enterCancelled: function () {
this$1.showPromise && this$1.showPromiseReject();
},
afterLeave: function () {
this$1.hidePromise && this$1.hidePromiseResolve();
},
leaveCancelled: function () {
this$1.hidePromise && this$1.hidePromiseReject();
}
}
}, [
h('div', {
staticClass: 'modal fullscreen row',
'class': this.modalClasses,
on: {
click: this.__dismiss
},
directives: [{
name: 'show',
value: this.showing
}]
}, [
h('div', {
ref: 'content',
staticClass: 'modal-content scroll',
style: this.modalCss,
'class': this.contentClasses,
on: {
click: function click (e) {
e.stopPropagation();
},
touchstart: function touchstart (e) {
e.stopPropagation();
}
}
}, [ this.$slots.default ])
])
])
}
}
var QModalLayout = {
name: 'q-modal-layout',
inject: {
__qmodal: {
default: function default$1 () {
console.error('QModalLayout needs to be child of QModal');
}
}
},
props: {
headerStyle: [String, Object, Array],
headerClass: [String, Object, Array],
contentStyle: [String, Object, Array],
contentClass: [String, Object, Array],
footerStyle: [String, Object, Array],
footerClass: [String, Object, Array]
},
render: function render (h) {
var child = [];
if (this.$slots.header || ("ios" !== 'ios' && this.$slots.navigation)) {
child.push(h('div', {
staticClass: 'q-layout-header',
style: this.headerStyle,
'class': this.headerClass
}, [
this.$slots.header,
null
]));
}
child.push(h('div', {
staticClass: 'q-modal-layout-content col scroll',
style: this.contentStyle,
'class': this.contentClass
}, [
this.$slots.default
]));
if (this.$slots.footer || ("ios" === 'ios' && this.$slots.navigation)) {
child.push(h('div', {
staticClass: 'q-layout-footer',
style: this.footerStyle,
'class': this.footerClass
}, [
this.$slots.footer,
this.$slots.navigation
]));
}
return h('div', {
staticClass: 'q-modal-layout column absolute-full'
}, child)
}
}
var QIcon = {
name: 'q-icon',
props: {
name: String,
mat: String,
ios: String,
color: String,
size: String
},
computed: {
icon: function icon () {
return this.mat && "ios" === 'mat'
? this.mat
: (this.ios && "ios" === 'ios' ? this.ios : this.name)
},
classes: function classes () {
var cls;
var icon = this.icon;
if (!icon) {
cls = '';
}
else if (icon.startsWith('fa-')) {
// Fontawesome 4
cls = "fa " + icon;
}
else if (/^fa[s|r|l|b]{0,1} /.test(icon)) {
// Fontawesome 5
cls = icon;
}
else if (icon.startsWith('bt-')) {
cls = "bt " + icon;
}
else if (icon.startsWith('ion-') || icon.startsWith('icon-')) {
cls = "" + icon;
}
else if (icon.startsWith('mdi-')) {
cls = "mdi " + icon;
}
else {
cls = 'material-icons';
}
return this.color
? (cls + " text-" + (this.color))
: cls
},
content: function content () {
return this.classes.startsWith('material-icons')
? this.icon.replace(/ /g, '_')
: ' '
},
style: function style () {
if (this.size) {
return { fontSize: this.size }
}
}
},
render: function render (h) {
return h('i', {
staticClass: 'q-icon',
'class': this.classes,
style: this.style,
attrs: { 'aria-hidden': true }
}, [
this.content,
this.$slots.default
])
}
}
function textStyle (n) {
return n === void 0 || n < 2
? {}
: {overflow: 'hidden', display: '-webkit-box', '-webkit-box-orient': 'vertical', '-webkit-line-clamp': n}
}
function itemClasses (prop) {
return {
'q-item': true,
'q-item-division': true,
'relative-position': true,
'q-item-dark': prop.dark,
'q-item-dense': prop.dense,
'q-item-sparse': prop.sparse,
'q-item-separator': prop.separator,
'q-item-inset-separator': prop.insetSeparator,
'q-item-multiline': prop.multiline,
'q-item-highlight': prop.highlight,
'q-item-link': prop.to || prop.link
}
}
var ItemMixin = {
props: {
dark: Boolean,
dense: Boolean,
sparse: Boolean,
separator: Boolean,
insetSeparator: Boolean,
multiline: Boolean,
highlight: Boolean,
tag: {
type: String,
default: 'div'
}
}
};
var routerLinkEventName = 'qrouterlinkclick';
var evt = null;
if (!isSSR) {
try {
evt = new Event(routerLinkEventName);
}
catch (e) {
// IE doesn't support `new Event()`, so...`
evt = document.createEvent('Event');
evt.initEvent(routerLinkEventName, true, false);
}
}
var RouterLinkMixin = {
props: {
to: [String, Object],
exact: Boolean,
append: Boolean,
replace: Boolean
},
data: function data () {
return {
routerLinkEventName: routerLinkEventName
}
}
};
var QItem = {
name: 'q-item',
mixins: [
ItemMixin,
{ props: RouterLinkMixin.props }
],
props: {
active: Boolean,
link: Boolean
},
computed: {
classes: function classes () {
var cls = itemClasses(this.$props);
return this.to !== void 0
? cls
: [{active: this.active}, cls]
}
},
render: function render (h) {
return this.to !== void 0
? h('router-link', { props: this.$props, 'class': this.classes }, [ this.$slots.default ])
: h(this.tag, { 'class': this.classes }, [ this.$slots.default ])
}
}
var QItemSeparator = {
name: 'q-item-separator',
props: {
inset: Boolean
},
render: function render (h) {
return h('div', {
staticClass: 'q-item-separator-component',
'class': {
'q-item-separator-inset-component': this.inset
}
}, [
this.$slots.default
])
}
}
function text (h, name, val, n) {
n = parseInt(n, 10);
return h('div', {
staticClass: ("q-item-" + name + (n === 1 ? ' ellipsis' : '')),
style: textStyle(n)
}, [ val ])
}
var QItemMain = {
name: 'q-item-main',
props: {
label: String,
labelLines: [String, Number],
sublabel: String,
sublabelLines: [String, Number],
inset: Boolean,
tag: {
type: String,
default: 'div'
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-item-main q-item-section',
'class': {
'q-item-main-inset': this.inset
}
}, [
this.label ? text(h, 'label', this.label, this.labelLines) : null,
this.sublabel ? text(h, 'sublabel', this.sublabel, this.sublabelLines) : null,
this.$slots.default
])
}
}
var QItemSide = {
name: 'q-item-side',
props: {
right: Boolean,
icon: String,
letter: {
type: String,
validator: function (v) { return v.length === 1; }
},
inverted: Boolean, // for icon and letter only
avatar: String,
image: String,
stamp: String,
color: String,
textColor: String // only for inverted icon/letter
},
computed: {
type: function type () {
var this$1 = this;
return ['icon', 'image', 'avatar', 'letter', 'stamp'].find(function (type) { return this$1[type]; })
},
classes: function classes () {
var cls = [ ("q-item-side-" + (this.right ? 'right' : 'left')) ];
if (this.color && (!this.icon && !this.letter)) {
cls.push(("text-" + (this.color)));
}
return cls
},
typeClasses: function typeClasses () {
var cls = [ ("q-item-" + (this.type)) ];
if (this.color) {
if (this.inverted && (this.icon || this.letter)) {
cls.push(("bg-" + (this.color)));
}
else if (!this.textColor) {
cls.push(("text-" + (this.color)));
}
}
this.textColor && cls.push(("text-" + (this.textColor)));
if (this.inverted) {
this.icon && cls.push('q-item-icon-inverted');
this.letter && cls.push('q-item-letter-inverted');
}
return cls
},
imagePath: function imagePath () {
return this.image || this.avatar
}
},
render: function render (h) {
var child;
if (this.type) {
if (this.icon) {
child = h(QIcon, {
'class': this.typeClasses,
props: { name: this.icon }
}, [ this.$slots.default ]);
}
else if (this.imagePath) {
child = h('img', {
'class': this.typeClasses,
attrs: { src: this.imagePath }
});
}
else {
child = h('div', { 'class': this.typeClasses }, [ this.stamp || this.letter ]);
}
}
return h('div', {
staticClass: 'q-item-side q-item-section',
'class': this.classes
}, [
child,
this.$slots.default
])
}
}
var QItemTile = {
name: 'q-item-tile',
props: {
icon: String,
letter: Boolean,
inverted: Boolean, // for icon and letter only
image: Boolean,
avatar: Boolean,
stamp: Boolean,
label: Boolean,
sublabel: Boolean,
lines: [Number, String],
color: String,
textColor: String // only for inverted icon/letter
},
computed: {
hasLines: function hasLines () {
return (this.label || this.sublabel) && this.lines
},
type: function type () {
var this$1 = this;
return ['icon', 'label', 'sublabel', 'image', 'avatar', 'letter', 'stamp'].find(function (type) { return this$1[type]; })
},
classes: function classes () {
var cls = [];
if (this.color) {
if (this.inverted) {
cls.push(("bg-" + (this.color)));
}
else if (!this.textColor) {
cls.push(("text-" + (this.color)));
}
}
this.textColor && cls.push(("text-" + (this.textColor)));
this.type && cls.push(("q-item-" + (this.type)));
if (this.inverted) {
this.icon && cls.push('q-item-icon-inverted');
this.letter && cls.push('q-item-letter-inverted');
}
if (this.hasLines && (this.lines === '1' || this.lines === 1)) {
cls.push('ellipsis');
}
return cls
},
style: function style () {
if (this.hasLines) {
return textStyle(this.lines)
}
}
},
render: function render (h) {
var data = {
'class': this.classes,
style: this.style
};
if (this.icon) {
data.props = { name: this.icon };
}
return h(this.icon ? QIcon : 'div', data, [ this.$slots.default ])
}
}
function push (child, h, name, slot, replace, conf) {
var defaultProps = { props: { right: conf.right } };
if (slot && replace) {
child.push(h(name, defaultProps, slot));
return
}
var v = false;
for (var p in conf) {
if (conf.hasOwnProperty(p)) {
v = conf[p];
if (v !== void 0 && v !== true) {
child.push(h(name, { props: conf }));
break
}
}
}
slot && child.push(h(name, defaultProps, slot));
}
var QItemWrapper = {
name: 'q-item-wrapper',
props: {
cfg: {
type: Object,
default: function () { return ({}); }
},
slotReplace: Boolean
},
render: function render (h) {
var
cfg = this.cfg,
replace = this.slotReplace,
child = [];
push(child, h, QItemSide, this.$slots.left, replace, {
icon: cfg.icon,
color: cfg.leftColor,
avatar: cfg.avatar,
letter: cfg.letter,
image: cfg.image
});
push(child, h, QItemMain, this.$slots.main, replace, {
label: cfg.label,
sublabel: cfg.sublabel,
labelLines: cfg.labelLines,
sublabelLines: cfg.sublabelLines,
inset: cfg.inset
});
push(child, h, QItemSide, this.$slots.right, replace, {
right: true,
icon: cfg.rightIcon,
color: cfg.rightColor,
avatar: cfg.rightAvatar,
letter: cfg.rightLetter,
image: cfg.rightImage,
stamp: cfg.stamp
});
child.push(this.$slots.default);
return h(QItem, {
attrs: this.$attrs,
on: this.$listeners,
props: cfg
}, child)
}
}
var QList = {
name: 'q-list',
props: {
noBorder: Boolean,
dark: Boolean,
dense: Boolean,
sparse: Boolean,
striped: Boolean,
stripedOdd: Boolean,
separator: Boolean,
insetSeparator: Boolean,
multiline: Boolean,
highlight: Boolean,
link: Boolean
},
computed: {
classes: function classes () {
return {
'no-border': this.noBorder,
'q-list-dark': this.dark,
'q-list-dense': this.dense,
'q-list-sparse': this.sparse,
'q-list-striped': this.striped,
'q-list-striped-odd': this.stripedOdd,
'q-list-separator': this.separator,
'q-list-inset-separator': this.insetSeparator,
'q-list-multiline': this.multiline,
'q-list-highlight': this.highlight,
'q-list-link': this.link
}
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-list',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QListHeader = {
name: 'q-list-header',
props: {
inset: Boolean
},
render: function render (h) {
return h('div', {
staticClass: 'q-list-header',
'class': {
'q-list-header-inset': this.inset
}
}, [
this.$slots.default
])
}
}
var QActionSheet = {
name: 'q-action-sheet',
props: {
value: Boolean,
title: String,
grid: Boolean,
actions: Array,
dismissLabel: String
},
computed: {
contentCss: function contentCss () {
{
return {backgroundColor: 'transparent'}
}
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
title = this.$slots.title || this.title;
if (title) {
child.push(
h('div', {
staticClass: 'q-actionsheet-title column justify-center'
}, [ title ])
);
}
child.push(
h(
'div',
{ staticClass: 'q-actionsheet-body scroll' },
this.actions
? [
this.grid
? h('div', { staticClass: 'q-actionsheet-grid row wrap items-center justify-between' }, this.__getActions(h))
: h(QList, { staticClass: 'no-border', props: { link: true } }, this.__getActions(h))
]
: [ this.$slots.default ]
)
);
{
child = [
h('div', { staticClass: 'q-actionsheet' }, child),
h('div', { staticClass: 'q-actionsheet' }, [
h(QItem, {
props: {
link: true
},
attrs: {
tabindex: 0
},
nativeOn: {
click: this.__onCancel,
keydown: this.__onCancel
}
}, [
h(QItemMain, { staticClass: 'text-center text-primary' }, [
this.dismissLabel || this.$q.i18n.label.cancel
])
])
])
];
}
return h(QModal, {
ref: 'modal',
props: {
value: this.value,
position: 'bottom',
contentCss: this.contentCss
},
on: {
input: function (val) {
this$1.$emit('input', val);
},
show: function () {
this$1.$emit('show');
},
hide: function () {
this$1.$emit('hide');
},
dismiss: function () {
this$1.__onCancel();
},
'escape-key': function () {
this$1.hide().then(function () {
this$1.$emit('escape-key');
this$1.__onCancel();
});
}
}
}, child)
},
methods: {
show: function show () {
return this.$refs.modal.show()
},
hide: function hide () {
return this.$refs.modal.hide()
},
__getActions: function __getActions (h) {
var this$1 = this;
var obj;
return this.actions.map(function (action) { return action.label
? h(this$1.grid ? 'div' : QItem, ( obj = {
staticClass: this$1.grid
? 'q-actionsheet-grid-item cursor-pointer relative-position column inline flex-center'
: null,
'class': action.classes,
attrs: {
tabindex: 0
}
}, obj[this$1.grid ? 'on' : 'nativeOn'] = {
click: function () { return this$1.__onOk(action); },
keydown: function () { return this$1.__onOk(action); }
}, obj), this$1.grid
? [
action.icon ? h(QIcon, { props: { name: action.icon, color: action.color } }) : null,
action.avatar ? h('img', { domProps: { src: action.avatar }, staticClass: 'avatar' }) : null,
h('span', [ action.label ])
]
: [
h(QItemSide, { props: { icon: action.icon, color: action.color, avatar: action.avatar } }),
h(QItemMain, { props: { inset: true, label: action.label } })
]
)
: h(QItemSeparator, { staticClass: 'col-12' }); }
)
},
__onOk: function __onOk (action) {
var this$1 = this;
this.hide().then(function () {
if (typeof action.handler === 'function') {
action.handler();
}
this$1.$emit('ok', action);
});
},
__onCancel: function __onCancel () {
var this$1 = this;
this.hide().then(function () {
this$1.$emit('cancel');
});
}
}
}
var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
function humanStorageSize (bytes) {
var u = 0;
while (Math.abs(bytes) >= 1024 && u < units.length - 1) {
bytes /= 1024;
++u;
}
return ((bytes.toFixed(1)) + " " + (units[u]))
}
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function between (v, min, max) {
if (max <= min) {
return min
}
return Math.min(max, Math.max(min, v))
}
function normalizeToInterval (v, min, max) {
if (max <= min) {
return min
}
var size = (max - min + 1);
var index = v % size;
if (index < min) {
index = size + index;
}
return index
}
function pad (v, length, char) {
if ( length === void 0 ) length = 2;
if ( char === void 0 ) char = '0';
var val = '' + v;
return val.length >= length
? val
: new Array(length - val.length + 1).join(char) + val
}
var format = Object.freeze({
humanStorageSize: humanStorageSize,
capitalize: capitalize,
between: between,
normalizeToInterval: normalizeToInterval,
pad: pad
});
var xhr = isSSR ? null : XMLHttpRequest;
var send = isSSR ? null : xhr.prototype.send;
function translate (ref) {
var p = ref.p;
var pos = ref.pos;
var active = ref.active;
var horiz = ref.horiz;
var reverse = ref.reverse;
var x = 1, y = 1;
if (horiz) {
if (reverse) { x = -1; }
if (pos === 'bottom') { y = -1; }
return cssTransform(("translate3d(" + (x * (p - 100)) + "%, " + (active ? 0 : y * -200) + "%, 0)"))
}
if (reverse) { y = -1; }
if (pos === 'right') { x = -1; }
return cssTransform(("translate3d(" + (active ? 0 : x * -200) + "%, " + (y * (p - 100)) + "%, 0)"))
}
function inc (p, amount) {
if (typeof amount !== 'number') {
if (p < 25) {
amount = Math.random() * (5 - 3 + 1) + 3;
}
else if (p < 65) {
amount = Math.random() * 3;
}
else if (p < 85) {
amount = Math.random() * 2;
}
else if (p < 99) {
amount = 0.5;
}
else {
amount = 0;
}
}
return between(p + amount, 0, 100)
}
function highjackAjax (startHandler, endHandler) {
xhr.prototype.send = function () {
var this$1 = this;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
startHandler();
this.addEventListener('abort', endHandler, false);
this.addEventListener('readystatechange', function () {
if (this$1.readyState === 4) {
endHandler();
}
}, false);
send.apply(this, args);
};
}
function restoreAjax () {
xhr.prototype.send = send;
}
var QAjaxBar = {
name: 'q-ajax-bar',
props: {
position: {
type: String,
default: 'top',
validator: function validator (val) {
return ['top', 'right', 'bottom', 'left'].includes(val)
}
},
size: {
type: String,
default: '4px'
},
color: {
type: String,
default: 'red'
},
speed: {
type: Number,
default: 250
},
delay: {
type: Number,
default: 1000
},
reverse: Boolean
},
data: function data () {
return {
animate: false,
active: false,
progress: 0,
calls: 0
}
},
computed: {
classes: function classes () {
return [
this.position,
{ 'no-trantion': this.animate }
]
},
innerClasses: function innerClasses () {
return ("bg-" + (this.color))
},
style: function style$$1 () {
var o = translate({
p: this.progress,
pos: this.position,
active: this.active,
horiz: this.horizontal,
reverse: this.reverse
});
o[this.sizeProp] = this.size;
return o
},
horizontal: function horizontal () {
return this.position === 'top' || this.position === 'bottom'
},
sizeProp: function sizeProp () {
return this.horizontal ? 'height' : 'width'
}
},
methods: {
start: function start () {
var this$1 = this;
this.calls++;
if (!this.active) {
this.progress = 0;
this.active = true;
this.animate = false;
this.$emit('start');
this.timer = setTimeout(function () {
this$1.animate = true;
this$1.move();
}, this.delay);
}
else if (this.closing) {
this.closing = false;
clearTimeout(this.timer);
this.progress = 0;
this.move();
}
},
increment: function increment (amount) {
if (this.active) {
this.progress = inc(this.progress, amount);
}
},
stop: function stop () {
var this$1 = this;
this.calls = Math.max(0, this.calls - 1);
if (this.calls > 0) {
return
}
clearTimeout(this.timer);
if (!this.animate) {
this.active = false;
return
}
this.closing = true;
this.progress = 100;
this.$emit('stop');
this.timer = setTimeout(function () {
this$1.closing = false;
this$1.active = false;
}, 1050);
},
move: function move () {
var this$1 = this;
this.timer = setTimeout(function () {
this$1.increment();
this$1.move();
}, this.speed);
}
},
mounted: function mounted () {
highjackAjax(this.start, this.stop);
},
beforeDestroy: function beforeDestroy () {
if (!isSSR) {
clearTimeout(this.timer);
restoreAjax();
}
},
render: function render (h) {
if (isSSR) { return }
return h('div', {
staticClass: 'q-loading-bar shadow-4',
'class': this.classes,
style: this.style
}, [
h('div', {
staticClass: 'q-loading-bar-inner',
'class': this.innerClasses
})
])
}
}
function hasPassiveEvents () {
var has = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function get () {
has = true;
}
});
window.addEventListener('qtest', null, opts);
window.removeEventListener('qtest', null, opts);
}
catch (e) {}
return has
}
var listenOpts = {};
Object.defineProperty(listenOpts, 'passive', {
configurable: true,
get: function get () {
listenOpts.passive = hasPassiveEvents()
? { passive: true }
: void 0;
return listenOpts.passive
},
set: function set (val) {
Object.defineProperty(this, 'passive', {
value: val
});
}
});
function leftClick (e) {
if ( e === void 0 ) e = window.event;
return e.button === 0
}
function middleClick (e) {
if ( e === void 0 ) e = window.event;
return e.button === 1
}
function rightClick (e) {
if ( e === void 0 ) e = window.event;
return e.button === 2
}
function getEventKey (e) {
if ( e === void 0 ) e = window.event;
return e.which || e.keyCode
}
function position (e) {
if ( e === void 0 ) e = window.event;
var posx, posy;
if (e.touches && e.touches[0]) {
e = e.touches[0];
}
else if (e.changedTouches && e.changedTouches[0]) {
e = e.changedTouches[0];
}
if (e.clientX || e.clientY) {
posx = e.clientX;
posy = e.clientY;
}
else if (e.pageX || e.pageY) {
posx = e.pageX - document.body.scrollLeft - document.documentElement.scrollLeft;
posy = e.pageY - document.body.scrollTop - document.documentElement.scrollTop;
}
else {
var offset = targetElement(e).getBoundingClientRect();
posx = ((offset.right - offset.left) / 2) + offset.left;
posy = ((offset.bottom - offset.top) / 2) + offset.top;
}
return {
top: posy,
left: posx
}
}
function targetElement (e) {
if ( e === void 0 ) e = window.event;
var target;
if (e.target) {
target = e.target;
}
else if (e.srcElement) {
target = e.srcElement;
}
// defeat Safari bug
if (target.nodeType === 3) {
target = target.parentNode;
}
return target
}
// Reasonable defaults
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
function getMouseWheelDistance (e) {
if ( e === void 0 ) e = window.event;
var
sX = 0, sY = 0, // spinX, spinY
pX = 0, pY = 0; // pixelX, pixelY
// Legacy
if ('detail' in e) { sY = e.detail; }
if ('wheelDelta' in e) { sY = -e.wheelDelta / 120; }
if ('wheelDeltaY' in e) { sY = -e.wheelDeltaY / 120; }
if ('wheelDeltaX' in e) { sX = -e.wheelDeltaX / 120; }
// side scrolling on FF with DOMMouseScroll
if ('axis' in e && e.axis === e.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in e) { pY = e.deltaY; }
if ('deltaX' in e) { pX = e.deltaX; }
if ((pX || pY) && e.deltaMode) {
if (e.deltaMode === 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
}
else { // delta in PAGE units
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; }
/*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*/
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY
}
}
function stopAndPrevent (e) {
if ( e === void 0 ) e = window.event;
if (!e) {
return
}
e.preventDefault();
e.stopPropagation();
}
var event = Object.freeze({
listenOpts: listenOpts,
leftClick: leftClick,
middleClick: middleClick,
rightClick: rightClick,
getEventKey: getEventKey,
position: position,
targetElement: targetElement,
getMouseWheelDistance: getMouseWheelDistance,
stopAndPrevent: stopAndPrevent
});
function showRipple (evt, el, stopPropagation) {
if (stopPropagation) {
evt.stopPropagation();
}
var
container = document.createElement('span'),
animNode = document.createElement('span');
container.appendChild(animNode);
container.className = 'q-ripple-container';
var size = el.clientWidth > el.clientHeight ? el.clientWidth : el.clientHeight;
size = (size * 2) + "px";
animNode.className = 'q-ripple-animation';
css(animNode, { width: size, height: size });
el.appendChild(container);
var
offset$$1 = el.getBoundingClientRect(),
pos = position(evt),
x = pos.left - offset$$1.left,
y = pos.top - offset$$1.top;
animNode.classList.add('q-ripple-animation-enter', 'q-ripple-animation-visible');
css(animNode, cssTransform(("translate(-50%, -50%) translate(" + x + "px, " + y + "px) scale(.001)")));
setTimeout(function () {
animNode.classList.remove('q-ripple-animation-enter');
css(animNode, cssTransform(("translate(-50%, -50%) translate(" + x + "px, " + y + "px)")));
setTimeout(function () {
animNode.classList.remove('q-ripple-animation-visible');
setTimeout(function () {
animNode.parentNode.remove();
}, 300);
}, 400);
}, 25);
}
function shouldAbort (ref) {
var mat = ref.mat;
var ios = ref.ios;
return (
(mat && "ios" !== 'mat') ||
(ios && "ios" !== 'ios')
)
}
var Ripple = {
name: 'ripple',
inserted: function inserted (el, ref) {
var value = ref.value;
var modifiers = ref.modifiers;
if (shouldAbort(modifiers)) {
return
}
var ctx = {
enabled: value !== false,
click: function click (evt) {
if (ctx.enabled) {
showRipple(evt, el, modifiers.stop);
}
}
};
el.__qripple = ctx;
el.addEventListener('click', ctx.click, false);
},
update: function update (el, ref) {
var value = ref.value;
var oldValue = ref.oldValue;
if (el.__qripple && value !== oldValue) {
el.__qripple.enabled = value !== false;
}
},
unbind: function unbind (el, ref) {
var modifiers = ref.modifiers;
if (shouldAbort(modifiers)) {
return
}
el.removeEventListener('click', el.__qripple.click, false);
delete el.__qripple;
}
}
var alignMap = {
left: 'start',
center: 'center',
right: 'end',
between: 'between',
around: 'around'
};
var AlignMixin = {
props: {
align: {
type: String,
default: 'center',
validator: function (v) { return ['left', 'right', 'center', 'between', 'around'].includes(v); }
}
},
computed: {
alignClass: function alignClass () {
return ("justify-" + (alignMap[this.align]))
}
}
}
var sizes = {
xs: 8, sm: 10, md: 14, lg: 20, xl: 24
};
var BtnMixin = {
mixins: [AlignMixin],
components: {
QIcon: QIcon
},
directives: {
Ripple: Ripple
},
props: {
disable: Boolean,
label: [Number, String],
noCaps: Boolean,
noWrap: Boolean,
icon: String,
iconRight: String,
round: Boolean,
outline: Boolean,
flat: Boolean,
rounded: Boolean,
push: Boolean,
size: String,
fab: Boolean,
fabMini: Boolean,
color: String,
textColor: String,
glossy: Boolean,
dense: Boolean,
noRipple: Boolean,
tabindex: Number
},
computed: {
style: function style () {
if (this.size && !this.fab && !this.fabMini) {
return {
fontSize: this.size in sizes ? ((sizes[this.size]) + "px") : this.size
}
}
},
isRectangle: function isRectangle () {
return !this.isRound
},
isRound: function isRound () {
return this.round || this.fab || this.fabMini
},
shape: function shape () {
return ("q-btn-" + (this.isRound ? 'round' : 'rectangle'))
},
isDisabled: function isDisabled () {
return this.disable || this.loading
},
hasRipple: function hasRipple () {
return "ios" === 'mat' && !this.noRipple && !this.isDisabled
},
classes: function classes () {
var cls = [ this.shape ];
if (this.fab) {
cls.push('q-btn-fab');
}
else if (this.fabMini) {
cls.push('q-btn-fab-mini');
}
if (this.flat) {
cls.push('q-btn-flat');
}
else if (this.outline) {
cls.push('q-btn-outline');
}
else if (this.push) {
cls.push('q-btn-push');
}
if (this.isDisabled) {
cls.push('disabled');
}
else {
cls.push('q-focusable q-hoverable');
}
if (this.color) {
if (this.flat || this.outline) {
cls.push(("text-" + (this.textColor || this.color)));
}
else {
cls.push(("bg-" + (this.color)));
cls.push(("text-" + (this.textColor || 'white')));
}
}
else if (this.textColor) {
cls.push(("text-" + (this.textColor)));
}
cls.push({
'q-btn-no-uppercase': this.noCaps,
'q-btn-rounded': this.rounded,
'q-btn-dense': this.dense,
'glossy': this.glossy
});
return cls
},
innerClasses: function innerClasses () {
var classes = [ this.alignClass ];
if (this.noWrap) {
classes.push('no-wrap', 'text-no-wrap');
}
return classes
}
},
methods: {
removeFocus: function removeFocus (e) {
// if is touch enabled and focus was received from pointer
if (this.$q.platform.has.touch && e.detail) {
this.$el.blur();
}
}
}
}
var mixin = {
props: {
color: String,
size: {
type: [Number, String],
default: '1em'
}
},
computed: {
classes: function classes () {
if (this.color) {
return ("text-" + (this.color))
}
}
}
}
var DefaultSpinner = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"stroke":"currentColor","fill":"currentColor","viewBox":"0 0 64 64"}},[_c('g',{attrs:{"stroke-width":"4","stroke-linecap":"round"}},[_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(180)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":"1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0;1","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(210)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":"0;1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(240)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".1;0;1;.85;.7;.65;.55;.45;.35;.25;.15;.1","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(270)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".15;.1;0;1;.85;.7;.65;.55;.45;.35;.25;.15","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(300)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".25;.15;.1;0;1;.85;.7;.65;.55;.45;.35;.25","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(330)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".35;.25;.15;.1;0;1;.85;.7;.65;.55;.45;.35","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(0)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".45;.35;.25;.15;.1;0;1;.85;.7;.65;.55;.45","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(30)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".55;.45;.35;.25;.15;.1;0;1;.85;.7;.65;.55","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(60)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".65;.55;.45;.35;.25;.15;.1;0;1;.85;.7;.65","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(90)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".7;.65;.55;.45;.35;.25;.15;.1;0;1;.85;.7","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(120)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".85;.7;.65;.55;.45;.35;.25;.15;.1;0;1;.85","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(150)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":"1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0;1","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-ios',
mixins: [mixin]
}
var audio = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 55 80","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"matrix(1 0 0 -1 0 80)"}},[_c('rect',{attrs:{"width":"10","height":"20","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"4.3s","values":"20;45;57;80;64;32;66;45;64;23;66;13;64;56;34;34;2;23;76;79;20","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"15","width":"10","height":"80","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"2s","values":"80;55;33;5;75;23;73;33;12;14;60;80","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"30","width":"10","height":"50","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"1.4s","values":"50;34;78;23;56;23;34;76;80;54;21;50","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"45","width":"10","height":"30","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"2s","values":"30;45;13;80;56;72;45;76;34;23;67;30","calcMode":"linear","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-audio',
mixins: [mixin]
}
var ball = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 57 57","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"translate(1 1)","stroke-width":"2","fill":"none","fill-rule":"evenodd"}},[_c('circle',{attrs:{"cx":"5","cy":"50","r":"5"}},[_c('animate',{attrs:{"attributeName":"cy","begin":"0s","dur":"2.2s","values":"50;5;50;50","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"cx","begin":"0s","dur":"2.2s","values":"5;27;49;5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"27","cy":"5","r":"5"}},[_c('animate',{attrs:{"attributeName":"cy","begin":"0s","dur":"2.2s","from":"5","to":"5","values":"5;50;50;5","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"cx","begin":"0s","dur":"2.2s","from":"27","to":"27","values":"27;49;5;27","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"49","cy":"50","r":"5"}},[_c('animate',{attrs:{"attributeName":"cy","begin":"0s","dur":"2.2s","values":"50;50;5;50","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"cx","from":"49","to":"49","begin":"0s","dur":"2.2s","values":"49;5;27;49","calcMode":"linear","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-ball',
mixins: [mixin]
}
var bars = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 135 140","xmlns":"http://www.w3.org/2000/svg"}},[_c('rect',{attrs:{"y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.5s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.5s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"30","y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.25s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.25s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"60","width":"15","height":"140","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"90","y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.25s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.25s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"120","y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.5s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.5s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-bars',
mixins: [mixin]
}
var circles = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 135 135","xmlns":"http://www.w3.org/2000/svg"}},[_c('path',{attrs:{"d":"M67.447 58c5.523 0 10-4.477 10-10s-4.477-10-10-10-10 4.477-10 10 4.477 10 10 10zm9.448 9.447c0 5.523 4.477 10 10 10 5.522 0 10-4.477 10-10s-4.478-10-10-10c-5.523 0-10 4.477-10 10zm-9.448 9.448c-5.523 0-10 4.477-10 10 0 5.522 4.477 10 10 10s10-4.478 10-10c0-5.523-4.477-10-10-10zM58 67.447c0-5.523-4.477-10-10-10s-10 4.477-10 10 4.477 10 10 10 10-4.477 10-10z"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 67 67","to":"-360 67 67","dur":"2.5s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M28.19 40.31c6.627 0 12-5.374 12-12 0-6.628-5.373-12-12-12-6.628 0-12 5.372-12 12 0 6.626 5.372 12 12 12zm30.72-19.825c4.686 4.687 12.284 4.687 16.97 0 4.686-4.686 4.686-12.284 0-16.97-4.686-4.687-12.284-4.687-16.97 0-4.687 4.686-4.687 12.284 0 16.97zm35.74 7.705c0 6.627 5.37 12 12 12 6.626 0 12-5.373 12-12 0-6.628-5.374-12-12-12-6.63 0-12 5.372-12 12zm19.822 30.72c-4.686 4.686-4.686 12.284 0 16.97 4.687 4.686 12.285 4.686 16.97 0 4.687-4.686 4.687-12.284 0-16.97-4.685-4.687-12.283-4.687-16.97 0zm-7.704 35.74c-6.627 0-12 5.37-12 12 0 6.626 5.373 12 12 12s12-5.374 12-12c0-6.63-5.373-12-12-12zm-30.72 19.822c-4.686-4.686-12.284-4.686-16.97 0-4.686 4.687-4.686 12.285 0 16.97 4.686 4.687 12.284 4.687 16.97 0 4.687-4.685 4.687-12.283 0-16.97zm-35.74-7.704c0-6.627-5.372-12-12-12-6.626 0-12 5.373-12 12s5.374 12 12 12c6.628 0 12-5.373 12-12zm-19.823-30.72c4.687-4.686 4.687-12.284 0-16.97-4.686-4.686-12.284-4.686-16.97 0-4.687 4.686-4.687 12.284 0 16.97 4.686 4.687 12.284 4.687 16.97 0z"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 67 67","to":"360 67 67","dur":"8s","repeatCount":"indefinite"}})],1)])},staticRenderFns: [],
name: 'q-spinner-circles',
mixins: [mixin]
}
var comment = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid"}},[_c('rect',{attrs:{"x":"0","y":"0","width":"100","height":"100","fill":"none"}}),_c('path',{attrs:{"d":"M78,19H22c-6.6,0-12,5.4-12,12v31c0,6.6,5.4,12,12,12h37.2c0.4,3,1.8,5.6,3.7,7.6c2.4,2.5,5.1,4.1,9.1,4 c-1.4-2.1-2-7.2-2-10.3c0-0.4,0-0.8,0-1.3h8c6.6,0,12-5.4,12-12V31C90,24.4,84.6,19,78,19z","fill":"currentColor"}}),_c('circle',{attrs:{"cx":"30","cy":"47","r":"5","fill":"#fff"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","values":"0;1;1","keyTimes":"0;0.2;1","dur":"1s","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"50","cy":"47","r":"5","fill":"#fff"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","values":"0;0;1;1","keyTimes":"0;0.2;0.4;1","dur":"1s","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"70","cy":"47","r":"5","fill":"#fff"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","values":"0;0;1;1","keyTimes":"0;0.4;0.6;1","dur":"1s","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-comment',
mixins: [mixin]
}
var cube = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid"}},[_c('rect',{attrs:{"x":"0","y":"0","width":"100","height":"100","fill":"none"}}),_c('g',{attrs:{"transform":"translate(25 25)"}},[_c('rect',{attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.9"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)]),_c('g',{attrs:{"transform":"translate(75 25)"}},[_c('rect',{attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.8"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0.1s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)]),_c('g',{attrs:{"transform":"translate(25 75)"}},[_c('rect',{staticClass:"cube",attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.7"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0.3s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)]),_c('g',{attrs:{"transform":"translate(75 75)"}},[_c('rect',{staticClass:"cube",attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.6"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0.2s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-cube',
mixins: [mixin]
}
var dots = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 120 30","xmlns":"http://www.w3.org/2000/svg"}},[_c('circle',{attrs:{"cx":"15","cy":"15","r":"15"}},[_c('animate',{attrs:{"attributeName":"r","from":"15","to":"15","begin":"0s","dur":"0.8s","values":"15;9;15","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"fill-opacity","from":"1","to":"1","begin":"0s","dur":"0.8s","values":"1;.5;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"60","cy":"15","r":"9","fill-opacity":".3"}},[_c('animate',{attrs:{"attributeName":"r","from":"9","to":"9","begin":"0s","dur":"0.8s","values":"9;15;9","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"fill-opacity","from":".5","to":".5","begin":"0s","dur":"0.8s","values":".5;1;.5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"105","cy":"15","r":"15"}},[_c('animate',{attrs:{"attributeName":"r","from":"15","to":"15","begin":"0s","dur":"0.8s","values":"15;9;15","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"fill-opacity","from":"1","to":"1","begin":"0s","dur":"0.8s","values":"1;.5;1","calcMode":"linear","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-dots',
mixins: [mixin]
}
var facebook = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","xmlns":"http://www.w3.org/2000/svg","preserveAspectRatio":"xMidYMid"}},[_c('g',{attrs:{"transform":"translate(20 50)"}},[_c('rect',{attrs:{"x":"-10","y":"-30","width":"20","height":"60","fill":"currentColor","opacity":"0.6"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"2","to":"1","begin":"0s","repeatCount":"indefinite","dur":"1s","calcMode":"spline","keySplines":"0.1 0.9 0.4 1","keyTimes":"0;1","values":"2;1"}})],1)]),_c('g',{attrs:{"transform":"translate(50 50)"}},[_c('rect',{attrs:{"x":"-10","y":"-30","width":"20","height":"60","fill":"currentColor","opacity":"0.8"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"2","to":"1","begin":"0.1s","repeatCount":"indefinite","dur":"1s","calcMode":"spline","keySplines":"0.1 0.9 0.4 1","keyTimes":"0;1","values":"2;1"}})],1)]),_c('g',{attrs:{"transform":"translate(80 50)"}},[_c('rect',{attrs:{"x":"-10","y":"-30","width":"20","height":"60","fill":"currentColor","opacity":"0.9"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"2","to":"1","begin":"0.2s","repeatCount":"indefinite","dur":"1s","calcMode":"spline","keySplines":"0.1 0.9 0.4 1","keyTimes":"0;1","values":"2;1"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-facebook',
mixins: [mixin]
}
var gears = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"translate(-20,-20)"}},[_c('path',{attrs:{"d":"M79.9,52.6C80,51.8,80,50.9,80,50s0-1.8-0.1-2.6l-5.1-0.4c-0.3-2.4-0.9-4.6-1.8-6.7l4.2-2.9c-0.7-1.6-1.6-3.1-2.6-4.5 L70,35c-1.4-1.9-3.1-3.5-4.9-4.9l2.2-4.6c-1.4-1-2.9-1.9-4.5-2.6L59.8,27c-2.1-0.9-4.4-1.5-6.7-1.8l-0.4-5.1C51.8,20,50.9,20,50,20 s-1.8,0-2.6,0.1l-0.4,5.1c-2.4,0.3-4.6,0.9-6.7,1.8l-2.9-4.1c-1.6,0.7-3.1,1.6-4.5,2.6l2.1,4.6c-1.9,1.4-3.5,3.1-5,4.9l-4.5-2.1 c-1,1.4-1.9,2.9-2.6,4.5l4.1,2.9c-0.9,2.1-1.5,4.4-1.8,6.8l-5,0.4C20,48.2,20,49.1,20,50s0,1.8,0.1,2.6l5,0.4 c0.3,2.4,0.9,4.7,1.8,6.8l-4.1,2.9c0.7,1.6,1.6,3.1,2.6,4.5l4.5-2.1c1.4,1.9,3.1,3.5,5,4.9l-2.1,4.6c1.4,1,2.9,1.9,4.5,2.6l2.9-4.1 c2.1,0.9,4.4,1.5,6.7,1.8l0.4,5.1C48.2,80,49.1,80,50,80s1.8,0,2.6-0.1l0.4-5.1c2.3-0.3,4.6-0.9,6.7-1.8l2.9,4.2 c1.6-0.7,3.1-1.6,4.5-2.6L65,69.9c1.9-1.4,3.5-3,4.9-4.9l4.6,2.2c1-1.4,1.9-2.9,2.6-4.5L73,59.8c0.9-2.1,1.5-4.4,1.8-6.7L79.9,52.6 z M50,65c-8.3,0-15-6.7-15-15c0-8.3,6.7-15,15-15s15,6.7,15,15C65,58.3,58.3,65,50,65z","fill":"currentColor"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"90 50 50","to":"0 50 50","dur":"1s","repeatCount":"indefinite"}})],1)]),_c('g',{attrs:{"transform":"translate(20,20) rotate(15 50 50)"}},[_c('path',{attrs:{"d":"M79.9,52.6C80,51.8,80,50.9,80,50s0-1.8-0.1-2.6l-5.1-0.4c-0.3-2.4-0.9-4.6-1.8-6.7l4.2-2.9c-0.7-1.6-1.6-3.1-2.6-4.5 L70,35c-1.4-1.9-3.1-3.5-4.9-4.9l2.2-4.6c-1.4-1-2.9-1.9-4.5-2.6L59.8,27c-2.1-0.9-4.4-1.5-6.7-1.8l-0.4-5.1C51.8,20,50.9,20,50,20 s-1.8,0-2.6,0.1l-0.4,5.1c-2.4,0.3-4.6,0.9-6.7,1.8l-2.9-4.1c-1.6,0.7-3.1,1.6-4.5,2.6l2.1,4.6c-1.9,1.4-3.5,3.1-5,4.9l-4.5-2.1 c-1,1.4-1.9,2.9-2.6,4.5l4.1,2.9c-0.9,2.1-1.5,4.4-1.8,6.8l-5,0.4C20,48.2,20,49.1,20,50s0,1.8,0.1,2.6l5,0.4 c0.3,2.4,0.9,4.7,1.8,6.8l-4.1,2.9c0.7,1.6,1.6,3.1,2.6,4.5l4.5-2.1c1.4,1.9,3.1,3.5,5,4.9l-2.1,4.6c1.4,1,2.9,1.9,4.5,2.6l2.9-4.1 c2.1,0.9,4.4,1.5,6.7,1.8l0.4,5.1C48.2,80,49.1,80,50,80s1.8,0,2.6-0.1l0.4-5.1c2.3-0.3,4.6-0.9,6.7-1.8l2.9,4.2 c1.6-0.7,3.1-1.6,4.5-2.6L65,69.9c1.9-1.4,3.5-3,4.9-4.9l4.6,2.2c1-1.4,1.9-2.9,2.6-4.5L73,59.8c0.9-2.1,1.5-4.4,1.8-6.7L79.9,52.6 z M50,65c-8.3,0-15-6.7-15-15c0-8.3,6.7-15,15-15s15,6.7,15,15C65,58.3,58.3,65,50,65z","fill":"currentColor"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"90 50 50","dur":"1s","repeatCount":"indefinite"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-gears',
mixins: [mixin]
}
var grid = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 105 105","xmlns":"http://www.w3.org/2000/svg"}},[_c('circle',{attrs:{"cx":"12.5","cy":"12.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"0s","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"12.5","cy":"52.5","r":"12.5","fill-opacity":".5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"100ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"52.5","cy":"12.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"300ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"52.5","cy":"52.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"600ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"92.5","cy":"12.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"800ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"92.5","cy":"52.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"400ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"12.5","cy":"92.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"700ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"52.5","cy":"92.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"500ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"92.5","cy":"92.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"200ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-grid',
mixins: [mixin]
}
var hearts = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 140 64","xmlns":"http://www.w3.org/2000/svg"}},[_c('path',{attrs:{"d":"M30.262 57.02L7.195 40.723c-5.84-3.976-7.56-12.06-3.842-18.063 3.715-6 11.467-7.65 17.306-3.68l4.52 3.76 2.6-5.274c3.716-6.002 11.47-7.65 17.304-3.68 5.84 3.97 7.56 12.054 3.842 18.062L34.49 56.118c-.897 1.512-2.793 1.915-4.228.9z","fill-opacity":".5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"0s","dur":"1.4s","values":"0.5;1;0.5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('path',{attrs:{"d":"M105.512 56.12l-14.44-24.272c-3.716-6.008-1.996-14.093 3.843-18.062 5.835-3.97 13.588-2.322 17.306 3.68l2.6 5.274 4.52-3.76c5.84-3.97 13.593-2.32 17.308 3.68 3.718 6.003 1.998 14.088-3.842 18.064L109.74 57.02c-1.434 1.014-3.33.61-4.228-.9z","fill-opacity":".5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"0.7s","dur":"1.4s","values":"0.5;1;0.5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('path',{attrs:{"d":"M67.408 57.834l-23.01-24.98c-5.864-6.15-5.864-16.108 0-22.248 5.86-6.14 15.37-6.14 21.234 0L70 16.168l4.368-5.562c5.863-6.14 15.375-6.14 21.235 0 5.863 6.14 5.863 16.098 0 22.247l-23.007 24.98c-1.43 1.556-3.757 1.556-5.188 0z"}})])},staticRenderFns: [],
name: 'q-spinner-hearts',
mixins: [mixin]
}
var hourglass = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',[_c('path',{staticClass:"glass",attrs:{"fill":"none","stroke":"currentColor","stroke-width":"5","stroke-miterlimit":"10","d":"M58.4,51.7c-0.9-0.9-1.4-2-1.4-2.3s0.5-0.4,1.4-1.4 C70.8,43.8,79.8,30.5,80,15.5H70H30H20c0.2,15,9.2,28.1,21.6,32.3c0.9,0.9,1.4,1.2,1.4,1.5s-0.5,1.6-1.4,2.5 C29.2,56.1,20.2,69.5,20,85.5h10h40h10C79.8,69.5,70.8,55.9,58.4,51.7z"}}),_c('clipPath',{attrs:{"id":"uil-hourglass-clip1"}},[_c('rect',{staticClass:"clip",attrs:{"x":"15","y":"20","width":"70","height":"25"}},[_c('animate',{attrs:{"attributeName":"height","from":"25","to":"0","dur":"1s","repeatCount":"indefinite","vlaues":"25;0;0","keyTimes":"0;0.5;1"}}),_c('animate',{attrs:{"attributeName":"y","from":"20","to":"45","dur":"1s","repeatCount":"indefinite","vlaues":"20;45;45","keyTimes":"0;0.5;1"}})])]),_c('clipPath',{attrs:{"id":"uil-hourglass-clip2"}},[_c('rect',{staticClass:"clip",attrs:{"x":"15","y":"55","width":"70","height":"25"}},[_c('animate',{attrs:{"attributeName":"height","from":"0","to":"25","dur":"1s","repeatCount":"indefinite","vlaues":"0;25;25","keyTimes":"0;0.5;1"}}),_c('animate',{attrs:{"attributeName":"y","from":"80","to":"55","dur":"1s","repeatCount":"indefinite","vlaues":"80;55;55","keyTimes":"0;0.5;1"}})])]),_c('path',{staticClass:"sand",attrs:{"d":"M29,23c3.1,11.4,11.3,19.5,21,19.5S67.9,34.4,71,23H29z","clip-path":"url(#uil-hourglass-clip1)","fill":"currentColor"}}),_c('path',{staticClass:"sand",attrs:{"d":"M71.6,78c-3-11.6-11.5-20-21.5-20s-18.5,8.4-21.5,20H71.6z","clip-path":"url(#uil-hourglass-clip2)","fill":"currentColor"}}),_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"180 50 50","repeatCount":"indefinite","dur":"1s","values":"0 50 50;0 50 50;180 50 50","keyTimes":"0;0.7;1"}})],1)])},staticRenderFns: [],
name: 'q-spinner-hourglass',
mixins: [mixin]
}
var infinity = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid"}},[_c('path',{attrs:{"d":"M24.3,30C11.4,30,5,43.3,5,50s6.4,20,19.3,20c19.3,0,32.1-40,51.4-40C88.6,30,95,43.3,95,50s-6.4,20-19.3,20C56.4,70,43.6,30,24.3,30z","fill":"none","stroke":"currentColor","stroke-width":"8","stroke-dasharray":"10.691205342610678 10.691205342610678","stroke-dashoffset":"0"}},[_c('animate',{attrs:{"attributeName":"stroke-dashoffset","from":"0","to":"21.382410685221355","begin":"0","dur":"2s","repeatCount":"indefinite","fill":"freeze"}})])])},staticRenderFns: [],
name: 'q-spinner-infinity',
mixins: [mixin]
}
var QSpinner_mat = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner q-spinner-mat",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"25 25 50 50"}},[_c('circle',{staticClass:"path",attrs:{"cx":"50","cy":"50","r":"20","fill":"none","stroke":"currentColor","stroke-width":"3","stroke-miterlimit":"10"}})])},staticRenderFns: [],
name: 'q-spinner-mat',
mixins: [mixin]
}
var oval = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 38 38","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"translate(1 1)","stroke-width":"2","fill":"none","fill-rule":"evenodd"}},[_c('circle',{attrs:{"stroke-opacity":".5","cx":"18","cy":"18","r":"18"}}),_c('path',{attrs:{"d":"M36 18c0-9.94-8.06-18-18-18"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 18 18","to":"360 18 18","dur":"1s","repeatCount":"indefinite"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-oval',
mixins: [mixin]
}
var pie = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('path',{attrs:{"d":"M0 50A50 50 0 0 1 50 0L50 50L0 50","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"0.8s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M50 0A50 50 0 0 1 100 50L50 50L50 0","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"1.6s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M100 50A50 50 0 0 1 50 100L50 50L100 50","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"2.4s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M50 100A50 50 0 0 1 0 50L50 50L50 100","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"3.2s","repeatCount":"indefinite"}})],1)])},staticRenderFns: [],
name: 'q-spinner-pie',
mixins: [mixin]
}
var puff = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 44 44","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"fill":"none","fill-rule":"evenodd","stroke-width":"2"}},[_c('circle',{attrs:{"cx":"22","cy":"22","r":"1"}},[_c('animate',{attrs:{"attributeName":"r","begin":"0s","dur":"1.8s","values":"1; 20","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.165, 0.84, 0.44, 1","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"0s","dur":"1.8s","values":"1; 0","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.3, 0.61, 0.355, 1","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"22","cy":"22","r":"1"}},[_c('animate',{attrs:{"attributeName":"r","begin":"-0.9s","dur":"1.8s","values":"1; 20","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.165, 0.84, 0.44, 1","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"-0.9s","dur":"1.8s","values":"1; 0","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.3, 0.61, 0.355, 1","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-puff',
mixins: [mixin]
}
var radio = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"scale(0.55)"}},[_c('circle',{attrs:{"cx":"30","cy":"150","r":"30","fill":"currentColor"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","dur":"1s","begin":"0","repeatCount":"indefinite","keyTimes":"0;0.5;1","values":"0;1;1"}})]),_c('path',{attrs:{"d":"M90,150h30c0-49.7-40.3-90-90-90v30C63.1,90,90,116.9,90,150z","fill":"currentColor"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","dur":"1s","begin":"0.1","repeatCount":"indefinite","keyTimes":"0;0.5;1","values":"0;1;1"}})]),_c('path',{attrs:{"d":"M150,150h30C180,67.2,112.8,0,30,0v30C96.3,30,150,83.7,150,150z","fill":"currentColor"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","dur":"1s","begin":"0.2","repeatCount":"indefinite","keyTimes":"0;0.5;1","values":"0;1;1"}})])])])},staticRenderFns: [],
name: 'q-spinner-radio',
mixins: [mixin]
}
var rings = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 45 45","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"fill":"none","fill-rule":"evenodd","transform":"translate(1 1)","stroke-width":"2"}},[_c('circle',{attrs:{"cx":"22","cy":"22","r":"6"}},[_c('animate',{attrs:{"attributeName":"r","begin":"1.5s","dur":"3s","values":"6;22","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"1.5s","dur":"3s","values":"1;0","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-width","begin":"1.5s","dur":"3s","values":"2;0","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"22","cy":"22","r":"6"}},[_c('animate',{attrs:{"attributeName":"r","begin":"3s","dur":"3s","values":"6;22","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"3s","dur":"3s","values":"1;0","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-width","begin":"3s","dur":"3s","values":"2;0","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"22","cy":"22","r":"8"}},[_c('animate',{attrs:{"attributeName":"r","begin":"0s","dur":"1.5s","values":"6;1;2;3;4;5;6","calcMode":"linear","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-rings',
mixins: [mixin]
}
var tail = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 38 38","xmlns":"http://www.w3.org/2000/svg"}},[_c('defs',[_c('linearGradient',{attrs:{"x1":"8.042%","y1":"0%","x2":"65.682%","y2":"23.865%","id":"a"}},[_c('stop',{attrs:{"stop-color":"currentColor","stop-opacity":"0","offset":"0%"}}),_c('stop',{attrs:{"stop-color":"currentColor","stop-opacity":".631","offset":"63.146%"}}),_c('stop',{attrs:{"stop-color":"currentColor","offset":"100%"}})],1)],1),_c('g',{attrs:{"transform":"translate(1 1)","fill":"none","fill-rule":"evenodd"}},[_c('path',{attrs:{"d":"M36 18c0-9.94-8.06-18-18-18","stroke":"url(#a)","stroke-width":"2"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 18 18","to":"360 18 18","dur":"0.9s","repeatCount":"indefinite"}})],1),_c('circle',{attrs:{"fill":"currentColor","cx":"36","cy":"18","r":"1"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 18 18","to":"360 18 18","dur":"0.9s","repeatCount":"indefinite"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-tail',
mixins: [mixin]
}
var QSpinner = {
mixins: [DefaultSpinner],
name: 'q-spinner'
};
var QBtn = {
name: 'q-btn',
mixins: [BtnMixin],
props: {
value: Boolean,
loader: Boolean,
percentage: Number,
darkPercentage: Boolean,
waitForRipple: Boolean,
repeatTimeout: [Number, Function]
},
data: function data () {
return {
loading: this.value || false,
repeated: 0
}
},
watch: {
value: function value (val) {
if (this.loading !== val) {
this.loading = val;
}
}
},
computed: {
hasPercentage: function hasPercentage () {
return this.percentage !== void 0
},
width: function width () {
return ((between(this.percentage, 0, 100)) + "%")
},
hasNoRepeat: function hasNoRepeat () {
return this.isDisabled || !this.repeatTimeout || this.loader !== false
}
},
methods: {
click: function click (e) {
var this$1 = this;
clearTimeout(this.timer);
if (this.isDisabled || this.repeated) {
this.repeated = 0;
return
}
var trigger = function () {
this$1.removeFocus(e);
if (this$1.loader !== false || this$1.$slots.loading) {
this$1.loading = true;
this$1.$emit('input', true);
}
this$1.$emit('click', e, function () {
this$1.loading = false;
this$1.$emit('input', false);
});
};
if (this.waitForRipple && this.hasRipple) {
this.timer = setTimeout(trigger, 350);
}
else {
trigger();
}
},
startRepeat: function startRepeat (e) {
var this$1 = this;
this.repeated = 0;
var setTimer = function () {
this$1.timer = setTimeout(
trigger,
typeof this$1.repeatTimeout === 'function'
? this$1.repeatTimeout(this$1.repeated)
: this$1.repeatTimeout
);
};
var trigger = function () {
if (this$1.hasNoRepeat || this$1.$slots.loading) {
return
}
this$1.repeated += 1;
this$1.$emit('click', e);
setTimer();
};
setTimer();
},
endRepeat: function endRepeat () {
clearTimeout(this.timer);
}
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
},
render: function render (h) {
var on = this.hasNoRepeat || this.$slots.loading
? {}
: {
mousedown: this.startRepeat,
touchstart: this.startRepeat,
mouseup: this.endRepeat,
mouseleave: this.endRepeat,
touchend: this.endRepeat
};
on.click = this.click;
return h('button', {
staticClass: 'q-btn inline relative-position',
'class': this.classes,
style: this.style,
attrs: { tabindex: this.isDisabled ? -1 : this.tabindex || 0 },
on: on,
directives: this.hasRipple
? [{
name: 'ripple',
value: true
}]
: null
}, [
h('div', { staticClass: 'q-focus-helper' }),
this.loading && this.hasPercentage
? h('div', {
staticClass: 'q-btn-progress absolute-full',
'class': { 'q-btn-dark-progress': this.darkPercentage },
style: { width: this.width }
})
: null,
h('div', {
staticClass: 'q-btn-inner row col items-center',
'class': this.innerClasses
},
this.loading
? [ this.$slots.loading || h(QSpinner) ]
: [
this.icon
? h('q-icon', {
'class': { 'on-left': this.label && this.isRectangle },
props: { name: this.icon }
})
: null,
this.label && this.isRectangle ? h('div', [ this.label ]) : null,
this.$slots.default,
this.iconRight && this.isRectangle
? h('q-icon', {
staticClass: 'on-right',
props: { name: this.iconRight }
})
: null
]
)
])
}
}
var QBtnGroup = {
name: 'q-btn-group',
props: {
outline: Boolean,
flat: Boolean,
rounded: Boolean,
push: Boolean
},
computed: {
classes: function classes () {
var this$1 = this;
return ['outline', 'flat', 'rounded', 'push']
.filter(function (t) { return this$1[t]; })
.map(function (t) { return ("q-btn-group-" + t); }).join(' ')
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-btn-group row no-wrap inline',
'class': this.classes
}, [
this.$slots.default
])
}
}
function getAnchorPosition (el, offset) {
var ref = el.getBoundingClientRect();
var top = ref.top;
var left = ref.left;
var right = ref.right;
var bottom = ref.bottom;
var a = {
top: top,
left: left,
width: el.offsetWidth,
height: el.offsetHeight
};
if (offset) {
a.top -= offset[1];
a.left -= offset[0];
if (bottom) {
bottom += offset[1];
}
if (right) {
right += offset[0];
}
a.width += offset[0];
a.height += offset[1];
}
a.right = right || a.left + a.width;
a.bottom = bottom || a.top + a.height;
a.middle = a.left + ((a.right - a.left) / 2);
a.center = a.top + ((a.bottom - a.top) / 2);
return a
}
function getTargetPosition (el) {
return {
top: 0,
center: el.offsetHeight / 2,
bottom: el.offsetHeight,
left: 0,
middle: el.offsetWidth / 2,
right: el.offsetWidth
}
}
function getOverlapMode (anchor, target, median) {
if ([anchor, target].indexOf(median) >= 0) { return 'auto' }
if (anchor === target) { return 'inclusive' }
return 'exclusive'
}
function getPositions (anchor, target) {
var
a = extend({}, anchor),
t = extend({}, target);
var positions = {
x: ['left', 'right'].filter(function (p) { return p !== t.horizontal; }),
y: ['top', 'bottom'].filter(function (p) { return p !== t.vertical; })
};
var overlap = {
x: getOverlapMode(a.horizontal, t.horizontal, 'middle'),
y: getOverlapMode(a.vertical, t.vertical, 'center')
};
positions.x.splice(overlap.x === 'auto' ? 0 : 1, 0, 'middle');
positions.y.splice(overlap.y === 'auto' ? 0 : 1, 0, 'center');
if (overlap.y !== 'auto') {
a.vertical = a.vertical === 'top' ? 'bottom' : 'top';
if (overlap.y === 'inclusive') {
t.vertical = t.vertical;
}
}
if (overlap.x !== 'auto') {
a.horizontal = a.horizontal === 'left' ? 'right' : 'left';
if (overlap.y === 'inclusive') {
t.horizontal = t.horizontal;
}
}
return {
positions: positions,
anchorPos: a
}
}
function applyAutoPositionIfNeeded (anchor, target, selfOrigin, anchorOrigin, targetPosition) {
var ref = getPositions(anchorOrigin, selfOrigin);
var positions = ref.positions;
var anchorPos = ref.anchorPos;
if (targetPosition.top < 0 || targetPosition.top + target.bottom > window.innerHeight) {
var newTop = anchor[anchorPos.vertical] - target[positions.y[0]];
if (newTop + target.bottom <= window.innerHeight) {
targetPosition.top = newTop;
}
else {
newTop = anchor[anchorPos.vertical] - target[positions.y[1]];
if (newTop + target.bottom <= window.innerHeight) {
targetPosition.top = newTop;
}
}
}
if (targetPosition.left < 0 || targetPosition.left + target.right > window.innerWidth) {
var newLeft = anchor[anchorPos.horizontal] - target[positions.x[0]];
if (newLeft + target.right <= window.innerWidth) {
targetPosition.left = newLeft;
}
else {
newLeft = anchor[anchorPos.horizontal] - target[positions.x[1]];
if (newLeft + target.right <= window.innerWidth) {
targetPosition.left = newLeft;
}
}
}
return targetPosition
}
function parseHorizTransformOrigin (pos) {
return pos === 'middle' ? 'center' : pos
}
function getTransformProperties (ref) {
var selfOrigin = ref.selfOrigin;
var
vert = selfOrigin.vertical,
horiz = parseHorizTransformOrigin(selfOrigin.horizontal);
return {
'transform-origin': vert + ' ' + horiz + ' 0px'
}
}
function setPosition (ref) {
var el = ref.el;
var anchorEl = ref.anchorEl;
var anchorOrigin = ref.anchorOrigin;
var selfOrigin = ref.selfOrigin;
var maxHeight = ref.maxHeight;
var event = ref.event;
var anchorClick = ref.anchorClick;
var touchPosition = ref.touchPosition;
var offset = ref.offset;
var anchor;
el.style.maxHeight = maxHeight || '65vh';
if (event && (!anchorClick || touchPosition)) {
var ref$1 = position(event);
var top = ref$1.top;
var left = ref$1.left;
anchor = {top: top, left: left, width: 1, height: 1, right: left + 1, center: top, middle: left, bottom: top + 1};
}
else {
anchor = getAnchorPosition(anchorEl, offset);
}
var target = getTargetPosition(el);
var targetPosition = {
top: anchor[anchorOrigin.vertical] - target[selfOrigin.vertical],
left: anchor[anchorOrigin.horizontal] - target[selfOrigin.horizontal]
};
targetPosition = applyAutoPositionIfNeeded(anchor, target, selfOrigin, anchorOrigin, targetPosition);
el.style.top = Math.max(0, targetPosition.top) + 'px';
el.style.left = Math.max(0, targetPosition.left) + 'px';
}
function positionValidator (pos) {
var parts = pos.split(' ');
if (parts.length !== 2) {
return false
}
if (!['top', 'center', 'bottom'].includes(parts[0])) {
console.error('Anchor/Self position must start with one of top/center/bottom');
return false
}
if (!['left', 'middle', 'right'].includes(parts[1])) {
console.error('Anchor/Self position must end with one of left/middle/right');
return false
}
return true
}
function offsetValidator (val) {
if (!val) { return true }
if (val.length !== 2) { return false }
if (typeof val[0] !== 'number' || typeof val[1] !== 'number') {
return false
}
return true
}
function parsePosition (pos) {
var parts = pos.split(' ');
return {vertical: parts[0], horizontal: parts[1]}
}
function debounce (fn, wait, immediate) {
if ( wait === void 0 ) wait = 250;
var timeout;
function debounced () {
var this$1 = this;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var later = function () {
timeout = null;
if (!immediate) {
fn.apply(this$1, args);
}
};
clearTimeout(timeout);
if (immediate && !timeout) {
fn.apply(this, args);
}
timeout = setTimeout(later, wait);
}
debounced.cancel = function () {
clearTimeout(timeout);
};
return debounced
}
function frameDebounce (fn) {
var wait = false;
return function () {
var this$1 = this;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (wait) { return }
wait = true;
window.requestAnimationFrame(function () {
fn.apply(this$1, args);
wait = false;
});
}
}
function getScrollTarget (el) {
return el.closest('.scroll') || window
}
function getScrollHeight (el) {
return (el === window ? document.body : el).scrollHeight
}
function getScrollPosition (scrollTarget) {
if (scrollTarget === window) {
return window.pageYOffset || window.scrollY || document.body.scrollTop || 0
}
return scrollTarget.scrollTop
}
function animScrollTo (el, to, duration) {
if (duration <= 0) {
return
}
var pos = getScrollPosition(el);
window.requestAnimationFrame(function () {
setScroll(el, pos + (to - pos) / duration * 16);
if (el.scrollTop !== to) {
animScrollTo(el, to, duration - 16);
}
});
}
function setScroll (scrollTarget, offset$$1) {
if (scrollTarget === window) {
document.documentElement.scrollTop = offset$$1;
document.body.scrollTop = offset$$1;
return
}
scrollTarget.scrollTop = offset$$1;
}
function setScrollPosition (scrollTarget, offset$$1, duration) {
if (duration) {
animScrollTo(scrollTarget, offset$$1, duration);
return
}
setScroll(scrollTarget, offset$$1);
}
var size;
function getScrollbarWidth () {
if (size !== undefined) {
return size
}
var
inner = document.createElement('p'),
outer = document.createElement('div');
css(inner, {
width: '100%',
height: '200px'
});
css(outer, {
position: 'absolute',
top: '0px',
left: '0px',
visibility: 'hidden',
width: '200px',
height: '150px',
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);
size = w1 - w2;
return size
}
var scroll = Object.freeze({
getScrollTarget: getScrollTarget,
getScrollHeight: getScrollHeight,
getScrollPosition: getScrollPosition,
animScrollTo: animScrollTo,
setScrollPosition: setScrollPosition,
getScrollbarWidth: getScrollbarWidth
});
var QPopover = {
name: 'q-popover',
mixins: [ModelToggleMixin],
props: {
anchor: {
type: String,
default: 'bottom left',
validator: positionValidator
},
self: {
type: String,
default: 'top left',
validator: positionValidator
},
fit: Boolean,
maxHeight: String,
touchPosition: Boolean,
anchorClick: {
/*
for handling anchor outside of Popover
example: context menu component
*/
type: Boolean,
default: true
},
offset: {
type: Array,
validator: offsetValidator
},
disable: Boolean
},
watch: {
$route: function $route () {
this.hide();
}
},
computed: {
transformCSS: function transformCSS () {
return getTransformProperties({selfOrigin: this.selfOrigin})
},
anchorOrigin: function anchorOrigin () {
return parsePosition(this.anchor)
},
selfOrigin: function selfOrigin () {
return parsePosition(this.self)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-popover animate-scale',
style: this.transformCSS,
on: {
click: function click (e) { e.stopPropagation(); }
}
}, this.$slots.default)
},
created: function created () {
var this$1 = this;
this.__updatePosition = frameDebounce(function () { this$1.reposition(); });
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.anchorEl = this$1.$el.parentNode;
this$1.anchorEl.removeChild(this$1.$el);
if (this$1.anchorEl.classList.contains('q-btn-inner') || this$1.anchorEl.classList.contains('q-if-inner')) {
this$1.anchorEl = this$1.anchorEl.parentNode;
}
if (this$1.anchorClick) {
this$1.anchorEl.classList.add('cursor-pointer');
this$1.anchorEl.addEventListener('click', this$1.toggle);
}
});
if (this.value) {
this.show();
}
},
beforeDestroy: function beforeDestroy () {
if (this.anchorClick && this.anchorEl) {
this.anchorEl.removeEventListener('click', this.toggle);
}
},
methods: {
__show: function __show (evt) {
var this$1 = this;
document.body.appendChild(this.$el);
EscapeKey.register(function () { this$1.hide(); });
this.scrollTarget = getScrollTarget(this.anchorEl);
this.scrollTarget.addEventListener('scroll', this.__updatePosition, listenOpts.passive);
window.addEventListener('resize', this.__updatePosition, listenOpts.passive);
this.reposition(evt);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
document.body.addEventListener('click', this$1.__bodyHide, true);
document.body.addEventListener('touchstart', this$1.__bodyHide, true);
this$1.showPromise && this$1.showPromiseResolve();
}, 0);
},
__bodyHide: function __bodyHide (evt) {
if (
evt && evt.target &&
(this.$el.contains(evt.target) || this.anchorEl.contains(evt.target))
) {
return
}
this.hide(evt);
},
__hide: function __hide () {
clearTimeout(this.timer);
document.body.removeEventListener('click', this.__bodyHide, true);
document.body.removeEventListener('touchstart', this.__bodyHide, true);
this.scrollTarget.removeEventListener('scroll', this.__updatePosition, listenOpts.passive);
window.removeEventListener('resize', this.__updatePosition, listenOpts.passive);
EscapeKey.pop();
document.body.removeChild(this.$el);
this.hidePromise && this.hidePromiseResolve();
},
reposition: function reposition (event) {
var this$1 = this;
this.$nextTick(function () {
if (this$1.fit) {
this$1.$el.style.minWidth = width(this$1.anchorEl) + 'px';
}
var ref = this$1.anchorEl.getBoundingClientRect();
var top = ref.top;
var ref$1 = viewport();
var height$$1 = ref$1.height;
if (top < 0 || top > height$$1) {
return this$1.hide()
}
setPosition({
event: event,
el: this$1.$el,
offset: this$1.offset,
anchorEl: this$1.anchorEl,
anchorOrigin: this$1.anchorOrigin,
selfOrigin: this$1.selfOrigin,
maxHeight: this$1.maxHeight,
anchorClick: this$1.anchorClick,
touchPosition: this$1.touchPosition
});
});
}
}
}
var QBtnDropdown = {
name: 'q-btn-dropdown',
mixins: [BtnMixin],
props: {
value: Boolean,
split: Boolean
},
render: function render (h) {
var this$1 = this;
var
Popover = h(
QPopover,
{
ref: 'popover',
props: {
value: this.value,
disable: this.disable,
fit: true,
anchorClick: !this.split,
anchor: 'bottom right',
self: 'top right'
},
on: {
show: function (e) {
this$1.$emit('show', e);
this$1.$emit('input', true);
},
hide: function (e) {
this$1.$emit('hide', e);
this$1.$emit('input', false);
}
}
},
[ this.$slots.default ]
),
Icon = h(
'q-icon',
{
props: {
name: this.$q.icon.input.dropdown
},
staticClass: 'transition-generic',
'class': {
'rotate-180': this.showing,
'on-right': !this.split,
'q-btn-dropdown-arrow': !this.split
}
}
),
Btn = h(QBtn, {
props: {
disable: this.disable,
noCaps: this.noCaps,
noWrap: this.noWrap,
icon: this.icon,
label: this.label,
iconRight: this.split ? this.iconRight : null,
outline: this.outline,
flat: this.flat,
rounded: this.rounded,
push: this.push,
size: this.size,
color: this.color,
textColor: this.textColor,
glossy: this.glossy,
dense: this.dense,
noRipple: this.noRipple,
waitForRipple: this.waitForRipple
},
'class': this.split ? 'q-btn-dropdown-current' : 'q-btn-dropdown q-btn-dropdown-simple',
on: {
click: function (e) {
this$1.split && this$1.hide();
if (!this$1.disable) {
this$1.$emit('click', e);
}
}
}
}, this.split ? null : [ Icon, Popover ]);
if (!this.split) {
return Btn
}
return h(
QBtnGroup,
{
props: {
outline: this.outline,
flat: this.flat,
rounded: this.rounded,
push: this.push
},
staticClass: 'q-btn-dropdown q-btn-dropdown-split no-wrap'
},
[
Btn,
h(
QBtn,
{
props: {
disable: this.disable,
flat: this.flat,
rounded: this.rounded,
push: this.push,
size: this.size,
color: this.color,
textColor: this.textColor,
dense: this.dense,
glossy: this.glossy,
noRipple: this.noRipple,
waitForRipple: this.waitForRipple
},
staticClass: 'q-btn-dropdown-arrow',
on: { click: function () { this$1.toggle(); } }
},
[ Icon ]
),
[ Popover ]
]
)
},
methods: {
toggle: function toggle () {
return this.$refs.popover.toggle()
},
show: function show () {
return this.$refs.popover.show()
},
hide: function hide () {
return this.$refs.popover.hide()
}
}
}
var QBtnToggle = {
name: 'q-btn-toggle',
props: {
value: {
required: true
},
// To avoid seeing the active raise shadow through the transparent button, give it a color (even white).
color: String,
textColor: String,
toggleColor: {
type: String,
default: 'primary'
},
textToggleColor: String,
options: {
type: Array,
required: true,
validator: function (v) { return v.every(function (opt) { return ('label' in opt || 'icon' in opt) && 'value' in opt; }); }
},
readonly: Boolean,
disable: Boolean,
noCaps: Boolean,
noWrap: Boolean,
outline: Boolean,
flat: Boolean,
dense: Boolean,
rounded: Boolean,
push: Boolean,
size: String,
glossy: Boolean,
noRipple: Boolean,
waitForRipple: Boolean
},
computed: {
val: function val () {
var this$1 = this;
return this.options.map(function (opt) { return opt.value === this$1.value; })
}
},
methods: {
set: function set (value, opt) {
var this$1 = this;
if (this.readonly) {
return
}
this.$emit('input', value, opt);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value, opt);
}
});
}
},
render: function render (h) {
var this$1 = this;
return h(QBtnGroup, {
staticClass: 'q-btn-toggle',
props: {
outline: this.outline,
flat: this.flat,
rounded: this.rounded,
push: this.push
}
},
this.options.map(
function (opt, i) { return h(QBtn, {
key: ("" + (opt.label) + (opt.icon) + (opt.iconRight)),
on: { click: function () { return this$1.set(opt.value, opt); } },
props: {
disable: this$1.disable,
label: opt.label,
// Colors come from the button specific options first, then from general props
color: this$1.val[i] ? opt.toggleColor || this$1.toggleColor : opt.color || this$1.color,
textColor: this$1.val[i] ? opt.textToggleColor || this$1.textToggleColor : opt.textColor || this$1.textColor,
icon: opt.icon,
iconRight: opt.iconRight,
noCaps: this$1.noCaps,
noWrap: this$1.noWrap,
outline: this$1.outline,
flat: this$1.flat,
rounded: this$1.rounded,
push: this$1.push,
glossy: this$1.glossy,
size: this$1.size,
dense: this$1.dense,
noRipple: this$1.noRipple,
waitForRipple: this$1.waitForRipple,
tabindex: opt.tabindex
}
}); }
))
}
}
var QAlert = {
name: 'q-alert',
props: {
type: {
type: String,
validator: function (v) { return ['positive', 'negative', 'warning', 'info'].includes(v); }
},
color: {
type: String,
default: 'negative'
},
textColor: String,
message: String,
detail: String,
icon: String,
avatar: String,
actions: Array
},
computed: {
computedIcon: function computedIcon () {
return this.icon
? this.icon
: this.$q.icon.type[this.type || this.color]
},
classes: function classes () {
return ("bg-" + (this.type || this.color) + " text-" + (this.textColor || 'white'))
}
},
render: function render (h) {
var this$1 = this;
var side = [];
if (this.avatar) {
side.push(
h('img', {
staticClass: 'avatar',
domProps: { src: this.avatar }
})
);
}
else if (this.icon || this.type) {
side.push(
h(QIcon, {
props: { name: this.computedIcon }
})
);
}
return h('div', [
h('div', {
staticClass: 'q-alert row no-wrap shadow-2',
'class': this.classes
}, [
side.length
? h('div', { staticClass: 'q-alert-side col-auto row flex-center' }, side)
: null,
h('div', {
staticClass: 'q-alert-content col self-center'
}, [
h('div', this.$slots.default || this.message),
this.detail ? h('div', { staticClass: 'q-alert-detail' }, [ this.detail ]) : null
]),
this.actions && this.actions.length
? h('div', {
staticClass: 'q-alert-actions col-auto gutter-xs column flex-center'
},
this.actions.map(function (action) { return h('div', [
h(QBtn, {
staticClass: 'full-width',
props: {
flat: true,
dense: true,
icon: action.icon,
align: 'left',
label: action.closeBtn === true
? (typeof action.label === 'string' ? action.label : this$1.$q.i18n.label.close)
: action.label
},
on: {
click: function () { return action.handler(); }
}
})
]); }
))
: null
])
])
}
}
function filter (terms, ref) {
var field = ref.field;
var list = ref.list;
var token = terms.toLowerCase();
return list.filter(function (item) { return ('' + item[field]).toLowerCase().startsWith(token); })
}
function s4 () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
}
function uid () {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4()
}
var QAutocomplete = {
name: 'q-autocomplete',
props: {
minCharacters: {
type: Number,
default: 1
},
maxResults: {
type: Number,
default: 6
},
debounce: {
type: Number,
default: 500
},
filter: {
type: Function,
default: filter
},
staticData: Object,
separator: Boolean
},
inject: {
__input: {
default: function default$1 () {
console.error('QAutocomplete needs to be child of QInput or QSearch');
}
},
__inputDebounce: { default: null }
},
data: function data () {
return {
searchId: '',
results: [],
selectedIndex: -1,
width: 0,
enterKey: false,
timer: null
}
},
watch: {
'__input.val': function _input_val () {
if (this.enterKey) {
this.enterKey = false;
}
else {
this.__delayTrigger();
}
}
},
computed: {
computedResults: function computedResults () {
return this.maxResults && this.results.length > 0
? this.results.slice(0, this.maxResults)
: []
},
computedWidth: function computedWidth () {
return {minWidth: this.width}
},
searching: function searching () {
return this.searchId.length > 0
}
},
methods: {
isWorking: function isWorking () {
return this.$refs && this.$refs.popover
},
trigger: function trigger () {
var this$1 = this;
if (!this.__input.hasFocus() || !this.isWorking()) {
return
}
var terms = [null, void 0].includes(this.__input.val) ? '' : String(this.__input.val);
var searchId = uid();
this.searchId = searchId;
if (terms.length < this.minCharacters) {
this.searchId = '';
this.__clearSearch();
this.hide();
return
}
this.width = width(this.inputEl) + 'px';
if (this.staticData) {
this.searchId = '';
this.results = this.filter(terms, this.staticData);
var popover = this.$refs.popover;
if (this.results.length) {
this.selectedIndex = 0;
if (popover.showing) {
popover.reposition();
}
else {
popover.show();
}
}
else {
popover.hide();
}
return
}
this.__input.loading = true;
this.$emit('search', terms, function (results) {
if (!this$1.isWorking() || this$1.searchId !== searchId) {
return
}
this$1.__clearSearch();
if (Array.isArray(results) && results.length > 0) {
this$1.results = results;
this$1.selectedIndex = 0;
this$1.$refs.popover.show();
return
}
this$1.hide();
});
},
hide: function hide () {
this.results = [];
this.selectedIndex = -1;
return this.isWorking()
? this.$refs.popover.hide()
: Promise.resolve()
},
blurHide: function blurHide () {
var this$1 = this;
this.__clearSearch();
setTimeout(function () { return this$1.hide(); }, 300);
},
__clearSearch: function __clearSearch () {
clearTimeout(this.timer);
this.__input.loading = false;
this.searchId = '';
},
setValue: function setValue (result) {
var value = this.staticData ? result[this.staticData.field] : result.value;
var suffix = this.__inputDebounce ? 'Debounce' : '';
if (this.inputEl && this.__input && !this.__input.hasFocus()) {
this.inputEl.focus();
}
this.enterKey = this.__input && value !== this.__input.val;
this[("__input" + suffix)].set(value);
this.$emit('selected', result);
this.__clearSearch();
this.hide();
},
move: function move (offset$$1) {
this.selectedIndex = normalizeToInterval(
this.selectedIndex + offset$$1,
0,
this.computedResults.length - 1
);
},
setCurrentSelection: function setCurrentSelection () {
if (this.selectedIndex >= 0 && this.selectedIndex < this.results.length) {
this.setValue(this.results[this.selectedIndex]);
}
},
__delayTrigger: function __delayTrigger () {
this.__clearSearch();
if (!this.__input.hasFocus()) {
return
}
if (this.staticData) {
this.trigger();
return
}
this.timer = setTimeout(this.trigger, this.debounce);
},
__handleKeyDown: function __handleKeyDown (e) {
switch (getEventKey(e)) {
case 38: // UP key
this.__moveCursor(-1, e);
break
case 40: // DOWN key
this.__moveCursor(1, e);
break
case 13: // ENTER key
case 32: // SPACE key
if (this.$refs.popover.showing) {
stopAndPrevent(e);
this.setCurrentSelection();
}
break
case 27: // ESCAPE key
this.__clearSearch();
break
case 9: // TAB key
this.hide();
break
}
},
__moveCursor: function __moveCursor (offset$$1, e) {
stopAndPrevent(e);
if (!this.$refs.popover.showing) {
this.trigger();
}
else {
this.move(offset$$1);
}
}
},
mounted: function mounted () {
var this$1 = this;
this.__input.register();
if (this.__inputDebounce) {
this.__inputDebounce.setChildDebounce(true);
}
this.$nextTick(function () {
this$1.inputEl = this$1.__input.getEl();
this$1.inputEl.addEventListener('keydown', this$1.__handleKeyDown);
this$1.inputEl.addEventListener('blur', this$1.blurHide);
});
},
beforeDestroy: function beforeDestroy () {
this.__clearSearch();
this.__input.unregister();
if (this.__inputDebounce) {
this.__inputDebounce.setChildDebounce(false);
}
if (this.inputEl) {
this.inputEl.removeEventListener('keydown', this.__handleKeyDown);
this.inputEl.removeEventListener('blur', this.blurHide);
this.hide();
}
},
render: function render (h) {
var this$1 = this;
return h(QPopover, {
ref: 'popover',
props: {
fit: true,
offset: [0, 10],
anchorClick: false
},
on: {
show: function () { return this$1.$emit('show'); },
hide: function () { return this$1.$emit('hide'); }
}
}, [
h(QList, {
props: {
noBorder: true,
separator: this.separator
},
style: this.computedWidth
},
this.computedResults.map(function (result, index) { return h(QItemWrapper, {
key: result.id || JSON.stringify(result),
'class': {
active: this$1.selectedIndex === index,
'cursor-pointer': !result.disable
},
props: { cfg: result },
nativeOn: {
mouseenter: function () { !result.disable && (this$1.selectedIndex = index); },
click: function () { !result.disable && this$1.setValue(result); }
}
}); }))
])
}
}
var QBreadcrumbs = {
name: 'q-breadcrumbs',
mixins: [AlignMixin],
props: {
color: {
type: String,
default: 'faded'
},
activeColor: {
type: String,
default: 'primary'
},
separator: {
type: String,
default: '/'
},
align: {
default: 'left'
}
},
computed: {
classes: function classes () {
return [("text-" + (this.color)), this.alignClass]
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
length = this.$slots.default.length - 1,
separator = this.$scopedSlots.separator || (function () { return this$1.separator; }),
color = "text-" + (this.color),
active = "text-" + (this.activeColor);
this.$slots.default.forEach(function (comp, i) {
if (comp.componentOptions && comp.componentOptions.tag === 'q-breadcrumbs-el') {
var middle = i < length;
child.push(h('div', {
'class': [ middle ? active : color, middle ? 'text-weight-bold' : 'q-breadcrumbs-last' ]
}, [ comp ]));
if (middle) {
child.push(h('div', { staticClass: "q-breadcrumbs-separator", 'class': color }, [ separator() ]));
}
}
else {
child.push(comp);
}
});
return h('div', {
staticClass: 'q-breadcrumbs flex gutter-xs items-center overflow-hidden',
'class': this.classes
}, child)
}
}
var QBreadcrumbsEl = {
name: 'q-breadcrumbs-el',
mixins: [{ props: RouterLinkMixin.props }],
props: {
label: String,
icon: String,
color: String,
noRipple: Boolean
},
computed: {
link: function link () {
return this.to !== void 0
}
},
render: function render (h) {
return h(this.link ? 'router-link' : 'span', {
staticClass: 'q-breadcrumbs-el flex inline items-center relative-position',
props: this.link
? {
to: this.to,
exact: this.exact,
append: this.append,
replace: this.replace
}
: null
},
this.label || this.icon
? [
this.icon ? h(QIcon, { staticClass: 'q-breacrumbs-el-icon q-mr-sm', props: { name: this.icon } }) : null,
this.label
]
: [ this.$slots.default ]
)
}
}
var QCard = {
name: 'q-card',
props: {
square: Boolean,
flat: Boolean,
inline: Boolean,
color: String,
textColor: String
},
computed: {
classes: function classes () {
var cls = [{
'no-border-radius': this.square,
'no-shadow': this.flat,
'inline-block': this.inline
}];
if (this.color) {
cls.push(("bg-" + (this.color)));
cls.push("q-card-dark");
cls.push(("text-" + (this.textColor || 'white')));
}
else if (this.textColor) {
cls.push(("text-" + (this.textColor)));
}
return cls
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-card',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QCardTitle = {
name: 'q-card-title',
render: function render (h) {
return h('div', {
staticClass: 'q-card-primary q-card-container row no-wrap'
}, [
h('div', {staticClass: 'col column'}, [
h('div', {staticClass: 'q-card-title'}, [ this.$slots.default ]),
h('div', {staticClass: 'q-card-subtitle'}, [ this.$slots.subtitle ])
]),
h('div', {staticClass: 'col-auto self-center q-card-title-extra'}, [ this.$slots.right ])
])
}
}
var QCardMain = {
name: 'q-card-main',
render: function render (h) {
return h('div', {
staticClass: 'q-card-main q-card-container'
}, [
this.$slots.default
])
}
}
var QCardActions = {
name: 'q-card-actions',
props: {
vertical: Boolean,
align: {
type: String,
default: 'start',
validator: function (v) { return ['start', 'center', 'end', 'around', 'between'].includes(v); }
}
},
computed: {
classes: function classes () {
return "q-card-actions-" + (this.vertical ? 'vert column justify-start' : 'horiz row') + " " +
(this.vertical ? 'items' : 'justify') + "-" + (this.align)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-card-actions',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QCardMedia = {
name: 'q-card-media',
props: {
overlayPosition: {
type: String,
default: 'bottom',
validator: function (v) { return ['top', 'bottom', 'full'].includes(v); }
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-card-media relative-position'
}, [
this.$slots.default,
this.$slots.overlay
? h('div', {
staticClass: 'q-card-media-overlay',
'class': ("absolute-" + (this.overlayPosition))
}, [
this.$slots.overlay
])
: null
])
}
}
var QCardSeparator = {
name: 'q-card-separator',
props: {
inset: Boolean
},
render: function render (h) {
return h('div', {
staticClass: 'q-card-separator',
'class': { inset: this.inset }
}, [
this.$slots.default
])
}
}
function getDirection (mod) {
if (!mod.horizontal && !mod.vertical) {
return {
horizontal: true,
vertical: true
}
}
var dir = {};['horizontal', 'vertical'].forEach(function (direction) {
if (mod[direction]) {
dir[direction] = true;
}
});
return dir
}
function processChanges (evt, ctx, isFinal) {
var
direction,
pos = position(evt),
distX = pos.left - ctx.event.x,
distY = pos.top - ctx.event.y,
absDistX = Math.abs(distX),
absDistY = Math.abs(distY);
if (ctx.direction.horizontal && !ctx.direction.vertical) {
direction = distX < 0 ? 'left' : 'right';
}
else if (!ctx.direction.horizontal && ctx.direction.vertical) {
direction = distY < 0 ? 'up' : 'down';
}
else if (absDistX >= absDistY) {
direction = distX < 0 ? 'left' : 'right';
}
else {
direction = distY < 0 ? 'up' : 'down';
}
return {
evt: evt,
position: pos,
direction: direction,
isFirst: ctx.event.isFirst,
isFinal: Boolean(isFinal),
duration: new Date().getTime() - ctx.event.time,
distance: {
x: absDistX,
y: absDistY
},
delta: {
x: pos.left - ctx.event.lastX,
y: pos.top - ctx.event.lastY
}
}
}
function shouldTrigger (ctx, changes) {
if (ctx.direction.horizontal && ctx.direction.vertical) {
return true
}
if (ctx.direction.horizontal && !ctx.direction.vertical) {
return Math.abs(changes.delta.x) > 0
}
if (!ctx.direction.horizontal && ctx.direction.vertical) {
return Math.abs(changes.delta.y) > 0
}
}
var TouchPan = {
name: 'touch-pan',
bind: function bind (el, binding) {
var
mouse = !binding.modifiers.noMouse,
stopPropagation = binding.modifiers.stop,
preventDefault = binding.modifiers.prevent,
evtOpts = preventDefault || binding.modifiers.mightPrevent ? null : listenOpts.passive;
var ctx = {
handler: binding.value,
direction: getDirection(binding.modifiers),
mouseStart: function mouseStart (evt) {
if (leftClick(evt)) {
document.addEventListener('mousemove', ctx.move, evtOpts);
document.addEventListener('mouseup', ctx.mouseEnd, evtOpts);
ctx.start(evt);
}
},
mouseEnd: function mouseEnd (evt) {
document.removeEventListener('mousemove', ctx.move, evtOpts);
document.removeEventListener('mouseup', ctx.mouseEnd, evtOpts);
ctx.end(evt);
},
start: function start (evt) {
var pos = position(evt);
ctx.event = {
x: pos.left,
y: pos.top,
time: new Date().getTime(),
detected: ctx.direction.horizontal && ctx.direction.vertical,
abort: false,
isFirst: true,
lastX: pos.left,
lastY: pos.top
};
if (ctx.event.detected) {
stopPropagation && evt.stopPropagation();
preventDefault && evt.preventDefault();
}
},
move: function move (evt) {
if (ctx.event.abort) {
return
}
if (ctx.event.detected) {
stopPropagation && evt.stopPropagation();
preventDefault && evt.preventDefault();
var changes = processChanges(evt, ctx, false);
if (shouldTrigger(ctx, changes)) {
ctx.handler(changes);
ctx.event.lastX = changes.position.left;
ctx.event.lastY = changes.position.top;
ctx.event.isFirst = false;
}
return
}
var
pos = position(evt),
distX = Math.abs(pos.left - ctx.event.x),
distY = Math.abs(pos.top - ctx.event.y);
if (distX === distY) {
return
}
ctx.event.detected = true;
ctx.event.abort = ctx.direction.vertical
? distX > distY
: distX < distY;
ctx.move(evt);
},
end: function end (evt) {
if (ctx.event.abort || !ctx.event.detected || ctx.event.isFirst) {
return
}
stopPropagation && evt.stopPropagation();
preventDefault && evt.preventDefault();
ctx.handler(processChanges(evt, ctx, true));
}
};
el.__qtouchpan = ctx;
el.classList.add('q-touch');
if (mouse) {
el.addEventListener('mousedown', ctx.mouseStart, evtOpts);
}
el.addEventListener('touchstart', ctx.start, evtOpts);
el.addEventListener('touchmove', ctx.move, evtOpts);
el.addEventListener('touchend', ctx.end, evtOpts);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
el.__qtouchpan.handler = binding.value;
}
},
unbind: function unbind (el, binding) {
var ctx = el.__qtouchpan;
var evtOpts = binding.modifiers.prevent ? null : listenOpts.passive;
el.removeEventListener('mousedown', ctx.mouseStart, evtOpts);
el.removeEventListener('touchstart', ctx.start, evtOpts);
el.removeEventListener('touchmove', ctx.move, evtOpts);
el.removeEventListener('touchend', ctx.end, evtOpts);
delete el.__qtouchpan;
}
}
function isDate (v) {
return Object.prototype.toString.call(v) === '[object Date]'
}
function isNumber (v) {
return typeof v === 'number' && isFinite(v)
}
var linear = function (t) { return t; };
var easeInQuad = function (t) { return t * t; };
var easeOutQuad = function (t) { return t * (2 - t); };
var easeInOutQuad = function (t) { return t < 0.5
? 2 * t * t
: -1 + (4 - 2 * t) * t; };
var easeInCubic = function (t) { return Math.pow( t, 3 ); };
var easeOutCubic = function (t) { return 1 + Math.pow( (t - 1), 3 ); };
var easeInOutCubic = function (t) { return t < 0.5
? 4 * Math.pow( t, 3 )
: 1 + (t - 1) * Math.pow( (2 * t - 2), 2 ); };
var easeInQuart = function (t) { return Math.pow( t, 4 ); };
var easeOutQuart = function (t) { return 1 - Math.pow( (t - 1), 4 ); };
var easeInOutQuart = function (t) { return t < 0.5
? 8 * Math.pow( t, 4 )
: 1 - 8 * Math.pow( (t - 1), 4 ); };
var easeInQuint = function (t) { return Math.pow( t, 5 ); };
var easeOutQuint = function (t) { return 1 + Math.pow( (t - 1), 5 ); };
var easeInOutQuint = function (t) { return t < 0.5
? 16 * Math.pow( t, 5 )
: 1 + 16 * Math.pow( (t - 1), 5 ); };
var easeInCirc = function (t) { return -1 * Math.sqrt(1 - Math.pow( t, 2 )) + 1; };
var easeOutCirc = function (t) { return Math.sqrt(-1 * (t - 2) * t); };
var easeInOutCirc = function (t) { return t < 0.5
? 0.5 * (1 - Math.sqrt(1 - 4 * t * t))
: 0.5 * (1 + Math.sqrt(-3 + 8 * t - 4 * t * t)); };
var overshoot = function (t) { return -1 * (Math.pow( Math.E, (-6.3 * t) )) * (Math.cos(5 * t)) + 1; };
/* -- Material Design curves -- */
/**
* Faster ease in, slower ease out
*/
var standard = function (t) { return t < 0.4031
? 12 * Math.pow( t, 4 )
: 1 / 1290 * (11 * Math.sqrt(-40000 * t * t + 80000 * t - 23359) - 129); };
var decelerate = easeOutCubic;
var accelerate = easeInCubic;
var sharp = easeInOutQuad;
var easing = Object.freeze({
linear: linear,
easeInQuad: easeInQuad,
easeOutQuad: easeOutQuad,
easeInOutQuad: easeInOutQuad,
easeInCubic: easeInCubic,
easeOutCubic: easeOutCubic,
easeInOutCubic: easeInOutCubic,
easeInQuart: easeInQuart,
easeOutQuart: easeOutQuart,
easeInOutQuart: easeInOutQuart,
easeInQuint: easeInQuint,
easeOutQuint: easeOutQuint,
easeInOutQuint: easeInOutQuint,
easeInCirc: easeInCirc,
easeOutCirc: easeOutCirc,
easeInOutCirc: easeInOutCirc,
overshoot: overshoot,
standard: standard,
decelerate: decelerate,
accelerate: accelerate,
sharp: sharp
});
var ids = {};
function start (ref) {
var name = ref.name;
var duration = ref.duration; if ( duration === void 0 ) duration = 300;
var to = ref.to;
var from = ref.from;
var apply = ref.apply;
var done = ref.done;
var cancel = ref.cancel;
var easing = ref.easing;
var id = name;
var start = performance.now();
if (id) {
stop(id);
}
else {
id = uid();
}
var delta = easing || linear;
var handler = function () {
var progress = (performance.now() - start) / duration;
if (progress > 1) {
progress = 1;
}
var newPos = from + (to - from) * delta(progress);
apply(newPos, progress);
if (progress === 1) {
delete ids[id];
done && done(newPos);
return
}
anim.last = {
pos: newPos,
progress: progress
};
anim.timer = window.requestAnimationFrame(handler);
};
var anim = ids[id] = {
cancel: cancel,
timer: window.requestAnimationFrame(handler)
};
return id
}
function stop (id) {
if (!id) {
return
}
var anim = ids[id];
if (anim && anim.timer) {
cancelAnimationFrame(anim.timer);
anim.cancel && anim.cancel(anim.last);
delete ids[id];
}
}
var animate = Object.freeze({
start: start,
stop: stop
});
var FullscreenMixin = {
data: function data () {
return {
inFullscreen: false
}
},
watch: {
$route: function $route () {
this.exitFullscreen();
}
},
methods: {
toggleFullscreen: function toggleFullscreen () {
if (this.inFullscreen) {
this.exitFullscreen();
}
else {
this.setFullscreen();
}
},
setFullscreen: function setFullscreen () {
if (this.inFullscreen) {
return
}
this.inFullscreen = true;
this.container = this.$el.parentNode;
this.container.replaceChild(this.fullscreenFillerNode, this.$el);
document.body.appendChild(this.$el);
document.body.classList.add('with-mixin-fullscreen');
this.__historyFullscreen = {
handler: this.exitFullscreen
};
History.add(this.__historyFullscreen);
},
exitFullscreen: function exitFullscreen () {
if (!this.inFullscreen) {
return
}
if (this.__historyFullscreen) {
History.remove(this.__historyFullscreen);
this.__historyFullscreen = null;
}
this.container.replaceChild(this.$el, this.fullscreenFillerNode);
document.body.classList.remove('with-mixin-fullscreen');
this.inFullscreen = false;
}
},
created: function created () {
this.fullscreenFillerNode = document.createElement('span');
},
beforeDestroy: function beforeDestroy () {
this.exitFullscreen();
}
}
var QCarousel = {
name: 'q-carousel',
mixins: [FullscreenMixin],
directives: {
TouchPan: TouchPan
},
props: {
value: Number,
color: {
type: String,
default: 'primary'
},
height: String,
arrows: Boolean,
infinite: Boolean,
animation: {
type: [Number, Boolean],
default: true
},
easing: Function,
swipeEasing: Function,
noSwipe: Boolean,
autoplay: [Number, Boolean],
handleArrowKeys: Boolean,
quickNav: Boolean,
quickNavIcon: String
},
provide: function provide () {
return {
'carousel': this
}
},
data: function data () {
return {
position: 0,
slide: 0,
positionSlide: 0,
slidesNumber: 0,
animUid: false
}
},
watch: {
value: function value (v) {
if (v !== this.slide) {
this.goToSlide(v);
}
},
autoplay: function autoplay () {
this.__planAutoPlay();
},
infinite: function infinite () {
this.__planAutoPlay();
},
handleArrowKeys: function handleArrowKeys (v) {
this.__setArrowKeys(v);
}
},
computed: {
trackPosition: function trackPosition () {
return cssTransform(("translateX(" + (this.position) + "%)"))
},
infiniteLeft: function infiniteLeft () {
return this.infinite && this.slidesNumber > 1 && this.positionSlide < 0
},
infiniteRight: function infiniteRight () {
return this.infinite && this.slidesNumber > 1 && this.positionSlide >= this.slidesNumber
},
canGoToPrevious: function canGoToPrevious () {
return this.infinite ? this.slidesNumber > 1 : this.slide > 0
},
canGoToNext: function canGoToNext () {
return this.infinite ? this.slidesNumber > 1 : this.slide < this.slidesNumber - 1
},
computedQuickNavIcon: function computedQuickNavIcon () {
return this.quickNavIcon || this.$q.icon.carousel.quickNav
},
computedStyle: function computedStyle () {
if (!this.inFullscreen && this.height) {
return ("height: " + (this.height))
}
},
slotScope: function slotScope () {
return {
slide: this.slide,
slidesNumber: this.slidesNumber,
percentage: this.slidesNumber < 2
? 100
: 100 * this.slide / (this.slidesNumber - 1),
goToSlide: this.goToSlide,
previous: this.previous,
next: this.next,
color: this.color,
inFullscreen: this.inFullscreen,
toggleFullscreen: this.toggleFullscreen,
canGoToNext: this.canGoToNext,
canGoToPrevious: this.canGoToPrevious
}
}
},
methods: {
previous: function previous () {
return this.canGoToPrevious
? this.goToSlide(this.slide - 1)
: Promise.resolve()
},
next: function next () {
return this.canGoToNext
? this.goToSlide(this.slide + 1)
: Promise.resolve()
},
goToSlide: function goToSlide (slide, fromSwipe) {
var this$1 = this;
if ( fromSwipe === void 0 ) fromSwipe = false;
return new Promise(function (resolve, reject) {
var
direction = '',
pos;
this$1.__cleanup();
var finish = function () {
this$1.$emit('input', this$1.slide);
this$1.$emit('slide-direction', direction);
this$1.__planAutoPlay();
resolve();
};
if (this$1.slidesNumber < 2) {
this$1.slide = 0;
this$1.positionSlide = 0;
pos = 0;
}
else {
if (!this$1.hasOwnProperty('initialPosition')) {
this$1.position = -this$1.slide * 100;
}
direction = slide > this$1.slide ? 'next' : 'previous';
if (this$1.infinite) {
this$1.slide = normalizeToInterval(slide, 0, this$1.slidesNumber - 1);
pos = normalizeToInterval(slide, -1, this$1.slidesNumber);
if (!fromSwipe) {
this$1.positionSlide = pos;
}
}
else {
this$1.slide = between(slide, 0, this$1.slidesNumber - 1);
this$1.positionSlide = this$1.slide;
pos = this$1.slide;
}
}
pos = pos * -100;
if (!this$1.animation) {
this$1.position = pos;
finish();
return
}
this$1.animationInProgress = true;
this$1.animUid = start({
from: this$1.position,
to: pos,
duration: isNumber(this$1.animation) ? this$1.animation : 300,
easing: fromSwipe
? this$1.swipeEasing || decelerate
: this$1.easing || standard,
apply: function (pos) {
this$1.position = pos;
},
done: function () {
if (this$1.infinite) {
this$1.position = -this$1.slide * 100;
this$1.positionSlide = this$1.slide;
}
this$1.animationInProgress = false;
finish();
}
});
})
},
stopAnimation: function stopAnimation () {
stop(this.animUid);
this.animationInProgress = false;
},
__pan: function __pan (event) {
var this$1 = this;
if (this.infinite && this.animationInProgress) {
return
}
if (event.isFirst) {
this.initialPosition = this.position;
this.__cleanup();
}
var delta = (event.direction === 'left' ? -1 : 1) * event.distance.x;
if (
(this.infinite && this.slidesNumber < 2) ||
(
!this.infinite &&
(
(this.slide === 0 && delta > 0) ||
(this.slide === this.slidesNumber - 1 && delta < 0)
)
)
) {
delta = delta / 10;
}
this.position = this.initialPosition + delta / this.$refs.track.offsetWidth * 100;
this.positionSlide = (event.direction === 'left' ? this.slide + 1 : this.slide - 1);
if (event.isFinal) {
this.goToSlide(
event.distance.x < 40
? this.slide
: this.positionSlide,
true
).then(function () {
delete this$1.initialPosition;
});
}
},
__planAutoPlay: function __planAutoPlay () {
var this$1 = this;
this.$nextTick(function () {
if (this$1.autoplay) {
clearTimeout(this$1.timer);
this$1.timer = setTimeout(
this$1.next,
isNumber(this$1.autoplay) ? this$1.autoplay : 5000
);
}
});
},
__cleanup: function __cleanup () {
this.stopAnimation();
clearTimeout(this.timer);
},
__handleArrowKey: function __handleArrowKey (e) {
var key = getEventKey(e);
if (key === 37) { // left arrow key
this.previous();
}
else if (key === 39) { // right arrow key
this.next();
}
},
__setArrowKeys: function __setArrowKeys (/* boolean */ state) {
var op = (state === true ? 'add' : 'remove') + "EventListener";
document[op]('keydown', this.__handleArrowKey);
},
__registerSlide: function __registerSlide () {
this.slidesNumber++;
},
__unregisterSlide: function __unregisterSlide () {
this.slidesNumber--;
},
__getScopedSlots: function __getScopedSlots (h) {
var this$1 = this;
if (this.slidesNumber === 0) {
return
}
var slots = this.$scopedSlots;
if (slots) {
return Object.keys(slots)
.filter(function (key) { return key.startsWith('control-'); })
.map(function (key) { return slots[key](this$1.slotScope); })
}
},
__getQuickNav: function __getQuickNav (h) {
var this$1 = this;
if (this.slidesNumber === 0 || !this.quickNav) {
return
}
var
slot = this.$scopedSlots['quick-nav'],
items = [];
if (slot) {
var loop = function ( i ) {
items.push(slot({
slide: i,
before: i < this$1.slide,
current: i === this$1.slide,
after: i > this$1.slide,
color: this$1.color,
goToSlide: function (slide) { this$1.goToSlide(slide || i); }
}));
};
for (var i = 0; i < this.slidesNumber; i++) loop( i );
}
else {
var loop$1 = function ( i ) {
items.push(h(QBtn, {
key: i,
'class': { inactive: i !== this$1.slide },
props: {
icon: this$1.computedQuickNavIcon,
round: true,
flat: true,
dense: true,
color: this$1.color
},
on: {
click: function () {
this$1.goToSlide(i);
}
}
}));
};
for (var i$1 = 0; i$1 < this.slidesNumber; i$1++) loop$1( i$1 );
}
return h('div', {
staticClass: 'q-carousel-quick-nav absolute-bottom scroll text-center',
'class': ("text-" + (this.color))
}, items)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-carousel',
style: this.computedStyle,
'class': { fullscreen: this.inFullscreen }
}, [
h('div', {
staticClass: 'q-carousel-inner',
directives: this.noSwipe
? null
: [{
name: 'touch-pan',
modifiers: {
horizontal: true,
prevent: true,
stop: true
},
value: this.__pan
}]
}, [
h('div', {
ref: 'track',
staticClass: 'q-carousel-track',
style: this.trackPosition,
'class': {
'infinite-left': this.infiniteLeft,
'infinite-right': this.infiniteRight
}
}, [
h('div', { staticClass: 'q-carousel-slide', style: ("flex: 0 0 " + (100) + "%"), directives: [{ name: 'show', value: this.infiniteRight }] }),
this.$slots.default,
h('div', { staticClass: 'q-carousel-slide', style: ("flex: 0 0 " + (100) + "%"), directives: [{ name: 'show', value: this.infiniteLeft }] })
])
]),
this.arrows ? h(QBtn, {
staticClass: 'q-carousel-left-arrow absolute',
props: { color: this.color, icon: this.$q.icon.carousel.left, fabMini: true, flat: true },
directives: [{ name: 'show', value: this.canGoToPrevious }],
on: { click: this.previous }
}) : null,
this.arrows ? h(QBtn, {
staticClass: 'q-carousel-right-arrow absolute',
props: { color: this.color, icon: this.$q.icon.carousel.right, fabMini: true, flat: true },
directives: [{ name: 'show', value: this.canGoToNext }],
on: { click: this.next }
}) : null,
this.__getQuickNav(h),
this.__getScopedSlots(h),
this.$slots.control
])
},
mounted: function mounted () {
var this$1 = this;
this.__planAutoPlay();
if (this.handleArrowKeys) {
this.__setArrowKeys(true);
}
this.__stopSlideNumberNotifier = this.$watch('slidesNumber', function (val) {
this$1.$emit('slides-number', val);
if (this$1.value >= val) {
this$1.$emit('input', val - 1);
}
}, { immediate: true });
},
beforeDestroy: function beforeDestroy () {
this.__cleanup();
this.__stopSlideNumberNotifier();
if (this.handleArrowKeys) {
this.__setArrowKeys(false);
}
}
}
var QCarouselSlide = {
name: 'q-carousel-slide',
inject: {
carousel: {
default: function default$1 () {
console.error('QCarouselSlide needs to be child of QCarousel');
}
}
},
props: {
imgSrc: String
},
computed: {
computedStyle: function computedStyle () {
var style = {};
if (this.imgSrc) {
style.backgroundImage = "url(" + (this.imgSrc) + ")";
style.backgroundSize = "cover";
style.backgroundPosition = "50%";
}
if (!this.carousel.inFullscreen && this.carousel.height) {
style.maxHeight = this.carousel.height;
}
return style
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-carousel-slide relative-position scroll',
style: this.computedStyle
}, this.$slots.default)
},
created: function created () {
this.carousel.__registerSlide();
},
beforeDestroy: function beforeDestroy () {
this.carousel.__unregisterSlide();
}
}
var QCarouselControl = {
name: 'q-carousel-control',
props: {
position: {
type: String,
default: 'bottom-right'
},
offset: {
type: Array,
default: function () { return [18, 18]; }
}
},
computed: {
computedClass: function computedClass () {
return ("absolute-" + (this.position))
},
computedStyle: function computedStyle () {
return {
margin: ((this.offset[1]) + "px " + (this.offset[0]) + "px")
}
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-carousel-control absolute',
style: this.computedStyle,
'class': this.computedClass
}, this.$slots.default)
}
}
var QChatMessage = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-message",class:{ 'q-message-sent': _vm.sent, 'q-message-received': !_vm.sent }},[(_vm.label)?_c('p',{staticClass:"q-message-label text-center",domProps:{"innerHTML":_vm._s(_vm.label)}}):_vm._e(),_vm._v(" "),_c('div',{staticClass:"q-message-container row items-end no-wrap"},[(_vm.hasAvatarSlot())?_vm._t("avatar"):_vm._e(),_vm._v(" "),(_vm.avatar && !_vm.hasAvatarSlot())?_c('img',{staticClass:"q-message-avatar",attrs:{"src":_vm.avatar}}):_vm._e(),_vm._v(" "),_c('div',{class:_vm.sizeClass},[(_vm.name)?_c('div',{staticClass:"q-message-name",domProps:{"innerHTML":_vm._s(_vm.name)}}):_vm._e(),_vm._v(" "),(_vm.text)?_vm._l((_vm.text),function(msg,index){return _c('div',{key:index,staticClass:"q-message-text",class:_vm.messageClass},[_c('span',{staticClass:"q-message-text-content",class:_vm.textClass},[_c('div',{domProps:{"innerHTML":_vm._s(msg)}}),_vm._v(" "),(_vm.stamp)?_c('div',{staticClass:"q-message-stamp",domProps:{"innerHTML":_vm._s(_vm.stamp)}}):_vm._e()])])}):_vm._e(),_vm._v(" "),(_vm.hasDefaultSlot())?_c('div',{staticClass:"q-message-text",class:_vm.messageClass},[_c('span',{staticClass:"q-message-text-content",class:_vm.textClass},[_vm._t("default"),_vm._v(" "),(_vm.stamp)?_c('div',{staticClass:"q-message-stamp",domProps:{"innerHTML":_vm._s(_vm.stamp)}}):_vm._e()],2)]):_vm._e()],2)],2)])},staticRenderFns: [],
name: 'q-chat-message',
props: {
sent: Boolean,
label: String,
bgColor: String,
textColor: String,
name: String,
avatar: String,
text: Array,
stamp: String,
size: String
},
computed: {
textClass: function textClass () {
if (this.textColor) {
return ("text-" + (this.textColor))
}
},
messageClass: function messageClass () {
if (this.bgColor) {
return ("text-" + (this.bgColor))
}
},
sizeClass: function sizeClass () {
if (this.size) {
return ("col-" + (this.size))
}
}
},
methods: {
hasDefaultSlot: function hasDefaultSlot () {
return Boolean(this.$slots['default'])
},
hasAvatarSlot: function hasAvatarSlot () {
return Boolean(this.$slots['avatar'])
}
}
}
function getDirection$1 (mod) {
var dir = {};['left', 'right', 'up', 'down', 'horizontal', 'vertical'].forEach(function (direction) {
if (mod[direction]) {
dir[direction] = true;
}
});
if (Object.keys(dir).length === 0) {
return {
left: true, right: true, up: true, down: true, horizontal: true, vertical: true
}
}
if (dir.horizontal) {
dir.left = dir.right = true;
}
if (dir.vertical) {
dir.up = dir.down = true;
}
if (dir.left && dir.right) {
dir.horizontal = true;
}
if (dir.up && dir.down) {
dir.vertical = true;
}
return dir
}
var TouchSwipe = {
name: 'touch-swipe',
bind: function bind (el, binding) {
var mouse = !binding.modifiers.noMouse;
var ctx = {
handler: binding.value,
threshold: parseInt(binding.arg, 10) || 300,
direction: getDirection$1(binding.modifiers),
mouseStart: function mouseStart (evt) {
if (leftClick(evt)) {
document.addEventListener('mousemove', ctx.move);
document.addEventListener('mouseup', ctx.mouseEnd);
ctx.start(evt);
}
},
mouseEnd: function mouseEnd (evt) {
document.removeEventListener('mousemove', ctx.move);
document.removeEventListener('mouseup', ctx.mouseEnd);
ctx.end(evt);
},
start: function start (evt) {
var pos = position(evt);
ctx.event = {
x: pos.left,
y: pos.top,
time: new Date().getTime(),
detected: false,
abort: false
};
},
move: function move (evt) {
if (ctx.event.abort) {
return
}
if (new Date().getTime() - ctx.event.time > ctx.threshold) {
ctx.event.abort = true;
return
}
if (ctx.event.detected) {
evt.stopPropagation();
evt.preventDefault();
return
}
var
pos = position(evt),
distX = pos.left - ctx.event.x,
absX = Math.abs(distX),
distY = pos.top - ctx.event.y,
absY = Math.abs(distY);
if (absX === absY) {
return
}
ctx.event.detected = true;
ctx.event.abort = !(
(ctx.direction.vertical && absX < absY) ||
(ctx.direction.horizontal && absX > absY) ||
(ctx.direction.up && absX < absY && distY < 0) ||
(ctx.direction.down && absX < absY && distY > 0) ||
(ctx.direction.left && absX > absY && distX < 0) ||
(ctx.direction.right && absX > absY && distX > 0)
);
ctx.move(evt);
},
end: function end (evt) {
if (ctx.event.abort || !ctx.event.detected) {
return
}
var duration = new Date().getTime() - ctx.event.time;
if (duration > ctx.threshold) {
return
}
evt.stopPropagation();
evt.preventDefault();
var
direction,
pos = position(evt),
distX = pos.left - ctx.event.x,
absX = Math.abs(distX),
distY = pos.top - ctx.event.y,
absY = Math.abs(distY);
if (absX >= absY) {
if (absX < 50) {
return
}
direction = distX < 0 ? 'left' : 'right';
}
else {
if (absY < 50) {
return
}
direction = distY < 0 ? 'up' : 'down';
}
if (ctx.direction[direction]) {
ctx.handler({
evt: evt,
direction: direction,
duration: duration,
distance: {
x: absX,
y: absY
}
});
}
}
};
el.__qtouchswipe = ctx;
el.classList.add('q-touch');
if (mouse) {
el.addEventListener('mousedown', ctx.mouseStart);
}
el.addEventListener('touchstart', ctx.start);
el.addEventListener('touchmove', ctx.move);
el.addEventListener('touchend', ctx.end);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
el.__qtouchswipe.handler = binding.value;
}
},
unbind: function unbind (el, binding) {
var ctx = el.__qtouchswipe;
el.removeEventListener('mousedown', ctx.mouseStart);
el.removeEventListener('touchstart', ctx.start);
el.removeEventListener('touchmove', ctx.move);
el.removeEventListener('touchend', ctx.end);
delete el.__qtouchswipe;
}
}
var CheckboxMixin = {
directives: {
TouchSwipe: TouchSwipe
},
props: {
val: {},
trueValue: { default: true },
falseValue: { default: false }
},
computed: {
isTrue: function isTrue () {
return this.modelIsArray
? this.index > -1
: this.value === this.trueValue
},
isFalse: function isFalse () {
return this.modelIsArray
? this.index === -1
: this.value === this.falseValue
},
index: function index () {
if (this.modelIsArray) {
return this.value.indexOf(this.val)
}
},
modelIsArray: function modelIsArray () {
return Array.isArray(this.value)
}
},
methods: {
toggle: function toggle (evt, blur) {
if ( blur === void 0 ) blur = true;
if (this.disable || this.readonly) {
return
}
if (evt) {
stopAndPrevent(evt);
}
if (blur) {
this.$el.blur();
}
var val;
if (this.modelIsArray) {
if (this.isTrue) {
val = this.value.slice();
val.splice(this.index, 1);
}
else {
val = this.value.concat(this.val);
}
}
else if (this.isTrue) {
val = this.toggleIndeterminate ? this.indeterminateValue : this.falseValue;
}
else if (this.isFalse) {
val = this.trueValue;
}
else {
val = this.falseValue;
}
this.__update(val);
}
}
}
var OptionMixin = {
props: {
value: {
required: true
},
label: String,
leftLabel: Boolean,
color: {
type: String,
default: 'primary'
},
keepColor: Boolean,
dark: Boolean,
disable: Boolean,
readonly: Boolean,
noFocus: Boolean,
checkedIcon: String,
uncheckedIcon: String
},
computed: {
classes: function classes () {
return [
this.$options._componentTag,
{
disabled: this.disable,
reverse: this.leftLabel,
'q-focusable': this.focusable
}
]
},
innerClasses: function innerClasses () {
if (this.isTrue || this.isIndeterminate) {
return ['active', ("text-" + (this.color))]
}
else {
var color = this.keepColor
? this.color
: (this.dark ? 'light' : 'dark');
return ("text-" + color)
}
},
focusable: function focusable () {
return !this.noFocus && !this.disable && !this.readonly
},
tabindex: function tabindex () {
return this.focusable ? 0 : -1
}
},
methods: {
__update: function __update (value) {
var this$1 = this;
var ref = this.$refs.ripple;
if (ref) {
ref.classList.add('active');
setTimeout(function () {
ref.classList.remove('active');
}, 10);
}
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__handleKeyDown: function __handleKeyDown (e) {
if ([13, 32].includes(getEventKey(e))) {
this.toggle(e, false);
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-option cursor-pointer no-outline row inline no-wrap items-center',
'class': this.classes,
attrs: { tabindex: this.tabindex },
on: {
click: this.toggle,
focus: function () { this$1.$emit('focus'); },
blur: function () { this$1.$emit('blur'); },
keydown: this.__handleKeyDown
},
directives: this.$options._componentTag === 'q-toggle'
? [{
name: 'touch-swipe',
modifiers: { horizontal: true },
value: this.__swipe
}]
: null
}, [
h('div', {
staticClass: 'q-option-inner relative-position',
'class': this.innerClasses
}, [
h('input', {
attrs: { type: 'checkbox' },
on: { change: this.toggle }
}),
h('div', { staticClass: 'q-focus-helper' }),
this.__getContent(h)
]),
this.label
? h('span', {
staticClass: 'q-option-label',
domProps: { innerHTML: this.label }
})
: null,
this.$slots.default
])
}
}
var QCheckbox = {
name: 'q-checkbox',
mixins: [CheckboxMixin, OptionMixin],
props: {
toggleIndeterminate: Boolean,
indeterminateValue: { default: null },
indeterminateIcon: String
},
computed: {
isIndeterminate: function isIndeterminate () {
return this.value === void 0 || this.value === this.indeterminateValue
},
checkedStyle: function checkedStyle () {
return this.isTrue
? {transition: 'opacity 0ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 800ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', opacity: 1, transform: 'scale(1)'}
: {transition: 'opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms', opacity: 0, transform: 'scale(0)'}
},
indeterminateStyle: function indeterminateStyle () {
return this.isIndeterminate
? {transition: 'opacity 0ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 800ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', opacity: 1, transform: 'scale(1)'}
: {transition: 'opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms', opacity: 0, transform: 'scale(0)'}
},
uncheckedStyle: function uncheckedStyle () {
return this.isFalse
? {opacity: 1}
: {transition: 'opacity 650ms cubic-bezier(0.23, 1, 0.32, 1) 150ms', opacity: 0}
}
},
methods: {
__getContent: function __getContent (h) {
return [
h(QIcon, {
staticClass: 'q-checkbox-icon cursor-pointer',
props: { name: this.uncheckedIcon || this.$q.icon.checkbox.unchecked["ios"] },
style: this.uncheckedStyle
}),
h(QIcon, {
staticClass: 'q-checkbox-icon cursor-pointer absolute-full',
props: { name: this.indeterminateIcon || this.$q.icon.checkbox.indeterminate["ios"] },
style: this.indeterminateStyle
}),
h(QIcon, {
staticClass: 'q-checkbox-icon cursor-pointer absolute-full',
props: { name: this.checkedIcon || this.$q.icon.checkbox.checked["ios"] },
style: this.checkedStyle
}),
null
]
}
}
}
var QChip = {
name: 'q-chip',
props: {
small: Boolean,
tag: Boolean,
square: Boolean,
floating: Boolean,
pointing: {
type: String,
validator: function (v) { return ['up', 'right', 'down', 'left'].includes(v); }
},
color: String,
textColor: String,
icon: String,
iconRight: String,
avatar: String,
closable: Boolean,
detail: Boolean
},
computed: {
classes: function classes () {
var this$1 = this;
var cls = [];
this.pointing && cls.push(("q-chip-pointing-" + (this.pointing)))
;['tag', 'square', 'floating', 'pointing', 'small'].forEach(function (prop) {
this$1[prop] && cls.push(("q-chip-" + prop));
});
if (this.color) {
cls.push(("bg-" + (this.color)));
!this.textColor && cls.push("text-white");
}
if (this.textColor) {
cls.push(("text-" + (this.textColor)));
}
return cls
}
},
methods: {
__onClick: function __onClick (e) {
this.$emit('click', e);
},
__onMouseDown: function __onMouseDown (e) {
this.$emit('focus', e);
},
__handleKeyDown: function __handleKeyDown (e) {
if (this.closable && [8, 13, 32].includes(getEventKey(e))) {
stopAndPrevent(e);
this.$emit('hide');
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-chip row no-wrap inline items-center',
'class': this.classes,
on: {
mousedown: this.__onMouseDown,
touchstart: this.__onMouseDown,
click: this.__onClick,
keydown: this.__handleKeyDown
}
}, [
this.icon || this.avatar
? h('div', {
staticClass: 'q-chip-side q-chip-left row flex-center',
'class': { 'q-chip-detail': this.detail }
}, [
this.icon
? h(QIcon, { staticClass: 'q-chip-icon', props: { name: this.icon } })
: (this.avatar ? h('img', { domProps: { src: this.avatar } }) : null)
])
: null,
h('div', { staticClass: 'q-chip-main' }, [
this.$slots.default
]),
this.iconRight
? h(QIcon, {
props: { name: this.iconRight },
'class': this.closable ? 'on-right q-chip-icon' : 'q-chip-side q-chip-right'
})
: null,
this.closable
? h('div', { staticClass: 'q-chip-side q-chip-close q-chip-right row flex-center' }, [
h(QIcon, {
props: { name: this.$q.icon.chip.close },
staticClass: 'cursor-pointer',
nativeOn: {
click: function (e) {
e && e.stopPropagation();
this$1.$emit('hide');
}
}
})
])
: null
])
}
}
var marginal = {
type: Array,
validator: function (v) { return v.every(function (i) { return 'icon' in i; }); }
};
var FrameMixin = {
mixins: [AlignMixin],
components: {
QIcon: QIcon
},
props: {
prefix: String,
suffix: String,
stackLabel: String,
floatLabel: String,
error: Boolean,
warning: Boolean,
disable: Boolean,
readonly: Boolean,
clearable: Boolean,
color: {
type: String,
default: 'primary'
},
align: {
default: 'left'
},
dark: Boolean,
before: marginal,
after: marginal,
inverted: Boolean,
hideUnderline: Boolean,
clearValue: {
default: null
}
},
computed: {
labelIsAbove: function labelIsAbove () {
return this.focused || this.length || this.additionalLength || this.stackLabel
},
editable: function editable () {
return !this.disable && !this.readonly
}
},
methods: {
clear: function clear (evt) {
if (!this.editable) {
return
}
stopAndPrevent(evt);
var val = this.clearValue;
if (this.__setModel) {
this.__setModel(val, true);
}
this.$emit('clear', val);
}
}
}
var InputMixin = {
props: {
autofocus: [Boolean, String],
maxHeight: Number,
placeholder: String,
loading: Boolean
},
data: function data () {
return {
focused: false,
timer: null,
isNumberError: false
}
},
computed: {
inputPlaceholder: function inputPlaceholder () {
if ((!this.floatLabel && !this.stackLabel) || this.labelIsAbove) {
return this.placeholder
}
}
},
methods: {
focus: function focus () {
if (!this.disable) {
this.$refs.input.focus();
}
},
blur: function blur () {
this.$refs.input.blur();
},
select: function select () {
this.$refs.input.select();
},
__onFocus: function __onFocus (e) {
clearTimeout(this.timer);
this.focused = true;
this.$emit('focus', e);
},
__onInputBlur: function __onInputBlur (e) {
var this$1 = this;
clearTimeout(this.timer);
this.timer = setTimeout(function () {
this$1.__onBlur(e);
}, 200);
},
__onBlur: function __onBlur (e) {
this.focused = false;
this.$emit('blur', e);
this.__emit();
},
__emit: function __emit () {
var this$1 = this;
var isNumberError = this.isNumber && this.isNumberError;
var value = isNumberError ? null : this.model;
if (isNumberError) {
this.$emit('input', value);
}
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__onKeydown: function __onKeydown (e) {
this.$emit('keydown', e);
},
__onKeyup: function __onKeyup (e) {
this.$emit('keyup', e);
},
__onClick: function __onClick (e) {
this.focus();
this.$emit('click', e);
}
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
var input = this$1.$refs.input;
if (this$1.autofocus && input) {
input.focus();
if (this$1.autofocus === 'select') {
input.select();
}
}
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
}
}
var FieldParentMixin = {
inject: {
field: {
from: '__field',
default: null
}
},
beforeMount: function beforeMount () {
if (this.field) {
this.field.__registerInput(this);
}
},
beforeDestroy: function beforeDestroy () {
if (this.field) {
this.field.__unregisterInput();
}
}
}
var QInputFrame = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-if row no-wrap items-center relative-position",class:_vm.classes,attrs:{"tabindex":_vm.focusable && !_vm.disable ? 0 : -1},on:{"click":_vm.__onClick}},[(_vm.before)?_vm._l((_vm.before),function(item){return _c('q-icon',{key:("b" + (item.icon)),staticClass:"q-if-control q-if-control-before",class:{hidden: _vm.__additionalHidden(item, _vm.hasError, _vm.hasWarning, _vm.length)},attrs:{"name":item.icon},nativeOn:{"mousedown":function($event){_vm.__onMouseDown($event);},"touchstart":function($event){_vm.__onMouseDown($event);},"click":function($event){_vm.__baHandler($event, item);}}})}):_vm._e(),_vm._v(" "),_c('div',{staticClass:"q-if-inner col row no-wrap items-center relative-position"},[(_vm.hasLabel)?_c('div',{staticClass:"q-if-label ellipsis full-width absolute self-start",class:{'q-if-label-above': _vm.labelIsAbove},domProps:{"innerHTML":_vm._s(_vm.label)}}):_vm._e(),_vm._v(" "),(_vm.prefix)?_c('span',{staticClass:"q-if-addon q-if-addon-left",class:_vm.addonClass,domProps:{"innerHTML":_vm._s(_vm.prefix)}}):_vm._e(),_vm._v(" "),_vm._t("default"),_vm._v(" "),(_vm.suffix)?_c('span',{staticClass:"q-if-addon q-if-addon-right",class:_vm.addonClass,domProps:{"innerHTML":_vm._s(_vm.suffix)}}):_vm._e()],2),_vm._v(" "),_vm._t("after"),_vm._v(" "),(_vm.after)?_vm._l((_vm.after),function(item){return _c('q-icon',{key:("a" + (item.icon)),staticClass:"q-if-control",class:{hidden: _vm.__additionalHidden(item, _vm.hasError, _vm.hasWarning, _vm.length)},attrs:{"name":item.icon},nativeOn:{"mousedown":function($event){_vm.__onMouseDown($event);},"touchstart":function($event){_vm.__onMouseDown($event);},"click":function($event){_vm.__baHandler($event, item);}}})}):_vm._e()],2)},staticRenderFns: [],
name: 'q-input-frame',
mixins: [FrameMixin, FieldParentMixin],
props: {
topAddons: Boolean,
focused: Boolean,
length: Number,
focusable: Boolean,
additionalLength: Boolean
},
computed: {
hasStackLabel: function hasStackLabel () {
return typeof this.stackLabel === 'string' && this.stackLabel.length > 0
},
hasLabel: function hasLabel () {
return this.hasStackLabel || (typeof this.floatLabel === 'string' && this.floatLabel.length > 0)
},
label: function label () {
return this.hasStackLabel ? this.stackLabel : this.floatLabel
},
addonClass: function addonClass () {
return {
'q-if-addon-visible': !this.hasLabel || this.labelIsAbove,
'self-start': this.topAddons
}
},
classes: function classes () {
var cls = [{
'q-if-has-label': this.label,
'q-if-focused': this.focused,
'q-if-error': this.hasError,
'q-if-warning': this.hasWarning,
'q-if-disabled': this.disable,
'q-if-focusable': this.focusable && !this.disable,
'q-if-inverted': this.inverted,
'q-if-dark': this.dark || this.inverted,
'q-if-hide-underline': this.hideUnderline
}];
var color = this.hasError ? 'negative' : this.hasWarning ? 'warning' : this.color;
if (this.inverted) {
cls.push(("bg-" + color));
cls.push("text-white");
}
else {
cls.push(("text-" + color));
}
return cls
},
hasError: function hasError () {
return !!((this.field && this.field.error) || this.error)
},
hasWarning: function hasWarning () {
// error is the higher priority
return !!(!this.hasError && ((this.field && this.field.warning) || this.warning))
}
},
methods: {
__onClick: function __onClick (e) {
this.$emit('click', e);
},
__onMouseDown: function __onMouseDown (e) {
var this$1 = this;
this.$nextTick(function () { return this$1.$emit('focus', e); });
},
__additionalHidden: function __additionalHidden (item, hasError, hasWarning, length) {
if (item.condition !== void 0) {
return item.condition === false
}
return (
(item.content !== void 0 && !item.content === (length > 0)) ||
(item.error !== void 0 && !item.error === hasError) ||
(item.warning !== void 0 && !item.warning === hasWarning)
)
},
__baHandler: function __baHandler (evt, item) {
if (!item.allowPropagation) {
evt.stopPropagation();
}
if (item.handler) {
item.handler(evt);
}
}
}
}
var QChipsInput = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('q-input-frame',{staticClass:"q-chips-input",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.computedColor,"focused":_vm.focused,"length":_vm.length,"additional-length":_vm.input.length > 0},on:{"click":_vm.__onClick}},[_c('div',{staticClass:"col row items-center group q-input-chips"},[_vm._l((_vm.model),function(label,index){return _c('q-chip',{key:(label + "#" + index),attrs:{"small":"","closable":_vm.editable,"color":_vm.computedChipColor,"text-color":_vm.computedChipTextColor,"tabindex":_vm.editable && _vm.focused ? 0 : -1},on:{"blur":_vm.__onInputBlur,"focus":_vm.__clearTimer,"hide":function($event){_vm.remove(index);}},nativeOn:{"blur":function($event){_vm.__onInputBlur($event);},"focus":function($event){_vm.__clearTimer($event);}}},[_vm._v(" "+_vm._s(label)+" ")])}),_vm._v(" "),_c('input',_vm._b({directives:[{name:"model",rawName:"v-model",value:(_vm.input),expression:"input"}],ref:"input",staticClass:"col q-input-target",class:[("text-" + (_vm.align))],attrs:{"placeholder":_vm.inputPlaceholder,"disabled":_vm.disable,"readonly":_vm.readonly},domProps:{"value":(_vm.input)},on:{"focus":_vm.__onFocus,"blur":_vm.__onInputBlur,"keydown":_vm.__handleKeyDown,"keyup":_vm.__onKeyup,"input":function($event){if($event.target.composing){ return; }_vm.input=$event.target.value;}}},'input',_vm.$attrs,false))],2),_vm._v(" "),(_vm.editable)?_c('q-icon',{staticClass:"q-if-control self-end",class:{invisible: !_vm.input.length},attrs:{"slot":"after","name":_vm.computedAddIcon},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.add();}},slot:"after"}):_vm._e()],1)},staticRenderFns: [],
name: 'q-chips-input',
mixins: [FrameMixin, InputMixin],
components: {
QInputFrame: QInputFrame,
QChip: QChip
},
props: {
value: {
type: Array,
required: true
},
frameColor: String,
readonly: Boolean,
addIcon: String
},
data: function data () {
return {
input: '',
model: [].concat( this.value )
}
},
watch: {
value: function value (v) {
this.model = Array.isArray(v) ? [].concat( v ) : [];
}
},
computed: {
length: function length () {
return this.model
? this.model.length
: 0
},
computedAddIcon: function computedAddIcon () {
return this.addIcon || this.$q.icon.chipsInput.add
},
computedColor: function computedColor () {
return this.inverted ? this.frameColor || this.color : this.color
},
computedChipColor: function computedChipColor () {
if (this.inverted) {
if (this.frameColor) {
return this.color
}
return this.dark !== false ? 'white' : null
}
return this.color
},
computedChipTextColor: function computedChipTextColor () {
if (this.inverted) {
return this.frameColor || this.color
}
return this.dark !== false ? 'white' : null
}
},
methods: {
add: function add (value) {
if ( value === void 0 ) value = this.input;
clearTimeout(this.timer);
this.focus();
if (this.editable && value) {
this.model.push(value);
this.$emit('input', this.model);
this.input = '';
}
},
remove: function remove (index) {
clearTimeout(this.timer);
this.focus();
if (this.editable && index >= 0 && index < this.length) {
this.model.splice(index, 1);
this.$emit('input', this.model);
}
},
__clearTimer: function __clearTimer () {
var this$1 = this;
this.$nextTick(function () { return clearTimeout(this$1.timer); });
},
__handleKeyDown: function __handleKeyDown (e) {
switch (getEventKey(e)) {
case 13: // ENTER key
stopAndPrevent(e);
return this.add()
case 8: // Backspace key
if (!this.input.length && this.length) {
this.remove(this.length - 1);
}
return
default:
return this.__onKeydown(e)
}
},
__onClick: function __onClick () {
this.focus();
}
}
}
function getHeight (el, style$$1) {
var initial = {
visibility: el.style.visibility,
maxHeight: el.style.maxHeight
};
css(el, {
visibility: 'hidden',
maxHeight: ''
});
var height$$1 = style$$1.height;
css(el, initial);
return parseFloat(height$$1)
}
function parseSize (padding) {
return padding.split(' ').map(function (t) {
var unit = t.match(/[a-zA-Z]+/) || '';
if (unit) {
unit = unit[0];
}
return [parseFloat(t), unit]
})
}
function toggleSlide (el, showing, done) {
var store = el.__qslidetoggle || {};
function anim () {
store.uid = start({
to: showing ? 100 : 0,
from: store.pos !== null ? store.pos : showing ? 0 : 100,
apply: function apply (pos) {
store.pos = pos;
css(el, {
maxHeight: ((store.height * pos / 100) + "px"),
padding: store.padding ? store.padding.map(function (t) { return (t[0] * pos / 100) + t[1]; }).join(' ') : '',
margin: store.margin ? store.margin.map(function (t) { return (t[0] * pos / 100) + t[1]; }).join(' ') : ''
});
},
done: function done$1 () {
store.uid = null;
store.pos = null;
done();
css(el, store.css);
}
});
el.__qslidetoggle = store;
}
if (store.uid) {
stop(store.uid);
return anim()
}
store.css = {
overflowY: el.style.overflowY,
maxHeight: el.style.maxHeight,
padding: el.style.padding,
margin: el.style.margin
};
var style$$1 = window.getComputedStyle(el);
if (style$$1.padding && style$$1.padding !== '0px') {
store.padding = parseSize(style$$1.padding);
}
if (style$$1.margin && style$$1.margin !== '0px') {
store.margin = parseSize(style$$1.margin);
}
store.height = getHeight(el, style$$1);
store.pos = null;
el.style.overflowY = 'hidden';
anim();
}
var QSlideTransition = {
name: 'q-slide-transition',
props: {
appear: Boolean
},
render: function render (h) {
return h('transition', {
props: {
mode: 'out-in',
css: false,
appear: this.appear
},
on: {
enter: function enter (el, done) {
toggleSlide(el, true, done);
},
leave: function leave (el, done) {
toggleSlide(el, false, done);
}
}
}, this.$slots.default)
}
}
var eventName = 'q:collapsible:close';
var QCollapsible = {
name: 'q-collapsible',
mixins: [ModelToggleMixin],
modelToggle: {
history: false
},
directives: {
Ripple: Ripple
},
props: {
disable: Boolean,
popup: Boolean,
indent: Boolean,
group: String,
iconToggle: Boolean,
separator: Boolean,
insetSeparator: Boolean,
noRipple: Boolean,
collapseIcon: String,
opened: Boolean,
dense: Boolean,
sparse: Boolean,
multiline: Boolean,
icon: String,
rightIcon: String,
image: String,
rightImage: String,
avatar: String,
rightAvatar: String,
letter: String,
rightLetter: String,
label: String,
sublabel: String,
labelLines: [String, Number],
sublabelLines: [String, Number],
headerStyle: [Array, String, Object],
headerClass: [Array, String, Object]
},
computed: {
cfg: function cfg () {
return {
link: !this.iconToggle,
dark: this.dark,
dense: this.dense,
sparse: this.sparse,
multiline: this.multiline,
icon: this.icon,
rightIcon: this.rightIcon,
image: this.image,
rightImage: this.rightImage,
avatar: this.avatar,
rightAvatar: this.rightAvatar,
letter: this.letter,
rightLetter: this.rightLetter,
label: this.label,
sublabel: this.sublabel,
labelLines: this.labelLines,
sublabelLines: this.sublabelLines
}
},
hasRipple: function hasRipple () {
return "ios" === 'mat' && !this.noRipple && !this.disable
},
classes: function classes () {
return {
'q-collapsible-opened': this.popup && this.showing,
'q-collapsible-closed': this.popup && !this.showing,
'q-item-separator': this.separator,
'q-item-inset-separator': this.insetSeparator,
disabled: this.disable
}
}
},
watch: {
showing: function showing (val) {
if (val && this.group) {
this.$root.$emit(eventName, this);
}
}
},
methods: {
__toggleItem: function __toggleItem () {
if (!this.iconToggle) {
this.toggle();
}
},
__toggleIcon: function __toggleIcon (e) {
if (this.iconToggle) {
e && e.stopPropagation();
this.toggle();
}
},
__eventHandler: function __eventHandler (comp) {
if (this.group && this !== comp && comp.group === this.group) {
this.hide();
}
},
__getToggleSide: function __getToggleSide (h, slot) {
return [
h(QItemTile, {
slot: slot ? 'right' : undefined,
staticClass: 'cursor-pointer transition-generic relative-position',
'class': {
'rotate-180': this.showing,
invisible: this.disable
},
nativeOn: {
click: this.__toggleIcon
},
props: { icon: this.collapseIcon || this.$q.icon.collapsible.icon },
directives: this.iconToggle && this.hasRipple
? [{ name: 'ripple' }]
: null
})
]
},
__getItemProps: function __getItemProps (wrapper) {
return {
props: wrapper
? { cfg: this.cfg }
: { link: !this.iconToggle },
style: this.headerStyle,
'class': this.headerClass,
nativeOn: {
click: this.__toggleItem
},
directives: this.hasRipple && !this.iconToggle
? [{ name: 'ripple' }]
: null
}
}
},
created: function created () {
this.$root.$on(eventName, this.__eventHandler);
if (this.opened || this.value) {
this.show();
}
},
beforeDestroy: function beforeDestroy () {
this.$root.$off(eventName, this.__eventHandler);
},
render: function render (h) {
return h('div', {
staticClass: 'q-collapsible q-item-division relative-position',
'class': this.classes
}, [
h('div', {
staticClass: 'q-collapsible-inner'
}, [
this.$slots.header
? h(QItem, this.__getItemProps(), [
this.$slots.header,
h(QItemSide, { props: { right: true }, staticClass: 'relative-position' }, this.__getToggleSide(h))
])
: h(QItemWrapper, this.__getItemProps(true), this.__getToggleSide(h, true)),
h(QSlideTransition, [
h('div', {
directives: [{ name: 'show', value: this.showing }]
}, [
h('div', {
staticClass: 'q-collapsible-sub-item relative-position',
'class': { indent: this.indent }
}, [
this.$slots.default
])
])
])
])
])
}
}
var DisplayModeMixin = {
props: {
popover: Boolean,
modal: Boolean
},
computed: {
isPopover: function isPopover () {
// Explicit popover / modal choice
if (this.popover) { return true }
if (this.modal) { return false }
// Automatically determine the default popover or modal behavior
return this.$q.platform.is.desktop && !this.$q.platform.within.iframe
}
}
}
function getPercentage (event, dragging) {
return between((position(event).left - dragging.left) / dragging.width, 0, 1)
}
function notDivides (res, decimals) {
var number = decimals
? parseFloat(res.toFixed(decimals))
: res;
return number !== parseInt(number, 10)
}
function getModel (percentage, min, max, step, decimals) {
var
model = min + percentage * (max - min),
modulo = (model - min) % step;
model += (Math.abs(modulo) >= step / 2 ? (modulo < 0 ? -1 : 1) * step : 0) - modulo;
if (decimals) {
model = parseFloat(model.toFixed(decimals));
}
return between(model, min, max)
}
var SliderMixin = {
directives: {
TouchPan: TouchPan
},
props: {
min: {
type: Number,
default: 1
},
max: {
type: Number,
default: 5
},
step: {
type: Number,
default: 1
},
decimals: Number,
snap: Boolean,
markers: Boolean,
label: Boolean,
labelAlways: Boolean,
square: Boolean,
color: String,
fillHandleAlways: Boolean,
error: Boolean,
warning: Boolean,
readonly: Boolean,
disable: Boolean
},
data: function data () {
return {
clickDisabled: false
}
},
computed: {
editable: function editable () {
return !this.disable && !this.readonly
},
classes: function classes () {
var cls = {
disabled: this.disable,
readonly: this.readonly,
'label-always': this.labelAlways,
'has-error': this.error,
'has-warning': this.warning
};
if (!this.error && !this.warning && this.color) {
cls[("text-" + (this.color))] = true;
}
return cls
},
markersLen: function markersLen () {
return (this.max - this.min) / this.step + 1
},
labelColor: function labelColor () {
return this.error
? 'negative'
: (this.warning ? 'warning' : (this.color || 'primary'))
},
computedDecimals: function computedDecimals () {
return this.decimals !== void 0 ? this.decimals || 0 : (String(this.step).trim('0').split('.')[1] || '').length
}
},
methods: {
__pan: function __pan (event) {
var this$1 = this;
if (event.isFinal) {
this.clickDisabled = true;
this.$nextTick(function () {
this$1.clickDisabled = false;
});
this.__end(event.evt);
}
else if (event.isFirst) {
this.__setActive(event.evt);
}
else if (this.dragging) {
this.__update(event.evt);
}
},
__click: function __click (event) {
if (this.clickDisabled) {
return
}
this.__setActive(event);
this.__end(event);
},
__getMarkers: function __getMarkers (h) {
var this$1 = this;
if (!this.markers) {
return
}
var markers = [];
for (var i = 0; i < this.markersLen; i++) {
markers.push(h('div', {
staticClass: 'q-slider-mark',
key: ("marker" + i),
style: {
left: ((i * 100 * this$1.step / (this$1.max - this$1.min)) + "%")
}
}));
}
return markers
}
},
created: function created () {
this.__validateProps();
},
render: function render (h) {
return h('div', {
staticClass: 'q-slider non-selectable',
'class': this.classes,
on: this.editable ? { click: this.__click } : null,
directives: this.editable
? [{
name: 'touch-pan',
modifiers: {
horizontal: true,
prevent: true,
stop: true
},
value: this.__pan
}]
: null
}, [
h('div', {
ref: 'handle',
staticClass: 'q-slider-handle-container'
}, [
h('div', { staticClass: 'q-slider-track' }),
this.__getMarkers(h)
].concat(this.__getContent(h)))
])
}
};
var QSlider = {
name: 'q-slider',
mixins: [SliderMixin],
props: {
value: Number,
labelValue: String
},
data: function data () {
return {
model: this.value,
dragging: false,
currentPercentage: (this.value - this.min) / (this.max - this.min)
}
},
computed: {
percentage: function percentage () {
if (this.snap) {
return (this.model - this.min) / (this.max - this.min) * 100 + '%'
}
return 100 * this.currentPercentage + '%'
},
displayValue: function displayValue () {
return this.labelValue !== void 0
? this.labelValue
: this.model
}
},
watch: {
value: function value (value$1) {
if (this.dragging) {
return
}
if (value$1 < this.min) {
this.model = this.min;
}
else if (value$1 > this.max) {
this.model = this.max;
}
else {
this.model = value$1;
}
this.currentPercentage = (this.model - this.min) / (this.max - this.min);
},
min: function min (value) {
if (this.model < value) {
this.model = value;
return
}
this.$nextTick(this.__validateProps);
},
max: function max (value) {
if (this.model > value) {
this.model = value;
return
}
this.$nextTick(this.__validateProps);
},
step: function step () {
this.$nextTick(this.__validateProps);
}
},
methods: {
__setActive: function __setActive (event) {
var container = this.$refs.handle;
this.dragging = {
left: container.getBoundingClientRect().left,
width: container.offsetWidth
};
this.__update(event);
},
__update: function __update (event) {
var
percentage = getPercentage(event, this.dragging),
model = getModel(percentage, this.min, this.max, this.step, this.computedDecimals);
this.currentPercentage = percentage;
this.model = model;
this.$emit('input', model);
},
__end: function __end () {
var this$1 = this;
this.dragging = false;
this.currentPercentage = (this.model - this.min) / (this.max - this.min);
this.$nextTick(function () {
if (JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
this$1.$emit('dragend', this$1.model);
});
},
__validateProps: function __validateProps () {
if (this.min >= this.max) {
console.error('Range error: min >= max', this.$el, this.min, this.max);
}
else if (notDivides((this.max - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of max - min', this.min, this.max, this.step, this.computedDecimals);
}
},
__getContent: function __getContent (h) {
return [
h('div', {
staticClass: 'q-slider-track active-track',
style: { width: this.percentage },
'class': {
'no-transition': this.dragging,
'handle-at-minimum': this.model === this.min
}
}),
h('div', {
staticClass: 'q-slider-handle',
style: {
left: this.percentage,
borderRadius: this.square ? '0' : '50%'
},
'class': {
dragging: this.dragging,
'handle-at-minimum': !this.fillHandleAlways && this.model === this.min
}
}, [
this.label || this.labelAlways
? h(QChip, {
staticClass: 'q-slider-label no-pointer-events',
'class': { 'label-always': this.labelAlways },
props: {
pointing: 'down',
square: true,
color: this.labelColor
}
}, [ this.displayValue ])
: null,
null
])
]
}
}
}
function throttle (fn, limit) {
if ( limit === void 0 ) limit = 250;
var wait = false;
return function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (wait) {
return
}
wait = true;
fn.apply(this, args);
setTimeout(function () {
wait = false;
}, limit);
}
}
function clone (data) {
var s = JSON.stringify(data);
if (s) {
return JSON.parse(s)
}
}
function rgbToHex (ref) {
var r = ref.r;
var g = ref.g;
var b = ref.b;
var a = ref.a;
var alpha = a !== void 0;
r = Math.round(r);
g = Math.round(g);
b = Math.round(b);
if (
r > 255 ||
g > 255 ||
b > 255 ||
(alpha && a > 100)
) {
throw new TypeError('Expected 3 numbers below 256 (and optionally one below 100)')
}
a = alpha
? (Math.round(255 * a / 100) | 1 << 8).toString(16).slice(1)
: '';
return '#' + ((b | g << 8 | r << 16) | 1 << 24).toString(16).slice(1) + a
}
function hexToRgb (hex) {
if (typeof hex !== 'string') {
throw new TypeError('Expected a string')
}
hex = hex.replace(/^#/, '');
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
else if (hex.length === 4) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
}
var num = parseInt(hex, 16);
return hex.length > 6
? {r: num >> 24 & 255, g: num >> 16 & 255, b: num >> 8 & 255, a: Math.round((num & 255) / 2.55)}
: {r: num >> 16, g: num >> 8 & 255, b: num & 255}
}
function hsvToRgb (ref) {
var h = ref.h;
var s = ref.s;
var v = ref.v;
var a = ref.a;
var r, g, b, i, f, p, q, t;
s = s / 100;
v = v / 100;
h = h / 360;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
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
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255),
a: a
}
}
function rgbToHsv (ref) {
var r = ref.r;
var g = ref.g;
var b = ref.b;
var a = ref.a;
var
max = Math.max(r, g, b), min = Math.min(r, g, b),
d = max - min,
h,
s = (max === 0 ? 0 : d / max),
v = max / 255;
switch (max) {
case min:
h = 0;
break
case r:
h = (g - b) + d * (g < b ? 6 : 0);
h /= 6 * d;
break
case g:
h = (b - r) + d * 2;
h /= 6 * d;
break
case b:
h = (r - g) + d * 4;
h /= 6 * d;
break
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
v: Math.round(v * 100),
a: a
}
}
var colors = Object.freeze({
rgbToHex: rgbToHex,
hexToRgb: hexToRgb,
hsvToRgb: hsvToRgb,
rgbToHsv: rgbToHsv
});
var QColorPicker = {
name: 'q-color-picker',
mixins: [FieldParentMixin],
directives: {
TouchPan: TouchPan
},
props: {
value: [String, Object],
defaultSelection: {
type: [String, Object],
default: '#000'
},
type: {
type: String,
default: 'auto',
validator: function (v) { return ['auto', 'hex', 'rgb', 'hexa', 'rgba'].includes(v); }
},
disable: Boolean,
readonly: Boolean
},
data: function data () {
return {
view: !this.value || typeof this.value === 'string' ? 'hex' : 'rgb',
model: this.__parseModel(this.value || this.defaultSelection),
inputError: {
hex: false,
r: false,
g: false,
b: false
}
}
},
watch: {
value: {
handler: function handler (v) {
var model = this.__parseModel(v || this.defaultSelection);
if (model.hex !== this.model.hex) {
this.model = model;
}
},
deep: true
}
},
computed: {
forceHex: function forceHex () {
return this.type === 'auto'
? null
: this.type.indexOf('hex') > -1
},
forceAlpha: function forceAlpha () {
return this.type === 'auto'
? null
: this.type.indexOf('a') > -1
},
isHex: function isHex () {
return typeof this.value === 'string'
},
isOutputHex: function isOutputHex () {
return this.forceHex !== null
? this.forceHex
: this.isHex
},
editable: function editable () {
return !this.disable && !this.readonly
},
hasAlpha: function hasAlpha () {
if (this.forceAlpha !== null) {
return this.forceAlpha
}
return this.isHex
? this.value.length > 7
: this.value && this.value.a !== void 0
},
swatchStyle: function swatchStyle () {
return {
backgroundColor: ("rgba(" + (this.model.r) + "," + (this.model.g) + "," + (this.model.b) + "," + ((this.model.a === void 0 ? 100 : this.model.a) / 100) + ")")
}
},
saturationStyle: function saturationStyle () {
return {
background: ("hsl(" + (this.model.h) + ",100%,50%)")
}
},
saturationPointerStyle: function saturationPointerStyle () {
return {
top: ((101 - this.model.v) + "%"),
left: ((this.model.s) + "%")
}
},
inputsArray: function inputsArray () {
var inp = ['r', 'g', 'b'];
if (this.hasAlpha) {
inp.push('a');
}
return inp
}
},
created: function created () {
this.__saturationChange = throttle(this.__saturationChange, 20);
},
render: function render (h) {
return h('div', {
staticClass: 'q-color',
'class': { disabled: this.disable }
}, [
this.__getSaturation(h),
this.__getSliders(h),
this.__getInputs(h)
])
},
methods: {
__getSaturation: function __getSaturation (h) {
return h('div', {
ref: 'saturation',
staticClass: 'q-color-saturation non-selectable relative-position overflow-hidden cursor-pointer',
style: this.saturationStyle,
'class': { readonly: !this.editable },
on: this.editable
? { click: this.__saturationClick }
: null,
directives: this.editable
? [{
name: 'touch-pan',
modifiers: {
prevent: true,
stop: true
},
value: this.__saturationPan
}]
: null
}, [
h('div', { staticClass: 'q-color-saturation-white absolute-full' }),
h('div', { staticClass: 'q-color-saturation-black absolute-full' }),
h('div', {
staticClass: 'absolute',
style: this.saturationPointerStyle
}, [
h('div', { staticClass: 'q-color-saturation-circle' })
])
])
},
__getSliders: function __getSliders (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-color-sliders row items-center'
}, [
h('div', {
staticClass: 'q-color-swatch q-mt-sm q-ml-sm q-mb-sm non-selectable overflow-hidden',
style: this.swatchStyle
}),
h('div', { staticClass: 'col q-pa-sm' }, [
h('div', { staticClass: 'q-color-hue non-selectable' }, [
h(QSlider, {
props: {
value: this.model.h,
color: 'white',
min: 0,
max: 360,
fillHandleAlways: true,
readonly: !this.editable
},
on: {
input: this.__onHueChange,
dragend: function (val) { return this$1.__onHueChange(val, true); }
}
})
]),
this.hasAlpha
? h('div', { staticClass: 'q-color-alpha non-selectable' }, [
h(QSlider, {
props: {
value: this.model.a,
color: 'white',
min: 0,
max: 100,
fillHandleAlways: true,
readonly: !this.editable
},
on: {
input: function (value) { return this$1.__onNumericChange({ target: { value: value } }, 'a', 100); },
dragend: function (value) { return this$1.__onNumericChange({ target: { value: value } }, 'a', 100, true); }
}
})
])
: null
])
])
},
__getNumericInputs: function __getNumericInputs (h) {
var this$1 = this;
return this.inputsArray.map(function (type) {
var max = type === 'a' ? 100 : 255;
return h('div', { staticClass: 'col q-color-padding' }, [
h('input', {
attrs: {
type: 'number',
min: 0,
max: max,
readonly: !this$1.editable,
tabindex: this$1.disable ? 0 : -1
},
staticClass: 'full-width text-center q-no-input-spinner',
domProps: {
value: Math.round(this$1.model[type])
},
on: {
input: function (evt) { return this$1.__onNumericChange(evt, type, max); },
blur: function (evt) { return this$1.editable && this$1.__onNumericChange(evt, type, max, true); }
}
}),
h('div', { staticClass: 'q-color-label text-center uppercase' }, [
type
])
])
})
},
__getInputs: function __getInputs (h) {
var this$1 = this;
var inputs = this.view === 'hex'
? [
h('div', { staticClass: 'col' }, [
h('input', {
domProps: { value: this.model.hex },
attrs: {
readonly: !this.editable,
tabindex: this.disable ? 0 : -1
},
on: {
input: this.__onHexChange,
blur: function (evt) { return this$1.editable && this$1.__onHexChange(evt, true); }
},
staticClass: 'full-width text-center uppercase'
}),
h('div', { staticClass: 'q-color-label text-center' }, [
("HEX" + (this.hasAlpha ? ' / A' : ''))
])
])
]
: this.__getNumericInputs(h);
return h('div', {
staticClass: 'q-color-inputs row items-center q-px-sm q-pb-sm'
}, [
h('div', { staticClass: 'col q-mr-sm row no-wrap' }, inputs),
h('div', [
h(QBtn, {
props: {
flat: true,
color: 'grey-7',
disable: this.disable
},
on: {
click: this.__nextInputView
},
staticClass: 'q-pa-none'
}, [
h('svg', {
attrs: {
viewBox: '0 0 24 24'
},
style: {width: '24px', height: '24px'}
}, [
h('path', {
attrs: {
fill: 'currentColor',
d: 'M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z'
}
})
])
])
])
])
},
__onSaturationChange: function __onSaturationChange (left, top, change) {
var
panel = this.$refs.saturation,
width = panel.clientWidth,
height = panel.clientHeight,
rect = panel.getBoundingClientRect(),
x = Math.min(width, Math.max(0, left - rect.left)),
y = Math.min(height, Math.max(0, top - rect.top)),
s = Math.round(100 * x / width),
v = Math.round(100 * Math.max(0, Math.min(1, -(y / height) + 1))),
rgb = hsvToRgb({
h: this.model.h,
s: s,
v: v,
a: this.hasAlpha ? this.model.a : void 0
});
this.model.s = s;
this.model.v = v;
this.__update(rgb, rgbToHex(rgb), change);
},
__onHueChange: function __onHueChange (h, change) {
h = Math.round(h);
var val = hsvToRgb({
h: h,
s: this.model.s,
v: this.model.v,
a: this.hasAlpha ? this.model.a : void 0
});
this.model.h = h;
this.__update(val, rgbToHex(val), change);
},
__onNumericChange: function __onNumericChange (evt, type, max, change) {
var val = Number(evt.target.value);
if (isNaN(val)) {
return
}
val = Math.floor(val);
if (val < 0 || val > max) {
if (change) {
this.$forceUpdate();
}
return
}
var rgb = {
r: type === 'r' ? val : this.model.r,
g: type === 'g' ? val : this.model.g,
b: type === 'b' ? val : this.model.b,
a: this.hasAlpha
? (type === 'a' ? val : this.model.a)
: void 0
};
if (type !== 'a') {
var hsv = rgbToHsv(rgb);
this.model.h = hsv.h;
this.model.s = hsv.s;
this.model.v = hsv.v;
}
this.__update(rgb, rgbToHex(rgb), change);
},
__onHexChange: function __onHexChange (evt, change) {
var
hex = evt.target.value,
len = hex.length,
edges = this.hasAlpha ? [5, 9] : [4, 7];
if (len !== edges[0] && len !== edges[1]) {
if (change) {
this.$forceUpdate();
}
return
}
var
rgb = hexToRgb(hex),
hsv = rgbToHsv(rgb);
this.model.h = hsv.h;
this.model.s = hsv.s;
this.model.v = hsv.v;
this.__update(rgb, hex, change);
},
__update: function __update (rgb, hex, change) {
var this$1 = this;
var value = this.isOutputHex ? hex : rgb;
// update internally
this.model.hex = hex;
this.model.r = rgb.r;
this.model.g = rgb.g;
this.model.b = rgb.b;
this.model.a = this.hasAlpha ? rgb.a : void 0;
// emit new value
this.$emit('input', value);
this.$nextTick(function () {
if (change && JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__nextInputView: function __nextInputView () {
this.view = this.view === 'hex' ? 'rgba' : 'hex';
},
__parseModel: function __parseModel (v) {
var model = typeof v === 'string' ? hexToRgb(v) : clone(v);
if (this.forceAlpha === (model.a === void 0)) {
model.a = this.forceAlpha ? 100 : void 0;
}
model.hex = rgbToHex(model);
return extend({ a: 100 }, model, rgbToHsv(model))
},
__saturationPan: function __saturationPan (evt) {
if (evt.isFinal) {
this.__dragStop(evt);
}
else if (evt.isFirst) {
this.__dragStart(evt);
}
else {
this.__dragMove(evt);
}
},
__dragStart: function __dragStart (event) {
stopAndPrevent(event.evt);
this.saturationDragging = true;
this.__saturationChange(event);
},
__dragMove: function __dragMove (event) {
if (!this.saturationDragging) {
return
}
stopAndPrevent(event.evt);
this.__saturationChange(event);
},
__dragStop: function __dragStop (event) {
var this$1 = this;
stopAndPrevent(event.evt);
setTimeout(function () {
this$1.saturationDragging = false;
}, 100);
this.__onSaturationChange(
event.position.left,
event.position.top,
true
);
},
__saturationChange: function __saturationChange (evt) {
this.__onSaturationChange(
evt.position.left,
evt.position.top
);
},
__saturationClick: function __saturationClick (evt) {
if (this.saturationDragging) {
return
}
this.__onSaturationChange(
evt.pageX - window.pageXOffset,
evt.pageY - window.pageYOffset,
true
);
}
}
}
var QField = {
name: 'q-field',
props: {
inset: {
type: String,
validator: function (v) { return ['icon', 'label', 'full'].includes(v); }
},
label: String,
count: {
type: [Number, Boolean],
default: false
},
error: Boolean,
errorLabel: String,
warning: Boolean,
warningLabel: String,
helper: String,
icon: String,
dark: Boolean,
orientation: {
type: String,
validator: function (v) { return ['vertical', 'horizontal'].includes(v); }
},
labelWidth: {
type: [Number, String],
default: 5,
validator: function validator (val) {
var v = parseInt(val, 10);
return v > 0 && v < 13
}
}
},
data: function data () {
return {
input: {}
}
},
computed: {
hasError: function hasError () {
return this.input.error || this.error
},
hasWarning: function hasWarning () {
return !this.hasError && (this.input.warning || this.warning)
},
hasBottom: function hasBottom () {
return (this.hasError && this.errorLabel) ||
(this.hasWarning && this.warningLabel) ||
this.helper ||
this.count
},
hasLabel: function hasLabel () {
return this.label || this.$slots.label || ['label', 'full'].includes(this.inset)
},
childHasLabel: function childHasLabel () {
return this.input.floatLabel || this.input.stackLabel
},
isDark: function isDark () {
return this.input.dark || this.dark
},
insetIcon: function insetIcon () {
return ['icon', 'full'].includes(this.inset)
},
hasNoInput: function hasNoInput () {
return !this.input.$options || this.input.__needsBorder
},
counter: function counter () {
if (this.count) {
var length = this.input.length || '0';
return Number.isInteger(this.count)
? (length + " / " + (this.count))
: length
}
},
classes: function classes () {
return {
'q-field-responsive': !this.isVertical && !this.isHorizontal,
'q-field-vertical': this.isVertical,
'q-field-horizontal': this.isHorizontal,
'q-field-floating': this.childHasLabel,
'q-field-no-label': !this.label && !this.$slots.label,
'q-field-with-error': this.hasError,
'q-field-with-warning': this.hasWarning,
'q-field-dark': this.isDark
}
},
computedLabelWidth: function computedLabelWidth () {
return parseInt(this.labelWidth, 10)
},
isVertical: function isVertical () {
return this.orientation === 'vertical' || this.computedLabelWidth === 12
},
isHorizontal: function isHorizontal () {
return this.orientation === 'horizontal'
},
labelClasses: function labelClasses () {
return this.isVertical
? "col-12"
: (this.isHorizontal ? ("col-" + (this.labelWidth)) : ("col-xs-12 col-sm-" + (this.labelWidth)))
},
inputClasses: function inputClasses () {
return this.isVertical
? "col-xs-12"
: (this.isHorizontal ? 'col' : 'col-xs-12 col-sm')
}
},
provide: function provide () {
return {
__field: this
}
},
methods: {
__registerInput: function __registerInput (vm) {
this.input = vm;
},
__unregisterInput: function __unregisterInput () {
this.input = {};
},
__getBottomContent: function __getBottomContent (h) {
if (this.hasError && this.errorLabel) {
return h('div', { staticClass: 'q-field-error col' }, this.errorLabel)
}
if (this.hasWarning && this.warningLabel) {
return h('div', { staticClass: 'q-field-warning col' }, this.warningLabel)
}
if (this.helper) {
return h('div', { staticClass: 'q-field-helper col' }, this.helper)
}
return h('div', { staticClass: 'col' })
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-field row no-wrap items-start',
'class': this.classes
}, [
this.icon
? h(QIcon, {
props: { name: this.icon },
staticClass: 'q-field-icon q-field-margin'
})
: (this.insetIcon ? h('div', { staticClass: 'q-field-icon' }) : null),
h('div', { staticClass: 'row col' }, [
this.hasLabel
? h('div', {
staticClass: 'q-field-label q-field-margin',
'class': this.labelClasses
}, [
h('div', { staticClass: 'q-field-label-inner row items-center' }, [
this.label,
this.$slots.label
])
])
: null,
h('div', {
staticClass: 'q-field-content',
'class': this.inputClasses
}, [
this.$slots.default,
this.hasBottom
? h('div', {
staticClass: 'q-field-bottom row no-wrap',
'class': { 'q-field-no-input': this.hasNoInput }
}, [
this.__getBottomContent(h),
this.counter
? h('div', { staticClass: 'q-field-counter col-auto' }, [ this.counter ])
: null
])
: null
])
])
])
}
}
var QFieldReset = {
name: 'q-field-reset',
provide: function provide () {
return {
__field: undefined
}
},
render: function render (h) {
return h('div', [
this.$slots.default
])
}
}
var contentCss = {
maxHeight: '80vh',
height: 'auto',
boxShadow: 'none',
backgroundColor: '#e4e4e4'
};
var QColor = {
name: 'q-color',
mixins: [FrameMixin, DisplayModeMixin],
props: {
value: {
required: true
},
color: {
type: String,
default: 'primary'
},
defaultSelection: {
type: [String, Object],
default: null
},
type: {
type: String,
default: 'auto',
validator: function (v) { return ['auto', 'hex', 'rgb', 'hexa', 'rgba'].includes(v); }
},
displayValue: String,
placeholder: String,
okLabel: String,
cancelLabel: String
},
data: function data () {
var data = this.isPopover ? {} : {
transition: 'q-modal-bottom'
};
data.focused = false;
data.model = clone(this.value || this.defaultSelection);
return data
},
computed: {
actualValue: function actualValue () {
if (this.displayValue) {
return this.displayValue
}
if (!this.value) {
return this.placeholder || ''
}
if (this.value) {
return typeof this.value === 'string'
? this.value
: ("rgb" + (this.value.a !== void 0 ? 'a' : '') + "(" + (this.value.r) + "," + (this.value.g) + "," + (this.value.b) + (this.value.a !== void 0 ? ("," + (this.value.a / 100)) : '') + ")")
}
}
},
methods: {
toggle: function toggle () {
this[this.$refs.popup.showing ? 'hide' : 'show']();
},
show: function show () {
if (!this.disable) {
if (!this.focused) {
this.__setModel(this.value || this.defaultSelection);
}
return this.$refs.popup.show()
}
},
hide: function hide () {
this.focused = false;
return this.$refs.popup.hide()
},
__handleKeyDown: function __handleKeyDown (e) {
switch (getEventKey(e)) {
case 13: // ENTER key
case 32: // SPACE key
stopAndPrevent(e);
return this.show()
case 8: // BACKSPACE key
if (this.editable && this.clearable && this.actualValue.length) {
this.clear();
}
}
},
__onFocus: function __onFocus () {
if (this.disable || this.focused) {
return
}
this.__setModel(this.value || this.defaultSelection);
this.focused = true;
this.$emit('focus');
},
__onBlur: function __onBlur (e) {
var this$1 = this;
this.__onHide();
setTimeout(function () {
var el = document.activeElement;
if (el !== document.body && !this$1.$refs.popup.$el.contains(el)) {
this$1.hide();
}
}, 1);
},
__onHide: function __onHide (forceUpdate) {
this.focused = false;
this.$emit('blur');
if (forceUpdate || (this.isPopover && this.$refs.popup.showing)) {
this.__update(true);
}
},
__setModel: function __setModel (val, forceUpdate) {
this.model = clone(val);
if (forceUpdate || (this.isPopover && this.$refs.popup.showing)) {
this.__update(forceUpdate);
}
},
__update: function __update (change) {
var this$1 = this;
this.$nextTick(function () {
this$1.$emit('input', this$1.model);
this$1.$nextTick(function () {
if (change && JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
});
});
},
__getPicker: function __getPicker (h, modal) {
var this$1 = this;
var child = [
h(QFieldReset, [
h(QColorPicker, {
staticClass: ("no-border" + (modal ? ' full-width' : '')),
props: extend({
value: this.model || '#000',
disable: this.disable,
readonly: this.readonly,
type: this.type
}, this.$attrs),
on: {
input: function (v) { return this$1.$nextTick(function () { return this$1.__setModel(v); }); }
}
})
])
];
if (modal) {
child['unshift'](h('div', {
staticClass: 'modal-buttons modal-buttons-top row full-width'
}, [
h('div', { staticClass: 'col' }),
h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.cancelLabel || this.$q.i18n.label.cancel,
waitForRipple: true
},
on: { click: this.hide }
}),
this.editable
? h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.okLabel || this.$q.i18n.label.set,
waitForRipple: true
},
on: {
click: function () {
this$1.hide();
this$1.__update(true);
}
}
})
: null
]));
}
return child
}
},
render: function render (h) {
var this$1 = this;
return h(QInputFrame, {
props: {
prefix: this.prefix,
suffix: this.suffix,
stackLabel: this.stackLabel,
floatLabel: this.floatLabel,
error: this.error,
warning: this.warning,
disable: this.disable,
inverted: this.inverted,
dark: this.dark,
hideUnderline: this.hideUnderline,
before: this.before,
after: this.after,
color: this.color,
focused: this.focused,
focusable: true,
length: this.actualValue.length
},
nativeOn: {
click: this.toggle,
focus: this.__onFocus,
blur: this.__onBlur,
keydown: this.__handleKeyDown
}
}, [
h('div', {
staticClass: 'col row items-center q-input-target',
'class': this.alignClass,
domProps: {
innerHTML: this.actualValue
}
}),
this.isPopover
? h(QPopover, {
ref: 'popup',
props: {
offset: [0, 10],
disable: this.disable,
anchorClick: false,
maxHeight: '100vh'
},
on: {
show: this.__onFocus,
hide: function (val) { return this$1.__onHide(true); }
}
}, this.__getPicker(h))
: h(QModal, {
ref: 'popup',
staticClass: 'with-backdrop',
props: {
contentCss: contentCss,
minimized: "ios" === 'mat',
position: 'bottom',
transition: this.transition
},
on: {
show: this.__onFocus,
hide: function (val) { return this$1.__onHide(true); }
}
}, this.__getPicker(h, true)),
this.editable && this.clearable && this.actualValue.length
? h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input[("clear" + (this.inverted ? 'Inverted' : ''))] },
nativeOn: { click: this.clear },
staticClass: 'q-if-control'
})
: null,
h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input.dropdown },
staticClass: 'q-if-control'
})
])
}
}
var ContextMenuDesktop = {
name: 'q-context-menu',
components: {
QPopover: QPopover
},
props: {
disable: Boolean
},
render: function render (h) {
var this$1 = this;
return h(QPopover, {
ref: 'popover',
props: {
anchorClick: false
},
on: {
show: function () { this$1.$emit('show'); },
hide: function () { this$1.$emit('hide'); }
}
}, this.$slots.default)
},
methods: {
hide: function hide () {
return this.$refs.popover.hide()
},
__show: function __show (evt) {
var this$1 = this;
if (!evt || this.disable) {
return
}
this.hide();
stopAndPrevent(evt);
/*
Opening with a timeout for
Firefox workaround
*/
setTimeout(function () {
this$1.$refs.popover.show(evt);
}, 100);
}
},
mounted: function mounted () {
this.target = this.$refs.popover.$el.parentNode;
this.target.addEventListener('contextmenu', this.__show);
this.target.addEventListener('click', this.hide);
},
beforeDestroy: function beforeDestroy () {
this.target.removeEventListener('contexmenu', this.__show);
this.target.removeEventListener('click', this.hide);
}
}
var ContextMenuMobile = {
name: 'q-context-menu',
props: {
disable: Boolean
},
methods: {
hide: function hide () {
this.target.classList.remove('non-selectable');
return this.$refs.dialog.hide()
},
__show: function __show () {
if (!this.disable && this.$refs.dialog) {
this.$refs.dialog.show();
}
},
__touchStartHandler: function __touchStartHandler (evt) {
var this$1 = this;
this.target.classList.add('non-selectable');
this.touchTimer = setTimeout(function () {
stopAndPrevent(evt);
setTimeout(function () {
this$1.__cleanup();
this$1.__show();
}, 10);
}, 600);
},
__cleanup: function __cleanup () {
this.target.classList.remove('non-selectable');
clearTimeout(this.touchTimer);
}
},
render: function render (h) {
var this$1 = this;
return h(QModal, {
ref: 'dialog',
props: {
minimized: true
},
on: {
show: function () { this$1.$emit('show'); },
hide: function () { this$1.$emit('hide'); }
}
}, this.$slots.default)
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.target = this$1.$el.parentNode;
this$1.target.addEventListener('touchstart', this$1.__touchStartHandler)
;['touchcancel', 'touchmove', 'touchend'].forEach(function (evt) {
this$1.target.addEventListener(evt, this$1.__cleanup);
});
});
},
beforeDestroy: function beforeDestroy () {
var this$1 = this;
this.target.removeEventListener('touchstart', this.__touchStartHandler)
;['touchcancel', 'touchmove', 'touchend'].forEach(function (evt) {
this$1.target.removeEventListener(evt, this$1.__cleanup);
});
}
}
var QContextMenu = {
name: 'q-context-menu',
functional: true,
render: function render (h, ctx) {
return h(
Platform.is.mobile ? ContextMenuMobile : ContextMenuDesktop,
ctx.data,
ctx.children
)
}
}
var modelValidator = function (v) {
var type = typeof v;
return (
v === null || v === undefined ||
type === 'number' || type === 'string' ||
isDate(v)
)
};
var inline = {
value: {
validator: modelValidator,
required: true
},
defaultSelection: {
type: [String, Number, Date],
default: null
},
type: {
type: String,
default: 'date',
validator: function (v) { return ['date', 'time', 'datetime'].includes(v); }
},
color: {
type: String,
default: 'primary'
},
dark: Boolean,
min: {
validator: modelValidator,
default: null
},
max: {
validator: modelValidator,
default: null
},
firstDayOfWeek: Number,
formatModel: {
type: String,
default: 'auto',
validator: function (v) { return ['auto', 'date', 'number', 'string'].includes(v); }
},
format24h: {
type: [Boolean, Number],
default: 0,
validator: function (v) { return [true, false, 0].includes(v); }
},
defaultView: {
type: String,
validator: function (v) { return ['year', 'month', 'day', 'hour', 'minute'].includes(v); }
}
};
var input = {
format: String,
placeholder: String,
okLabel: String,
cancelLabel: String,
displayValue: String
};
/* eslint no-fallthrough: 0 */
var MILLISECONDS_IN_DAY = 86400000;
var MILLISECONDS_IN_HOUR = 3600000;
var MILLISECONDS_IN_MINUTE = 60000;
var token = /\[((?:[^\]\\]|\\]|\\)*)\]|d{1,4}|M{1,4}|m{1,2}|w{1,2}|Qo|Do|D{1,4}|YY(?:YY)?|H{1,2}|h{1,2}|s{1,2}|S{1,3}|Z{1,2}|a{1,2}|[AQExX]/g;
function formatTimezone (offset, delimeter) {
if ( delimeter === void 0 ) delimeter = '';
var
sign = offset > 0 ? '-' : '+',
absOffset = Math.abs(offset),
hours = Math.floor(absOffset / 60),
minutes = absOffset % 60;
return sign + pad(hours) + delimeter + pad(minutes)
}
function setMonth (date, newMonth /* 1-based */) {
var
test = new Date(date.getFullYear(), newMonth, 0, 0, 0, 0, 0),
days = test.getDate();
date.setMonth(newMonth - 1, Math.min(days, date.getDate()));
}
function getChange (date, mod, add) {
var
t = new Date(date),
sign = (add ? 1 : -1);
Object.keys(mod).forEach(function (key) {
if (key === 'month') {
setMonth(t, t.getMonth() + 1 + sign * mod.month);
return
}
var op = key === 'year'
? 'FullYear'
: capitalize(key === 'days' ? 'date' : key);
t[("set" + op)](t[("get" + op)]() + sign * mod[key]);
});
return t
}
function isValid (date) {
if (typeof date === 'number') {
return true
}
var t = Date.parse(date);
return isNaN(t) === false
}
function buildDate (mod, utc) {
return adjustDate(new Date(), mod, utc)
}
function getDayOfWeek (date) {
var dow = new Date(date).getDay();
return dow === 0 ? 7 : dow
}
function getWeekOfYear (date) {
// Remove time components of date
var thursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Change date to Thursday same week
thursday.setDate(thursday.getDate() - ((thursday.getDay() + 6) % 7) + 3);
// Take January 4th as it is always in week 1 (see ISO 8601)
var firstThursday = new Date(thursday.getFullYear(), 0, 4);
// Change date to Thursday same week
firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3);
// Check if daylight-saving-time-switch occurred and correct for it
var ds = thursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
thursday.setHours(thursday.getHours() - ds);
// Number of weeks between target Thursday and first Thursday
var weekDiff = (thursday - firstThursday) / (MILLISECONDS_IN_DAY * 7);
return 1 + Math.floor(weekDiff)
}
function isBetweenDates (date, from, to) {
var
d1 = new Date(from).getTime(),
d2 = new Date(to).getTime(),
cur = new Date(date).getTime();
return cur > d1 && cur < d2
}
function addToDate (date, mod) {
return getChange(date, mod, true)
}
function subtractFromDate (date, mod) {
return getChange(date, mod, false)
}
function adjustDate (date, mod, utc) {
var
t = new Date(date),
prefix = "set" + (utc ? 'UTC' : '');
Object.keys(mod).forEach(function (key) {
if (key === 'month') {
setMonth(t, mod.month);
return
}
var op = key === 'year'
? 'FullYear'
: key.charAt(0).toUpperCase() + key.slice(1);
t[("" + prefix + op)](mod[key]);
});
return t
}
function startOfDate (date, unit) {
var t = new Date(date);
switch (unit) {
case 'year':
t.setMonth(0);
case 'month':
t.setDate(1);
case 'day':
t.setHours(0);
case 'hour':
t.setMinutes(0);
case 'minute':
t.setSeconds(0);
case 'second':
t.setMilliseconds(0);
}
return t
}
function endOfDate (date, unit) {
var t = new Date(date);
switch (unit) {
case 'year':
t.setMonth(11);
case 'month':
t.setDate(daysInMonth(date));
case 'day':
t.setHours(23);
case 'hour':
t.setMinutes(59);
case 'minute':
t.setSeconds(59);
case 'second':
t.setMilliseconds(59);
}
return t
}
function getMaxDate (date) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
var t = new Date(date);
args.forEach(function (d) {
t = Math.max(t, new Date(d));
});
return t
}
function getMinDate (date) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
var t = new Date(date);
args.forEach(function (d) {
t = Math.min(t, new Date(d));
});
return t
}
function getDiff (t, sub, interval) {
return (
(t.getTime() - t.getTimezoneOffset() * MILLISECONDS_IN_MINUTE) -
(sub.getTime() - sub.getTimezoneOffset() * MILLISECONDS_IN_MINUTE)
) / interval
}
function getDateDiff (date, subtract, unit) {
if ( unit === void 0 ) unit = 'days';
var
t = new Date(date),
sub = new Date(subtract);
switch (unit) {
case 'years':
return (t.getFullYear() - sub.getFullYear())
case 'months':
return (t.getFullYear() - sub.getFullYear()) * 12 + t.getMonth() - sub.getMonth()
case 'days':
return getDiff(startOfDate(t, 'day'), startOfDate(sub, 'day'), MILLISECONDS_IN_DAY)
case 'hours':
return getDiff(startOfDate(t, 'hour'), startOfDate(sub, 'hour'), MILLISECONDS_IN_HOUR)
case 'minutes':
return getDiff(startOfDate(t, 'minute'), startOfDate(sub, 'minute'), MILLISECONDS_IN_MINUTE)
case 'seconds':
return getDiff(startOfDate(t, 'second'), startOfDate(sub, 'second'), 1000)
}
}
function getDayOfYear (date) {
return getDateDiff(date, startOfDate(date, 'year'), 'days') + 1
}
function inferDateFormat (example) {
if (isDate(example)) {
return 'date'
}
if (typeof example === 'number') {
return 'number'
}
return 'string'
}
function convertDateToFormat (date, type) {
if (!date && date !== 0) {
return
}
switch (type) {
case 'date':
return date
case 'number':
return date.getTime()
default:
return formatDate(date)
}
}
function getDateBetween (date, min, max) {
var t = new Date(date);
if (min) {
var low = new Date(min);
if (t < low) {
return low
}
}
if (max) {
var high = new Date(max);
if (t > high) {
return high
}
}
return t
}
function isSameDate (date, date2, unit) {
var
t = new Date(date),
d = new Date(date2);
if (unit === void 0) {
return t.getTime() === d.getTime()
}
switch (unit) {
case 'second':
if (t.getUTCSeconds() !== d.getUTCSeconds()) {
return false
}
case 'minute': // intentional fall-through
if (t.getUTCMinutes() !== d.getUTCMinutes()) {
return false
}
case 'hour': // intentional fall-through
if (t.getUTCHours() !== d.getUTCHours()) {
return false
}
case 'day': // intentional fall-through
if (t.getUTCDate() !== d.getUTCDate()) {
return false
}
case 'month': // intentional fall-through
if (t.getUTCMonth() !== d.getUTCMonth()) {
return false
}
case 'year': // intentional fall-through
if (t.getUTCFullYear() !== d.getUTCFullYear()) {
return false
}
break
default:
throw new Error(("date isSameDate unknown unit " + unit))
}
return true
}
function daysInMonth (date) {
return (new Date(date.getFullYear(), date.getMonth() + 1, 0)).getDate()
}
function getOrdinal (n) {
if (n >= 11 && n <= 13) {
return (n + "th")
}
switch (n % 10) {
case 1: return (n + "st")
case 2: return (n + "nd")
case 3: return (n + "rd")
}
return (n + "th")
}
var formatter = {
// Year: 00, 01, ..., 99
YY: function YY (date) {
return pad(date.getFullYear(), 4).substr(2)
},
// Year: 1900, 1901, ..., 2099
YYYY: function YYYY (date) {
return pad(date.getFullYear(), 4)
},
// Month: 1, 2, ..., 12
M: function M (date) {
return date.getMonth() + 1
},
// Month: 01, 02, ..., 12
MM: function MM (date) {
return pad(date.getMonth() + 1)
},
// Month Short Name: Jan, Feb, ...
MMM: function MMM (date) {
return i18n.lang.date.monthsShort[date.getMonth()]
},
// Month Name: January, February, ...
MMMM: function MMMM (date) {
return i18n.lang.date.months[date.getMonth()]
},
// Quarter: 1, 2, 3, 4
Q: function Q (date) {
return Math.ceil((date.getMonth() + 1) / 3)
},
// Quarter: 1st, 2nd, 3rd, 4th
Qo: function Qo (date) {
return getOrdinal(this.Q(date))
},
// Day of month: 1, 2, ..., 31
D: function D (date) {
return date.getDate()
},
// Day of month: 1st, 2nd, ..., 31st
Do: function Do (date) {
return getOrdinal(date.getDate())
},
// Day of month: 01, 02, ..., 31
DD: function DD (date) {
return pad(date.getDate())
},
// Day of year: 1, 2, ..., 366
DDD: function DDD (date) {
return getDayOfYear(date)
},
// Day of year: 001, 002, ..., 366
DDDD: function DDDD (date) {
return pad(getDayOfYear(date), 3)
},
// Day of week: 0, 1, ..., 6
d: function d (date) {
return date.getDay()
},
// Day of week: Su, Mo, ...
dd: function dd (date) {
return this.dddd(date).slice(0, 2)
},
// Day of week: Sun, Mon, ...
ddd: function ddd (date) {
return i18n.lang.date.daysShort[date.getDay()]
},
// Day of week: Sunday, Monday, ...
dddd: function dddd (date) {
return i18n.lang.date.days[date.getDay()]
},
// Day of ISO week: 1, 2, ..., 7
E: function E (date) {
return date.getDay() || 7
},
// Week of Year: 1 2 ... 52 53
w: function w (date) {
return getWeekOfYear(date)
},
// Week of Year: 01 02 ... 52 53
ww: function ww (date) {
return pad(getWeekOfYear(date))
},
// Hour: 0, 1, ... 23
H: function H (date) {
return date.getHours()
},
// Hour: 00, 01, ..., 23
HH: function HH (date) {
return pad(date.getHours())
},
// Hour: 1, 2, ..., 12
h: function h (date) {
var hours = date.getHours();
if (hours === 0) {
return 12
}
if (hours > 12) {
return hours % 12
}
return hours
},
// Hour: 01, 02, ..., 12
hh: function hh (date) {
return pad(this.h(date))
},
// Minute: 0, 1, ..., 59
m: function m (date) {
return date.getMinutes()
},
// Minute: 00, 01, ..., 59
mm: function mm (date) {
return pad(date.getMinutes())
},
// Second: 0, 1, ..., 59
s: function s (date) {
return date.getSeconds()
},
// Second: 00, 01, ..., 59
ss: function ss (date) {
return pad(date.getSeconds())
},
// 1/10 of second: 0, 1, ..., 9
S: function S (date) {
return Math.floor(date.getMilliseconds() / 100)
},
// 1/100 of second: 00, 01, ..., 99
SS: function SS (date) {
return pad(Math.floor(date.getMilliseconds() / 10))
},
// Millisecond: 000, 001, ..., 999
SSS: function SSS (date) {
return pad(date.getMilliseconds(), 3)
},
// Meridiem: AM, PM
A: function A (date) {
return this.H(date) < 12 ? 'AM' : 'PM'
},
// Meridiem: am, pm
a: function a (date) {
return this.H(date) < 12 ? 'am' : 'pm'
},
// Meridiem: a.m., p.m
aa: function aa (date) {
return this.H(date) < 12 ? 'a.m.' : 'p.m.'
},
// Timezone: -01:00, +00:00, ... +12:00
Z: function Z (date) {
return formatTimezone(date.getTimezoneOffset(), ':')
},
// Timezone: -0100, +0000, ... +1200
ZZ: function ZZ (date) {
return formatTimezone(date.getTimezoneOffset())
},
// Seconds timestamp: 512969520
X: function X (date) {
return Math.floor(date.getTime() / 1000)
},
// Milliseconds timestamp: 512969520900
x: function x (date) {
return date.getTime()
}
};
function formatDate (val, mask) {
if ( mask === void 0 ) mask = 'YYYY-MM-DDTHH:mm:ss.SSSZ';
if (val !== 0 && !val) {
return
}
var date = new Date(val);
return mask.replace(token, function (match, text) {
if (match in formatter) {
return formatter[match](date)
}
return text === void 0
? match
: text.split('\\]').join(']')
})
}
function matchFormat (format) {
if ( format === void 0 ) format = '';
return format.match(token)
}
function clone$1 (value) {
return isDate(value) ? new Date(value.getTime()) : value
}
var date = Object.freeze({
isValid: isValid,
buildDate: buildDate,
getDayOfWeek: getDayOfWeek,
getWeekOfYear: getWeekOfYear,
isBetweenDates: isBetweenDates,
addToDate: addToDate,
subtractFromDate: subtractFromDate,
adjustDate: adjustDate,
startOfDate: startOfDate,
endOfDate: endOfDate,
getMaxDate: getMaxDate,
getMinDate: getMinDate,
getDateDiff: getDateDiff,
getDayOfYear: getDayOfYear,
inferDateFormat: inferDateFormat,
convertDateToFormat: convertDateToFormat,
getDateBetween: getDateBetween,
isSameDate: isSameDate,
daysInMonth: daysInMonth,
formatter: formatter,
formatDate: formatDate,
matchFormat: matchFormat,
clone: clone$1
});
var DateMixin = {
props: inline,
computed: {
model: {
get: function get () {
var date = isValid(this.value)
? new Date(this.value)
: (this.defaultSelection ? new Date(this.defaultSelection) : startOfDate(new Date(), 'day'));
return getDateBetween(
date,
this.pmin,
this.pmax
)
},
set: function set (val) {
var this$1 = this;
var date = getDateBetween(val, this.pmin, this.pmax);
var value = convertDateToFormat(date, this.formatModel === 'auto' ? inferDateFormat(this.value) : this.formatModel);
this.$emit('input', value);
this.$nextTick(function () {
if (!isSameDate(value, this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
pmin: function pmin () {
return this.min ? new Date(this.min) : null
},
pmax: function pmax () {
return this.max ? new Date(this.max) : null
},
typeHasDate: function typeHasDate () {
return this.type === 'date' || this.type === 'datetime'
},
typeHasTime: function typeHasTime () {
return this.type === 'time' || this.type === 'datetime'
},
year: function year () {
return this.model.getFullYear()
},
month: function month () {
return this.model.getMonth() + 1
},
day: function day () {
return this.model.getDate()
},
minute: function minute () {
return this.model.getMinutes()
},
yearInterval: function yearInterval () {
var
min = this.pmin !== null ? this.pmin.getFullYear() : 1950,
max = this.pmax !== null ? this.pmax.getFullYear() : 2050;
return Math.max(1, max - min + 1)
},
yearMin: function yearMin () {
return this.pmin !== null ? this.pmin.getFullYear() - 1 : 1949
},
monthInterval: function monthInterval () {
var
min = this.pmin !== null && this.pmin.getFullYear() === this.model.getFullYear() ? this.pmin.getMonth() : 0,
max = this.pmax !== null && this.pmax.getFullYear() === this.model.getFullYear() ? this.pmax.getMonth() : 11;
return Math.max(1, max - min + 1)
},
monthMin: function monthMin () {
return this.pmin !== null && this.pmin.getFullYear() === this.model.getFullYear()
? this.pmin.getMonth()
: 0
},
daysInMonth: function daysInMonth$$1 () {
return (new Date(this.model.getFullYear(), this.model.getMonth() + 1, 0)).getDate()
},
editable: function editable () {
return !this.disable && !this.readonly
}
},
methods: {
toggleAmPm: function toggleAmPm () {
if (!this.editable) {
return
}
var
hour = this.model.getHours(),
offset = this.am ? 12 : -12;
this.model = new Date(this.model.setHours(hour + offset));
},
__parseTypeValue: function __parseTypeValue (type, value) {
if (type === 'month') {
return between(value, 1, 12)
}
if (type === 'date') {
return between(value, 1, this.daysInMonth)
}
if (type === 'year') {
var
min = this.pmin ? this.pmin.getFullYear() : 1950,
max = this.pmax ? this.pmax.getFullYear() : 2050;
return between(value, min, max)
}
if (type === 'hour') {
return between(value, 0, 23)
}
if (type === 'minute') {
return between(value, 0, 59)
}
}
}
}
var QDatetimePicker = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-datetime",class:['type-' + _vm.type, _vm.disable ? 'disabled' : '', _vm.readonly ? 'readonly' : '', _vm.dark ? 'q-datetime-dark' : '']},[_vm._t("default"),_vm._v(" "),_c('div',{staticClass:"q-datetime-content non-selectable"},[_c('div',{staticClass:"q-datetime-inner full-height flex justify-center",on:{"touchstart":function($event){$event.stopPropagation();$event.preventDefault();}}},[(_vm.typeHasDate)?[_c('div',{directives:[{name:"touch-pan",rawName:"v-touch-pan.vertical",value:(_vm.__dragMonth),expression:"__dragMonth",modifiers:{"vertical":true}}],staticClass:"q-datetime-col q-datetime-col-month"},[_c('div',{ref:"month",staticClass:"q-datetime-col-wrapper",style:(_vm.__monthStyle)},_vm._l((_vm.monthInterval),function(index){return _c('div',{key:("mi" + index),staticClass:"q-datetime-item"},[_vm._v(" "+_vm._s(_vm.$q.i18n.date.months[index + _vm.monthMin - 1])+" ")])}))]),_vm._v(" "),_c('div',{directives:[{name:"touch-pan",rawName:"v-touch-pan.vertical",value:(_vm.__dragDate),expression:"__dragDate",modifiers:{"vertical":true}}],staticClass:"q-datetime-col q-datetime-col-day"},[_c('div',{ref:"date",staticClass:"q-datetime-col-wrapper",style:(_vm.__dayStyle)},_vm._l((_vm.daysInterval),function(index){return _c('div',{key:("di" + index),staticClass:"q-datetime-item"},[_vm._v(" "+_vm._s(index + _vm.dayMin - 1)+" ")])}))]),_vm._v(" "),_c('div',{directives:[{name:"touch-pan",rawName:"v-touch-pan.vertical",value:(_vm.__dragYear),expression:"__dragYear",modifiers:{"vertical":true}}],staticClass:"q-datetime-col q-datetime-col-year"},[_c('div',{ref:"year",staticClass:"q-datetime-col-wrapper",style:(_vm.__yearStyle)},_vm._l((_vm.yearInterval),function(n){return _c('div',{key:("yi" + n),staticClass:"q-datetime-item"},[_vm._v(" "+_vm._s(n + _vm.yearMin)+" ")])}))])]:_vm._e(),_vm._v(" "),(_vm.typeHasTime)?[_c('div',{directives:[{name:"touch-pan",rawName:"v-touch-pan.vertical",value:(_vm.__dragHour),expression:"__dragHour",modifiers:{"vertical":true}}],staticClass:"q-datetime-col q-datetime-col-hour"},[_c('div',{ref:"hour",staticClass:"q-datetime-col-wrapper",style:(_vm.__hourStyle)},_vm._l((_vm.hourInterval),function(n){return _c('div',{key:("hi" + n),staticClass:"q-datetime-item"},[_vm._v(" "+_vm._s(n + _vm.hourMin - 1)+" ")])}))]),_vm._v(" "),_c('div',{directives:[{name:"touch-pan",rawName:"v-touch-pan.vertical",value:(_vm.__dragMinute),expression:"__dragMinute",modifiers:{"vertical":true}}],staticClass:"q-datetime-col q-datetime-col-minute"},[_c('div',{ref:"minute",staticClass:"q-datetime-col-wrapper",style:(_vm.__minuteStyle)},_vm._l((_vm.minuteInterval),function(n){return _c('div',{key:("ni" + n),staticClass:"q-datetime-item"},[_vm._v(" "+_vm._s(_vm.__pad(n + _vm.minuteMin - 1))+" ")])}))])]:_vm._e()],2),_vm._v(" "),_c('div',{staticClass:"q-datetime-mask"}),_vm._v(" "),_c('div',{staticClass:"q-datetime-highlight"})])],2)},staticRenderFns: [],
name: 'q-datetime-picker',
mixins: [DateMixin, FieldParentMixin],
directives: {
TouchPan: TouchPan
},
props: {
defaultSelection: [String, Number, Date],
disable: Boolean,
readonly: Boolean
},
data: function data () {
return {
monthDragOffset: 0,
dateDragOffset: 0,
yearDragOffset: 0,
hourDragOffset: 0,
minuteDragOffset: 0,
dragging: false
}
},
watch: {
model: function model () {
this.$nextTick(this.__updateAllPositions);
}
},
computed: {
dayMin: function dayMin () {
return this.pmin !== null && isSameDate(this.pmin, this.model, 'month')
? this.pmin.getDate()
: 1
},
dayMax: function dayMax () {
return this.pmax !== null && isSameDate(this.pmax, this.model, 'month')
? this.pmax.getDate()
: this.daysInMonth
},
daysInterval: function daysInterval () {
return this.dayMax - this.dayMin + 1
},
hour: function hour () {
return this.model.getHours()
},
hourMin: function hourMin () {
return this.pmin && isSameDate(this.pmin, this.model, 'day') ? this.pmin.getHours() : 0
},
hourInterval: function hourInterval () {
return (this.pmax && isSameDate(this.pmax, this.model, 'day') ? this.pmax.getHours() : 23) - this.hourMin + 1
},
minuteMin: function minuteMin () {
return this.pmin && isSameDate(this.pmin, this.model, 'hour') ? this.pmin.getMinutes() : 0
},
minuteInterval: function minuteInterval () {
return (this.pmax && isSameDate(this.pmax, this.model, 'hour') ? this.pmax.getMinutes() : 59) - this.minuteMin + 1
},
__monthStyle: function __monthStyle () {
return this.__colStyle(82 - (this.month - 1 + this.monthDragOffset) * 36)
},
__dayStyle: function __dayStyle () {
return this.__colStyle(82 - (this.day + this.dateDragOffset) * 36)
},
__yearStyle: function __yearStyle () {
return this.__colStyle(82 - (this.year + this.yearDragOffset) * 36)
},
__hourStyle: function __hourStyle () {
return this.__colStyle(82 - (this.hour + this.hourDragOffset) * 36)
},
__minuteStyle: function __minuteStyle () {
return this.__colStyle(82 - (this.minute + this.minuteDragOffset) * 36)
}
},
methods: {
__dragMonth: function __dragMonth (e) {
this.__drag(e, 'month');
},
__dragDate: function __dragDate (e) {
this.__drag(e, 'date');
},
__dragYear: function __dragYear (e) {
this.__drag(e, 'year');
},
__dragHour: function __dragHour (e) {
this.__drag(e, 'hour');
},
__dragMinute: function __dragMinute (e) {
this.__drag(e, 'minute');
},
__drag: function __drag (e, type) {
var method = e.isFirst
? '__dragStart' : (e.isFinal ? '__dragStop' : '__dragMove');
this[method](e.evt, type);
},
/* date */
setYear: function setYear (value) {
if (this.editable) {
this.model = new Date(this.model.setFullYear(this.__parseTypeValue('year', value)));
}
},
setMonth: function setMonth (value) {
if (this.editable) {
this.model = adjustDate(this.model, {month: value});
}
},
setDay: function setDay (value) {
if (this.editable) {
this.model = new Date(this.model.setDate(this.__parseTypeValue('date', value)));
}
},
/* time */
setHour: function setHour (value) {
if (this.editable) {
this.model = new Date(this.model.setHours(this.__parseTypeValue('hour', value)));
}
},
setMinute: function setMinute (value) {
if (this.editable) {
this.model = new Date(this.model.setMinutes(this.__parseTypeValue('minute', value)));
}
},
setView: function setView () {},
/* helpers */
__pad: function __pad (unit, filler) {
return (unit < 10 ? filler || '0' : '') + unit
},
__scrollView: function __scrollView () {},
__updateAllPositions: function __updateAllPositions () {
var this$1 = this;
this.$nextTick(function () {
if (this$1.typeHasDate) {
this$1.__updatePositions('month', this$1.model.getMonth());
this$1.__updatePositions('date', this$1.model.getDate());
this$1.__updatePositions('year', this$1.model.getFullYear());
}
if (this$1.typeHasTime) {
this$1.__updatePositions('hour', this$1.model.getHours());
this$1.__updatePositions('minute', this$1.model.getMinutes());
}
});
},
__updatePositions: function __updatePositions (type, value) {
var this$1 = this;
var root = this.$refs[type];
if (!root) {
return
}
var delta = -value;
if (type === 'year') {
delta += this.yearMin + 1;
}
else if (type === 'date') {
delta += this.dayMin;
}
else {
delta += this[type + 'Min'];
}
[].slice.call(root.children).forEach(function (item) {
css(item, this$1.__itemStyle(value * 36, between(delta * -18, -180, 180)));
delta++;
});
},
__colStyle: function __colStyle (value) {
return {
'-webkit-transform': 'translate3d(0,' + value + 'px,0)',
'-ms-transform': 'translate3d(0,' + value + 'px,0)',
'transform': 'translate3d(0,' + value + 'px,0)'
}
},
__itemStyle: function __itemStyle (translation, rotation) {
return {
'-webkit-transform': 'translate3d(0, ' + translation + 'px, 0) rotateX(' + rotation + 'deg)',
'-ms-transform': 'translate3d(0, ' + translation + 'px, 0) rotateX(' + rotation + 'deg)',
'transform': 'translate3d(0, ' + translation + 'px, 0) rotateX(' + rotation + 'deg)'
}
},
/* common */
__dragStart: function __dragStart (ev, type) {
if (!this.editable) {
return
}
stopAndPrevent(ev);
this[type + 'DragOffset'] = 0;
this.dragging = type;
this.__actualType = type === 'date' ? 'day' : type;
this.__typeOffset = type === 'month' ? -1 : 0;
this.__dragPosition = position(ev).top;
},
__dragMove: function __dragMove (ev, type) {
if (this.dragging !== type || !this.editable) {
return
}
stopAndPrevent(ev);
var offset$$1 = (this.__dragPosition - position(ev).top) / 36;
this[type + 'DragOffset'] = offset$$1;
this.__updatePositions(type, this[this.__actualType] + offset$$1 + this.__typeOffset);
},
__dragStop: function __dragStop (ev, type) {
var this$1 = this;
if (this.dragging !== type || !this.editable) {
return
}
stopAndPrevent(ev);
this.dragging = false;
var
offset$$1 = Math.round(this[type + 'DragOffset']),
newValue = this.__parseTypeValue(type, this[this.__actualType] + offset$$1);
if (newValue !== this[this.__actualType]) {
this[("set" + (capitalize(this.__actualType)))](newValue);
}
else {
this.__updatePositions(type, this[this.__actualType] + this.__typeOffset);
}
this.$nextTick(function () {
this$1[type + 'DragOffset'] = 0;
});
}
},
mounted: function mounted () {
this.$nextTick(this.__updateAllPositions);
}
}
var contentCss$1 = {
maxHeight: '80vh',
height: 'auto',
boxShadow: 'none',
backgroundColor: '#e4e4e4'
};
var QDatetime = {
name: 'q-datetime',
mixins: [FrameMixin, DisplayModeMixin],
props: extend(
input,
inline
),
data: function data () {
var data = this.isPopover ? {} : {
transition: 'q-modal-bottom'
};
data.focused = false;
data.model = clone$1(isValid(this.value) ? this.value : this.defaultSelection);
return data
},
computed: {
actualValue: function actualValue () {
if (this.displayValue) {
return this.displayValue
}
if (!isValid(this.value)) {
return this.placeholder || ''
}
var format;
if (this.format) {
format = this.format;
}
else if (this.type === 'date') {
format = 'YYYY-MM-DD';
}
else if (this.type === 'time') {
format = 'HH:mm';
}
else {
format = 'YYYY-MM-DD HH:mm:ss';
}
return formatDate(this.value, format, /* for reactiveness */ this.$q.i18n.date)
}
},
methods: {
toggle: function toggle () {
this[this.$refs.popup.showing ? 'hide' : 'show']();
},
show: function show () {
if (!this.disable) {
if (!this.focused) {
this.__setModel(isValid(this.value) ? this.value : this.defaultSelection);
}
return this.$refs.popup.show()
}
},
hide: function hide () {
this.focused = false;
return this.$refs.popup.hide()
},
__handleKeyDown: function __handleKeyDown (e) {
switch (getEventKey(e)) {
case 13: // ENTER key
case 32: // SPACE key
stopAndPrevent(e);
return this.show()
case 8: // BACKSPACE key
if (this.editable && this.clearable && this.actualValue.length) {
this.clear();
}
}
},
__onFocus: function __onFocus () {
if (this.disable || this.focused) {
return
}
if (this.defaultView) {
var target = this.$refs.target;
if (target.view !== this.defaultView) {
target.setView(this.defaultView);
}
else {
target.__scrollView();
}
}
this.__setModel(isValid(this.value) ? this.value : this.defaultSelection);
this.focused = true;
this.$emit('focus');
},
__onBlur: function __onBlur (e) {
var this$1 = this;
this.__onHide();
setTimeout(function () {
var el = document.activeElement;
if (el !== document.body && !this$1.$refs.popup.$el.contains(el)) {
this$1.hide();
}
}, 1);
},
__onHide: function __onHide (forceUpdate) {
this.focused = false;
this.$emit('blur');
if (forceUpdate || (this.isPopover && this.$refs.popup.showing)) {
this.__update(true);
}
},
__setModel: function __setModel (val, forceUpdate) {
this.model = clone$1(val);
if (forceUpdate || (this.isPopover && this.$refs.popup.showing)) {
this.__update(forceUpdate);
}
},
__update: function __update (change) {
var this$1 = this;
this.$nextTick(function () {
this$1.$emit('input', this$1.model);
this$1.$nextTick(function () {
if (change && !isSameDate(this$1.model, this$1.value)) {
this$1.$emit('change', this$1.model);
}
});
});
},
__getPicker: function __getPicker (h, modal) {
var this$1 = this;
return [
h(QFieldReset, [
h(QDatetimePicker, {
ref: 'target',
staticClass: "no-border",
props: {
type: this.type,
min: this.min,
max: this.max,
formatModel: this.formatModel,
format24h: this.format24h,
firstDayOfWeek: this.firstDayOfWeek,
defaultView: this.defaultView,
color: this.color,
value: this.model,
disable: this.disable,
readonly: this.readonly
},
on: {
input: function (v) { return this$1.$nextTick(function () { return this$1.__setModel(v); }); },
canClose: function () {
if (this$1.isPopover) {
this$1.hide();
}
}
}
}, [
modal
? h('div', {
staticClass: 'modal-buttons modal-buttons-top row full-width'
}, [
h('div', { staticClass: 'col' }),
h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.cancelLabel || this.$q.i18n.label.cancel,
waitForRipple: true
},
on: { click: this.hide }
}),
this.editable
? h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.okLabel || this.$q.i18n.label.set,
waitForRipple: true
},
on: {
click: function () {
this$1.hide();
this$1.__update(true);
}
}
})
: null
])
: null
])
])
]
}
},
render: function render (h) {
var this$1 = this;
return h(QInputFrame, {
props: {
prefix: this.prefix,
suffix: this.suffix,
stackLabel: this.stackLabel,
floatLabel: this.floatLabel,
error: this.error,
warning: this.warning,
disable: this.disable,
readonly: this.readonly,
inverted: this.inverted,
dark: this.dark,
hideUnderline: this.hideUnderline,
before: this.before,
after: this.after,
color: this.color,
focused: this.focused,
focusable: true,
length: this.actualValue.length
},
nativeOn: {
click: this.toggle,
focus: this.__onFocus,
blur: this.__onBlur,
keydown: this.__handleKeyDown
}
}, [
h('div', {
staticClass: 'col row items-center q-input-target',
'class': this.alignClass,
domProps: {
innerHTML: this.actualValue
}
}),
this.isPopover
? h(QPopover, {
ref: 'popup',
props: {
offset: [0, 10],
disable: this.disable,
anchorClick: false,
maxHeight: '100vh'
},
on: {
show: this.__onFocus,
hide: function (val) { return this$1.__onHide(true); }
}
}, this.__getPicker(h))
: h(QModal, {
ref: 'popup',
staticClass: 'with-backdrop',
props: {
contentCss: contentCss$1,
minimized: "ios" === 'mat',
position: 'bottom',
transition: this.transition
},
on: {
show: this.__onFocus,
hide: function (val) { return this$1.__onHide(true); }
}
}, this.__getPicker(h, true)),
this.editable && this.clearable && this.actualValue.length
? h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input[("clear" + (this.inverted ? 'Inverted' : ''))] },
nativeOn: { click: this.clear },
staticClass: 'q-if-control'
})
: null,
h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input.dropdown },
staticClass: 'q-if-control'
})
])
}
}
var inputTypes = [
'text', 'textarea', 'email',
'tel', 'file', 'number',
'password', 'url', 'time', 'date'
]
var QResizeObservable = {
name: 'q-resize-observable',
methods: {
onResize: function onResize () {
var size = {
width: this.parent.offsetWidth,
height: this.parent.offsetHeight
};
if (size.width === this.size.width && size.height === this.size.height) {
return
}
this.size = size;
this.$emit('resize', this.size);
}
},
render: function render (h) {
return h('div', {
staticClass: 'absolute-full overflow-hidden invisible',
style: 'z-index: -1;'
})
},
mounted: function mounted () {
var this$1 = this;
var
object = document.createElement('object'),
onIE = this.$q.platform.is.ie;
this.parent = this.$el.parentNode;
this.size = { width: -1, height: -1 };
this.onResize = debounce(this.onResize, 100);
this.onResize();
this.object = object;
object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
object.onload = function () {
object.contentDocument.defaultView.addEventListener('resize', this$1.onResize, listenOpts.passive);
};
object.type = 'text/html';
if (onIE) {
this.$el.appendChild(object);
}
object.data = 'about:blank';
if (!onIE) {
this.$el.appendChild(object);
}
},
beforeDestroy: function beforeDestroy () {
if (this.object && this.object.onload) {
if (!this.$q.platform.is.ie && this.object.contentDocument) {
this.object.contentDocument.defaultView.removeEventListener('resize', this.onResize, listenOpts.passive);
}
delete this.object.onload;
}
}
}
var QScrollObservable = {
name: 'q-scroll-observable',
render: function render () {},
data: function data () {
return {
pos: 0,
dir: 'down',
dirChanged: false,
dirChangePos: 0
}
},
methods: {
getPosition: function getPosition () {
return {
position: this.pos,
direction: this.dir,
directionChanged: this.dirChanged,
inflexionPosition: this.dirChangePos
}
},
trigger: function trigger () {
if (!this.timer) {
this.timer = window.requestAnimationFrame(this.emit);
}
},
emit: function emit () {
var
pos = Math.max(0, getScrollPosition(this.target)),
delta = pos - this.pos,
dir = delta < 0 ? 'up' : 'down';
this.dirChanged = this.dir !== dir;
if (this.dirChanged) {
this.dir = dir;
this.dirChangePos = this.pos;
}
this.timer = null;
this.pos = pos;
this.$emit('scroll', this.getPosition());
}
},
mounted: function mounted () {
this.target = getScrollTarget(this.$el.parentNode);
this.target.addEventListener('scroll', this.trigger, listenOpts.passive);
this.trigger();
},
beforeDestroy: function beforeDestroy () {
this.target.removeEventListener('scroll', this.trigger, listenOpts.passive);
}
}
var QWindowResizeObservable = {
name: 'q-window-resize-observable',
render: function render () {},
methods: {
trigger: function trigger () {
if (!this.timer) {
this.timer = window.requestAnimationFrame(this.emit);
}
},
emit: function emit () {
this.timer = null;
this.$emit('resize', viewport());
}
},
created: function created () {
this.emit();
},
mounted: function mounted () {
window.addEventListener('resize', this.trigger, listenOpts.passive);
},
beforeDestroy: function beforeDestroy () {
window.removeEventListener('resize', this.trigger, listenOpts.passive);
}
}
var QInput = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('q-input-frame',{staticClass:"q-input",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.color,"focused":_vm.focused,"length":_vm.length,"top-addons":_vm.isTextarea},on:{"click":_vm.__onClick,"focus":_vm.__onFocus}},[_vm._t("before"),_vm._v(" "),(_vm.isTextarea)?[_c('div',{staticClass:"col row relative-position"},[_c('q-resize-observable',{on:{"resize":function($event){_vm.__updateArea();}}}),_vm._v(" "),_c('textarea',_vm._b({ref:"shadow",staticClass:"col q-input-target q-input-shadow absolute-top",domProps:{"value":_vm.model}},'textarea',_vm.$attrs,false)),_vm._v(" "),_c('textarea',_vm._b({ref:"input",staticClass:"col q-input-target q-input-area",attrs:{"placeholder":_vm.inputPlaceholder,"disabled":_vm.disable,"readonly":_vm.readonly},domProps:{"value":_vm.model},on:{"input":_vm.__set,"focus":_vm.__onFocus,"blur":_vm.__onInputBlur,"keydown":_vm.__onKeydown,"keyup":_vm.__onKeyup}},'textarea',_vm.$attrs,false))],1)]:_c('input',_vm._b({ref:"input",staticClass:"col q-input-target q-no-input-spinner",class:[("text-" + (_vm.align))],attrs:{"placeholder":_vm.inputPlaceholder,"disabled":_vm.disable,"readonly":_vm.readonly,"step":_vm.computedStep,"type":_vm.inputType},domProps:{"value":_vm.model},on:{"input":_vm.__set,"focus":_vm.__onFocus,"blur":_vm.__onInputBlur,"keydown":_vm.__onKeydown,"keyup":_vm.__onKeyup}},'input',_vm.$attrs,false)),_vm._v(" "),(!_vm.disable && _vm.isPassword && !_vm.noPassToggle && _vm.length)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input[_vm.showPass ? 'showPass' : 'hidePass']},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.togglePass($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.editable && _vm.keyboardToggle)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input[_vm.showNumber ? 'showNumber' : 'hideNumber']},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.toggleNumber($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.editable && _vm.clearable && _vm.length)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input[("clear" + (this.inverted ? 'Inverted' : ''))]},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.clear($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.isLoading)?_c('q-spinner',{staticClass:"q-if-control",attrs:{"slot":"after","size":"24px"},slot:"after"}):_vm._e(),_vm._v(" "),_vm._t("after"),_vm._v(" "),_vm._t("default")],2)},staticRenderFns: [],
name: 'q-input',
mixins: [FrameMixin, InputMixin],
components: {
QInputFrame: QInputFrame,
QSpinner: QSpinner,
QResizeObservable: QResizeObservable
},
props: {
value: { required: true },
type: {
type: String,
default: 'text',
validator: function (t) { return inputTypes.includes(t); }
},
clearable: Boolean,
noPassToggle: Boolean,
numericKeyboardToggle: Boolean,
readonly: Boolean,
decimals: Number,
step: Number,
upperCase: Boolean
},
data: function data () {
var this$1 = this;
return {
showPass: false,
showNumber: true,
model: this.value,
watcher: null,
shadow: {
val: this.model,
set: this.__set,
loading: false,
watched: false,
hasFocus: function () {
return document.activeElement === this$1.$refs.input
},
register: function () {
this$1.shadow.watched = true;
this$1.__watcherRegister();
},
unregister: function () {
this$1.shadow.watched = false;
this$1.__watcherUnregister();
},
getEl: function () {
return this$1.$refs.input
}
}
}
},
watch: {
value: function value (v) {
this.model = v;
this.isNumberError = false;
},
isTextarea: function isTextarea (v) {
this[v ? '__watcherRegister' : '__watcherUnregister']();
}
},
provide: function provide () {
return {
__input: this.shadow
}
},
computed: {
isNumber: function isNumber () {
return this.type === 'number'
},
isPassword: function isPassword () {
return this.type === 'password'
},
isTextarea: function isTextarea () {
return this.type === 'textarea'
},
isLoading: function isLoading () {
return this.loading || this.shadow.loading
},
pattern: function pattern () {
if (this.isNumber) {
return this.$attrs.pattern || '[0-9]*'
}
},
keyboardToggle: function keyboardToggle () {
return this.$q.platform.is.mobile &&
this.isNumber &&
this.numericKeyboardToggle &&
length
},
inputType: function inputType () {
if (this.isPassword) {
return this.showPass && this.editable ? 'text' : 'password'
}
return this.isNumber
? (this.showNumber || !this.editable ? 'number' : 'text')
: this.type
},
length: function length () {
return this.model !== null && this.model !== undefined
? ('' + this.model).length
: 0
},
computedStep: function computedStep () {
return this.step || (this.decimals ? Math.pow( 10, -this.decimals ) : 'any')
}
},
methods: {
togglePass: function togglePass () {
this.showPass = !this.showPass;
clearTimeout(this.timer);
this.focus();
},
toggleNumber: function toggleNumber () {
this.showNumber = !this.showNumber;
clearTimeout(this.timer);
this.focus();
},
__clearTimer: function __clearTimer () {
var this$1 = this;
this.$nextTick(function () { return clearTimeout(this$1.timer); });
},
__setModel: function __setModel (val) {
clearTimeout(this.timer);
this.focus();
this.__set(val || (this.isNumber ? null : ''), true);
},
__set: function __set (e, forceUpdate) {
var this$1 = this;
var val = e && e.target ? e.target.value : e;
if (this.isNumber) {
var forcedValue = val;
val = parseFloat(val);
if (isNaN(val)) {
this.isNumberError = true;
if (forceUpdate) {
this.$emit('input', forcedValue);
this.$nextTick(function () {
if (JSON.stringify(forcedValue) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', forcedValue);
}
});
}
return
}
this.isNumberError = false;
if (Number.isInteger(this.decimals)) {
val = parseFloat(val.toFixed(this.decimals));
}
}
else if (this.upperCase) {
val = val.toUpperCase();
}
this.model = val;
this.$emit('input', val);
if (forceUpdate) {
this.$nextTick(function () {
if (JSON.stringify(val) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', val);
}
});
}
},
__updateArea: function __updateArea () {
var shadow = this.$refs.shadow;
if (shadow) {
var h = shadow.scrollHeight;
var max = this.maxHeight || h;
this.$refs.input.style.minHeight = (between(h, 19, max)) + "px";
}
},
__watcher: function __watcher (value) {
if (this.isTextarea) {
this.__updateArea(value);
}
if (this.shadow.watched) {
this.shadow.val = value;
}
},
__watcherRegister: function __watcherRegister () {
if (!this.watcher) {
this.watcher = this.$watch('model', this.__watcher);
}
},
__watcherUnregister: function __watcherUnregister (forceUnregister) {
if (
this.watcher &&
(forceUnregister || (!this.isTextarea && !this.shadow.watched))
) {
this.watcher();
this.watcher = null;
}
}
},
mounted: function mounted () {
this.__updateArea = frameDebounce(this.__updateArea);
if (this.isTextarea) {
this.__updateArea();
this.__watcherRegister();
}
},
beforeDestroy: function beforeDestroy () {
this.__watcherUnregister(true);
}
}
var QRadio = {
name: 'q-radio',
mixins: [OptionMixin],
props: {
val: {
required: true
}
},
computed: {
isTrue: function isTrue () {
return this.value === this.val
}
},
methods: {
toggle: function toggle (evt, blur) {
if ( blur === void 0 ) blur = true;
if (this.disable || this.readonly) {
return
}
if (evt) {
stopAndPrevent(evt);
}
if (blur) {
this.$el.blur();
}
if (!this.isTrue) {
this.__update(this.val);
}
},
__getContent: function __getContent (h) {
return [
h(QIcon, {
staticClass: 'q-radio-unchecked cursor-pointer absolute-full',
props: {
name: this.uncheckedIcon || this.$q.icon.radio.unchecked["ios"]
}
}),
h(QIcon, {
staticClass: 'q-radio-checked cursor-pointer absolute-full',
props: {
name: this.checkedIcon || this.$q.icon.radio.checked["ios"]
}
}),
null
]
}
}
}
var QToggle = {
name: 'q-toggle',
mixins: [CheckboxMixin, OptionMixin],
props: {
icon: String
},
computed: {
currentIcon: function currentIcon () {
return (this.isActive ? this.checkedIcon : this.uncheckedIcon) || this.icon
},
iconColor: function iconColor () {
return 'dark'
},
baseClass: function baseClass () {
if ("ios" === 'ios' && this.dark) {
return "q-toggle-base-dark"
}
}
},
methods: {
__swipe: function __swipe (evt) {
if (evt.direction === 'left') {
if (this.isTrue) {
this.toggle();
}
}
else if (evt.direction === 'right') {
if (this.isFalse) {
this.toggle();
}
}
},
__getContent: function __getContent (h) {
return [
h('div', { staticClass: 'q-toggle-base', 'class': this.baseClass }),
h('div', { staticClass: 'q-toggle-handle row flex-center' }, [
this.currentIcon
? h(QIcon, {
staticClass: 'q-toggle-icon',
props: { name: this.currentIcon, color: this.iconColor }
})
: null,
null
])
]
}
}
}
var QOptionGroup = {
name: 'q-option-group',
mixins: [FieldParentMixin],
components: {
QRadio: QRadio,
QCheckbox: QCheckbox,
QToggle: QToggle
},
props: {
value: {
required: true
},
type: {
default: 'radio',
validator: function (v) { return ['radio', 'checkbox', 'toggle'].includes(v); }
},
color: String,
keepColor: Boolean,
dark: Boolean,
options: {
type: Array,
validator: function validator (opts) {
return opts.every(function (opt) { return 'value' in opt && 'label' in opt; })
}
},
leftLabel: Boolean,
inline: Boolean,
disable: Boolean,
readonly: Boolean
},
computed: {
component: function component () {
return ("q-" + (this.type))
},
model: function model () {
return Array.isArray(this.value) ? this.value.slice() : this.value
},
length: function length () {
return this.value
? (this.type === 'radio' ? 1 : this.value.length)
: 0
},
__needsBorder: function __needsBorder () {
return true
}
},
methods: {
__onFocus: function __onFocus () {
this.$emit('focus');
},
__onBlur: function __onBlur () {
this.$emit('blur');
},
__update: function __update (value) {
var this$1 = this;
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
created: function created () {
var isArray = Array.isArray(this.value);
if (this.type === 'radio') {
if (isArray) {
console.error('q-option-group: model should not be array');
}
}
else if (!isArray) {
console.error('q-option-group: model should be array in your case');
}
},
render: function render (h) {
var this$1 = this;
return h(
'div',
{
staticClass: 'q-option-group group',
'class': { 'q-option-group-inline-opts': this.inline }
},
this.options.map(
function (opt) { return h('div', [
h(this$1.component, {
props: {
value: this$1.value,
val: opt.value,
readonly: this$1.readonly || opt.readonly,
disable: this$1.disable || opt.disable,
label: opt.label,
leftLabel: this$1.leftLabel || opt.leftLabel,
color: opt.color || this$1.color,
checkedIcon: opt.checkedIcon,
uncheckedIcon: opt.uncheckedIcon,
dark: opt.dark || this$1.dark,
keepColor: opt.keepColor || this$1.keepColor
},
on: {
input: this$1.__update,
focus: this$1.__onFocus,
blur: this$1.__onBlur
}
})
]); }
)
)
}
}
var QDialog = {
name: 'q-dialog',
props: {
value: Boolean,
title: String,
message: String,
prompt: Object,
options: Object,
ok: {
type: [String, Boolean],
default: true
},
cancel: [String, Boolean],
stackButtons: Boolean,
preventClose: Boolean,
position: String,
color: {
type: String,
default: 'primary'
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
title = this.$slots.title || this.title,
msg = this.$slots.message || this.message;
if (title) {
child.push(
h('div', {
staticClass: 'modal-header'
}, [ title ])
);
}
if (msg) {
child.push(
h('div', {
staticClass: 'modal-body modal-message modal-scroll'
}, [ msg ])
);
}
if (this.hasForm || this.$slots.body) {
child.push(
h(
'div',
{ staticClass: 'modal-body modal-scroll' },
this.hasForm
? (this.prompt ? this.__getPrompt(h) : this.__getOptions(h))
: [ this.$slots.body ]
)
);
}
if (this.$scopedSlots.buttons) {
child.push(
h('div', {
staticClass: 'modal-buttons',
'class': this.buttonClass
}, [
this.$scopedSlots.buttons({
ok: this.__onOk,
cancel: this.__onCancel
})
])
);
}
else if (this.ok || this.cancel) {
child.push(this.__getButtons(h));
}
return h(QModal, {
ref: 'modal',
props: {
value: this.value,
minimized: true,
noBackdropDismiss: this.preventClose,
noEscDismiss: this.preventClose,
position: this.position
},
on: {
input: function (val) {
this$1.$emit('input', val);
},
show: function () {
this$1.$emit('show');
if (!this$1.$q.platform.is.desktop) {
return
}
var node = this$1.prompt
? this$1.$refs.modal.$el.getElementsByTagName('INPUT')
: this$1.$refs.modal.$el.getElementsByClassName('q-option');
if (node.length) {
node[0].focus();
return
}
node = this$1.$refs.modal.$el.getElementsByTagName('BUTTON');
if (node.length) {
node[node.length - 1].focus();
}
},
hide: function () {
this$1.$emit('hide');
},
dismiss: function () {
this$1.$emit('cancel');
},
'escape-key': function () {
this$1.hide().then(function () {
this$1.$emit('escape-key');
this$1.$emit('cancel');
});
}
}
}, child)
},
computed: {
hasForm: function hasForm () {
return this.prompt || this.options
},
okLabel: function okLabel () {
return this.ok === true
? this.$q.i18n.label.ok
: this.ok
},
cancelLabel: function cancelLabel () {
return this.cancel === true
? this.$q.i18n.label.cancel
: this.cancel
},
buttonClass: function buttonClass () {
return this.stackButtons
? 'column'
: 'row'
}
},
methods: {
show: function show () {
return this.$refs.modal.show()
},
hide: function hide () {
var this$1 = this;
var data;
return this.$refs.modal.hide().then(function () {
if (this$1.hasForm) {
data = clone(this$1.__getData());
}
return data
})
},
__getPrompt: function __getPrompt (h) {
var this$1 = this;
return [
h(QInput, {
style: 'margin-bottom: 10px',
props: {
value: this.prompt.model,
type: this.prompt.type || 'text',
color: this.color,
noPassToggle: true
},
on: {
change: function (v) { this$1.prompt.model = v; }
}
})
]
},
__getOptions: function __getOptions (h) {
var this$1 = this;
return [
h(QOptionGroup, {
props: {
value: this.options.model,
type: this.options.type,
color: this.color,
inline: this.options.inline,
options: this.options.items
},
on: {
change: function (v) { this$1.options.model = v; }
}
})
]
},
__getButtons: function __getButtons (h) {
var child = [];
if (this.cancel) {
child.push(h(QBtn, {
props: { color: this.color, flat: true, label: this.cancelLabel, waitForRipple: true },
on: { click: this.__onCancel }
}));
}
if (this.ok) {
child.push(h(QBtn, {
props: { color: this.color, flat: true, label: this.okLabel, waitForRipple: true },
on: { click: this.__onOk }
}));
}
return h('div', {
staticClass: 'modal-buttons',
'class': this.buttonClass
}, child)
},
__onOk: function __onOk () {
var this$1 = this;
return this.hide().then(function (data) {
this$1.$emit('ok', data);
})
},
__onCancel: function __onCancel () {
var this$1 = this;
return this.hide().then(function () {
this$1.$emit('cancel');
})
},
__getData: function __getData () {
if (this.prompt) {
return this.prompt.model
}
if (this.options) {
return this.options.model
}
}
}
}
var QTooltip = {
name: 'q-tooltip',
mixins: [ModelToggleMixin],
props: {
anchor: {
type: String,
default: 'top middle',
validator: positionValidator
},
self: {
type: String,
default: 'bottom middle',
validator: positionValidator
},
offset: {
type: Array,
validator: offsetValidator
},
delay: {
type: Number,
default: 0
},
maxHeight: String,
disable: Boolean
},
watch: {
$route: function $route () {
this.hide();
}
},
computed: {
anchorOrigin: function anchorOrigin () {
return parsePosition(this.anchor)
},
selfOrigin: function selfOrigin () {
return parsePosition(this.self)
},
transformCSS: function transformCSS () {
return getTransformProperties({
selfOrigin: this.selfOrigin
})
}
},
methods: {
__show: function __show () {
clearTimeout(this.timer);
document.body.appendChild(this.$el);
this.scrollTarget = getScrollTarget(this.anchorEl);
this.scrollTarget.addEventListener('scroll', this.hide, listenOpts.passive);
window.addEventListener('resize', this.__debouncedUpdatePosition, listenOpts.passive);
if (this.$q.platform.is.mobile) {
document.body.addEventListener('click', this.hide, true);
}
this.__updatePosition();
this.showPromise && this.showPromiseResolve();
},
__hide: function __hide () {
clearTimeout(this.timer);
this.scrollTarget.removeEventListener('scroll', this.hide, listenOpts.passive);
window.removeEventListener('resize', this.__debouncedUpdatePosition, listenOpts.passive);
document.body.removeChild(this.$el);
if (this.$q.platform.is.mobile) {
document.body.removeEventListener('click', this.hide, true);
}
this.hidePromise && this.hidePromiseResolve();
},
__updatePosition: function __updatePosition () {
setPosition({
el: this.$el,
offset: this.offset,
anchorEl: this.anchorEl,
anchorOrigin: this.anchorOrigin,
selfOrigin: this.selfOrigin,
maxHeight: this.maxHeight
});
},
__delayShow: function __delayShow () {
clearTimeout(this.timer);
this.timer = setTimeout(this.show, this.delay);
},
__delayHide: function __delayHide () {
clearTimeout(this.timer);
this.hide();
}
},
render: function render (h) {
return h('span', {
staticClass: 'q-tooltip animate-scale',
style: this.transformCSS
}, [ this.$slots.default ])
},
created: function created () {
var this$1 = this;
this.__debouncedUpdatePosition = debounce(function () {
this$1.__updatePosition();
}, 70);
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
/*
The following is intentional.
Fixes a bug in Chrome regarding offsetHeight by requiring browser
to calculate this before removing from DOM and using it for first time.
*/
this$1.$el.offsetHeight; // eslint-disable-line
this$1.anchorEl = this$1.$el.parentNode;
this$1.anchorEl.removeChild(this$1.$el);
if (this$1.anchorEl.classList.contains('q-btn-inner')) {
this$1.anchorEl = this$1.anchorEl.parentNode;
}
if (this$1.$q.platform.is.mobile) {
this$1.anchorEl.addEventListener('click', this$1.show);
}
else {
this$1.anchorEl.addEventListener('mouseenter', this$1.__delayShow);
this$1.anchorEl.addEventListener('focus', this$1.__delayShow);
this$1.anchorEl.addEventListener('mouseleave', this$1.__delayHide);
this$1.anchorEl.addEventListener('blur', this$1.__delayHide);
}
if (this$1.value) {
this$1.show();
}
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
if (!this.anchorEl) {
return
}
if (this.$q.platform.is.mobile) {
this.anchorEl.removeEventListener('click', this.show);
}
else {
this.anchorEl.removeEventListener('mouseenter', this.__delayShow);
this.anchorEl.removeEventListener('focus', this.__delayShow);
this.anchorEl.removeEventListener('mouseleave', this.__delayHide);
this.anchorEl.removeEventListener('blur', this.__delayHide);
}
}
}
function run (e, btn, vm) {
if (btn.handler) {
btn.handler(e, vm, vm.caret);
}
else {
vm.runCmd(btn.cmd, btn.param);
}
}
function getBtn (h, vm, btn, clickHandler, active) {
if ( active === void 0 ) active = false;
var
toggled = active || (btn.type === 'toggle'
? (btn.toggled ? btn.toggled(vm) : btn.cmd && vm.caret.is(btn.cmd, btn.param))
: false),
child = [],
events = {
click: function click (e) {
clickHandler && clickHandler();
run(e, btn, vm);
}
};
if (btn.tip && vm.$q.platform.is.desktop) {
var Key = btn.key
? h('div', [h('small', ("(CTRL + " + (String.fromCharCode(btn.key)) + ")"))])
: null;
child.push(h(QTooltip, { props: {delay: 1000} }, [
h('div', { domProps: { innerHTML: btn.tip } }),
Key
]));
}
return h(QBtn, {
props: extend({
icon: btn.icon,
color: toggled ? btn.toggleColor || vm.toolbarToggleColor : btn.color || vm.toolbarColor,
textColor: toggled && (vm.toolbarFlat || vm.toolbarOutline) ? null : btn.textColor || vm.toolbarTextColor,
label: btn.label,
disable: btn.disable ? (typeof btn.disable === 'function' ? btn.disable(vm) : true) : false
}, vm.buttonProps),
on: events
}, child)
}
function getDropdown (h, vm, btn) {
var
label = btn.label,
icon = btn.icon,
noIcons = btn.list === 'no-icons',
onlyIcons = btn.list === 'only-icons',
Items;
function closeDropdown () {
Dropdown.componentInstance.hide();
}
if (onlyIcons) {
Items = btn.options.map(function (btn) {
var active = btn.type === void 0
? vm.caret.is(btn.cmd, btn.param)
: false;
if (active) {
label = btn.tip;
icon = btn.icon;
}
return getBtn(h, vm, btn, closeDropdown, active)
});
Items = [
h(
QBtnGroup,
{
props: vm.buttonProps,
staticClass: 'relative-position q-editor-toolbar-padding',
'class': vm.toolbarBackgroundClass,
style: { borderRadius: '0' }
},
Items
)
];
}
else {
Items = btn.options.map(function (btn) {
var disable = btn.disable ? btn.disable(vm) : false;
var active = btn.type === void 0
? vm.caret.is(btn.cmd, btn.param)
: false;
if (active) {
label = btn.tip;
icon = btn.icon;
}
return h(
QItem,
{
props: { active: active, link: !disable },
'class': { disabled: disable },
nativeOn: {
click: function click (e) {
if (disable) { return }
closeDropdown();
vm.$refs.content.focus();
vm.caret.restore();
run(e, btn, vm);
}
}
},
[
noIcons ? '' : h(QItemSide, {props: {icon: btn.icon}}),
h(QItemMain, {
props: {
label: btn.htmlTip || btn.tip
}
})
]
)
});
Items = [
h(QList, {
props: { separator: true },
'class': [vm.toolbarBackgroundClass, vm.toolbarTextColor ? ("text-" + (vm.toolbarTextColor)) : '']
}, [ Items ])
];
}
var highlight = btn.highlight && label !== btn.label;
var Dropdown = h(
QBtnDropdown,
{
props: extend({
noCaps: true,
noWrap: true,
color: highlight ? vm.toolbarToggleColor : vm.toolbarColor,
textColor: highlight && (vm.toolbarFlat || vm.toolbarOutline) ? null : vm.toolbarTextColor,
label: btn.fixedLabel ? btn.label : label,
icon: btn.fixedIcon ? btn.icon : icon
}, vm.buttonProps)
},
Items
);
return Dropdown
}
function getToolbar (h, vm) {
if (vm.caret) {
return vm.buttons.map(function (group) { return h(
QBtnGroup,
{ props: vm.buttonProps, staticClass: 'items-center relative-position' },
group.map(function (btn) {
if (btn.type === 'slot') {
return vm.$slots[btn.slot]
}
if (btn.type === 'dropdown') {
return getDropdown(h, vm, btn)
}
return getBtn(h, vm, btn)
})
); })
}
}
function getFonts (defaultFont, defaultFontLabel, defaultFontIcon, fonts) {
if ( fonts === void 0 ) fonts = {};
var aliases = Object.keys(fonts);
if (aliases.length === 0) {
return {}
}
var def = {
default_font: {
cmd: 'fontName',
param: defaultFont,
icon: defaultFontIcon,
tip: defaultFontLabel
}
};
aliases.forEach(function (alias) {
var name = fonts[alias];
def[alias] = {
cmd: 'fontName',
param: name,
icon: defaultFontIcon,
tip: name,
htmlTip: ("<font face=\"" + name + "\">" + name + "</font>")
};
});
return def
}
function getLinkEditor (h, vm) {
if (vm.caret) {
var color = vm.toolbarColor || vm.toolbarTextColor;
var link = vm.editLinkUrl;
var updateLink = function () {
vm.caret.restore();
if (link !== vm.editLinkUrl) {
document.execCommand('createLink', false, link === '' ? ' ' : link);
}
vm.editLinkUrl = null;
};
return [
h('div', { staticClass: 'q-mx-xs', 'class': ("text-" + color) }, [((vm.$q.i18n.editor.url) + ": ")]),
h(QInput, {
key: 'qedt_btm_input',
staticClass: 'q-ma-none q-pa-none col q-editor-input',
props: {
value: link,
color: color,
autofocus: true,
hideUnderline: true
},
on: {
input: function (val) { link = val; },
keydown: function (event) {
switch (getEventKey(event)) {
case 13: // ENTER key
return updateLink()
case 27: // ESCAPE key
vm.caret.restore();
vm.editLinkUrl = null;
break
}
}
}
}),
h(QBtnGroup, {
key: 'qedt_btm_grp',
props: vm.buttonProps
}, [
h(QBtn, {
key: 'qedt_btm_rem',
attrs: {
tabindex: -1
},
props: extend({
label: vm.$q.i18n.label.remove,
noCaps: true
}, vm.buttonProps),
on: {
click: function () {
vm.caret.restore();
document.execCommand('unlink');
vm.editLinkUrl = null;
}
}
}),
h(QBtn, {
key: 'qedt_btm_upd',
props: extend({
label: vm.$q.i18n.label.update,
noCaps: true
}, vm.buttonProps),
on: {
click: updateLink
}
})
])
]
}
}
function getBlockElement (el, parent) {
if (parent && el === parent) {
return null
}
var
style = window.getComputedStyle
? window.getComputedStyle(el)
: el.currentStyle,
display = style.display;
if (display === 'block' || display === 'table') {
return el
}
return getBlockElement(el.parentNode)
}
function isChildOf (el, parent) {
if (!el) {
return false
}
while ((el = el.parentNode)) {
if (el === document.body) {
return false
}
if (el === parent) {
return true
}
}
return false
}
var urlRegex = /^https?:\/\//;
var Caret = function Caret (el, vm) {
this.el = el;
this.vm = vm;
};
var prototypeAccessors = { selection: { configurable: true },hasSelection: { configurable: true },range: { configurable: true },parent: { configurable: true },blockParent: { configurable: true } };
prototypeAccessors.selection.get = function () {
if (!this.el) {
return
}
var sel = document.getSelection();
// only when the selection in element
if (isChildOf(sel.anchorNode, this.el) && isChildOf(sel.focusNode, this.el)) {
return sel
}
};
prototypeAccessors.hasSelection.get = function () {
return this.selection
? this.selection.toString().length > 0
: null
};
prototypeAccessors.range.get = function () {
var sel = this.selection;
if (!sel) {
return
}
return sel.rangeCount
? sel.getRangeAt(0)
: null
};
prototypeAccessors.parent.get = function () {
var range = this.range;
if (!range) {
return
}
var node = range.startContainer;
return node.nodeType === document.ELEMENT_NODE
? node
: node.parentNode
};
prototypeAccessors.blockParent.get = function () {
var parent = this.parent;
if (!parent) {
return
}
return getBlockElement(parent, this.el)
};
Caret.prototype.save = function save (range) {
if ( range === void 0 ) range = this.range;
this._range = range;
};
Caret.prototype.restore = function restore (range) {
if ( range === void 0 ) range = this._range;
var
r = document.createRange(),
sel = document.getSelection();
if (range) {
r.setStart(range.startContainer, range.startOffset);
r.setEnd(range.endContainer, range.endOffset);
sel.removeAllRanges();
sel.addRange(r);
}
else {
sel.selectAllChildren(this.el);
sel.collapseToEnd();
}
};
Caret.prototype.hasParent = function hasParent (name, spanLevel) {
var el = spanLevel
? this.parent
: this.blockParent;
return el
? el.nodeName.toLowerCase() === name.toLowerCase()
: false
};
Caret.prototype.hasParents = function hasParents (list) {
var el = this.parent;
return el
? list.includes(el.nodeName.toLowerCase())
: false
};
Caret.prototype.is = function is (cmd, param) {
switch (cmd) {
case 'formatBlock':
if (param === 'DIV' && this.parent === this.el) {
return true
}
return this.hasParent(param, param === 'PRE')
case 'link':
return this.hasParent('A', true)
case 'fontSize':
return document.queryCommandValue(cmd) === param
case 'fontName':
var res = document.queryCommandValue(cmd);
return res === ("\"" + param + "\"") || res === param
case 'fullscreen':
return this.vm.inFullscreen
default:
var state = document.queryCommandState(cmd);
return param ? state === param : state
}
};
Caret.prototype.getParentAttribute = function getParentAttribute (attrib) {
if (this.parent) {
return this.parent.getAttribute(attrib)
}
};
Caret.prototype.can = function can (name) {
if (name === 'outdent') {
return this.hasParents(['blockquote', 'li'])
}
if (name === 'indent') {
var parentName = this.parent ? this.parent.nodeName.toLowerCase() : false;
if (parentName === 'blockquote') {
return false
}
if (parentName === 'li') {
var previousEl = this.parent.previousSibling;
return previousEl && previousEl.nodeName.toLowerCase() === 'li'
}
return false
}
};
Caret.prototype.apply = function apply (cmd, param, done) {
if ( done === void 0 ) done = function () {};
if (cmd === 'formatBlock') {
if (['BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'PRE'].includes(param) && this.is(cmd, param)) {
cmd = 'outdent';
param = null;
}
}
else if (cmd === 'print') {
done();
var win = window.open();
win.document.write(("\n <!doctype html>\n <html>\n <head>\n <title>Print - " + (document.title) + "</title>\n </head>\n <body>\n <div>" + (this.el.innerHTML) + "</div>\n </body>\n </html>\n "));
win.print();
win.close();
return
}
else if (cmd === 'link') {
var link = this.getParentAttribute('href');
if (!link) {
var selection = this.selectWord(this.selection);
var url = selection ? selection.toString() : '';
if (!url.length) {
return
}
this.vm.editLinkUrl = urlRegex.test(url) ? url : ("https://" + url);
document.execCommand('createLink', false, this.vm.editLinkUrl);
}
else {
this.vm.editLinkUrl = link;
}
this.range.selectNodeContents(this.parent);
this.save();
return
}
else if (cmd === 'fullscreen') {
this.vm.toggleFullscreen();
done();
return
}
document.execCommand(cmd, false, param);
done();
};
Caret.prototype.selectWord = function selectWord (sel) {
if (!sel.isCollapsed) {
return sel
}
// Detect if selection is backwards
var range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
var direction = range.collapsed ? ['backward', 'forward'] : ['forward', 'backward'];
range.detach();
// modify() works on the focus of the selection
var
endNode = sel.focusNode,
endOffset = sel.focusOffset;
sel.collapse(sel.anchorNode, sel.anchorOffset);
sel.modify('move', direction[0], 'character');
sel.modify('move', direction[1], 'word');
sel.extend(endNode, endOffset);
sel.modify('extend', direction[1], 'character');
sel.modify('extend', direction[0], 'word');
return sel
};
Object.defineProperties( Caret.prototype, prototypeAccessors );
var QEditor = {
name: 'q-editor',
mixins: [FullscreenMixin],
props: {
value: {
type: String,
required: true
},
readonly: Boolean,
disable: Boolean,
minHeight: {
type: String,
default: '10rem'
},
maxHeight: String,
height: String,
definitions: Object,
fonts: Object,
toolbar: {
type: Array,
validator: function (v) { return v.length === 0 || v.every(function (group) { return group.length; }); },
default: function default$1 () {
return [
['left', 'center', 'right', 'justify'],
['bold', 'italic', 'underline', 'strike'],
['undo', 'redo']
]
}
},
toolbarColor: String,
toolbarTextColor: String,
toolbarToggleColor: {
type: String,
default: 'primary'
},
toolbarBg: {
type: String,
default: 'grey-3'
},
toolbarFlat: Boolean,
toolbarOutline: Boolean,
toolbarPush: Boolean,
toolbarRounded: Boolean,
contentStyle: Object,
contentClass: [Object, Array, String]
},
computed: {
editable: function editable () {
return !this.readonly && !this.disable
},
hasToolbar: function hasToolbar () {
return this.toolbar && this.toolbar.length > 0
},
toolbarBackgroundClass: function toolbarBackgroundClass () {
if (this.toolbarBg) {
return ("bg-" + (this.toolbarBg))
}
},
buttonProps: function buttonProps () {
return {
outline: this.toolbarOutline,
flat: this.toolbarFlat,
push: this.toolbarPush,
rounded: this.toolbarRounded,
dense: true,
color: this.toolbarColor,
disable: !this.editable
}
},
buttonDef: function buttonDef () {
var
e = this.$q.i18n.editor,
i = this.$q.icon.editor;
return {
bold: {cmd: 'bold', icon: i.bold, tip: e.bold, key: 66},
italic: {cmd: 'italic', icon: i.italic, tip: e.italic, key: 73},
strike: {cmd: 'strikeThrough', icon: i.strikethrough, tip: e.strikethrough, key: 83},
underline: {cmd: 'underline', icon: i.underline, tip: e.underline, key: 85},
unordered: {cmd: 'insertUnorderedList', icon: i.unorderedList, tip: e.unorderedList},
ordered: {cmd: 'insertOrderedList', icon: i.orderedList, tip: e.orderedList},
subscript: {cmd: 'subscript', icon: i.subscript, tip: e.subscript, htmlTip: 'x<subscript>2</subscript>'},
superscript: {cmd: 'superscript', icon: i.superscript, tip: e.superscript, htmlTip: 'x<superscript>2</superscript>'},
link: {cmd: 'link', icon: i.hyperlink, tip: e.hyperlink, key: 76},
fullscreen: {cmd: 'fullscreen', icon: i.toggleFullscreen, tip: e.toggleFullscreen, key: 70},
quote: {cmd: 'formatBlock', param: 'BLOCKQUOTE', icon: i.quote, tip: e.quote, key: 81},
left: {cmd: 'justifyLeft', icon: i.left, tip: e.left},
center: {cmd: 'justifyCenter', icon: i.center, tip: e.center},
right: {cmd: 'justifyRight', icon: i.right, tip: e.right},
justify: {cmd: 'justifyFull', icon: i.justify, tip: e.justify},
print: {type: 'no-state', cmd: 'print', icon: i.print, tip: e.print, key: 80},
outdent: {type: 'no-state', disable: function (vm) { return vm.caret && !vm.caret.can('outdent'); }, cmd: 'outdent', icon: i.outdent, tip: e.outdent},
indent: {type: 'no-state', disable: function (vm) { return vm.caret && !vm.caret.can('indent'); }, cmd: 'indent', icon: i.indent, tip: e.indent},
removeFormat: {type: 'no-state', cmd: 'removeFormat', icon: i.removeFormat, tip: e.removeFormat},
hr: {type: 'no-state', cmd: 'insertHorizontalRule', icon: i.hr, tip: e.hr},
undo: {type: 'no-state', cmd: 'undo', icon: i.undo, tip: e.undo, key: 90},
redo: {type: 'no-state', cmd: 'redo', icon: i.redo, tip: e.redo, key: 89},
h1: {cmd: 'formatBlock', param: 'H1', icon: i.header, tip: e.header1, htmlTip: ("<h1 class=\"q-ma-none\">" + (e.header1) + "</h1>")},
h2: {cmd: 'formatBlock', param: 'H2', icon: i.header, tip: e.header2, htmlTip: ("<h2 class=\"q-ma-none\">" + (e.header2) + "</h2>")},
h3: {cmd: 'formatBlock', param: 'H3', icon: i.header, tip: e.header3, htmlTip: ("<h3 class=\"q-ma-none\">" + (e.header3) + "</h3>")},
h4: {cmd: 'formatBlock', param: 'H4', icon: i.header, tip: e.header4, htmlTip: ("<h4 class=\"q-ma-none\">" + (e.header4) + "</h4>")},
h5: {cmd: 'formatBlock', param: 'H5', icon: i.header, tip: e.header5, htmlTip: ("<h5 class=\"q-ma-none\">" + (e.header5) + "</h5>")},
h6: {cmd: 'formatBlock', param: 'H6', icon: i.header, tip: e.header6, htmlTip: ("<h6 class=\"q-ma-none\">" + (e.header6) + "</h6>")},
p: {cmd: 'formatBlock', param: 'DIV', icon: i.header, tip: e.paragraph},
code: {cmd: 'formatBlock', param: 'PRE', icon: i.code, tip: ("<code>" + (e.code) + "</code>")},
'size-1': {cmd: 'fontSize', param: '1', icon: i.size, tip: e.size1, htmlTip: ("<font size=\"1\">" + (e.size1) + "</font>")},
'size-2': {cmd: 'fontSize', param: '2', icon: i.size, tip: e.size2, htmlTip: ("<font size=\"2\">" + (e.size2) + "</font>")},
'size-3': {cmd: 'fontSize', param: '3', icon: i.size, tip: e.size3, htmlTip: ("<font size=\"3\">" + (e.size3) + "</font>")},
'size-4': {cmd: 'fontSize', param: '4', icon: i.size, tip: e.size4, htmlTip: ("<font size=\"4\">" + (e.size4) + "</font>")},
'size-5': {cmd: 'fontSize', param: '5', icon: i.size, tip: e.size5, htmlTip: ("<font size=\"5\">" + (e.size5) + "</font>")},
'size-6': {cmd: 'fontSize', param: '6', icon: i.size, tip: e.size6, htmlTip: ("<font size=\"6\">" + (e.size6) + "</font>")},
'size-7': {cmd: 'fontSize', param: '7', icon: i.size, tip: e.size7, htmlTip: ("<font size=\"7\">" + (e.size7) + "</font>")}
}
},
buttons: function buttons () {
var this$1 = this;
var userDef = this.definitions || {};
var def = this.definitions || this.fonts
? extend(
true,
{},
this.buttonDef,
userDef,
getFonts(
this.defaultFont,
this.$q.i18n.editor.defaultFont,
this.$q.icon.editor.font,
this.fonts
)
)
: this.buttonDef;
return this.toolbar.map(
function (group) { return group.map(function (token) {
if (token.options) {
return {
type: 'dropdown',
icon: token.icon,
label: token.label,
fixedLabel: token.fixedLabel,
fixedIcon: token.fixedIcon,
highlight: token.highlight,
list: token.list,
options: token.options.map(function (item) { return def[item]; })
}
}
var obj = def[token];
if (obj) {
return obj.type === 'no-state' || (userDef[token] && (
obj.cmd === void 0 || (this$1.buttonDef[obj.cmd] && this$1.buttonDef[obj.cmd].type === 'no-state')
))
? obj
: extend(true, { type: 'toggle' }, obj)
}
else {
return {
type: 'slot',
slot: token
}
}
}); }
)
},
keys: function keys () {
var
k = {},
add = function (btn) {
if (btn.key) {
k[btn.key] = {
cmd: btn.cmd,
param: btn.param
};
}
};
this.buttons.forEach(function (group) {
group.forEach(function (token) {
if (token.options) {
token.options.forEach(add);
}
else {
add(token);
}
});
});
return k
}
},
data: function data () {
return {
editWatcher: true,
editLinkUrl: null
}
},
watch: {
value: function value (v) {
if (this.editWatcher) {
this.$refs.content.innerHTML = v;
}
else {
this.editWatcher = true;
}
}
},
methods: {
onInput: function onInput (e) {
if (this.editWatcher) {
this.editWatcher = false;
this.$emit('input', this.$refs.content.innerHTML);
}
},
onKeydown: function onKeydown (e) {
var key = getEventKey(e);
if (!e.ctrlKey) {
this.refreshToolbar();
return
}
var target = this.keys[key];
if (target !== void 0) {
var cmd = target.cmd;
var param = target.param;
stopAndPrevent(e);
this.runCmd(cmd, param, false);
}
},
runCmd: function runCmd (cmd, param, update) {
var this$1 = this;
if ( update === void 0 ) update = true;
this.focus();
this.caret.apply(cmd, param, function () {
this$1.focus();
if (update) {
this$1.refreshToolbar();
}
});
},
refreshToolbar: function refreshToolbar () {
var this$1 = this;
setTimeout(function () {
this$1.editLinkUrl = null;
this$1.$forceUpdate();
}, 1);
},
focus: function focus () {
this.$refs.content.focus();
},
getContentEl: function getContentEl () {
return this.$refs.content
}
},
created: function created () {
document.execCommand('defaultParagraphSeparator', false, 'div');
this.defaultFont = window.getComputedStyle(document.body).fontFamily;
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.caret = new Caret(this$1.$refs.content, this$1);
this$1.$refs.content.innerHTML = this$1.value;
this$1.$nextTick(this$1.refreshToolbar);
});
},
render: function render (h) {
var this$1 = this;
var toolbars;
if (this.hasToolbar) {
var toolbarConfig = {
staticClass: "q-editor-toolbar row no-wrap scroll",
'class': [
{ 'q-editor-toolbar-separator': !this.toolbarOutline && !this.toolbarPush },
this.toolbarBackgroundClass
]
};
toolbars = [];
toolbars.push(h('div', extend({key: 'qedt_top'}, toolbarConfig), [
h('div', { staticClass: 'row no-wrap q-editor-toolbar-padding fit items-center' }, getToolbar(h, this))
]));
if (this.editLinkUrl !== null) {
toolbars.push(h('div', extend({key: 'qedt_btm'}, toolbarConfig), [
h('div', { staticClass: 'row no-wrap q-editor-toolbar-padding fit items-center' }, getLinkEditor(h, this))
]));
}
toolbars = h('div', toolbars);
}
return h(
'div',
{
staticClass: 'q-editor',
style: {
height: this.inFullscreen ? '100vh' : null
},
'class': {
disabled: this.disable,
fullscreen: this.inFullscreen,
column: this.inFullscreen
}
},
[
toolbars,
h(
'div',
{
ref: 'content',
staticClass: "q-editor-content",
style: this.inFullscreen
? this.contentStyle
: [{ minHeight: this.minHeight, height: this.height, maxHeight: this.maxHeight }, this.contentStyle],
class: [
this.contentClass,
{ col: this.inFullscreen, 'overflow-auto': this.inFullscreen }
],
attrs: { contenteditable: this.editable },
on: {
input: this.onInput,
keydown: this.onKeydown,
click: this.refreshToolbar,
blur: function () {
this$1.caret.save();
}
}
}
)
]
)
}
}
var FabMixin = {
props: {
outline: Boolean,
push: Boolean,
flat: Boolean,
color: String,
textColor: String,
glossy: Boolean
}
}
var QFab = {
name: 'q-fab',
mixins: [FabMixin, ModelToggleMixin],
provide: function provide () {
return {
__qFabClose: this.hide
}
},
props: {
icon: String,
activeIcon: String,
direction: {
type: String,
default: 'right'
}
},
watch: {
$route: function $route () {
this.hide();
}
},
created: function created () {
if (this.value) {
this.show();
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-fab z-fab row inline justify-center',
'class': {
'q-fab-opened': this.showing
}
}, [
h(QBtn, {
props: {
fab: true,
outline: this.outline,
push: this.push,
flat: this.flat,
color: this.color,
textColor: this.textColor,
glossy: this.glossy
},
on: {
click: this.toggle
}
}, [
this.$slots.tooltip,
h(QIcon, {
staticClass: 'q-fab-icon absolute-full',
props: { name: this.icon || this.$q.icon.fab.icon }
}),
h(QIcon, {
staticClass: 'q-fab-active-icon absolute-full',
props: { name: this.activeIcon || this.$q.icon.fab.activeIcon }
})
]),
h('div', {
staticClass: 'q-fab-actions flex no-wrap inline items-center',
'class': ("q-fab-" + (this.direction))
}, [
this.$slots.default
])
])
}
}
var QFabAction = {
name: 'q-fab-action',
mixins: [FabMixin],
inject: {
__qFabClose: {
default: function default$1 () {
console.error('QFabAction needs to be child of QFab');
}
}
},
props: {
icon: {
type: String,
required: true
}
},
methods: {
click: function click (e) {
var this$1 = this;
this.__qFabClose().then(function () {
this$1.$emit('click', e);
});
}
},
render: function render (h) {
return h(QBtn, {
props: {
fabMini: true,
outline: this.outline,
push: this.push,
flat: this.flat,
color: this.color,
textColor: this.textColor,
glossy: this.glossy,
icon: this.icon
},
on: {
click: this.click
}
}, [
this.$slots.default
])
}
}
var QInfiniteScroll = {
name: 'q-infinite-scroll',
props: {
handler: {
type: Function,
required: true
},
inline: Boolean,
offset: {
type: Number,
default: 0
}
},
data: function data () {
return {
index: 0,
fetching: false,
working: true
}
},
methods: {
poll: function poll () {
if (this.fetching || !this.working) {
return
}
var
containerHeight = height(this.scrollContainer),
containerBottom = offset(this.scrollContainer).top + containerHeight,
triggerPosition = offset(this.element).top + height(this.element) - (this.offset || containerHeight);
if (triggerPosition < containerBottom) {
this.loadMore();
}
},
loadMore: function loadMore () {
var this$1 = this;
if (this.fetching || !this.working) {
return
}
this.index++;
this.fetching = true;
this.handler(this.index, function (stopLoading) {
this$1.fetching = false;
if (stopLoading) {
this$1.stop();
return
}
if (this$1.element.closest('body')) {
this$1.poll();
}
});
},
reset: function reset () {
this.index = 0;
},
resume: function resume () {
this.working = true;
this.scrollContainer.addEventListener('scroll', this.poll, listenOpts.passive);
this.poll();
},
stop: function stop () {
this.working = false;
this.scrollContainer.removeEventListener('scroll', this.poll, listenOpts.passive);
}
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.poll = debounce(this$1.poll, 50);
this$1.element = this$1.$refs.content;
this$1.scrollContainer = this$1.inline ? this$1.$el : getScrollTarget(this$1.$el);
if (this$1.working) {
this$1.scrollContainer.addEventListener('scroll', this$1.poll, listenOpts.passive);
}
this$1.poll();
});
},
beforeDestroy: function beforeDestroy () {
this.scrollContainer.removeEventListener('scroll', this.poll, listenOpts.passive);
},
render: function render (h) {
return h('div', { staticClass: 'q-infinite-scroll' }, [
h('div', {
ref: 'content',
staticClass: 'q-infinite-scroll-content'
}, [ this.$slots.default ]),
h('div', {
staticClass: 'q-infinite-scroll-message',
directives: [{
name: 'show',
value: this.fetching
}]
}, [
this.$slots.message
])
])
}
}
var QInnerLoading = {
name: 'q-inner-loading',
props: {
dark: Boolean,
visible: Boolean,
size: {
type: [String, Number],
default: 42
},
color: String
},
render: function render (h) {
if (!this.visible) {
return
}
return h('div', {
staticClass: 'q-inner-loading animate-fade absolute-full column flex-center',
'class': { dark: this.dark }
}, [
this.$slots.default ||
h(QSpinner, {
props: {
size: this.size,
color: this.color
}
})
])
}
}
var QKnob = {
name: 'q-knob',
directives: {
TouchPan: TouchPan
},
props: {
value: Number,
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
color: String,
trackColor: {
type: String,
default: 'grey-3'
},
lineWidth: {
type: String,
default: '6px'
},
size: {
type: String,
default: '100px'
},
step: {
type: Number,
default: 1
},
decimals: Number,
disable: Boolean,
readonly: Boolean
},
computed: {
classes: function classes () {
var cls = [];
if (this.disable) {
cls.push('disabled');
}
if (!this.readonly) {
cls.push('cursor-pointer');
}
if (this.color) {
cls.push(("text-" + (this.color)));
}
return cls
},
svgStyle: function svgStyle () {
return {
'stroke-dasharray': '295.31px, 295.31px',
'stroke-dashoffset': (295.31 * (1.0 - (this.model - this.min) / (this.max - this.min))) + 'px',
'transition': this.dragging ? '' : 'stroke-dashoffset 0.6s ease 0s, stroke 0.6s ease'
}
},
editable: function editable () {
return !this.disable && !this.readonly
},
computedDecimals: function computedDecimals () {
return this.decimals !== void 0 ? this.decimals || 0 : (String(this.step).trim('0').split('.')[1] || '').length
}
},
data: function data () {
return {
model: this.value,
dragging: false
}
},
watch: {
value: function value (value$1) {
var this$1 = this;
if (value$1 < this.min) {
this.$emit('input', this.min);
this.model = this.min;
this.$nextTick(function () {
if (this$1.model !== this$1.value) {
this$1.$emit('change', this$1.model);
}
});
}
else if (value$1 > this.max) {
this.$emit('input', this.max);
this.model = this.max;
this.$nextTick(function () {
if (this$1.model !== this$1.value) {
this$1.$emit('change', this$1.model);
}
});
}
else {
this.model = this.computedDecimals && typeof value$1 === 'number'
? parseFloat(value$1.toFixed(this.computedDecimals))
: value$1;
}
}
},
methods: {
__pan: function __pan (event) {
if (!this.editable) {
return
}
if (event.isFinal) {
this.__dragStop(event.evt);
}
else if (event.isFirst) {
this.__dragStart(event.evt);
}
else {
this.__dragMove(event.evt);
}
},
__dragStart: function __dragStart (ev) {
if (!this.editable) {
return
}
stopAndPrevent(ev);
this.centerPosition = this.__getCenter();
this.dragging = true;
this.__onInput(ev);
},
__dragMove: function __dragMove (ev) {
if (!this.dragging || !this.editable) {
return
}
stopAndPrevent(ev);
this.__onInput(ev, this.centerPosition);
},
__dragStop: function __dragStop (ev) {
var this$1 = this;
if (!this.editable) {
return
}
stopAndPrevent(ev);
setTimeout(function () {
this$1.dragging = false;
}, 100);
this.__onInput(ev, this.centerPosition, true, true);
},
__onInput: function __onInput (ev, center, emitChange, dragStop) {
var this$1 = this;
if ( center === void 0 ) center = this.__getCenter();
if (!this.editable) {
return
}
var
pos = position(ev),
height$$1 = Math.abs(pos.top - center.top),
distance = Math.sqrt(
Math.pow(Math.abs(pos.top - center.top), 2) +
Math.pow(Math.abs(pos.left - center.left), 2)
),
angle = Math.asin(height$$1 / distance) * (180 / Math.PI);
if (pos.top < center.top) {
angle = center.left < pos.left ? 90 - angle : 270 + angle;
}
else {
angle = center.left < pos.left ? angle + 90 : 270 - angle;
}
var
model = this.min + (angle / 360) * (this.max - this.min),
modulo = model % this.step;
var value = between(
model - modulo + (Math.abs(modulo) >= this.step / 2 ? (modulo < 0 ? -1 : 1) * this.step : 0),
this.min,
this.max
);
if (this.computedDecimals) {
value = parseFloat(value.toFixed(this.computedDecimals));
}
this.model = value;
this.$emit('input', value);
this.$nextTick(function () {
if (emitChange && JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
if (dragStop) {
this$1.$emit('dragend', value);
}
});
},
__getCenter: function __getCenter () {
var knobOffset = offset(this.$el);
return {
top: knobOffset.top + height(this.$el) / 2,
left: knobOffset.left + width(this.$el) / 2
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-knob non-selectable',
'class': this.classes,
style: {
width: this.size,
height: this.size
}
}, [
h('div', {
on: {
click: function (e) { return this$1.__onInput(e, undefined, true); }
},
directives: [{
name: 'touch-pan',
modifiers: {
prevent: true,
stop: true
},
value: this.__pan
}]
}, [
h('svg', { attrs: { viewBox: '0 0 100 100' } }, [
h('path', {
attrs: {
d: 'M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94',
'fill-opacity': '0',
stroke: 'currentColor',
'stroke-width': this.lineWidth
},
'class': ("text-" + (this.trackColor))
}),
h('path', {
attrs: {
d: 'M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94',
'fill-opacity': '0',
stroke: 'currentColor',
'stroke-linecap': 'round',
'stroke-width': this.lineWidth
},
style: this.svgStyle
})
]),
h('div', {
staticClass: 'q-knob-label row flex-center content-center'
}, [
this.$slots.default
? this.$slots.default
: h('span', [ this.model ])
])
])
])
}
}
var QLayout = {
name: 'q-layout',
provide: function provide () {
return {
layout: this
}
},
props: {
view: {
type: String,
default: 'hhh lpr fff',
validator: function (v) { return /^(h|l)h(h|r) lpr (f|l)f(f|r)$/.test(v.toLowerCase()); }
}
},
data: function data () {
var ref = viewport();
var height$$1 = ref.height;
var width$$1 = ref.width;
return {
height: height$$1, // window height
width: width$$1, // window width
header: {
size: 0,
offset: 0,
space: true
},
right: {
size: 300,
offset: 0,
space: false
},
footer: {
size: 0,
offset: 0,
space: true
},
left: {
size: 300,
offset: 0,
space: false
},
scrollHeight: 0,
scroll: {
position: 0,
direction: 'down'
}
}
},
computed: {
rows: function rows () {
var rows = this.view.toLowerCase().split(' ');
return {
top: rows[0].split(''),
middle: rows[1].split(''),
bottom: rows[2].split('')
}
}
},
render: function render (h) {
return h('div', { staticClass: 'q-layout' }, [
h(QScrollObservable, {
on: { scroll: this.__onPageScroll }
}),
h(QResizeObservable, {
on: { resize: this.__onLayoutResize }
}),
h(QWindowResizeObservable, {
on: { resize: this.__onWindowResize }
}),
this.$slots.default
])
},
methods: {
__animate: function __animate () {
var this$1 = this;
if (this.timer) {
clearTimeout(this.timer);
}
else {
document.body.classList.add('q-layout-animate');
}
this.timer = setTimeout(function () {
document.body.classList.remove('q-layout-animate');
this$1.timer = null;
}, 150);
},
__onPageScroll: function __onPageScroll (data) {
this.scroll = data;
this.$emit('scroll', data);
},
__onLayoutResize: function __onLayoutResize () {
this.scrollHeight = getScrollHeight(this.$el);
this.$emit('scrollHeight', this.scrollHeight);
},
__onWindowResize: function __onWindowResize (ref) {
var height$$1 = ref.height;
var width$$1 = ref.width;
if (this.height !== height$$1) {
this.height = height$$1;
}
if (this.width !== width$$1) {
this.width = width$$1;
}
}
}
}
var bodyClassBelow = 'with-layout-drawer-opened';
var bodyClassAbove = 'with-layout-drawer-opened-above';
var duration = 150;
var QLayoutDrawer = {
name: 'q-layout-drawer',
inject: {
layout: {
default: function default$1 () {
console.error('QLayoutDrawer needs to be child of QLayout');
}
}
},
mixins: [ModelToggleMixin],
directives: {
TouchPan: TouchPan
},
props: {
overlay: Boolean,
side: {
type: String,
default: 'left',
validator: function (v) { return ['left', 'right'].includes(v); }
},
breakpoint: {
type: Number,
default: 992
},
behavior: {
type: String,
validator: function (v) { return ['default', 'desktop', 'mobile'].includes(v); },
default: 'default'
},
contentStyle: Object,
contentClass: [String, Object, Array],
noSwipeOpen: Boolean,
noSwipeClose: Boolean
},
data: function data () {
var
largeScreenState = this.value !== void 0 ? this.value : true,
showing = this.behavior !== 'mobile' && this.breakpoint < this.layout.width && !this.overlay
? largeScreenState
: false;
if (this.value !== void 0 && this.value !== showing) {
this.$emit('input', showing);
}
return {
showing: showing,
belowBreakpoint: (
this.behavior === 'mobile' ||
(this.behavior !== 'desktop' && this.breakpoint >= this.layout.width)
),
largeScreenState: largeScreenState,
mobileOpened: false,
size: 300,
inTransit: false,
position: 0,
percentage: 0
}
},
watch: {
belowBreakpoint: function belowBreakpoint (val, old) {
if (this.mobileOpened) {
return
}
if (val) { // from lg to xs
if (!this.overlay) {
this.largeScreenState = this.showing;
}
// ensure we close it for small screen
this.hide();
}
else if (!this.overlay) { // from xs to lg
this[this.largeScreenState ? 'show' : 'hide']();
}
},
behavior: function behavior (val) {
this.__updateLocal('belowBreakpoint', (
val === 'mobile' ||
(val !== 'desktop' && this.breakpoint >= this.layout.width)
));
},
breakpoint: function breakpoint (val) {
this.__updateLocal('belowBreakpoint', (
this.behavior === 'mobile' ||
(this.behavior !== 'desktop' && val >= this.layout.width)
));
},
'layout.width': function layout_width (val) {
this.__updateLocal('belowBreakpoint', (
this.behavior === 'mobile' ||
(this.behavior !== 'desktop' && this.breakpoint >= val)
));
},
offset: function offset$$1 (val) {
this.__update('offset', val);
},
onScreenOverlay: function onScreenOverlay () {
if (this.animateOverlay) {
this.layout.__animate();
}
},
onLayout: function onLayout (val) {
this.__update('space', val);
this.layout.__animate();
},
$route: function $route () {
if (this.mobileOpened || this.onScreenOverlay) {
this.hide();
}
}
},
computed: {
rightSide: function rightSide () {
return this.side === 'right'
},
offset: function offset$$1 () {
return this.showing && !this.mobileOpened
? this.size
: 0
},
fixed: function fixed () {
return this.overlay || this.layout.view.indexOf(this.rightSide ? 'R' : 'L') > -1
},
onLayout: function onLayout () {
return this.showing && !this.mobileView && !this.overlay
},
onScreenOverlay: function onScreenOverlay () {
return this.showing && !this.mobileView && this.overlay
},
backdropClass: function backdropClass () {
return {
'q-layout-backdrop-transition': !this.inTransit,
'no-pointer-events': !this.inTransit && !this.showing
}
},
mobileView: function mobileView () {
return this.belowBreakpoint || this.mobileOpened
},
headerSlot: function headerSlot () {
return this.overlay
? false
: (this.rightSide
? this.layout.rows.top[2] === 'r'
: this.layout.rows.top[0] === 'l'
)
},
footerSlot: function footerSlot () {
return this.overlay
? false
: (this.rightSide
? this.layout.rows.bottom[2] === 'r'
: this.layout.rows.bottom[0] === 'l'
)
},
backdropStyle: function backdropStyle () {
return { backgroundColor: ("rgba(0,0,0," + (this.percentage * 0.4) + ")") }
},
belowClass: function belowClass () {
return {
'fixed': true,
'on-top': true,
'on-screen': this.showing,
'off-screen': !this.showing,
'transition-generic': !this.inTransit,
'top-padding': this.fixed || this.headerSlot
}
},
belowStyle: function belowStyle () {
if (this.inTransit) {
return cssTransform(("translateX(" + (this.position) + "px)"))
}
},
aboveClass: function aboveClass () {
var onScreen = this.onLayout || this.onScreenOverlay;
return {
'off-screen': !onScreen,
'on-screen': onScreen,
'fixed': this.fixed || !this.onLayout,
'top-padding': this.fixed || this.headerSlot
}
},
aboveStyle: function aboveStyle () {
var css$$1 = {};
if (this.layout.header.space && !this.headerSlot) {
if (this.fixed) {
css$$1.top = (this.layout.header.offset) + "px";
}
else if (this.layout.header.space) {
css$$1.top = (this.layout.header.size) + "px";
}
}
if (this.layout.footer.space && !this.footerSlot) {
if (this.fixed) {
css$$1.bottom = (this.layout.footer.offset) + "px";
}
else if (this.layout.footer.space) {
css$$1.bottom = (this.layout.footer.size) + "px";
}
}
return css$$1
},
computedStyle: function computedStyle () {
return [this.contentStyle, this.mobileView ? this.belowStyle : this.aboveStyle]
},
computedClass: function computedClass () {
return [this.contentClass, this.mobileView ? this.belowClass : this.aboveClass]
}
},
render: function render (h) {
var child = [];
if (this.mobileView) {
if (!this.noSwipeOpen) {
child.push(h('div', {
staticClass: ("q-layout-drawer-opener fixed-" + (this.side)),
directives: [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__openByTouch
}]
}));
}
child.push(h('div', {
staticClass: 'fullscreen q-layout-backdrop',
'class': this.backdropClass,
style: this.backdropStyle,
on: { click: this.hide },
directives: [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__closeByTouch
}]
}));
}
return h('div', { staticClass: 'q-drawer-container' }, child.concat([
h('aside', {
staticClass: ("q-layout-drawer q-layout-drawer-" + (this.side) + " scroll q-layout-transition"),
'class': this.computedClass,
style: this.computedStyle,
attrs: this.$attrs,
listeners: this.$listeners,
directives: this.mobileView && !this.noSwipeClose ? [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__closeByTouch
}] : null
}, [
this.$slots.default,
h(QResizeObservable, {
on: { resize: this.__onResize }
})
])
]))
},
created: function created () {
var this$1 = this;
if (this.onLayout) {
this.__update('space', true);
this.__update('offset', this.offset);
}
this.$nextTick(function () {
this$1.animateOverlay = true;
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
this.__update('size', 0);
this.__update('space', false);
},
methods: {
__openByTouch: function __openByTouch (evt) {
if (!this.belowBreakpoint) {
return
}
var
width$$1 = this.size,
position = between(evt.distance.x, 0, width$$1);
if (evt.isFinal) {
var opened = position >= Math.min(75, width$$1);
this.inTransit = false;
if (opened) { this.show(); }
else { this.percentage = 0; }
return
}
this.position = this.rightSide
? Math.max(width$$1 - position, 0)
: Math.min(0, position - width$$1);
this.percentage = between(position / width$$1, 0, 1);
if (evt.isFirst) {
document.body.classList.add(bodyClassBelow);
this.inTransit = true;
}
},
__closeByTouch: function __closeByTouch (evt) {
if (!this.mobileOpened) {
return
}
var
width$$1 = this.size,
position = evt.direction === this.side
? between(evt.distance.x, 0, width$$1)
: 0;
if (evt.isFinal) {
var opened = Math.abs(position) < Math.min(75, width$$1);
this.inTransit = false;
if (opened) { this.percentage = 1; }
else { this.hide(); }
return
}
this.position = (this.rightSide ? 1 : -1) * position;
this.percentage = between(1 - position / width$$1, 0, 1);
if (evt.isFirst) {
this.inTransit = true;
}
},
__show: function __show () {
var this$1 = this;
if (this.belowBreakpoint) {
this.mobileOpened = true;
this.percentage = 1;
}
document.body.classList.add(this.belowBreakpoint ? bodyClassBelow : bodyClassAbove);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
if (this$1.showPromise) {
this$1.showPromise.then(function () {
document.body.classList.remove(bodyClassAbove);
});
this$1.showPromiseResolve();
}
}, duration);
},
__hide: function __hide () {
var this$1 = this;
this.mobileOpened = false;
this.percentage = 0;
document.body.classList.remove(bodyClassAbove);
document.body.classList.remove(bodyClassBelow);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
this$1.hidePromise && this$1.hidePromiseResolve();
}, duration);
},
__onResize: function __onResize (ref) {
var width$$1 = ref.width;
this.__update('size', width$$1);
this.__updateLocal('size', width$$1);
},
__update: function __update (prop, val) {
if (this.layout[this.side][prop] !== val) {
this.layout[this.side][prop] = val;
}
},
__updateLocal: function __updateLocal (prop, val) {
if (this[prop] !== val) {
this[prop] = val;
}
}
}
}
var QLayoutFooter = {
name: 'q-layout-footer',
inject: {
layout: {
default: function default$1 () {
console.error('QLayoutFooter needs to be child of QLayout');
}
}
},
props: {
value: {
type: Boolean,
default: true
},
reveal: Boolean
},
data: function data () {
return {
size: 0,
revealed: true
}
},
watch: {
value: function value (val) {
this.__update('space', val);
this.__updateLocal('revealed', true);
this.layout.__animate();
},
offset: function offset (val) {
this.__update('offset', val);
},
revealed: function revealed () {
this.layout.__animate();
},
'layout.scroll': function layout_scroll () {
this.__updateRevealed();
},
'layout.scrollHeight': function layout_scrollHeight () {
this.__updateRevealed();
},
size: function size () {
this.__updateRevealed();
}
},
computed: {
fixed: function fixed () {
return this.reveal || this.layout.view.indexOf('F') > -1
},
offset: function offset () {
if (!this.value) {
return 0
}
if (this.fixed) {
return this.revealed ? this.size : 0
}
var offset = this.layout.height + this.layout.scroll.position + this.size - this.layout.scrollHeight;
return offset > 0 ? offset : 0
},
computedClass: function computedClass () {
return {
'fixed-bottom': this.fixed,
'absolute-bottom': !this.fixed,
'hidden': !this.value && !this.fixed,
'q-layout-footer-hidden': !this.value || (this.fixed && !this.revealed)
}
},
computedStyle: function computedStyle () {
var
view = this.layout.rows.bottom,
css = {};
if (view[0] === 'l' && this.layout.left.space) {
css.marginLeft = (this.layout.left.size) + "px";
}
if (view[2] === 'r' && this.layout.right.space) {
css.marginRight = (this.layout.right.size) + "px";
}
return css
}
},
render: function render (h) {
return h('footer', {
staticClass: 'q-layout-footer q-layout-transition',
'class': this.computedClass,
style: this.computedStyle
}, [
h(QResizeObservable, {
on: { resize: this.__onResize }
}),
this.$slots.default
])
},
created: function created () {
this.__update('space', this.value);
},
destroyed: function destroyed () {
this.__update('size', 0);
this.__update('space', false);
},
methods: {
__onResize: function __onResize (ref) {
var height = ref.height;
this.__updateLocal('size', height);
this.__update('size', height);
},
__update: function __update (prop, val) {
if (this.layout.footer[prop] !== val) {
this.layout.footer[prop] = val;
}
},
__updateLocal: function __updateLocal (prop, val) {
if (this[prop] !== val) {
this[prop] = val;
}
},
__updateRevealed: function __updateRevealed () {
if (!this.reveal) {
return
}
var
scroll = this.layout.scroll,
scrollHeight = this.layout.scrollHeight,
height = this.layout.height;
this.__updateLocal('revealed',
scroll.direction === 'up' ||
scroll.position - scroll.inflexionPosition < 100 ||
scrollHeight - height - scroll.position < this.size + 300
);
}
}
}
var QLayoutHeader = {
name: 'q-layout-header',
inject: {
layout: {
default: function default$1 () {
console.error('QLayoutHeader needs to be child of QLayout');
}
}
},
props: {
value: {
type: Boolean,
default: true
},
reveal: Boolean,
revealOffset: {
type: Number,
default: 250
}
},
data: function data () {
return {
size: 0,
revealed: true
}
},
watch: {
value: function value (val) {
this.__update('space', val);
this.__updateLocal('revealed', true);
this.layout.__animate();
},
offset: function offset (val) {
this.__update('offset', val);
},
revealed: function revealed () {
this.layout.__animate();
},
'layout.scroll': function layout_scroll (scroll) {
if (!this.reveal) {
return
}
this.__updateLocal('revealed',
scroll.direction === 'up' ||
scroll.position <= this.revealOffset ||
scroll.position - scroll.inflexionPosition < 100
);
}
},
computed: {
fixed: function fixed () {
return this.reveal || this.layout.view.indexOf('H') > -1
},
offset: function offset () {
if (!this.value) {
return 0
}
if (this.fixed) {
return this.revealed ? this.size : 0
}
var offset = this.size - this.layout.scroll.position;
return offset > 0 ? offset : 0
},
computedClass: function computedClass () {
return {
'fixed-top': this.fixed,
'absolute-top': !this.fixed,
'q-layout-header-hidden': !this.value || (this.fixed && !this.revealed)
}
},
computedStyle: function computedStyle () {
var
view = this.layout.rows.top,
css = {};
if (view[0] === 'l' && this.layout.left.space) {
css.marginLeft = (this.layout.left.size) + "px";
}
if (view[2] === 'r' && this.layout.right.space) {
css.marginRight = (this.layout.right.size) + "px";
}
return css
}
},
render: function render (h) {
return h('header', {
staticClass: 'q-layout-header q-layout-transition',
'class': this.computedClass,
style: this.computedStyle
}, [
h(QResizeObservable, {
on: { resize: this.__onResize }
}),
this.$slots.default
])
},
created: function created () {
this.__update('space', this.value);
},
destroyed: function destroyed () {
this.__update('size', 0);
this.__update('space', false);
},
methods: {
__onResize: function __onResize (ref) {
var height = ref.height;
this.__updateLocal('size', height);
this.__update('size', height);
},
__update: function __update (prop, val) {
if (this.layout.header[prop] !== val) {
this.layout.header[prop] = val;
}
},
__updateLocal: function __updateLocal (prop, val) {
if (this[prop] !== val) {
this[prop] = val;
}
}
}
}
var QPage = {
name: 'q-page',
inject: {
pageContainer: {
default: function default$1 () {
console.error('QPage needs to be child of QPageContainer');
}
},
layout: {}
},
props: {
padding: Boolean
},
computed: {
computedStyle: function computedStyle () {
var offset =
(this.layout.header.space ? this.layout.header.size : 0) +
(this.layout.footer.space ? this.layout.footer.size : 0);
return {
minHeight: offset ? ("calc(100vh - " + offset + "px)") : '100vh'
}
},
computedClass: function computedClass () {
if (this.padding) {
return 'layout-padding'
}
}
},
render: function render (h) {
return h('main', {
staticClass: 'q-layout-page',
style: this.computedStyle,
'class': this.computedClass
}, [
this.$slots.default
])
}
}
var QPageContainer = {
name: 'q-page-container',
inject: {
layout: {
default: function default$1 () {
console.error('QPageContainer needs to be child of QLayout');
}
}
},
provide: {
pageContainer: true
},
computed: {
computedStyle: function computedStyle () {
var css = {};
if (this.layout.header.space) {
css.paddingTop = (this.layout.header.size) + "px";
}
if (this.layout.right.space) {
css.paddingRight = (this.layout.right.size) + "px";
}
if (this.layout.footer.space) {
css.paddingBottom = (this.layout.footer.size) + "px";
}
if (this.layout.left.space) {
css.paddingLeft = (this.layout.left.size) + "px";
}
return css
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-layout-page-container q-layout-transition',
style: this.computedStyle
}, [
this.$slots.default
])
}
}
var QPageSticky = {
name: 'q-page-sticky',
inject: {
layout: {
default: function default$1 () {
console.error('QPageSticky needs to be child of QLayout');
}
}
},
props: {
position: {
type: String,
default: 'bottom-right',
validator: function (v) { return [
'top-right', 'top-left',
'bottom-right', 'bottom-left',
'top', 'right', 'bottom', 'left'
].includes(v); }
},
offset: {
type: Array,
validator: function (v) { return v.length === 2; }
}
},
computed: {
attach: function attach () {
var pos = this.position;
return {
top: pos.indexOf('top') > -1,
right: pos.indexOf('right') > -1,
bottom: pos.indexOf('bottom') > -1,
left: pos.indexOf('left') > -1,
vertical: pos === 'top' || pos === 'bottom',
horizontal: pos === 'left' || pos === 'right'
}
},
top: function top () {
return this.layout.header.offset
},
right: function right () {
return this.layout.right.offset
},
bottom: function bottom () {
return this.layout.footer.offset
},
left: function left () {
return this.layout.left.offset
},
computedStyle: function computedStyle () {
var
attach = this.attach,
transforms = [];
if (attach.top && this.top) {
transforms.push(("translateY(" + (this.top) + "px)"));
}
else if (attach.bottom && this.bottom) {
transforms.push(("translateY(" + (-this.bottom) + "px)"));
}
if (attach.left && this.left) {
transforms.push(("translateX(" + (this.left) + "px)"));
}
else if (attach.right && this.right) {
transforms.push(("translateX(" + (-this.right) + "px)"));
}
var css$$1 = transforms.length
? cssTransform(transforms.join(' '))
: {};
if (this.offset) {
css$$1.margin = (this.offset[1]) + "px " + (this.offset[0]) + "px";
}
if (attach.vertical) {
if (this.left) {
css$$1.left = (this.left) + "px";
}
if (this.right) {
css$$1.right = (this.right) + "px";
}
}
else if (attach.horizontal) {
if (this.top) {
css$$1.top = (this.top) + "px";
}
if (this.bottom) {
css$$1.bottom = (this.bottom) + "px";
}
}
return css$$1
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-page-sticky q-layout-transition z-fixed',
'class': ("fixed-" + (this.position)),
style: this.computedStyle
}, [
this.$slots.default
])
}
}
var QPagination = {
name: 'q-pagination',
props: {
value: {
type: Number,
required: true
},
min: {
type: Number,
default: 1
},
max: {
type: Number,
required: true
},
color: {
type: String,
default: 'primary'
},
size: String,
disable: Boolean,
input: Boolean,
boundaryLinks: {
type: Boolean,
default: null
},
boundaryNumbers: {
type: Boolean,
default: null
},
directionLinks: {
type: Boolean,
default: null
},
ellipses: {
type: Boolean,
default: null
},
maxPages: {
type: Number,
default: 0,
validator: function (v) {
if (v < 0) {
console.error('maxPages should not be negative');
return false
}
return true
}
}
},
data: function data () {
return {
newPage: null
}
},
watch: {
min: function min (value) {
this.model = this.value;
},
max: function max (value) {
this.model = this.value;
}
},
computed: {
model: {
get: function get () {
return this.value
},
set: function set (val) {
var this$1 = this;
if (this.disable || !val || isNaN(val)) {
return
}
var value = between(parseInt(val, 10), this.min, this.max);
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
inputPlaceholder: function inputPlaceholder () {
return this.model + ' / ' + this.max
},
__boundaryLinks: function __boundaryLinks () {
return this.__getBool(this.boundaryLinks, this.input)
},
__boundaryNumbers: function __boundaryNumbers () {
return this.__getBool(this.boundaryNumbers, !this.input)
},
__directionLinks: function __directionLinks () {
return this.__getBool(this.directionLinks, this.input)
},
__ellipses: function __ellipses () {
return this.__getBool(this.ellipses, !this.input)
}
},
methods: {
set: function set (value) {
this.model = value;
},
setByOffset: function setByOffset (offset) {
this.model = this.model + offset;
},
__update: function __update () {
this.model = this.newPage;
this.newPage = null;
},
__getRepeatEasing: function __getRepeatEasing (from, step, to) {
if ( from === void 0 ) from = 300;
if ( step === void 0 ) step = 10;
if ( to === void 0 ) to = 100;
return function (cnt) { return cnt ? Math.max(to, from - cnt * cnt * step) : 100; }
},
__getBool: function __getBool (val, otherwise) {
return [true, false].includes(val)
? val
: otherwise
},
__getBtn: function __getBtn (h, props) {
return h(QBtn, extend(true, {
props: {
color: this.color,
flat: true,
size: this.size
}
}, props))
}
},
render: function render (h) {
var this$1 = this;
var
contentStart = [],
contentEnd = [],
contentMiddle = [];
if (this.__boundaryLinks) {
contentStart.push(this.__getBtn(h, {
key: 'bls',
props: {
disable: this.disable || this.value <= this.min,
icon: this.$q.icon.pagination.first
},
on: {
click: function () { return this$1.set(this$1.min); }
}
}));
contentEnd.unshift(this.__getBtn(h, {
key: 'ble',
props: {
disable: this.disable || this.value >= this.max,
icon: this.$q.icon.pagination.last
},
on: {
click: function () { return this$1.set(this$1.max); }
}
}));
}
if (this.__directionLinks) {
contentStart.push(this.__getBtn(h, {
key: 'bdp',
props: {
disable: this.disable || this.value <= this.min,
icon: this.$q.icon.pagination.prev,
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.setByOffset(-1); }
}
}));
contentEnd.unshift(this.__getBtn(h, {
key: 'bdn',
props: {
disable: this.disable || this.value >= this.max,
icon: this.$q.icon.pagination.next,
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.setByOffset(1); }
}
}));
}
if (this.input) {
contentMiddle.push(h(QInput, {
staticClass: 'inline no-padding',
style: {
width: ((this.inputPlaceholder.length) + "rem")
},
props: {
type: 'number',
value: this.newPage,
noNumberToggle: true,
min: this.min,
max: this.max,
color: this.color,
placeholder: this.inputPlaceholder,
disable: this.disable,
hideUnderline: true
},
on: {
input: function (value) { return (this$1.newPage = value); },
keydown: function (event) { return (getEventKey(event) === 13 && this$1.__update()); },
blur: function () { return this$1.__update(); }
}
}));
}
else { // is type select
var
maxPages = Math.max(
this.maxPages,
1 + (this.__ellipses ? 2 : 0) + (this.__boundaryNumbers ? 2 : 0)
),
pgFrom = this.min,
pgTo = this.max,
ellipsesStart = false,
ellipsesEnd = false,
boundaryStart = false,
boundaryEnd = false;
if (this.maxPages && maxPages < (this.max - this.min + 1)) {
maxPages = 1 + Math.floor(maxPages / 2) * 2;
pgFrom = Math.max(this.min, Math.min(this.max - maxPages + 1, this.value - Math.floor(maxPages / 2)));
pgTo = Math.min(this.max, pgFrom + maxPages - 1);
if (this.__boundaryNumbers && pgFrom > this.min) {
boundaryStart = true;
pgFrom += 1;
}
if (this.__ellipses && pgFrom > (this.min + (this.__boundaryNumbers ? 1 : 0))) {
ellipsesStart = true;
pgFrom += 1;
}
if (this.__boundaryNumbers && pgTo < this.max) {
boundaryEnd = true;
pgTo -= 1;
}
if (this.__ellipses && pgTo < (this.max - (this.__boundaryNumbers ? 1 : 0))) {
ellipsesEnd = true;
pgTo -= 1;
}
}
var style = {
minWidth: ((Math.max(1.5, String(this.max).length)) + "em")
};
if (boundaryStart) {
contentStart.push(this.__getBtn(h, {
key: 'bns',
style: style,
props: {
disable: this.disable || this.value <= this.min,
label: this.min
},
on: {
click: function () { return this$1.set(this$1.min); }
}
}));
}
if (boundaryEnd) {
contentEnd.unshift(this.__getBtn(h, {
key: 'bne',
style: style,
props: {
disable: this.disable || this.value >= this.max,
label: this.max
},
on: {
click: function () { return this$1.set(this$1.max); }
}
}));
}
if (ellipsesStart) {
contentStart.push(this.__getBtn(h, {
key: 'bes',
style: style,
props: {
disable: this.disable,
label: '…',
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.set(pgFrom - 1); }
}
}));
}
if (ellipsesEnd) {
contentEnd.unshift(this.__getBtn(h, {
key: 'bee',
style: style,
props: {
disable: this.disable,
label: '…',
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.set(pgTo + 1); }
}
}));
}
var loop = function ( i ) {
contentMiddle.push(this$1.__getBtn(h, {
key: (i + "." + (i === this$1.value)),
style: style,
props: {
disable: this$1.disable,
flat: i !== this$1.value,
label: i,
noRipple: true
},
on: {
click: function () { return this$1.set(i); }
}
}));
};
for (var i = pgFrom; i <= pgTo; i++) loop( i );
}
return h('div', {
staticClass: 'q-pagination',
'class': { disabled: this.disable }
}, [
contentStart,
h('div', { staticClass: 'row wrap justify-center' }, [
contentMiddle
]),
contentEnd
])
}
}
var QParallax = {
name: 'q-parallax',
props: {
src: {
type: String,
required: true
},
height: {
type: Number,
default: 500
},
speed: {
type: Number,
default: 1,
validator: function validator (value) {
return value >= 0 && value <= 1
}
}
},
data: function data () {
return {
imageHasBeenLoaded: false,
scrolling: false
}
},
watch: {
src: function src () {
this.imageHasBeenLoaded = false;
},
height: function height$$1 () {
this.__updatePos();
}
},
methods: {
__processImage: function __processImage () {
this.imageHasBeenLoaded = true;
this.__onResize();
},
__onResize: function __onResize () {
if (!this.imageHasBeenLoaded || !this.scrollTarget) {
return
}
if (this.scrollTarget === window) {
this.viewportHeight = viewport().height;
}
this.imageHeight = height(this.image);
this.__updatePos();
},
__updatePos: function __updatePos () {
if (!this.imageHasBeenLoaded) {
return
}
var containerTop, containerHeight, containerBottom, top, bottom;
if (this.scrollTarget === window) {
containerTop = 0;
containerHeight = this.viewportHeight;
containerBottom = containerHeight;
}
else {
containerTop = offset(this.scrollTarget).top;
containerHeight = height(this.scrollTarget);
containerBottom = containerTop + containerHeight;
}
top = offset(this.container).top;
bottom = top + this.height;
if (bottom > containerTop && top < containerBottom) {
var percentScrolled = (containerBottom - top) / (this.height + containerHeight);
this.__setPos(Math.round((this.imageHeight - this.height) * percentScrolled * this.speed));
}
},
__setPos: function __setPos (offset$$1) {
css(this.$refs.img, cssTransform(("translate3D(-50%," + offset$$1 + "px, 0)")));
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-parallax',
style: { height: ((this.height) + "px") }
}, [
h('div', {
staticClass: 'q-parallax-image absolute-full'
}, [
h('img', {
ref: 'img',
domProps: {
src: this.src
},
'class': { ready: this.imageHasBeenLoaded },
on: {
load: this.__processImage
}
})
]),
h('div', {
staticClass: 'q-parallax-text absolute-full column flex-center'
}, [
this.imageHasBeenLoaded
? this.$slots.default
: this.$slots.loading
])
])
},
created: function created () {
this.__setPos = frameDebounce(this.__setPos);
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.container = this$1.$el;
this$1.image = this$1.$refs.img;
this$1.scrollTarget = getScrollTarget(this$1.$el);
this$1.resizeHandler = debounce(this$1.__onResize, 50);
window.addEventListener('resize', this$1.resizeHandler, listenOpts.passive);
this$1.scrollTarget.addEventListener('scroll', this$1.__updatePos, listenOpts.passive);
this$1.__onResize();
});
},
beforeDestroy: function beforeDestroy () {
window.removeEventListener('resize', this.resizeHandler, listenOpts.passive);
this.scrollTarget.removeEventListener('scroll', this.__updatePos, listenOpts.passive);
}
}
function width$1 (val) {
return { width: (val + "%") }
}
var QProgress = {
name: 'q-progress',
props: {
percentage: {
type: Number,
default: 0
},
color: String,
stripe: Boolean,
animate: Boolean,
indeterminate: Boolean,
buffer: Number,
height: {
type: String,
default: '4px'
}
},
computed: {
model: function model () {
return between(this.percentage, 0, 100)
},
bufferModel: function bufferModel () {
return between(this.buffer || 0, 0, 100 - this.model)
},
bufferStyle: function bufferStyle () {
return width$1(this.bufferModel)
},
trackStyle: function trackStyle () {
return width$1(this.buffer ? 100 - this.buffer : 100)
},
computedClass: function computedClass () {
if (this.color) {
return ("text-" + (this.color))
}
},
computedStyle: function computedStyle () {
return { height: this.height }
},
modelClass: function modelClass () {
return {
animate: this.animate,
stripe: this.stripe,
indeterminate: this.indeterminate
}
},
modelStyle: function modelStyle () {
return width$1(this.model)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-progress',
style: this.computedStyle,
'class': this.computedClass
}, [
this.buffer && !this.indeterminate
? h('div', {
staticClass: 'q-progress-buffer',
style: this.bufferStyle
})
: null,
h('div', {
staticClass: 'q-progress-track',
style: this.trackStyle
}),
h('div', {
staticClass: 'q-progress-model',
style: this.modelStyle,
'class': this.modelClass
})
])
}
}
var QPullToRefresh = {
name: 'q-pull-to-refresh',
directives: {
TouchPan: TouchPan
},
props: {
handler: {
type: Function,
required: true
},
distance: {
type: Number,
default: 35
},
pullMessage: String,
releaseMessage: String,
refreshMessage: String,
refreshIcon: String,
inline: Boolean,
disable: Boolean
},
data: function data () {
var height$$1 = 65;
return {
state: 'pull',
pullPosition: -height$$1,
height: height$$1,
animating: false,
pulling: false,
scrolling: false
}
},
computed: {
message: function message () {
switch (this.state) {
case 'pulled':
return this.releaseMessage || this.$q.i18n.pullToRefresh.release
case 'refreshing':
return this.refreshMessage || this.$q.i18n.pullToRefresh.refresh
case 'pull':
default:
return this.pullMessage || this.$q.i18n.pullToRefresh.pull
}
},
style: function style$$1 () {
return cssTransform(("translateY(" + (this.pullPosition) + "px)"))
}
},
methods: {
__pull: function __pull (event) {
if (this.disable) {
return
}
if (event.isFinal) {
this.scrolling = false;
this.pulling = false;
if (this.scrolling) {
return
}
if (this.state === 'pulled') {
this.state = 'refreshing';
this.__animateTo(0);
this.trigger();
}
else if (this.state === 'pull') {
this.__animateTo(-this.height);
}
return
}
if (this.animating || this.scrolling || this.state === 'refreshing') {
return true
}
var top = getScrollPosition(this.scrollContainer);
if (top !== 0 || (top === 0 && event.direction !== 'down')) {
this.scrolling = true;
if (this.pulling) {
this.pulling = false;
this.state = 'pull';
this.__animateTo(-this.height);
}
return true
}
event.evt.preventDefault();
this.pulling = true;
this.pullPosition = -this.height + Math.max(0, Math.pow(event.distance.y, 0.85));
this.state = this.pullPosition > this.distance ? 'pulled' : 'pull';
},
__animateTo: function __animateTo (target, done, previousCall) {
var this$1 = this;
if (!previousCall && this.animationId) {
cancelAnimationFrame(this.animating);
}
this.pullPosition -= (this.pullPosition - target) / 7;
if (this.pullPosition - target > 1) {
this.animating = window.requestAnimationFrame(function () {
this$1.__animateTo(target, done, true);
});
}
else {
this.animating = window.requestAnimationFrame(function () {
this$1.pullPosition = target;
this$1.animating = false;
done && done();
});
}
},
trigger: function trigger () {
var this$1 = this;
this.handler(function () {
this$1.__animateTo(-this$1.height, function () {
this$1.state = 'pull';
});
});
}
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.scrollContainer = this$1.inline ? this$1.$el.parentNode : getScrollTarget(this$1.$el);
});
},
render: function render (h) {
return h('div', { staticClass: 'pull-to-refresh' }, [
h('div', {
staticClass: 'pull-to-refresh-container',
style: this.style,
directives: [{
name: 'touch-pan',
modifiers: {
vertical: true,
mightPrevent: true
},
value: this.__pull
}]
}, [
h('div', { staticClass: 'pull-to-refresh-message row flex-center' }, [
h(QIcon, {
'class': { 'rotate-180': this.state === 'pulled' },
props: { name: this.$q.icon.pullToRefresh.arrow },
directives: [{
name: 'show',
value: this.state !== 'refreshing'
}]
}),
h(QIcon, {
staticClass: 'animate-spin',
props: { name: this.refreshIcon || this.$q.icon.pullToRefresh.refresh },
directives: [{
name: 'show',
value: this.state === 'refreshing'
}]
}),
(" " + (this.message))
]),
this.$slots.default
])
])
}
}
var dragType = {
MIN: 0,
RANGE: 1,
MAX: 2
};
var QRange = {
name: 'q-range',
mixins: [SliderMixin],
props: {
value: {
type: Object,
default: function () { return ({
min: 0,
max: 0
}); },
validator: function validator (value) {
return value.hasOwnProperty('min') && value.hasOwnProperty('max')
}
},
dragRange: Boolean,
dragOnlyRange: Boolean,
leftLabelColor: String,
leftLabelValue: String,
rightLabelColor: String,
rightLabelValue: String
},
data: function data () {
return {
model: extend({}, this.value),
dragging: false,
currentMinPercentage: (this.value.min - this.min) / (this.max - this.min),
currentMaxPercentage: (this.value.max - this.min) / (this.max - this.min)
}
},
computed: {
percentageMin: function percentageMin () {
return this.snap ? (this.model.min - this.min) / (this.max - this.min) : this.currentMinPercentage
},
percentageMax: function percentageMax () {
return this.snap ? (this.model.max - this.min) / (this.max - this.min) : this.currentMaxPercentage
},
activeTrackWidth: function activeTrackWidth () {
return 100 * (this.percentageMax - this.percentageMin) + '%'
},
leftDisplayValue: function leftDisplayValue () {
return this.leftLabelValue !== void 0
? this.leftLabelValue
: this.model.min
},
rightDisplayValue: function rightDisplayValue () {
return this.rightLabelValue !== void 0
? this.rightLabelValue
: this.model.max
},
leftTooltipColor: function leftTooltipColor () {
return this.leftLabelColor || this.labelColor
},
rightTooltipColor: function rightTooltipColor () {
return this.rightLabelColor || this.labelColor
}
},
watch: {
'value.min': function value_min (value) {
this.model.min = value;
},
'value.max': function value_max (value) {
this.model.max = value;
},
'model.min': function model_min (value) {
if (this.dragging) {
return
}
if (value > this.model.max) {
value = this.model.max;
}
this.currentMinPercentage = (value - this.min) / (this.max - this.min);
},
'model.max': function model_max (value) {
if (this.dragging) {
return
}
if (value < this.model.min) {
value = this.model.min;
}
this.currentMaxPercentage = (value - this.min) / (this.max - this.min);
},
min: function min (value) {
if (this.model.min < value) {
this.__update({min: value});
}
if (this.model.max < value) {
this.__update({max: value});
}
this.$nextTick(this.__validateProps);
},
max: function max (value) {
if (this.model.min > value) {
this.__update({min: value});
}
if (this.model.max > value) {
this.__update({max: value});
}
this.$nextTick(this.__validateProps);
},
step: function step () {
this.$nextTick(this.__validateProps);
}
},
methods: {
__setActive: function __setActive (event) {
var
container = this.$refs.handle,
width = container.offsetWidth,
sensitivity = (this.dragOnlyRange ? -1 : 1) * this.$refs.handleMin.offsetWidth / (2 * width);
this.dragging = {
left: container.getBoundingClientRect().left,
width: width,
valueMin: this.model.min,
valueMax: this.model.max,
percentageMin: this.currentMinPercentage,
percentageMax: this.currentMaxPercentage
};
var
percentage = getPercentage(event, this.dragging),
type;
if (percentage < this.currentMinPercentage + sensitivity) {
type = dragType.MIN;
}
else if (percentage < this.currentMaxPercentage - sensitivity) {
if (this.dragRange || this.dragOnlyRange) {
type = dragType.RANGE;
extend(this.dragging, {
offsetPercentage: percentage,
offsetModel: getModel(percentage, this.min, this.max, this.step, this.computedDecimals),
rangeValue: this.dragging.valueMax - this.dragging.valueMin,
rangePercentage: this.currentMaxPercentage - this.currentMinPercentage
});
}
else {
type = this.currentMaxPercentage - percentage < percentage - this.currentMinPercentage
? dragType.MAX
: dragType.MIN;
}
}
else {
type = dragType.MAX;
}
if (this.dragOnlyRange && type !== dragType.RANGE) {
this.dragging = false;
return
}
this.dragging.type = type;
this.__update(event);
},
__update: function __update (event) {
var
percentage = getPercentage(event, this.dragging),
model = getModel(percentage, this.min, this.max, this.step, this.computedDecimals),
pos;
switch (this.dragging.type) {
case dragType.MIN:
if (percentage <= this.dragging.percentageMax) {
pos = {
minP: percentage,
maxP: this.dragging.percentageMax,
min: model,
max: this.dragging.valueMax
};
}
else {
pos = {
minP: this.dragging.percentageMax,
maxP: percentage,
min: this.dragging.valueMax,
max: model
};
}
break
case dragType.MAX:
if (percentage >= this.dragging.percentageMin) {
pos = {
minP: this.dragging.percentageMin,
maxP: percentage,
min: this.dragging.valueMin,
max: model
};
}
else {
pos = {
minP: percentage,
maxP: this.dragging.percentageMin,
min: model,
max: this.dragging.valueMin
};
}
break
case dragType.RANGE:
var
percentageDelta = percentage - this.dragging.offsetPercentage,
minP = between(this.dragging.percentageMin + percentageDelta, 0, 1 - this.dragging.rangePercentage),
modelDelta = model - this.dragging.offsetModel,
min = between(this.dragging.valueMin + modelDelta, this.min, this.max - this.dragging.rangeValue);
pos = {
minP: minP,
maxP: minP + this.dragging.rangePercentage,
min: parseFloat(min.toFixed(this.computedDecimals)),
max: parseFloat((min + this.dragging.rangeValue).toFixed(this.computedDecimals))
};
break
}
this.currentMinPercentage = pos.minP;
this.currentMaxPercentage = pos.maxP;
this.__updateInput(pos);
},
__end: function __end () {
var this$1 = this;
this.dragging = false;
this.currentMinPercentage = (this.model.min - this.min) / (this.max - this.min);
this.currentMaxPercentage = (this.model.max - this.min) / (this.max - this.min);
this.$nextTick(function () {
if (JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
this$1.$emit('dragend', this$1.model);
});
},
__updateInput: function __updateInput (ref) {
var min = ref.min; if ( min === void 0 ) min = this.model.min;
var max = ref.max; if ( max === void 0 ) max = this.model.max;
var model = {min: min, max: max};
this.model = model;
this.$emit('input', model);
},
__validateProps: function __validateProps () {
if (this.min >= this.max) {
console.error('Range error: min >= max', this.$el, this.min, this.max);
}
else if (notDivides((this.max - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of max - min', this.min, this.max, this.step);
}
else if (notDivides((this.model.min - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of initial value.min - min', this.model.min, this.min, this.step);
}
else if (notDivides((this.model.max - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of initial value.max - min', this.model.max, this.max, this.step);
}
},
__getHandle: function __getHandle (h, lower, upper, edge, percentage, color, label) {
return h('div', {
ref: ("handle" + upper),
staticClass: ("q-slider-handle q-slider-handle-" + lower),
style: {
left: ((percentage * 100) + "%"),
borderRadius: this.square ? '0' : '50%'
},
'class': [
edge ? 'handle-at-minimum' : null,
{ dragging: this.dragging }
]
}, [
this.label || this.labelAlways
? h(QChip, {
props: {
pointing: 'down',
square: true,
color: color
},
staticClass: 'q-slider-label no-pointer-events',
'class': { 'label-always': this.labelAlways }
}, [ label ])
: null,
null
])
},
__getContent: function __getContent (h) {
return [
h('div', {
staticClass: 'q-slider-track active-track',
style: {
left: ((this.percentageMin * 100) + "%"),
width: this.activeTrackWidth
},
'class': {
dragging: this.dragging,
'track-draggable': this.dragRange || this.dragOnlyRange
}
}),
this.__getHandle(
h, 'min', 'Min', !this.fillHandleAlways && this.model.min === this.min, this.percentageMin,
this.leftTooltipColor, this.leftDisplayValue
),
this.__getHandle(
h, 'max', 'Max', false, this.percentageMax,
this.rightTooltipColor, this.rightDisplayValue
)
]
}
}
}
var QRating = {
name: 'q-rating',
props: {
value: Number,
max: {
type: Number,
default: 5
},
icon: String,
color: String,
size: String,
readonly: Boolean,
disable: Boolean
},
data: function data () {
return {
mouseModel: 0
}
},
computed: {
model: {
get: function get () {
return this.value
},
set: function set (value) {
var this$1 = this;
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
editable: function editable () {
return !this.readonly && !this.disable
},
classes: function classes () {
var cls = [];
this.disable && cls.push('disabled');
this.editable && cls.push('editable');
this.color && cls.push(("text-" + (this.color)));
return cls
}
},
methods: {
set: function set (value) {
if (this.editable) {
var model = between(parseInt(value, 10), 1, this.max);
this.model = this.model === model ? 0 : model;
this.mouseModel = 0;
}
},
__setHoverValue: function __setHoverValue (value) {
if (this.editable) {
this.mouseModel = value;
}
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
tabindex = this.editable ? 0 : -1;
var loop = function ( i ) {
child.push(h(QIcon, {
key: i,
ref: ("rt" + i),
props: { name: this$1.icon || this$1.$q.icon.rating.icon },
'class': {
active: (!this$1.mouseModel && this$1.model >= i) || (this$1.mouseModel && this$1.mouseModel >= i),
exselected: this$1.mouseModel && this$1.model >= i && this$1.mouseModel < i,
hovered: this$1.mouseModel === i
},
attrs: { tabindex: tabindex },
nativeOn: {
click: function (e) {
e.target.blur();
this$1.set(i);
},
mouseover: function () { return this$1.__setHoverValue(i); },
mouseout: function () { this$1.mouseModel = 0; },
keydown: function (e) {
switch (getEventKey(e)) {
case 13:
case 32:
this$1.set(i);
return stopAndPrevent(e)
case 37: // LEFT ARROW
case 40: // DOWN ARROW
if (this$1.$refs[("rt" + (i - 1))]) {
this$1.$refs[("rt" + (i - 1))].$el.focus();
}
return stopAndPrevent(e)
case 39: // RIGHT ARROW
case 38: // UP ARROW
if (this$1.$refs[("rt" + (i + 1))]) {
this$1.$refs[("rt" + (i + 1))].$el.focus();
}
return stopAndPrevent(e)
}
},
focus: function () { return this$1.__setHoverValue(i); },
blur: function () { this$1.mouseModel = 0; }
}
}));
};
for (var i = 1; i <= this.max; i++) loop( i );
return h('div', {
staticClass: 'q-rating row inline items-center no-wrap',
'class': this.classes,
style: this.size ? ("font-size: " + (this.size)) : ''
}, child)
}
}
var QScrollArea = {
name: 'q-scroll-area',
directives: {
TouchPan: TouchPan
},
props: {
thumbStyle: {
type: Object,
default: function () { return ({}); }
},
contentStyle: {
type: Object,
default: function () { return ({}); }
},
contentActiveStyle: {
type: Object,
default: function () { return ({}); }
},
delay: {
type: Number,
default: 1000
}
},
data: function data () {
return {
active: false,
hover: false,
containerHeight: 0,
scrollPosition: 0,
scrollHeight: 0
}
},
computed: {
thumbHidden: function thumbHidden () {
return this.scrollHeight <= this.containerHeight || (!this.active && !this.hover)
},
thumbHeight: function thumbHeight () {
return Math.round(between(this.containerHeight * this.containerHeight / this.scrollHeight, 50, this.containerHeight))
},
style: function style () {
var top = this.scrollPercentage * (this.containerHeight - this.thumbHeight);
return extend({}, this.thumbStyle, {
top: (top + "px"),
height: ((this.thumbHeight) + "px")
})
},
mainStyle: function mainStyle () {
return this.thumbHidden ? this.contentStyle : this.contentActiveStyle
},
scrollPercentage: function scrollPercentage () {
var p = between(this.scrollPosition / (this.scrollHeight - this.containerHeight), 0, 1);
return Math.round(p * 10000) / 10000
}
},
methods: {
setScrollPosition: function setScrollPosition$1 (offset, duration) {
setScrollPosition(this.$refs.target, offset, duration);
},
__updateContainer: function __updateContainer (size) {
if (this.containerHeight !== size.height) {
this.containerHeight = size.height;
this.__setActive(true, true);
}
},
__updateScroll: function __updateScroll (scroll) {
if (this.scrollPosition !== scroll.position) {
this.scrollPosition = scroll.position;
this.__setActive(true, true);
}
},
__updateScrollHeight: function __updateScrollHeight (ref) {
var height = ref.height;
if (this.scrollHeight !== height) {
this.scrollHeight = height;
this.__setActive(true, true);
}
},
__panThumb: function __panThumb (e) {
if (e.isFirst) {
this.refPos = this.scrollPosition;
this.__setActive(true, true);
document.body.classList.add('non-selectable');
if (document.selection) {
document.selection.empty();
}
else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
}
if (e.isFinal) {
this.__setActive(false);
document.body.classList.remove('non-selectable');
}
var multiplier = (this.scrollHeight - this.containerHeight) / (this.containerHeight - this.thumbHeight);
this.$refs.target.scrollTop = this.refPos + (e.direction === 'down' ? 1 : -1) * e.distance.y * multiplier;
},
__panContainer: function __panContainer (e) {
if (e.isFirst) {
this.refPos = this.scrollPosition;
this.__setActive(true, true);
}
if (e.isFinal) {
this.__setActive(false);
}
var pos = this.refPos + (e.direction === 'down' ? -1 : 1) * e.distance.y;
this.$refs.target.scrollTop = pos;
if (pos > 0 && pos + this.containerHeight < this.scrollHeight) {
e.evt.preventDefault();
}
},
__mouseWheel: function __mouseWheel (e) {
var el = this.$refs.target;
el.scrollTop += getMouseWheelDistance(e).pixelY;
if (el.scrollTop > 0 && el.scrollTop + this.containerHeight < this.scrollHeight) {
e.preventDefault();
}
},
__setActive: function __setActive (active, timer) {
clearTimeout(this.timer);
if (active === this.active) {
if (active && this.timer) {
this.__startTimer();
}
return
}
if (active) {
this.active = true;
if (timer) {
this.__startTimer();
}
}
else {
this.active = false;
}
},
__startTimer: function __startTimer () {
var this$1 = this;
this.timer = setTimeout(function () {
this$1.active = false;
this$1.timer = null;
}, this.delay);
}
},
render: function render (h) {
var this$1 = this;
if (!this.$q.platform.is.desktop) {
return h('div', {
ref: 'target',
staticClass: 'q-scroll-area scroll relative-position',
style: this.contentStyle
}, [
this.$slots.default
])
}
return h('div', {
staticClass: 'q-scrollarea relative-position',
on: {
mouseenter: function () { this$1.hover = true; },
mouseleave: function () { this$1.hover = false; }
}
}, [
h('div', {
ref: 'target',
staticClass: 'scroll relative-position overflow-hidden fit',
on: {
wheel: this.__mouseWheel,
mousewheel: this.__mouseWheel,
DOMMouseScroll: this.__mouseWheel
},
directives: [{
name: 'touch-pan',
modifiers: {
vertical: true,
noMouse: true,
mightPrevent: true
},
value: this.__panContainer
}]
}, [
h('div', {
staticClass: 'absolute full-width',
style: this.mainStyle
}, [
this.$slots.default,
h(QResizeObservable, {
staticClass: 'resize-obs',
on: { resize: this.__updateScrollHeight }
})
]),
h(QScrollObservable, {
staticClass: 'scroll-obs',
on: { scroll: this.__updateScroll }
})
]),
h(QResizeObservable, {
staticClass: 'main-resize-obs',
on: { resize: this.__updateContainer }
}),
h('div', {
staticClass: 'q-scrollarea-thumb absolute-right',
style: this.style,
'class': { 'invisible-thumb': this.thumbHidden },
directives: [{
name: 'touch-pan',
modifiers: {
vertical: true,
prevent: true
},
value: this.__panThumb
}]
})
])
}
}
var QSearch = {
name: 'q-search',
mixins: [FrameMixin, InputMixin],
props: {
value: { required: true },
type: String,
debounce: {
type: Number,
default: 300
},
icon: String,
placeholder: String
},
data: function data () {
return {
model: this.value,
childDebounce: false
}
},
provide: function provide () {
var this$1 = this;
return {
__inputDebounce: {
set: function (val) {
if (this$1.model !== val) {
this$1.model = val;
}
},
setChildDebounce: function (v) {
this$1.childDebounce = v;
}
}
}
},
watch: {
value: function value (v) {
this.model = v;
},
model: function model (val) {
var this$1 = this;
clearTimeout(this.timer);
if (this.value === val) {
return
}
if (!val && val !== 0) {
this.model = this.type === 'number' ? null : '';
}
this.timer = setTimeout(function () {
this$1.$emit('input', this$1.model);
}, this.debounceValue);
}
},
computed: {
debounceValue: function debounceValue () {
return this.childDebounce
? 0
: this.debounce
},
controlBefore: function controlBefore () {
return this.before || [{
icon: this.icon || this.$q.icon.search.icon,
handler: this.focus
}]
},
controlAfter: function controlAfter () {
if (this.after) {
return this.after
}
if (this.editable && this.clearable) {
return [{
icon: this.$q.icon.search[("clear" + (this.inverted ? 'Inverted' : ''))],
content: true,
handler: this.clear
}]
}
}
},
methods: {
clear: function clear () {
this.$refs.input.clear();
}
},
render: function render (h) {
var this$1 = this;
return h(QInput, {
ref: 'input',
staticClass: 'q-search',
props: {
value: this.model,
type: this.type,
autofocus: this.autofocus,
placeholder: this.placeholder || this.$q.i18n.label.search,
disable: this.disable,
readonly: this.readonly,
error: this.error,
warning: this.warning,
align: this.align,
floatLabel: this.floatLabel,
stackLabel: this.stackLabel,
prefix: this.prefix,
suffix: this.suffix,
inverted: this.inverted,
dark: this.dark,
hideUnderline: this.hideUnderline,
color: this.color,
before: this.controlBefore,
after: this.controlAfter,
clearValue: this.clearValue
},
attrs: this.$attrs,
on: {
input: function (v) { this$1.model = v; },
focus: this.__onFocus,
blur: this.__onBlur,
keyup: this.__onKeyup,
keydown: this.__onKeydown,
click: this.__onClick,
clear: function (val) {
this$1.$emit('clear', val);
this$1.__emit();
}
}
}, [
this.$slots.default
])
}
}
function defaultFilterFn (terms, obj) {
return obj.label.toLowerCase().indexOf(terms) > -1
}
var QSelect = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('q-input-frame',{ref:"input",staticClass:"q-select",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.computedColor,"focused":_vm.focused,"focusable":"","length":_vm.length,"additional-length":_vm.additionalLength},nativeOn:{"click":function($event){_vm.togglePopup($event);},"focus":function($event){_vm.__onFocus($event);},"blur":function($event){_vm.__onBlur($event);},"keydown":function($event){_vm.__handleKeyDown($event);}}},[(_vm.hasChips)?_c('div',{staticClass:"col row items-center group q-input-chips q-if-control",class:_vm.alignClass},_vm._l((_vm.selectedOptions),function(ref){
var label = ref.label;
var value = ref.value;
var optColor = ref.color;
var optIcon = ref.icon;
var optIconRight = ref.rightIcon;
var optAvatar = ref.avatar;
var optDisable = ref.disable;
return _c('q-chip',{key:label,attrs:{"small":"","closable":!_vm.disable && !_vm.readonly && !optDisable,"color":_vm.computedChipColor(optColor),"text-color":_vm.computedChipTextColor(optColor),"icon":optIcon,"iconRight":optIconRight,"avatar":optAvatar},on:{"hide":function($event){_vm.__toggleMultiple(value, _vm.disable || optDisable);}},nativeOn:{"click":function($event){$event.stopPropagation();}}},[_vm._v(" "+_vm._s(label)+" ")])})):_c('div',{staticClass:"col row items-center q-input-target q-if-control",class:_vm.alignClass,domProps:{"innerHTML":_vm._s(_vm.actualValue)}}),_vm._v(" "),(!_vm.disable && !_vm.readonly && _vm.clearable && _vm.length)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":"cancel"},nativeOn:{"click":function($event){$event.stopPropagation();_vm.clear($event);}},slot:"after"}):_vm._e(),_vm._v(" "),_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input.dropdown},slot:"after"}),_vm._v(" "),_c('q-popover',{ref:"popover",staticClass:"column no-wrap",attrs:{"fit":"","disable":_vm.readonly || _vm.disable,"offset":[0, 10],"anchor-click":false},on:{"show":_vm.__onFocus,"hide":_vm.__onClose}},[_c('q-field-reset',[(_vm.filter)?_c('q-search',{ref:"filter",staticStyle:{"min-height":"50px","padding":"10px"},attrs:{"placeholder":_vm.filterPlaceholder || _vm.$q.i18n.label.filter,"debounce":100,"color":_vm.color,"icon":"filter_list"},on:{"input":_vm.reposition},model:{value:(_vm.terms),callback:function ($$v) {_vm.terms=$$v;},expression:"terms"}}):_vm._e()],1),_vm._v(" "),_c('q-list',{staticClass:"no-border scroll",attrs:{"separator":_vm.separator}},[(_vm.multiple)?_vm._l((_vm.visibleOptions),function(opt){return _c('q-item-wrapper',{key:JSON.stringify(opt),class:{'text-faded': opt.disable},attrs:{"cfg":opt,"link":!opt.disable,"slot-replace":""},nativeOn:{"!click":function($event){_vm.__toggleMultiple(opt.value, opt.disable);}}},[(_vm.toggle)?_c('q-toggle',{attrs:{"slot":"right","color":opt.color || _vm.color,"keep-color":!!opt.color,"value":_vm.optModel[opt.index],"disable":opt.disable,"no-focus":""},slot:"right"}):_c('q-checkbox',{attrs:{"slot":"left","color":opt.color || _vm.color,"keep-color":!!opt.color,"value":_vm.optModel[opt.index],"disable":opt.disable,"no-focus":""},slot:"left"})],1)}):_vm._l((_vm.visibleOptions),function(opt){return _c('q-item-wrapper',{key:JSON.stringify(opt),class:{'text-faded': opt.disable},attrs:{"cfg":opt,"link":!opt.disable,"slot-replace":"","active":_vm.value === opt.value},nativeOn:{"!click":function($event){_vm.__singleSelect(opt.value, opt.disable);}}},[(_vm.radio)?_c('q-radio',{attrs:{"slot":"left","color":opt.color || _vm.color,"keep-color":!!opt.color,"value":_vm.value,"val":opt.value,"disable":opt.disable,"no-focus":""},slot:"left"}):_vm._e()],1)})],2)],1)],1)},staticRenderFns: [],
name: 'q-select',
mixins: [FrameMixin],
components: {
QFieldReset: QFieldReset,
QSearch: QSearch,
QPopover: QPopover,
QList: QList,
QItemWrapper: QItemWrapper,
QCheckbox: QCheckbox,
QRadio: QRadio,
QToggle: QToggle,
QIcon: QIcon,
QInputFrame: QInputFrame,
QChip: QChip
},
props: {
filter: [Function, Boolean],
filterPlaceholder: String,
autofocusFilter: Boolean,
radio: Boolean,
placeholder: String,
separator: Boolean,
value: { required: true },
multiple: Boolean,
toggle: Boolean,
chips: Boolean,
readonly: Boolean,
options: {
type: Array,
required: true,
validator: function (v) { return v.every(function (o) { return 'label' in o && 'value' in o; }); }
},
frameColor: String,
displayValue: String,
clearable: Boolean,
clearValue: {}
},
data: function data () {
return {
model: this.multiple && Array.isArray(this.value)
? this.value.slice()
: this.value,
terms: '',
focused: false
}
},
watch: {
value: function value (val) {
this.model = this.multiple && Array.isArray(val)
? val.slice()
: val;
}
},
computed: {
optModel: function optModel () {
var this$1 = this;
if (this.multiple) {
return this.model.length > 0
? this.options.map(function (opt) { return this$1.model.includes(opt.value); })
: this.options.map(function (opt) { return false; })
}
},
visibleOptions: function visibleOptions () {
var this$1 = this;
var opts = this.options.map(function (opt, index) { return extend({}, opt, { index: index }); });
if (this.filter && this.terms.length) {
var lowerTerms = this.terms.toLowerCase();
opts = opts.filter(function (opt) { return this$1.filterFn(lowerTerms, opt); });
}
return opts
},
filterFn: function filterFn () {
return typeof this.filter === 'boolean'
? defaultFilterFn
: this.filter
},
activeItemSelector: function activeItemSelector () {
return this.multiple
? (".q-item-side > " + (this.toggle ? '.q-toggle' : '.q-checkbox') + " > .active")
: ".q-item.active"
},
actualValue: function actualValue () {
var this$1 = this;
if (this.displayValue) {
return this.displayValue
}
if (!this.multiple) {
var opt$1 = this.options.find(function (opt) { return opt.value === this$1.model; });
return opt$1 ? opt$1.label : ''
}
var opt = this.selectedOptions.map(function (opt) { return opt.label; });
return opt.length ? opt.join(', ') : ''
},
selectedOptions: function selectedOptions () {
var this$1 = this;
if (this.multiple) {
return this.length > 0
? this.options.filter(function (opt) { return this$1.model.includes(opt.value); })
: []
}
},
hasChips: function hasChips () {
return this.multiple && this.chips
},
length: function length () {
return this.multiple
? this.model.length
: ([null, undefined, ''].includes(this.model) ? 0 : 1)
},
additionalLength: function additionalLength () {
return this.displayValue && this.displayValue.length > 0
},
computedColor: function computedColor () {
return this.inverted ? this.frameColor || this.color : this.color
}
},
methods: {
togglePopup: function togglePopup () {
this[this.$refs.popover.showing ? 'hide' : 'show']();
},
show: function show () {
return this.$refs.popover.show()
},
hide: function hide () {
return this.$refs.popover.hide()
},
reposition: function reposition () {
var popover = this.$refs.popover;
if (popover.showing) {
popover.reposition();
}
},
__handleKeyDown: function __handleKeyDown (e) {
switch (getEventKey(e)) {
case 13: // ENTER key
case 32: // SPACE key
stopAndPrevent(e);
return this.show()
case 8: // BACKSPACE key
if (this.editable && this.clearable && this.actualValue.length) {
this.clear();
}
}
},
__onFocus: function __onFocus () {
if (this.disable || this.focused) {
return
}
this.focused = true;
if (this.filter && this.autofocusFilter) {
this.$refs.filter.focus();
}
this.$emit('focus');
var selected = this.$refs.popover.$el.querySelector(this.activeItemSelector);
if (selected) {
selected.scrollIntoView();
}
},
__onBlur: function __onBlur (e) {
var this$1 = this;
setTimeout(function () {
var el = document.activeElement;
if (
!this$1.$refs.popover.showing ||
(el !== document.body && !this$1.$refs.popover.$el.contains(el))
) {
this$1.__onClose();
this$1.hide();
}
}, 1);
},
__onClose: function __onClose () {
var this$1 = this;
this.focused = false;
this.terms = '';
this.$emit('blur');
this.$nextTick(function () {
if (JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
});
},
__singleSelect: function __singleSelect (val, disable) {
if (disable) {
return
}
this.__emit(val);
this.hide();
},
__toggleMultiple: function __toggleMultiple (value, disable) {
if (disable) {
return
}
var
model = this.model,
index = model.indexOf(value);
if (index > -1) {
model.splice(index, 1);
}
else {
model.push(value);
}
this.$emit('input', model);
},
__emit: function __emit (value) {
var this$1 = this;
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__setModel: function __setModel (val, forceUpdate) {
this.model = val || (this.multiple ? [] : null);
this.$emit('input', this.model);
if (forceUpdate || !this.$refs.popover.showing) {
this.__onClose();
}
},
computedChipColor: function computedChipColor (optColor) {
if (this.inverted) {
if (this.frameColor) {
return this.color
}
return this.dark !== false ? 'white' : null
}
return optColor || this.color
},
computedChipTextColor: function computedChipTextColor (optColor) {
if (this.inverted) {
return optColor || this.frameColor || this.color
}
return this.dark !== false ? 'white' : null
}
}
}
var StepTab = {
name: 'q-step-tab',
components: {
QIcon: QIcon
},
directives: {
Ripple: Ripple
},
props: ['vm'],
computed: {
classes: function classes () {
return {
'step-error': this.vm.error,
'step-active': this.vm.active,
'step-done': this.vm.done,
'step-waiting': this.vm.waiting,
'step-disabled': this.vm.disable,
'step-colored': this.vm.active || this.vm.done,
'items-center': !this.vm.__stepper.vertical,
'items-start': this.vm.__stepper.vertical,
'q-stepper-first': this.vm.first,
'q-stepper-last': this.vm.last
}
}
},
methods: {
__select: function __select () {
this.vm.select();
}
},
render: function render (h) {
var icon = this.vm.stepIcon
? h(QIcon, { props: { name: this.vm.stepIcon } })
: h('span', [ (this.vm.innerOrder + 1) ]);
return h('div', {
staticClass: 'q-stepper-tab col-grow flex no-wrap relative-position',
'class': this.classes,
on: {
click: this.__select
},
directives: null
}, [
h('div', { staticClass: 'q-stepper-dot row flex-center q-stepper-line relative-position' }, [
h('span', { staticClass: 'row flex-center' }, [ icon ])
]),
this.vm.title
? h('div', {
staticClass: 'q-stepper-label q-stepper-line relative-position'
}, [
h('div', { staticClass: 'q-stepper-title' }, [ this.vm.title ]),
h('div', { staticClass: 'q-stepper-subtitle' }, [ this.vm.subtitle ])
])
: null
])
}
}
var QStep = {
name: 'q-step',
inject: {
__stepper: {
default: function default$1 () {
console.error('QStep needs to be child of QStepper');
}
}
},
props: {
name: {
type: [Number, String],
default: function default$2 () {
return uid()
}
},
default: Boolean,
title: {
type: String,
required: true
},
subtitle: String,
icon: String,
order: [Number, String],
error: Boolean,
activeIcon: String,
errorIcon: String,
doneIcon: String,
disable: Boolean
},
watch: {
order: function order () {
this.__stepper.__sortSteps();
}
},
data: function data () {
return {
innerOrder: 0,
first: false,
last: false
}
},
computed: {
stepIcon: function stepIcon () {
var data = this.__stepper;
if (this.active) {
return this.activeIcon || data.activeIcon || this.$q.icon.stepper.active
}
if (this.error) {
return this.errorIcon || data.errorIcon || this.$q.icon.stepper.error
}
if (this.done && !this.disable) {
return this.doneIcon || data.doneIcon || this.$q.icon.stepper.done
}
return this.icon
},
actualOrder: function actualOrder () {
return parseInt(this.order || this.innerOrder, 10)
},
active: function active () {
return this.__stepper.step === this.name
},
done: function done () {
return !this.disable && this.__stepper.currentOrder > this.innerOrder
},
waiting: function waiting () {
return !this.disable && this.__stepper.currentOrder < this.innerOrder
},
style: function style () {
var ord = this.actualOrder;
return {
'-webkit-box-ordinal-group': ord,
'-ms-flex-order': ord,
order: ord
}
}
},
methods: {
select: function select () {
if (this.done) {
this.__stepper.goToStep(this.name);
}
}
},
mounted: function mounted () {
this.__stepper.__registerStep(this);
if (this.default) {
this.select();
}
},
beforeDestroy: function beforeDestroy () {
this.__stepper.__unregisterStep(this);
},
render: function render (h) {
return h('div', {
staticClass: 'q-stepper-step',
style: this.style
}, [
this.__stepper.vertical
? h(StepTab, { props: { vm: this } })
: null,
h(QSlideTransition, [
this.active
? h('div', {
staticClass: 'q-stepper-step-content'
}, [
h('div', { staticClass: 'q-stepper-step-inner' }, [
this.$slots.default
])
])
: null
])
])
}
}
var QStepper = {
name: 'q-stepper',
components: {
StepTab: StepTab
},
props: {
value: [Number, String],
color: String,
vertical: Boolean,
alternativeLabels: Boolean,
contractable: Boolean,
doneIcon: Boolean,
activeIcon: Boolean,
errorIcon: Boolean
},
data: function data () {
return {
step: this.value || null,
steps: []
}
},
provide: function provide () {
return {
__stepper: this
}
},
watch: {
value: function value (v) {
this.goToStep(v);
}
},
computed: {
classes: function classes () {
var cls = [
("q-stepper-" + (this.vertical ? 'vertical' : 'horizontal'))
];
if (this.color) {
cls.push(("text-" + (this.color)));
}
if (this.contractable) {
cls.push("q-stepper-contractable");
}
return cls
},
hasSteps: function hasSteps () {
return this.steps.length > 0
},
currentStep: function currentStep () {
var this$1 = this;
if (this.hasSteps) {
return this.steps.find(function (step) { return step.name === this$1.step; })
}
},
currentOrder: function currentOrder () {
if (this.currentStep) {
return this.currentStep.innerOrder
}
},
length: function length () {
return this.steps.length
}
},
methods: {
goToStep: function goToStep (value) {
var this$1 = this;
if (this.step === value || value === void 0) {
return
}
this.step = value;
this.$emit('input', value);
this.$emit('step', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
next: function next () {
this.__go(1);
},
previous: function previous () {
this.__go(-1);
},
reset: function reset () {
if (this.hasSteps) {
this.goToStep(this.steps[0].name);
}
},
__go: function __go (offset) {
var
name,
index = this.currentOrder;
if (index === void 0) {
if (!this.hasSteps) {
return
}
name = this.steps[0].name;
}
else {
do {
index += offset;
} while (index >= 0 && index < this.length - 1 && this.steps[index].disable)
if (index < 0 || index > this.length - 1 || this.steps[index].disable) {
return
}
name = this.steps[index].name;
}
this.goToStep(name);
},
__sortSteps: function __sortSteps () {
var this$1 = this;
this.steps.sort(function (a, b) {
return a.actualOrder - b.actualOrder
});
var last = this.steps.length - 1;
this.steps.forEach(function (step, index) {
step.innerOrder = index;
step.first = index === 0;
step.last = index === last;
});
this.$nextTick(function () {
if (!this$1.steps.some(function (step) { return step.active; })) {
this$1.goToStep(this$1.steps[0].name);
}
});
},
__registerStep: function __registerStep (vm) {
this.steps.push(vm);
this.__sortSteps();
return this
},
__unregisterStep: function __unregisterStep (vm) {
this.steps = this.steps.filter(function (step) { return step !== vm; });
}
},
created: function created () {
this.__sortSteps = frameDebounce(this.__sortSteps);
},
render: function render (h) {
return h('div', {
staticClass: 'q-stepper column overflow-hidden relative-position',
'class': this.classes
}, [
this.vertical
? null
: h('div', {
staticClass: 'q-stepper-header row items-stretch justify-between shadow-1',
'class': { 'alternative-labels': this.alternativeLabels }
},
this.steps.map(function (step) { return h(StepTab, {
key: step.name,
props: {
vm: step
}
}); })),
this.$slots.default
])
}
}
var QStepperNavigation = {
name: 'q-stepper-navigation',
render: function render (h) {
return h('div', {
staticClass: 'q-stepper-nav order-last row no-wrap items-center'
}, [
this.$slots.left,
h('div', { staticClass: 'col' }),
this.$slots.default
])
}
}
var TabMixin = {
directives: {
Ripple: Ripple
},
props: {
label: String,
icon: String,
disable: Boolean,
hidden: Boolean,
hide: {
type: String,
default: ''
},
name: {
type: String,
default: function default$1 () {
return uid()
}
},
alert: Boolean,
count: [Number, String],
color: String
},
inject: {
data: {
default: function default$2 () {
console.error('QTab/QRouteTab components need to be child of QTabs');
}
},
selectTab: {}
},
watch: {
active: function active (val) {
if (val) {
this.$emit('select', this.name);
}
}
},
computed: {
active: function active () {
return this.data.tabName === this.name
},
classes: function classes () {
var cls = {
active: this.active,
hidden: this.hidden,
disabled: this.disable,
'icon-and-label': this.icon && this.label,
'hide-icon': this.hide === 'icon',
'hide-label': this.hide === 'label'
};
var color = this.data.inverted
? this.color || this.data.color
: this.color;
if (color) {
cls[("text-" + color)] = this.active;
}
return cls
},
barStyle: function barStyle () {
if (!this.active || !this.data.highlight) {
return 'display: none;'
}
}
},
methods: {
__getTabContent: function __getTabContent (h) {
var child = [];
this.icon && child.push(h(QIcon, {
staticClass: 'q-tab-icon',
props: {
name: this.icon
}
}));
this.label && child.push(h('span', {
staticClass: 'q-tab-label',
domProps: {
innerHTML: this.label
}
}));
if (this.count) {
child.push(h(QChip, {
props: {
floating: true
}
}, [ this.count ]));
}
else if (this.alert) {
child.push(h('div', {
staticClass: 'q-dot'
}));
}
child.push(this.$slots.default);
return child
}
}
}
var QRouteTab = {
name: 'q-route-tab',
mixins: [TabMixin, RouterLinkMixin],
watch: {
$route: function $route () {
this.checkIfSelected();
}
},
methods: {
select: function select () {
this.$emit('click', this.name);
if (!this.disable) {
this.$el.dispatchEvent(evt);
this.selectTab(this.name);
}
},
checkIfSelected: function checkIfSelected () {
var this$1 = this;
this.$nextTick(function () {
if (this$1.$el.classList.contains('router-link-active') || this$1.$el.classList.contains('router-link-exact-active')) {
this$1.selectTab(this$1.name);
}
else if (this$1.active) {
this$1.selectTab(null);
}
});
}
},
created: function created () {
this.checkIfSelected();
},
render: function render (h) {
return h('router-link', {
props: {
tag: 'div',
to: this.to,
replace: this.replace,
append: this.append,
event: routerLinkEventName
},
nativeOn: {
click: this.select
},
staticClass: 'q-tab column flex-center relative-position',
'class': this.classes,
directives: null
}, this.__getTabContent(h))
}
}
var QTab = {
name: 'q-tab',
mixins: [TabMixin],
props: {
default: Boolean
},
methods: {
select: function select () {
this.$emit('click', this.name);
if (!this.disable) {
this.selectTab(this.name);
}
}
},
mounted: function mounted () {
if (this.default && !this.disable) {
this.select();
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-tab column flex-center relative-position',
'class': this.classes,
on: {
click: this.select
},
directives: null
}, this.__getTabContent(h))
}
}
var QTabPane = {
name: 'q-tab-pane',
inject: {
data: {
default: function default$1 () {
console.error('QTabPane needs to be child of QTabs');
}
}
},
props: {
name: {
type: String,
required: true
},
keepAlive: Boolean
},
data: function data () {
return {
shown: false
}
},
computed: {
active: function active () {
return this.data.tabName === this.name
}
},
render: function render (h) {
var node = h('div', {staticClass: 'q-tab-pane', 'class': {hidden: !this.active}}, [this.$slots.default]);
if (this.keepAlive) {
if (!this.shown && !this.active) {
return
}
this.shown = true;
return node
}
else {
this.shown = this.active;
if (this.active) {
return node
}
}
}
}
var scrollNavigationSpeed = 5;
var debounceDelay = 50; // in ms
var QTabs = {render: function(){
var obj;
var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-tabs flex no-wrap",class:[ ("q-tabs-position-" + (_vm.position)), ("q-tabs-" + (_vm.inverted ? 'inverted' : 'normal')), _vm.noPaneBorder ? 'q-tabs-no-pane-border' : '', _vm.twoLines ? 'q-tabs-two-lines' : '' ]},[_c('div',{ref:"tabs",staticClass:"q-tabs-head row",class:( obj = {}, obj[("q-tabs-align-" + (_vm.align))] = true, obj.glossy = _vm.glossy, obj[("bg-" + (_vm.color))] = !_vm.inverted && _vm.color, obj)},[_c('div',{ref:"scroller",staticClass:"q-tabs-scroller row no-wrap"},[_vm._t("title"),_vm._v(" "),(_vm.$q.theme !== 'ios')?_c('div',{staticClass:"relative-position self-stretch q-tabs-global-bar-container",class:[_vm.inverted && _vm.color ? ("text-" + (_vm.color)) : '', _vm.data.highlight ? 'highlight' : '']},[_c('div',{ref:"posbar",staticClass:"q-tabs-bar q-tabs-global-bar",on:{"transitionend":_vm.__updatePosbarTransition}})]):_vm._e()],2),_vm._v(" "),_c('div',{ref:"leftScroll",staticClass:"row flex-center q-tabs-left-scroll",on:{"mousedown":function($event){_vm.__animScrollTo(0);},"touchstart":function($event){_vm.__animScrollTo(0);},"mouseup":_vm.__stopAnimScroll,"mouseleave":_vm.__stopAnimScroll,"touchend":_vm.__stopAnimScroll}},[_c('q-icon',{attrs:{"name":_vm.$q.icon.tabs.left}})],1),_vm._v(" "),_c('div',{ref:"rightScroll",staticClass:"row flex-center q-tabs-right-scroll",on:{"mousedown":function($event){_vm.__animScrollTo(9999);},"touchstart":function($event){_vm.__animScrollTo(9999);},"mouseup":_vm.__stopAnimScroll,"mouseleave":_vm.__stopAnimScroll,"touchend":_vm.__stopAnimScroll}},[_c('q-icon',{attrs:{"name":_vm.$q.icon.tabs.right}})],1)]),_vm._v(" "),_c('div',{staticClass:"q-tabs-panes"},[_vm._t("default")],2)])},staticRenderFns: [],
name: 'q-tabs',
provide: function provide () {
return {
data: this.data,
selectTab: this.selectTab
}
},
components: {
QIcon: QIcon
},
props: {
value: String,
align: {
type: String,
default: 'center',
validator: function (v) { return ['left', 'center', 'right', 'justify'].includes(v); }
},
position: {
type: String,
default: 'top',
validator: function (v) { return ['top', 'bottom'].includes(v); }
},
color: String,
inverted: Boolean,
twoLines: Boolean,
noPaneBorder: Boolean,
glossy: Boolean
},
data: function data () {
return {
currentEl: null,
posbar: {
width: 0,
left: 0
},
data: {
highlight: true,
tabName: this.value || '',
color: this.color,
inverted: this.inverted
}
}
},
watch: {
value: function value (name) {
this.selectTab(name);
},
color: function color (v) {
this.data.color = v;
},
inverted: function inverted (v) {
this.data.inverted = v;
}
},
methods: {
selectTab: function selectTab (value) {
var this$1 = this;
if (this.data.tabName === value) {
return
}
this.data.tabName = value;
this.$emit('select', value);
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
var el = this.__getTabElByName(value);
if (el) {
this.__scrollToTab(el);
}
},
__repositionBar: function __repositionBar () {
var this$1 = this;
clearTimeout(this.timer);
var needsUpdate = false;
var
ref = this.$refs.posbar,
el = this.currentEl;
if (this.data.highlight !== false) {
this.data.highlight = false;
needsUpdate = true;
}
if (!el) {
this.finalPosbar = {width: 0, left: 0};
this.__setPositionBar(0, 0);
return
}
var offsetReference = ref.parentNode.offsetLeft;
if (needsUpdate && this.oldEl) {
this.__setPositionBar(
this.oldEl.getBoundingClientRect().width,
this.oldEl.offsetLeft - offsetReference
);
}
this.timer = setTimeout(function () {
var
width$$1 = el.getBoundingClientRect().width,
left = el.offsetLeft - offsetReference;
ref.classList.remove('contract');
this$1.oldEl = el;
this$1.finalPosbar = {width: width$$1, left: left};
this$1.__setPositionBar(
this$1.posbar.left < left
? left + width$$1 - this$1.posbar.left
: this$1.posbar.left + this$1.posbar.width - left,
this$1.posbar.left < left
? this$1.posbar.left
: left
);
}, 20);
},
__setPositionBar: function __setPositionBar (width$$1, left) {
if ( width$$1 === void 0 ) width$$1 = 0;
if ( left === void 0 ) left = 0;
if (this.posbar.width === width$$1 && this.posbar.left === left) {
this.__updatePosbarTransition();
return
}
this.posbar = {width: width$$1, left: left};
css(this.$refs.posbar, cssTransform(("translateX(" + left + "px) scaleX(" + width$$1 + ")")));
},
__updatePosbarTransition: function __updatePosbarTransition () {
if (
this.finalPosbar.width === this.posbar.width &&
this.finalPosbar.left === this.posbar.left
) {
this.posbar = {};
if (this.data.highlight !== true) {
this.data.highlight = true;
}
return
}
this.$refs.posbar.classList.add('contract');
this.__setPositionBar(this.finalPosbar.width, this.finalPosbar.left);
},
__redraw: function __redraw () {
if (!this.$q.platform.is.desktop) {
return
}
if (width(this.$refs.scroller) === 0 && this.$refs.scroller.scrollWidth === 0) {
return
}
if (width(this.$refs.scroller) + 5 < this.$refs.scroller.scrollWidth) {
this.$refs.tabs.classList.add('scrollable');
this.scrollable = true;
this.__updateScrollIndicator();
}
else {
this.$refs.tabs.classList.remove('scrollable');
this.scrollable = false;
}
},
__updateScrollIndicator: function __updateScrollIndicator () {
if (!this.$q.platform.is.desktop || !this.scrollable) {
return
}
var action = this.$refs.scroller.scrollLeft + width(this.$refs.scroller) + 5 >= this.$refs.scroller.scrollWidth ? 'add' : 'remove';
this.$refs.leftScroll.classList[this.$refs.scroller.scrollLeft <= 0 ? 'add' : 'remove']('disabled');
this.$refs.rightScroll.classList[action]('disabled');
},
__getTabElByName: function __getTabElByName (value) {
var tab = this.$children.find(function (child) { return child.name === value && child.$el && child.$el.nodeType === 1; });
if (tab) {
return tab.$el
}
},
__findTabAndScroll: function __findTabAndScroll (name, noAnimation) {
var this$1 = this;
setTimeout(function () {
this$1.__scrollToTab(this$1.__getTabElByName(name), noAnimation);
}, debounceDelay * 4);
},
__scrollToTab: function __scrollToTab (tab, noAnimation) {
if (!tab || !this.scrollable) {
return
}
var
contentRect = this.$refs.scroller.getBoundingClientRect(),
rect = tab.getBoundingClientRect(),
tabWidth = rect.width,
offset$$1 = rect.left - contentRect.left;
if (offset$$1 < 0) {
if (noAnimation) {
this.$refs.scroller.scrollLeft += offset$$1;
}
else {
this.__animScrollTo(this.$refs.scroller.scrollLeft + offset$$1);
}
return
}
offset$$1 += tabWidth - this.$refs.scroller.offsetWidth;
if (offset$$1 > 0) {
if (noAnimation) {
this.$refs.scroller.scrollLeft += offset$$1;
}
else {
this.__animScrollTo(this.$refs.scroller.scrollLeft + offset$$1);
}
}
},
__animScrollTo: function __animScrollTo (value) {
var this$1 = this;
this.__stopAnimScroll();
this.__scrollTowards(value);
this.scrollTimer = setInterval(function () {
if (this$1.__scrollTowards(value)) {
this$1.__stopAnimScroll();
}
}, 5);
},
__stopAnimScroll: function __stopAnimScroll () {
clearInterval(this.scrollTimer);
},
__scrollTowards: function __scrollTowards (value) {
var
scrollPosition = this.$refs.scroller.scrollLeft,
direction = value < scrollPosition ? -1 : 1,
done = false;
scrollPosition += direction * scrollNavigationSpeed;
if (scrollPosition < 0) {
done = true;
scrollPosition = 0;
}
else if (
(direction === -1 && scrollPosition <= value) ||
(direction === 1 && scrollPosition >= value)
) {
done = true;
scrollPosition = value;
}
this.$refs.scroller.scrollLeft = scrollPosition;
return done
}
},
created: function created () {
this.scrollTimer = null;
this.scrollable = !this.$q.platform.is.desktop;
// debounce some costly methods;
// debouncing here because debounce needs to be per instance
this.__redraw = debounce(this.__redraw, debounceDelay);
this.__updateScrollIndicator = debounce(this.__updateScrollIndicator, debounceDelay);
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
if (!this$1.$refs.scroller) {
return
}
this$1.$refs.scroller.addEventListener('scroll', this$1.__updateScrollIndicator, listenOpts.passive);
window.addEventListener('resize', this$1.__redraw, listenOpts.passive);
if (this$1.data.tabName !== '' && this$1.value) {
this$1.selectTab(this$1.value);
}
this$1.__redraw();
this$1.__findTabAndScroll(this$1.data.tabName, true);
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
this.__stopAnimScroll();
this.$refs.scroller.removeEventListener('scroll', this.__updateScrollIndicator, listenOpts.passive);
window.removeEventListener('resize', this.__redraw, listenOpts.passive);
this.__redraw.cancel();
this.__updateScrollIndicator.cancel();
}
}
var Top = {
computed: {
marginalsProps: function marginalsProps () {
return {
pagination: this.computedPagination,
pagesNumber: this.pagesNumber,
isFirstPage: this.isFirstPage,
isLastPage: this.isLastPage,
prevPage: this.prevPage,
nextPage: this.nextPage,
inFullscreen: this.inFullscreen,
toggleFullscreen: this.toggleFullscreen
}
}
},
methods: {
getTop: function getTop (h) {
var
top = this.$scopedSlots.top,
topLeft = this.$scopedSlots['top-left'],
topRight = this.$scopedSlots['top-right'],
topSelection = this.$scopedSlots['top-selection'],
hasSelection = this.selection && topSelection && this.rowsSelectedNumber > 0,
staticClass = 'q-table-top relative-position row no-wrap items-center',
child = [];
if (top) {
return h('div', { staticClass: staticClass }, [ top(this.marginalsProps) ])
}
if (hasSelection) {
child.push(topSelection(this.marginalsProps));
}
else {
if (topLeft) {
child.push(topLeft(this.marginalsProps));
}
else if (this.title) {
child.push(h('div', { staticClass: 'q-table-title' }, this.title));
}
}
if (topRight) {
child.push(h('div', { staticClass: 'q-table-separator col' }));
child.push(topRight(this.marginalsProps));
}
if (child.length === 0) {
return
}
return h('div', { staticClass: staticClass }, child)
}
}
}
var QTh = {
name: 'q-th',
props: {
props: Object,
autoWidth: Boolean
},
render: function render (h) {
var this$1 = this;
if (!this.props) {
return h('td', {
'class': { 'q-table-col-auto-width': this.autoWidth }
}, [ this.$slots.default ])
}
var col;
var
name = this.$vnode.key,
child = [ this.$slots.default ];
if (name) {
col = this.props.colsMap[name];
if (!col) { return }
}
else {
col = this.props.col;
}
if (col.sortable) {
var action = col.align === 'right'
? 'unshift'
: 'push';
child[action](
h(QIcon, {
props: { name: this.$q.icon.table.arrowUp },
staticClass: col.__iconClass
})
);
}
return h('th', {
'class': [col.__thClass, {
'q-table-col-auto-width': this.autoWidth
}],
on: col.sortable
? { click: function () { this$1.props.sort(col); } }
: null
}, child)
}
}
var TableHeader = {
methods: {
getTableHeader: function getTableHeader (h) {
if (this.hideHeader) {
return
}
var child = [ this.getTableHeaderRow(h) ];
if (this.loader) {
child.push(h('tr', { staticClass: 'q-table-progress animate-fade' }, [
h('td', { attrs: {colspan: '100%'} }, [
h(QProgress, {
props: {
color: this.color,
indeterminate: true,
height: '2px'
}
})
])
]));
}
return h('thead', child)
},
getTableHeaderRow: function getTableHeaderRow (h) {
var this$1 = this;
var
header = this.$scopedSlots.header,
headerCell = this.$scopedSlots['header-cell'];
if (header) {
return header(this.addTableHeaderRowMeta({header: true, cols: this.computedCols, sort: this.sort, colsMap: this.computedColsMap}))
}
var mapFn;
if (headerCell) {
mapFn = function (col) { return headerCell({col: col, cols: this$1.computedCols, sort: this$1.sort, colsMap: this$1.computedColsMap}); };
}
else {
mapFn = function (col) { return h(QTh, {
key: col.name,
props: {
props: {
col: col,
cols: this$1.computedCols,
sort: this$1.sort,
colsMap: this$1.computedColsMap
}
}
}, col.label); };
}
var child = this.computedCols.map(mapFn);
if (this.singleSelection) {
child.unshift(h('th', { staticClass: 'q-table-col-auto-width' }, [' ']));
}
else if (this.multipleSelection) {
child.unshift(h('th', { staticClass: 'q-table-col-auto-width' }, [
h(QCheckbox, {
props: {
color: this.color,
value: this.someRowsSelected ? null : this.allRowsSelected,
dark: this.dark
},
on: {
input: function (val) {
if (this$1.someRowsSelected) {
val = false;
}
this$1.__updateSelection(
this$1.computedRows.map(function (row) { return row[this$1.rowKey]; }),
this$1.computedRows,
val
);
}
}
})
]));
}
return h('tr', child)
},
addTableHeaderRowMeta: function addTableHeaderRowMeta (data) {
var this$1 = this;
if (this.multipleSelection) {
Object.defineProperty(data, 'selected', {
get: function () { return this$1.someRowsSelected ? 'some' : this$1.allRowsSelected; },
set: function (val) {
if (this$1.someRowsSelected) {
val = false;
}
this$1.__updateSelection(
this$1.computedRows.map(function (row) { return row[this$1.rowKey]; }),
this$1.computedRows,
val
);
}
});
data.partialSelected = this.someRowsSelected;
data.multipleSelect = true;
}
return data
}
}
}
var TableBody = {
methods: {
getTableBody: function getTableBody (h) {
var this$1 = this;
var
body = this.$scopedSlots.body,
bodyCell = this.$scopedSlots['body-cell'],
topRow = this.$scopedSlots['top-row'],
bottomRow = this.$scopedSlots['bottom-row'];
var
child = [];
if (body) {
child = this.computedRows.map(function (row) {
var
key = row[this$1.rowKey],
selected = this$1.isRowSelected(key);
return body(this$1.addBodyRowMeta({
key: key,
row: row,
cols: this$1.computedCols,
colsMap: this$1.computedColsMap,
__trClass: selected ? 'selected' : ''
}))
});
}
else {
child = this.computedRows.map(function (row) {
var
key = row[this$1.rowKey],
selected = this$1.isRowSelected(key),
child = bodyCell
? this$1.computedCols.map(function (col) { return bodyCell(this$1.addBodyCellMetaData({ row: row, col: col })); })
: this$1.computedCols.map(function (col) {
var slot = this$1.$scopedSlots[("body-cell-" + (col.name))];
return slot
? slot(this$1.addBodyCellMetaData({ row: row, col: col }))
: h('td', { staticClass: col.__tdClass }, this$1.getCellValue(col, row))
});
if (this$1.selection) {
child.unshift(h('td', { staticClass: 'q-table-col-auto-width' }, [
h(QCheckbox, {
props: {
value: selected,
color: this$1.color,
dark: this$1.dark
},
on: {
input: function (adding) {
this$1.__updateSelection([key], [row], adding);
}
}
})
]));
}
return h('tr', { key: key, 'class': { selected: selected } }, child)
});
}
if (topRow) {
child.unshift(topRow({cols: this.computedCols}));
}
if (bottomRow) {
child.push(bottomRow({cols: this.computedCols}));
}
return h('tbody', child)
},
addBodyRowMeta: function addBodyRowMeta (data) {
var this$1 = this;
if (this.selection) {
Object.defineProperty(data, 'selected', {
get: function () { return this$1.isRowSelected(data.key); },
set: function (adding) {
this$1.__updateSelection([data.key], [data.row], adding);
}
});
}
Object.defineProperty(data, 'expand', {
get: function () { return this$1.rowsExpanded[data.key] === true; },
set: function (val) {
this$1.$set(this$1.rowsExpanded, data.key, val);
}
});
data.cols = data.cols.map(function (col) {
var c = Object.assign({}, col);
Object.defineProperty(c, 'value', {
get: function () { return this$1.getCellValue(col, data.row); }
});
return c
});
return data
},
addBodyCellMetaData: function addBodyCellMetaData (data) {
var this$1 = this;
Object.defineProperty(data, 'value', {
get: function () { return this$1.getCellValue(data.col, data.row); }
});
return data
},
getCellValue: function getCellValue (col, row) {
var val = typeof col.field === 'function' ? col.field(row) : row[col.field];
return col.format ? col.format(val) : val
}
}
}
var Bottom = {
methods: {
getBottom: function getBottom (h) {
if (this.hideBottom) {
return
}
if (this.nothingToDisplay) {
var message = this.filter
? this.noResultsLabel || this.$q.i18n.table.noResults
: (this.loader ? this.loaderLabel || this.$q.i18n.table.loader : this.noDataLabel || this.$q.i18n.table.noData);
return h('div', { staticClass: 'q-table-bottom row items-center q-table-nodata' }, [
h(QIcon, {props: { name: this.$q.icon.table.warning }}),
message
])
}
var bottom = this.$scopedSlots.bottom;
return h('div', { staticClass: 'q-table-bottom row items-center' },
bottom ? [ bottom(this.marginalsProps) ] : this.getPaginationRow(h)
)
},
getPaginationRow: function getPaginationRow (h) {
var this$1 = this;
var ref = this.computedPagination;
var rowsPerPage = ref.rowsPerPage;
var paginationLabel = this.paginationLabel || this.$q.i18n.table.pagination,
paginationSlot = this.$scopedSlots.pagination;
return [
h('div', { staticClass: 'col' }, [
this.selection && this.rowsSelectedNumber > 0
? (this.selectedRowsLabel || this.$q.i18n.table.selectedRows)(this.rowsSelectedNumber)
: ''
]),
h('div', { staticClass: 'flex items-center' }, [
h('span', { staticClass: 'q-mr-lg' }, [
this.rowsPerPageLabel || this.$q.i18n.table.rowsPerPage
]),
h(QSelect, {
staticClass: 'inline q-pb-none q-my-none q-ml-none q-mr-lg',
style: {
minWidth: '50px'
},
props: {
color: this.color,
value: rowsPerPage,
options: this.computedRowsPerPageOptions,
dark: this.dark,
hideUnderline: true
},
on: {
input: function (rowsPerPage) {
this$1.setPagination({
page: 1,
rowsPerPage: rowsPerPage
});
}
}
}),
paginationSlot
? paginationSlot(this.marginalsProps)
: [
h('span', { staticClass: 'q-mr-lg' }, [
rowsPerPage
? paginationLabel(this.firstRowIndex + 1, Math.min(this.lastRowIndex, this.computedRowsNumber), this.computedRowsNumber)
: paginationLabel(1, this.computedRowsNumber, this.computedRowsNumber)
]),
h(QBtn, {
props: {
color: this.color,
round: true,
icon: this.$q.icon.table.prevPage,
dense: true,
flat: true,
disable: this.isFirstPage
},
on: { click: this.prevPage }
}),
h(QBtn, {
props: {
color: this.color,
round: true,
icon: this.$q.icon.table.nextPage,
dense: true,
flat: true,
disable: this.isLastPage
},
on: { click: this.nextPage }
})
]
])
]
}
}
}
function sortDate (a, b) {
return (new Date(a)) - (new Date(b))
}
var Sort = {
props: {
sortMethod: {
type: Function,
default: function default$1 (data, sortBy, descending) {
var col = this.computedCols.find(function (def) { return def.name === sortBy; });
if (col === null || col.field === void 0) {
return data
}
var
dir = descending ? -1 : 1,
val = typeof col.field === 'function'
? function (v) { return col.field(v); }
: function (v) { return v[col.field]; };
return data.sort(function (a, b) {
var
A = val(a),
B = val(b);
if (A === null || A === void 0) {
return -1 * dir
}
if (B === null || B === void 0) {
return 1 * dir
}
if (col.sort) {
return col.sort(A, B) * dir
}
if (isNumber(A) && isNumber(B)) {
return (A - B) * dir
}
if (isDate(A) && isDate(B)) {
return sortDate(A, B) * dir
}
var assign;
(assign = [A, B].map(function (s) { return s.toLowerCase(); }), A = assign[0], B = assign[1]);
return A < B
? -1 * dir
: (A === B ? 0 : dir)
})
}
}
},
computed: {
columnToSort: function columnToSort () {
var ref = this.computedPagination;
var sortBy = ref.sortBy;
if (sortBy) {
var col = this.computedCols.find(function (def) { return def.name === sortBy; });
return col || null
}
}
},
methods: {
sort: function sort (col /* String(col name) or Object(col definition) */) {
if (col === Object(col)) {
col = col.name;
}
var ref = this.computedPagination;
var sortBy = ref.sortBy;
var descending = ref.descending;
if (sortBy !== col) {
sortBy = col;
descending = false;
}
else if (descending) {
sortBy = null;
}
else {
descending = true;
}
this.setPagination({ sortBy: sortBy, descending: descending, page: 1 });
}
}
}
var Filter = {
props: {
filter: String,
filterMethod: {
type: Function,
default: function default$1 (rows, terms, cols, cellValue) {
if ( cols === void 0 ) cols = this.computedCols;
if ( cellValue === void 0 ) cellValue = this.getCellValue;
var lowerTerms = terms ? terms.toLowerCase() : '';
return rows.filter(
function (row) { return cols.some(function (col) { return (cellValue(col, row) + '').toLowerCase().indexOf(lowerTerms) !== -1; }); }
)
}
}
},
computed: {
hasFilter: function hasFilter () {
return this.filter !== void 0 && this.filter.length > 0
}
},
watch: {
filter: function filter () {
var this$1 = this;
this.$nextTick(function () {
this$1.setPagination({ page: 1 });
});
}
}
}
var Pagination = {
props: {
pagination: Object,
rowsPerPageOptions: {
type: Array,
default: function () { return [3, 5, 7, 10, 15, 20, 25, 50, 0]; }
}
},
data: function data () {
return {
innerPagination: {
sortBy: null,
descending: false,
page: 1,
rowsPerPage: 5
}
}
},
computed: {
computedPagination: function computedPagination () {
return Object.assign({}, this.innerPagination, this.pagination)
},
firstRowIndex: function firstRowIndex () {
var ref = this.computedPagination;
var page = ref.page;
var rowsPerPage = ref.rowsPerPage;
return (page - 1) * rowsPerPage
},
lastRowIndex: function lastRowIndex () {
var ref = this.computedPagination;
var page = ref.page;
var rowsPerPage = ref.rowsPerPage;
return page * rowsPerPage
},
isFirstPage: function isFirstPage () {
var ref = this.computedPagination;
var page = ref.page;
return page <= 1
},
pagesNumber: function pagesNumber () {
var ref = this.computedPagination;
var rowsPerPage = ref.rowsPerPage;
return Math.ceil(this.computedRowsNumber / rowsPerPage)
},
isLastPage: function isLastPage () {
if (this.lastRowIndex === 0) {
return true
}
var ref = this.computedPagination;
var page = ref.page;
return page >= this.pagesNumber
},
computedRowsPerPageOptions: function computedRowsPerPageOptions () {
var this$1 = this;
return this.rowsPerPageOptions.map(function (count) { return ({
label: count === 0 ? this$1.$q.i18n.table.allRows : '' + count,
value: count
}); })
}
},
methods: {
setPagination: function setPagination (val) {
var newPagination = Object.assign({}, this.computedPagination, val);
if (this.isServerSide) {
this.requestServerInteraction({
pagination: newPagination
});
return
}
if (this.pagination) {
this.$emit('update:pagination', newPagination);
}
else {
this.innerPagination = newPagination;
}
},
prevPage: function prevPage () {
var ref = this.computedPagination;
var page = ref.page;
if (page > 1) {
this.setPagination({page: page - 1});
}
},
nextPage: function nextPage () {
var ref = this.computedPagination;
var page = ref.page;
var rowsPerPage = ref.rowsPerPage;
if (this.lastRowIndex > 0 && page * rowsPerPage < this.computedRowsNumber) {
this.setPagination({page: page + 1});
}
}
},
created: function created () {
this.$emit('update:pagination', Object.assign({}, this.computedPagination));
}
}
var RowSelection = {
props: {
selection: {
type: String,
validator: function (v) { return ['single', 'multiple'].includes(v); }
},
selected: {
type: Array,
default: function () { return []; }
}
},
computed: {
selectedKeys: function selectedKeys () {
var this$1 = this;
var keys = {};
this.selected.map(function (row) { return row[this$1.rowKey]; }).forEach(function (key) {
keys[key] = true;
});
return keys
},
singleSelection: function singleSelection () {
return this.selection === 'single'
},
multipleSelection: function multipleSelection () {
return this.selection === 'multiple'
},
allRowsSelected: function allRowsSelected () {
var this$1 = this;
if (this.multipleSelection) {
return this.computedRows.length > 0 && this.computedRows.every(function (row) { return this$1.selectedKeys[row[this$1.rowKey]] === true; })
}
},
someRowsSelected: function someRowsSelected () {
var this$1 = this;
if (this.multipleSelection) {
return !this.allRowsSelected && this.computedRows.some(function (row) { return this$1.selectedKeys[row[this$1.rowKey]] === true; })
}
},
rowsSelectedNumber: function rowsSelectedNumber () {
return this.selected.length
}
},
methods: {
isRowSelected: function isRowSelected (key) {
return this.selectedKeys[key] === true
},
clearSelection: function clearSelection () {
this.$emit('update:selected', []);
},
__updateSelection: function __updateSelection (keys, rows, adding) {
var this$1 = this;
if (this.singleSelection) {
this.$emit('update:selected', adding ? rows : []);
}
else {
this.$emit('update:selected', adding
? this.selected.concat(rows)
: this.selected.filter(function (row) { return !keys.includes(row[this$1.rowKey]); })
);
}
}
}
}
var ColumnSelection = {
props: {
visibleColumns: Array
},
computed: {
computedCols: function computedCols () {
var this$1 = this;
var ref = this.computedPagination;
var sortBy = ref.sortBy;
var descending = ref.descending;
var cols = this.visibleColumns
? this.columns.filter(function (col) { return col.required || this$1.visibleColumns.includes(col.name); })
: this.columns;
return cols.map(function (col) {
col.align = col.align || 'right';
col.__iconClass = "q-table-sort-icon q-table-sort-icon-" + (col.align);
col.__thClass = "text-" + (col.align) + (col.sortable ? ' sortable' : '') + (col.name === sortBy ? (" sorted " + (descending ? 'sort-desc' : '')) : '');
col.__tdClass = "text-" + (col.align);
return col
})
},
computedColsMap: function computedColsMap () {
var names = {};
this.computedCols.forEach(function (col) {
names[col.name] = col;
});
return names
}
}
}
var Expand = {
data: function data () {
return {
rowsExpanded: {}
}
}
}
var QTable = {
name: 'q-table',
mixins: [
FullscreenMixin,
Top,
TableHeader,
TableBody,
Bottom,
Sort,
Filter,
Pagination,
RowSelection,
ColumnSelection,
Expand
],
props: {
data: {
type: Array,
default: function () { return []; }
},
rowKey: {
type: String,
default: 'id'
},
color: {
type: String,
default: 'grey-8'
},
dense: Boolean,
columns: Array,
loader: Boolean,
title: String,
hideHeader: Boolean,
hideBottom: Boolean,
dark: Boolean,
separator: {
type: String,
default: 'horizontal',
validator: function (v) { return ['horizontal', 'vertical', 'cell', 'none'].includes(v); }
},
noDataLabel: String,
noResultsLabel: String,
loaderLabel: String,
selectedRowsLabel: Function,
rowsPerPageLabel: String,
paginationLabel: Function,
tableStyle: {
type: [String, Array, Object],
default: ''
},
tableClass: {
type: [String, Array, Object],
default: ''
}
},
computed: {
computedRows: function computedRows () {
var rows = this.data.slice().map(function (row, i) {
row.__index = i;
return row
});
if (rows.length === 0) {
return []
}
if (this.isServerSide) {
return rows
}
var ref = this.computedPagination;
var sortBy = ref.sortBy;
var descending = ref.descending;
var rowsPerPage = ref.rowsPerPage;
if (this.hasFilter) {
rows = this.filterMethod(rows, this.filter, this.computedCols, this.getCellValue);
}
if (this.columnToSort) {
rows = this.sortMethod(rows, sortBy, descending);
}
if (rowsPerPage) {
rows = rows.slice(this.firstRowIndex, this.lastRowIndex);
}
return rows
},
computedRowsNumber: function computedRowsNumber () {
return this.isServerSide
? this.computedPagination.rowsNumber || 0
: this.data.length
},
nothingToDisplay: function nothingToDisplay () {
return this.computedRows.length === 0
},
isServerSide: function isServerSide () {
return this.computedPagination.rowsNumber !== void 0
}
},
render: function render (h) {
return h('div',
{
'class': {
'q-table-container': true,
'q-table-dark': this.dark,
'q-table-dense': this.dense,
fullscreen: this.inFullscreen,
scroll: this.inFullscreen
}
},
[
this.getTop(h),
h('div', { staticClass: 'q-table-middle scroll', 'class': this.tableClass, style: this.tableStyle }, [
h('table', { staticClass: ("q-table q-table-" + (this.separator) + "-separator" + (this.dark ? ' q-table-dark' : '')) },
[
this.getTableHeader(h),
this.getTableBody(h)
]
)
]),
this.getBottom(h)
]
)
},
methods: {
requestServerInteraction: function requestServerInteraction (prop) {
var this$1 = this;
this.$nextTick(function () {
this$1.$emit('request', {
pagination: prop.pagination || this$1.computedPagination,
filter: prop.filter || this$1.filter,
getCellValue: this$1.getCellValue
});
});
}
}
}
var QTr = {
name: 'q-tr',
props: {
props: Object
},
render: function render (h) {
return h('tr',
!this.props || this.props.header ? {} : { 'class': this.props.__trClass },
[ this.$slots.default ]
)
}
}
var QTd = {
name: 'q-td',
props: {
props: Object,
autoWidth: Boolean
},
render: function render (h) {
if (!this.props) {
return h('td', {
'class': { 'q-table-col-auto-width': this.autoWidth }
}, [ this.$slots.default ])
}
var col;
var name = this.$vnode.key;
if (name) {
col = this.props.colsMap[name];
if (!col) { return }
}
else {
col = this.props.col;
}
return h('td', {
'class': [col.__tdClass, {
'q-table-col-auto-width': this.autoWidth
}]
}, [ this.$slots.default ])
}
}
var QTableColumns = {
name: 'q-table-columns',
props: {
value: {
type: Array,
required: true
},
label: String,
columns: {
type: Array,
required: true
},
color: String
},
computed: {
computedOptions: function computedOptions () {
return this.columns.filter(function (col) { return !col.required; }).map(function (col) { return ({
value: col.name,
label: col.label
}); })
}
},
render: function render (h) {
var this$1 = this;
return h(QSelect, {
props: {
multiple: true,
toggle: true,
value: this.value,
options: this.computedOptions,
displayValue: this.label || this.$q.i18n.table.columns,
color: this.color,
hideUnderline: true
},
on: {
input: function (v) { this$1.$emit('input', v); },
change: function (v) { this$1.$emit('change', v); }
}
})
}
}
var QTimeline = {
name: 'q-timeline',
provide: function provide () {
return {
__timeline: this
}
},
props: {
color: {
type: String,
default: 'primary'
},
dark: Boolean
},
render: function render (h) {
return h('ul', {
staticClass: 'q-timeline',
'class': { 'q-timeline-dark': this.dark }
}, [
this.$slots.default
])
}
}
var QTimelineEntry = {
name: 'q-timeline-entry',
inject: {
__timeline: {
default: function default$1 () {
console.error('QTimelineEntry needs to be child of QTimeline');
}
}
},
props: {
heading: Boolean,
tag: {
type: String,
default: 'h3'
},
side: {
type: String,
default: 'right',
validator: function (v) { return ['left', 'right'].includes(v); }
},
icon: String,
color: String,
title: String,
subtitle: String
},
computed: {
colorClass: function colorClass () {
return ("text-" + (this.color || this.__timeline.color))
},
classes: function classes () {
return [
("q-timeline-entry-" + (this.side === 'left' ? 'left' : 'right')),
this.icon ? 'q-timeline-entry-with-icon' : ''
]
}
},
render: function render (h) {
if (this.heading) {
return h('div', { staticClass: 'q-timeline-heading' }, [
h('div'),
h('div'),
h(this.tag, { staticClass: 'q-timeline-heading-title' }, [
this.$slots.default
])
])
}
return h('li', {
staticClass: "q-timeline-entry",
'class': this.classes
}, [
h('div', { staticClass: 'q-timeline-subtitle' }, [
h('span', this.subtitle)
]),
h('div', {
staticClass: 'q-timeline-dot',
'class': this.colorClass
}, [
this.icon
? h(QIcon, { props: { name: this.icon } })
: null
]),
h('div', { staticClass: 'q-timeline-content' }, [
h('h6', { staticClass: 'q-timeline-title' }, [ this.title ]),
this.$slots.default
])
])
}
}
var QToolbar = {
name: 'q-toolbar',
props: {
color: String,
inverted: Boolean,
glossy: Boolean
},
computed: {
classes: function classes () {
return [
("q-toolbar-" + (this.inverted ? 'inverted' : 'normal')),
this.color ? (" " + (this.inverted ? 'text' : 'bg') + "-" + (this.color)) : '',
this.glossy ? 'glossy' : ''
]
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-toolbar row no-wrap items-center relative-position',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QToolbarTitle = {
name: 'q-toolbar-title',
render: function render (h) {
return h('div', {
staticClass: 'q-toolbar-title'
}, [
this.$slots.default,
this.$slots.subtitle
? h('div', { staticClass: 'q-toolbar-subtitle' }, this.$slots.subtitle)
: null
])
}
}
var QTree = {
name: 'q-tree',
directives: {
Ripple: Ripple
},
props: {
nodes: Array,
nodeKey: {
type: String,
required: true
},
color: {
type: String,
default: 'grey'
},
controlColor: String,
textColor: String,
dark: Boolean,
icon: String,
tickStrategy: {
type: String,
default: 'none',
validator: function (v) { return ['none', 'strict', 'leaf', 'leaf-filtered'].includes(v); }
},
ticked: Array, // sync
expanded: Array, // sync
selected: {}, // sync
defaultExpandAll: Boolean,
accordion: Boolean,
filter: String,
filterMethod: {
type: Function,
default: function default$1 (node, filter) {
var filt = filter.toLowerCase();
return node.label && node.label.toLowerCase().indexOf(filt) > -1
}
},
noNodesLabel: String,
noResultsLabel: String
},
computed: {
hasRipple: function hasRipple () {
return "ios" === 'mat' && !this.noRipple
},
classes: function classes () {
return [
("text-" + (this.color)),
{ 'q-tree-dark': this.dark }
]
},
hasSelection: function hasSelection () {
return this.selected !== void 0
},
computedIcon: function computedIcon () {
return this.icon || this.$q.icon.tree.icon
},
computedControlColor: function computedControlColor () {
return this.controlColor || this.color
},
contentClass: function contentClass () {
return ("text-" + (this.textColor || (this.dark ? 'white' : 'black')))
},
meta: function meta () {
var this$1 = this;
var meta = {};
var travel = function (node, parent) {
var tickStrategy = node.tickStrategy || (parent ? parent.tickStrategy : this$1.tickStrategy);
var
key = node[this$1.nodeKey],
isParent = node.children && node.children.length > 0,
isLeaf = !isParent,
selectable = !node.disabled && this$1.hasSelection && node.selectable !== false,
expandable = !node.disabled && node.expandable !== false,
hasTicking = tickStrategy !== 'none',
strictTicking = tickStrategy === 'strict',
leafFilteredTicking = tickStrategy === 'leaf-filtered',
leafTicking = tickStrategy === 'leaf' || tickStrategy === 'leaf-filtered';
var tickable = !node.disabled && node.tickable !== false;
if (leafTicking && tickable && parent && !parent.tickable) {
tickable = false;
}
var lazy = node.lazy;
if (lazy && this$1.lazy[key]) {
lazy = this$1.lazy[key];
}
var m = {
key: key,
parent: parent,
isParent: isParent,
isLeaf: isLeaf,
lazy: lazy,
disabled: node.disabled,
link: selectable || (expandable && (isParent || lazy === true)),
children: [],
matchesFilter: this$1.filter ? this$1.filterMethod(node, this$1.filter) : true,
selected: key === this$1.selected && selectable,
selectable: selectable,
expanded: isParent ? this$1.innerExpanded.includes(key) : false,
expandable: expandable,
noTick: node.noTick || (!strictTicking && lazy && lazy !== 'loaded'),
tickable: tickable,
tickStrategy: tickStrategy,
hasTicking: hasTicking,
strictTicking: strictTicking,
leafFilteredTicking: leafFilteredTicking,
leafTicking: leafTicking,
ticked: strictTicking
? this$1.innerTicked.includes(key)
: (isLeaf ? this$1.innerTicked.includes(key) : false)
};
meta[key] = m;
if (isParent) {
m.children = node.children.map(function (n) { return travel(n, m); });
if (this$1.filter) {
if (!m.matchesFilter) {
m.matchesFilter = m.children.some(function (n) { return n.matchesFilter; });
}
if (
m.matchesFilter &&
!m.noTick &&
!m.disabled &&
m.tickable &&
leafFilteredTicking &&
m.children.every(function (n) { return !n.matchesFilter || n.noTick || !n.tickable; })
) {
m.tickable = false;
}
}
if (m.matchesFilter) {
if (!m.noTick && !strictTicking && m.children.every(function (n) { return n.noTick; })) {
m.noTick = true;
}
if (leafTicking) {
m.ticked = false;
m.indeterminate = m.children.some(function (node) { return node.indeterminate; });
if (!m.indeterminate) {
var sel = m.children
.reduce(function (acc, meta) { return meta.ticked ? acc + 1 : acc; }, 0);
if (sel === m.children.length) {
m.ticked = true;
}
else if (sel > 0) {
m.indeterminate = true;
}
}
}
}
}
return m
};
this.nodes.forEach(function (node) { return travel(node, null); });
return meta
}
},
data: function data () {
return {
lazy: {},
innerTicked: this.ticked || [],
innerExpanded: this.expanded || []
}
},
watch: {
ticked: function ticked (val) {
this.innerTicked = val;
},
expanded: function expanded (val) {
this.innerExpanded = val;
}
},
methods: {
getNodeByKey: function getNodeByKey (key) {
var this$1 = this;
var reduce = [].reduce;
var find = function (result, node) {
if (result || !node) {
return result
}
if (Array.isArray(node)) {
return reduce.call(Object(node), find, result)
}
if (node[this$1.nodeKey] === key) {
return node
}
if (node.children) {
return find(null, node.children)
}
};
return find(null, this.nodes)
},
getTickedNodes: function getTickedNodes () {
var this$1 = this;
return this.innerTicked.map(function (key) { return this$1.getNodeByKey(key); })
},
getExpandedNodes: function getExpandedNodes () {
var this$1 = this;
return this.innerExpanded.map(function (key) { return this$1.getNodeByKey(key); })
},
isExpanded: function isExpanded (key) {
return key && this.meta[key]
? this.meta[key].expanded
: false
},
collapseAll: function collapseAll () {
if (this.expanded !== void 0) {
this.$emit('update:expanded', []);
}
else {
this.innerExpanded = [];
}
},
expandAll: function expandAll () {
var this$1 = this;
var
expanded = this.innerExpanded,
travel = function (node) {
if (node.children && node.children.length > 0) {
if (node.expandable !== false && node.disabled !== true) {
expanded.push(node[this$1.nodeKey]);
node.children.forEach(travel);
}
}
};
this.nodes.forEach(travel);
if (this.expanded !== void 0) {
this.$emit('update:expanded', expanded);
}
else {
this.innerExpanded = expanded;
}
},
setExpanded: function setExpanded (key, state, node, meta) {
var this$1 = this;
if ( node === void 0 ) node = this.getNodeByKey(key);
if ( meta === void 0 ) meta = this.meta[key];
if (meta.lazy && meta.lazy !== 'loaded') {
if (meta.lazy === 'loading') {
return
}
this.$set(this.lazy, key, 'loading');
this.$emit('lazy-load', {
node: node,
key: key,
done: function (children) {
this$1.lazy[key] = 'loaded';
if (children) {
node.children = children;
}
this$1.$nextTick(function () {
var m = this$1.meta[key];
if (m && m.isParent) {
this$1.__setExpanded(key, true);
}
});
},
fail: function () {
this$1.$delete(this$1.lazy, key);
}
});
}
else if (meta.isParent && meta.expandable) {
this.__setExpanded(key, state);
}
},
__setExpanded: function __setExpanded (key, state) {
var this$1 = this;
var target = this.innerExpanded;
var emit = this.expanded !== void 0;
if (emit) {
target = target.slice();
}
if (state) {
if (this.accordion) {
if (this.meta[key]) {
var collapse = [];
if (this.meta[key].parent) {
this.meta[key].parent.children.forEach(function (m) {
if (m.key !== key && m.expandable) {
collapse.push(m.key);
}
});
}
else {
this.nodes.forEach(function (node) {
var k = node[this$1.nodeKey];
if (k !== key) {
collapse.push(k);
}
});
}
if (collapse.length > 0) {
target = target.filter(function (k) { return !collapse.includes(k); });
}
}
}
target = target.concat([ key ])
.filter(function (key, index, self) { return self.indexOf(key) === index; });
}
else {
target = target.filter(function (k) { return k !== key; });
}
if (emit) {
this.$emit("update:expanded", target);
}
else {
this.innerExpanded = target;
}
},
isTicked: function isTicked (key) {
return key && this.meta[key]
? this.meta[key].ticked
: false
},
setTicked: function setTicked (keys, state) {
var target = this.innerTicked;
var emit = this.ticked !== void 0;
if (emit) {
target = target.slice();
}
if (state) {
target = target.concat(keys)
.filter(function (key, index, self) { return self.indexOf(key) === index; });
}
else {
target = target.filter(function (k) { return !keys.includes(k); });
}
if (emit) {
this.$emit("update:ticked", target);
}
},
__getSlotScope: function __getSlotScope (node, meta, key) {
var this$1 = this;
var scope = { tree: this, node: node, key: key, color: this.color, dark: this.dark };
Object.defineProperty(scope, 'expanded', {
get: function () { return meta.expanded },
set: function (val) { val !== meta.expanded && this$1.setExpanded(key, val); }
});
Object.defineProperty(scope, 'ticked', {
get: function () { return meta.ticked },
set: function (val) { val !== meta.ticked && this$1.setTicked([ key ], val); }
});
return scope
},
__getChildren: function __getChildren (h, nodes) {
var this$1 = this;
return (
this.filter
? nodes.filter(function (n) { return this$1.meta[n[this$1.nodeKey]].matchesFilter; })
: nodes
).map(function (child) { return this$1.__getNode(h, child); })
},
__getNodeMedia: function __getNodeMedia (h, node) {
if (node.icon) {
return h(QIcon, {
staticClass: "q-tree-icon q-mr-sm",
props: { name: node.icon }
})
}
if (node.img || node.avatar) {
return h('img', {
staticClass: "q-tree-img q-mr-sm",
'class': { avatar: node.avatar },
domProps: { src: node.img || node.avatar }
})
}
},
__getNode: function __getNode (h, node) {
var this$1 = this;
var
key = node[this.nodeKey],
meta = this.meta[key],
header = node.header
? this.$scopedSlots[("header-" + (node.header))] || this.$scopedSlots['default-header']
: this.$scopedSlots['default-header'];
var children = meta.isParent
? this.__getChildren(h, node.children)
: [];
var isParent = children.length > 0 || (meta.lazy && meta.lazy !== 'loaded');
var
body = node.body
? this.$scopedSlots[("body-" + (node.body))] || this.$scopedSlots['default-body']
: this.$scopedSlots['default-body'],
slotScope = header || body
? this.__getSlotScope(node, meta, key)
: null;
if (body) {
body = h('div', { staticClass: 'q-tree-node-body relative-position' }, [
h('div', { 'class': this.contentClass }, [
body(slotScope)
])
]);
}
return h('div', {
key: key,
staticClass: 'q-tree-node',
'class': { 'q-tree-node-parent': isParent, 'q-tree-node-child': !isParent }
}, [
h('div', {
staticClass: 'q-tree-node-header relative-position row no-wrap items-center',
'class': {
'q-tree-node-link': meta.link,
'q-tree-node-selected': meta.selected,
disabled: meta.disabled
},
on: { click: function () { this$1.__onClick(node, meta); } },
directives: null
}, [
meta.lazy === 'loading'
? h(QSpinner, {
staticClass: 'q-tree-node-header-media q-mr-xs',
props: { color: this.computedControlColor }
})
: (
isParent
? h(QIcon, {
staticClass: 'q-tree-arrow q-mr-xs transition-generic',
'class': { 'rotate-90': meta.expanded },
props: { name: this.computedIcon },
nativeOn: {
click: function (e) {
this$1.__onExpandClick(node, meta, e);
}
}
})
: null
),
h('span', { 'staticClass': 'row no-wrap items-center', 'class': this.contentClass }, [
meta.hasTicking && !meta.noTick
? h(QCheckbox, {
staticClass: 'q-mr-xs',
props: {
value: meta.indeterminate ? null : meta.ticked,
color: this.computedControlColor,
dark: this.dark,
keepColor: true,
disable: !meta.tickable
},
on: {
input: function (v) {
this$1.__onTickedClick(node, meta, v);
}
}
})
: null,
header
? header(slotScope)
: [
this.__getNodeMedia(h, node),
h('span', node.label)
]
])
]),
isParent
? h(QSlideTransition, [
h('div', {
directives: [{ name: 'show', value: meta.expanded }],
staticClass: 'q-tree-node-collapsible',
'class': ("text-" + (this.color))
}, [
body,
h('div', {
staticClass: 'q-tree-children',
'class': { disabled: meta.disabled }
}, children)
])
])
: body
])
},
__onClick: function __onClick (node, meta) {
if (this.hasSelection) {
if (meta.selectable) {
this.$emit('update:selected', meta.key !== this.selected ? meta.key : null);
}
}
else {
this.__onExpandClick(node, meta);
}
if (typeof node.handler === 'function') {
node.handler(node);
}
},
__onExpandClick: function __onExpandClick (node, meta, e) {
if (e !== void 0) {
e.stopPropagation();
}
this.setExpanded(meta.key, !meta.expanded, node, meta);
},
__onTickedClick: function __onTickedClick (node, meta, state) {
if (meta.indeterminate && state) {
state = false;
}
if (meta.strictTicking) {
this.setTicked([ meta.key ], state);
}
else if (meta.leafTicking) {
var keys = [];
var travel = function (meta) {
if (meta.isParent) {
if (!state && !meta.noTick && meta.tickable) {
keys.push(meta.key);
}
if (meta.leafTicking) {
meta.children.forEach(travel);
}
}
else if (!meta.noTick && meta.tickable && (!meta.leafFilteredTicking || meta.matchesFilter)) {
keys.push(meta.key);
}
};
travel(meta);
this.setTicked(keys, state);
}
}
},
render: function render (h) {
var children = this.__getChildren(h, this.nodes);
return h(
'div', {
staticClass: 'q-tree relative-position',
'class': this.classes
},
children.length === 0
? (
this.filter
? this.noResultsLabel || this.$q.i18n.tree.noResults
: this.noNodesLabel || this.$q.i18n.tree.noNodes
)
: children
)
},
created: function created () {
if (this.defaultExpandAll) {
this.expandAll();
}
}
}
function initFile (file) {
file.__doneUploading = false;
file.__failed = false;
file.__uploaded = 0;
file.__progress = 0;
}
var QUploader = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-uploader relative-position",class:_vm.classes,on:{"dragover":function($event){$event.preventDefault();$event.stopPropagation();_vm.__onDragOver($event);}}},[_c('q-input-frame',{ref:"input",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.color,"align":_vm.align,"length":_vm.queueLength,"additional-length":""}},[_c('div',{staticClass:"col row items-center q-input-target",domProps:{"innerHTML":_vm._s(_vm.label)}}),_vm._v(" "),(_vm.uploading)?_c('q-spinner',{staticClass:"q-if-control",attrs:{"slot":"after","size":"24px"},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.uploading)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.uploader[("clear" + (this.inverted ? 'Inverted' : ''))]},nativeOn:{"click":function($event){_vm.abort($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(!_vm.uploading)?_c('q-icon',{staticClass:"q-uploader-pick-button q-if-control relative-position overflow-hidden",attrs:{"slot":"after","name":_vm.$q.icon.uploader.add,"disabled":_vm.addDisabled},nativeOn:{"click":function($event){_vm.__pick($event);}},slot:"after"},[_c('input',_vm._b({ref:"file",staticClass:"q-uploader-input absolute-full cursor-pointer",attrs:{"type":"file","accept":_vm.extensions},on:{"change":_vm.__add}},'input',{multiple: _vm.multiple},true))]):_vm._e(),_vm._v(" "),(!_vm.hideUploadButton && !_vm.uploading)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.uploader.upload,"disabled":_vm.queueLength === 0},nativeOn:{"click":function($event){_vm.upload($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.hasExpandedContent)?_c('q-icon',{staticClass:"q-if-control generic_transition",class:{'rotate-180': _vm.expanded},attrs:{"slot":"after","name":_vm.$q.icon.uploader.expand},nativeOn:{"click":function($event){_vm.expanded = !_vm.expanded;}},slot:"after"}):_vm._e()],1),_vm._v(" "),_c('q-slide-transition',[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.expanded),expression:"expanded"}]},[_c('div',{staticClass:"q-uploader-files scroll",style:(_vm.filesStyle)},_vm._l((_vm.files),function(file){return _c('q-item',{key:file.name + file.__timestamp,staticClass:"q-uploader-file q-pa-xs"},[(!_vm.hideUploadProgress)?_c('q-progress',{staticClass:"q-uploader-progress-bg absolute-full",attrs:{"color":file.__failed ? 'negative' : 'grey',"percentage":file.__progress,"height":"100%"}}):_vm._e(),_vm._v(" "),(!_vm.hideUploadProgress)?_c('div',{staticClass:"q-uploader-progress-text absolute"},[_vm._v(" "+_vm._s(file.__progress)+"% ")]):_vm._e(),_vm._v(" "),(file.__img)?_c('q-item-side',{attrs:{"image":file.__img.src}}):_c('q-item-side',{attrs:{"icon":_vm.$q.icon.uploader.file,"color":_vm.color}}),_vm._v(" "),_c('q-item-main',{attrs:{"label":file.name,"sublabel":file.__size}}),_vm._v(" "),_c('q-item-side',{attrs:{"right":""}},[_c('q-item-tile',{staticClass:"cursor-pointer",attrs:{"icon":_vm.$q.icon.uploader[file.__doneUploading ? 'done' : 'clear'],"color":_vm.color},nativeOn:{"click":function($event){_vm.__remove(file);}}})],1)],1)}))])]),_vm._v(" "),(_vm.dnd)?_c('div',{staticClass:"q-uploader-dnd flex row items-center justify-center absolute-full",class:_vm.dndClass,on:{"dragenter":function($event){$event.preventDefault();$event.stopPropagation();},"dragover":function($event){$event.preventDefault();$event.stopPropagation();},"dragleave":function($event){$event.preventDefault();$event.stopPropagation();_vm.__onDragLeave($event);},"drop":function($event){$event.preventDefault();$event.stopPropagation();_vm.__onDrop($event);}}}):_vm._e()],1)},staticRenderFns: [],
name: 'q-uploader',
mixins: [FrameMixin],
components: {
QInputFrame: QInputFrame,
QSpinner: QSpinner,
QIcon: QIcon,
QProgress: QProgress,
QItem: QItem,
QItemSide: QItemSide,
QItemMain: QItemMain,
QItemTile: QItemTile,
QSlideTransition: QSlideTransition
},
props: {
name: {
type: String,
default: 'file'
},
headers: Object,
url: {
type: String,
required: true
},
urlFactory: {
type: Function,
required: false
},
additionalFields: {
type: Array,
default: function () { return []; }
},
method: {
type: String,
default: 'POST'
},
extensions: String,
multiple: Boolean,
hideUploadButton: Boolean,
hideUploadProgress: Boolean,
noThumbnails: Boolean,
autoExpand: Boolean,
expandStyle: [Array, String, Object],
expandClass: [Array, String, Object],
sendRaw: {
type: Boolean,
default: false
}
},
data: function data () {
return {
queue: [],
files: [],
uploading: false,
uploadedSize: 0,
totalSize: 0,
xhrs: [],
focused: false,
dnd: false,
expanded: false
}
},
computed: {
queueLength: function queueLength () {
return this.queue.length
},
hasExpandedContent: function hasExpandedContent () {
return this.files.length > 0
},
label: function label () {
var total = humanStorageSize(this.totalSize);
return this.uploading
? (((this.progress).toFixed(2)) + "% (" + (humanStorageSize(this.uploadedSize)) + " / " + total + ")")
: ((this.queueLength) + " (" + total + ")")
},
progress: function progress () {
return this.totalSize ? Math.min(99.99, this.uploadedSize / this.totalSize * 100) : 0
},
addDisabled: function addDisabled () {
return !this.multiple && this.queueLength >= 1
},
filesStyle: function filesStyle () {
if (this.maxHeight) {
return { maxHeight: this.maxHeight }
}
},
dndClass: function dndClass () {
var cls = [("text-" + (this.color))];
if (this.inverted) {
cls.push('inverted');
}
return cls
},
classes: function classes () {
return {
'q-uploader-expanded': this.expanded,
'q-uploader-dark': this.dark,
'q-uploader-files-no-border': this.inverted || !this.hideUnderline
}
}
},
watch: {
hasExpandedContent: function hasExpandedContent (v) {
if (v === false) {
this.expanded = false;
}
else if (this.autoExpand) {
this.expanded = true;
}
}
},
methods: {
__onDragOver: function __onDragOver () {
this.dnd = true;
},
__onDragLeave: function __onDragLeave () {
this.dnd = false;
},
__onDrop: function __onDrop (e) {
this.dnd = false;
var
files = e.dataTransfer.files,
count = files.length;
if (count > 0) {
this.__add(null, this.multiple ? files : [ files[0] ]);
}
},
__add: function __add (e, files) {
var this$1 = this;
if (this.addDisabled) {
return
}
files = Array.prototype.slice.call(files || e.target.files);
this.$refs.file.value = '';
var filesReady = []; // List of image load promises
files = files.filter(function (file) { return !this$1.queue.some(function (f) { return file.name === f.name; }); })
.map(function (file) {
initFile(file);
file.__size = humanStorageSize(file.size);
file.__timestamp = new Date().getTime();
if (this$1.noThumbnails || !file.type.startsWith('image')) {
this$1.queue.push(file);
}
else {
var reader = new FileReader();
var p = new Promise(function (resolve, reject) {
reader.onload = function (e) {
var img = new Image();
img.src = e.target.result;
file.__img = img;
this$1.queue.push(file);
this$1.__computeTotalSize();
resolve(true);
};
reader.onerror = function (e) {
reject(e);
};
});
reader.readAsDataURL(file);
filesReady.push(p);
}
return file
});
if (files.length > 0) {
this.files = this.files.concat(files);
Promise.all(filesReady).then(function () {
this$1.$emit('add', files);
});
this.__computeTotalSize();
}
},
__computeTotalSize: function __computeTotalSize () {
this.totalSize = this.queueLength
? this.queue.map(function (f) { return f.size; }).reduce(function (total, size) { return total + size; })
: 0;
},
__remove: function __remove (file) {
var
name = file.name,
done = file.__doneUploading;
if (this.uploading && !done) {
this.$emit('remove:abort', file, file.xhr);
file.xhr.abort();
this.uploadedSize -= file.__uploaded;
}
else {
this.$emit(("remove:" + (done ? 'done' : 'cancel')), file, file.xhr);
}
if (!done) {
this.queue = this.queue.filter(function (obj) { return obj.name !== name; });
}
file.__removed = true;
this.files = this.files.filter(function (obj) { return obj.name !== name; });
this.__computeTotalSize();
},
__pick: function __pick () {
if (!this.addDisabled && this.$q.platform.is.mozilla) {
this.$refs.file.click();
}
},
__getUploadPromise: function __getUploadPromise (file) {
var this$1 = this;
var
form = new FormData(),
xhr = new XMLHttpRequest();
try {
this.additionalFields.forEach(function (field) {
form.append(field.name, field.value);
});
form.append('Content-Type', file.type || 'application/octet-stream');
form.append(this.name, file);
}
catch (e) {
return
}
initFile(file);
file.xhr = xhr;
return new Promise(function (resolve, reject) {
xhr.upload.addEventListener('progress', function (e) {
if (file.__removed) { return }
e.percent = e.total ? e.loaded / e.total : 0;
var uploaded = e.percent * file.size;
this$1.uploadedSize += uploaded - file.__uploaded;
file.__uploaded = uploaded;
file.__progress = Math.min(99, parseInt(e.percent * 100, 10));
}, false);
xhr.onreadystatechange = function () {
if (xhr.readyState < 4) {
return
}
if (xhr.status && xhr.status < 400) {
file.__doneUploading = true;
file.__progress = 100;
this$1.$emit('uploaded', file, xhr);
resolve(file);
}
else {
file.__failed = true;
this$1.$emit('fail', file, xhr);
reject(xhr);
}
};
xhr.onerror = function () {
file.__failed = true;
this$1.$emit('fail', file, xhr);
reject(xhr);
};
var resolver = this$1.urlFactory
? this$1.urlFactory(file)
: Promise.resolve(this$1.url);
resolver.then(function (url) {
xhr.open(this$1.method, url, true);
if (this$1.headers) {
Object.keys(this$1.headers).forEach(function (key) {
xhr.setRequestHeader(key, this$1.headers[key]);
});
}
this$1.xhrs.push(xhr);
if (this$1.sendRaw) {
xhr.send(file);
}
else {
xhr.send(form);
}
});
})
},
pick: function pick () {
if (!this.addDisabled) {
this.$refs.file.click();
}
},
upload: function upload () {
var this$1 = this;
var length = this.queueLength;
if (this.disable || length === 0) {
return
}
var filesDone = 0;
this.uploadedSize = 0;
this.uploading = true;
this.xhrs = [];
this.$emit('start');
var solved = function () {
filesDone++;
if (filesDone === length) {
this$1.uploading = false;
this$1.xhrs = [];
this$1.queue = this$1.queue.filter(function (f) { return !f.__doneUploading; });
this$1.__computeTotalSize();
this$1.$emit('finish');
}
};
this.queue
.map(function (file) { return this$1.__getUploadPromise(file); })
.forEach(function (promise) {
promise.then(solved).catch(solved);
});
},
abort: function abort () {
this.xhrs.forEach(function (xhr) { xhr.abort(); });
},
reset: function reset () {
this.abort();
this.files = [];
this.queue = [];
this.expanded = false;
this.__computeTotalSize();
this.$emit('reset');
}
}
}
var QVideo = {
name: 'q-video',
props: {
src: {
type: String,
required: true
}
},
computed: {
iframeData: function iframeData () {
return {
attrs: {
src: this.src,
frameborder: '0',
allowfullscreen: true
}
}
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-video'
}, [
h('iframe', this.iframeData)
])
}
}
var components = Object.freeze({
QActionSheet: QActionSheet,
QAjaxBar: QAjaxBar,
QAlert: QAlert,
QAutocomplete: QAutocomplete,
QBreadcrumbs: QBreadcrumbs,
QBreadcrumbsEl: QBreadcrumbsEl,
QBtn: QBtn,
QBtnGroup: QBtnGroup,
QBtnDropdown: QBtnDropdown,
QBtnToggle: QBtnToggle,
QCard: QCard,
QCardTitle: QCardTitle,
QCardMain: QCardMain,
QCardActions: QCardActions,
QCardMedia: QCardMedia,
QCardSeparator: QCardSeparator,
QCarousel: QCarousel,
QCarouselSlide: QCarouselSlide,
QCarouselControl: QCarouselControl,
QChatMessage: QChatMessage,
QCheckbox: QCheckbox,
QChip: QChip,
QChipsInput: QChipsInput,
QCollapsible: QCollapsible,
QColor: QColor,
QColorPicker: QColorPicker,
QContextMenu: QContextMenu,
QDatetime: QDatetime,
QDatetimePicker: QDatetimePicker,
QDialog: QDialog,
QEditor: QEditor,
QFab: QFab,
QFabAction: QFabAction,
QField: QField,
QFieldReset: QFieldReset,
QIcon: QIcon,
QInfiniteScroll: QInfiniteScroll,
QInnerLoading: QInnerLoading,
QInput: QInput,
QInputFrame: QInputFrame,
QKnob: QKnob,
QLayout: QLayout,
QLayoutDrawer: QLayoutDrawer,
QLayoutFooter: QLayoutFooter,
QLayoutHeader: QLayoutHeader,
QPage: QPage,
QPageContainer: QPageContainer,
QPageSticky: QPageSticky,
QItem: QItem,
QItemSeparator: QItemSeparator,
QItemMain: QItemMain,
QItemSide: QItemSide,
QItemTile: QItemTile,
QItemWrapper: QItemWrapper,
QList: QList,
QListHeader: QListHeader,
QModal: QModal,
QModalLayout: QModalLayout,
QResizeObservable: QResizeObservable,
QScrollObservable: QScrollObservable,
QWindowResizeObservable: QWindowResizeObservable,
QOptionGroup: QOptionGroup,
QPagination: QPagination,
QParallax: QParallax,
QPopover: QPopover,
QProgress: QProgress,
QPullToRefresh: QPullToRefresh,
QRadio: QRadio,
QRange: QRange,
QRating: QRating,
QScrollArea: QScrollArea,
QSearch: QSearch,
QSelect: QSelect,
QSlideTransition: QSlideTransition,
QSlider: QSlider,
QSpinner: QSpinner,
QSpinnerAudio: audio,
QSpinnerBall: ball,
QSpinnerBars: bars,
QSpinnerCircles: circles,
QSpinnerComment: comment,
QSpinnerCube: cube,
QSpinnerDots: dots,
QSpinnerFacebook: facebook,
QSpinnerGears: gears,
QSpinnerGrid: grid,
QSpinnerHearts: hearts,
QSpinnerHourglass: hourglass,
QSpinnerInfinity: infinity,
QSpinnerIos: DefaultSpinner,
QSpinnerMat: QSpinner_mat,
QSpinnerOval: oval,
QSpinnerPie: pie,
QSpinnerPuff: puff,
QSpinnerRadio: radio,
QSpinnerRings: rings,
QSpinnerTail: tail,
QStep: QStep,
QStepper: QStepper,
QStepperNavigation: QStepperNavigation,
QRouteTab: QRouteTab,
QTab: QTab,
QTabPane: QTabPane,
QTabs: QTabs,
QTable: QTable,
QTh: QTh,
QTr: QTr,
QTd: QTd,
QTableColumns: QTableColumns,
QTimeline: QTimeline,
QTimelineEntry: QTimelineEntry,
QToggle: QToggle,
QToolbar: QToolbar,
QToolbarTitle: QToolbarTitle,
QTooltip: QTooltip,
QTree: QTree,
QUploader: QUploader,
QVideo: QVideo
});
function updateBinding (el, ref) {
var value = ref.value;
var modifiers = ref.modifiers;
var ctx = el.__qbacktotop;
if (!value) {
ctx.update();
return
}
if (typeof value === 'number') {
ctx.offset = value;
ctx.update();
return
}
if (value && Object(value) !== value) {
console.error('v-back-to-top requires an object {offset, duration} as parameter', el);
return
}
if (value.offset) {
if (typeof value.offset !== 'number') {
console.error('v-back-to-top requires a number as offset', el);
return
}
ctx.offset = value.offset;
}
if (value.duration) {
if (typeof value.duration !== 'number') {
console.error('v-back-to-top requires a number as duration', el);
return
}
ctx.duration = value.duration;
}
ctx.update();
}
var backToTop = {
name: 'back-to-top',
bind: function bind (el) {
var ctx = {
offset: 200,
duration: 300,
update: debounce(function () {
var trigger = getScrollPosition(ctx.scrollTarget) > ctx.offset;
if (ctx.visible !== trigger) {
ctx.visible = trigger;
el.classList[trigger ? 'remove' : 'add']('hidden');
}
}, 25),
goToTop: function goToTop () {
setScrollPosition(ctx.scrollTarget, 0, ctx.animate ? ctx.duration : 0);
}
};
el.classList.add('hidden');
el.__qbacktotop = ctx;
},
inserted: function inserted (el, binding) {
var ctx = el.__qbacktotop;
ctx.scrollTarget = getScrollTarget(el);
ctx.animate = binding.modifiers.animate;
updateBinding(el, binding);
ctx.scrollTarget.addEventListener('scroll', ctx.update, listenOpts.passive);
window.addEventListener('resize', ctx.update, listenOpts.passive);
el.addEventListener('click', ctx.goToTop);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
updateBinding(el, binding);
}
},
unbind: function unbind (el) {
var ctx = el.__qbacktotop;
ctx.scrollTarget.removeEventListener('scroll', ctx.update, listenOpts.passive);
window.removeEventListener('resize', ctx.update, listenOpts.passive);
el.removeEventListener('click', ctx.goToTop);
delete el.__qbacktotop;
}
}
var closeOverlay = {
name: 'close-overlay',
bind: function bind (el, binding, vnode) {
var handler = function () {
var vm = vnode.componentInstance;
while ((vm = vm.$parent)) {
var name = vm.$options.name;
if (name === 'q-popover' || name === 'q-modal') {
vm.hide();
break
}
}
};
el.__qclose = { handler: handler };
el.addEventListener('click', handler);
},
unbind: function unbind (el) {
el.removeEventListener('click', el.__qclose.handler);
delete el.__qclose;
}
}
var goBack = {
name: 'go-back',
bind: function bind (el, ref, vnode) {
var value = ref.value;
var modifiers = ref.modifiers;
var ctx = { value: value, position: window.history.length - 1, single: modifiers.single };
if (Platform.is.cordova) {
ctx.goBack = function () {
vnode.context.$router.go(ctx.single ? -1 : ctx.position - window.history.length);
};
}
else {
ctx.goBack = function () {
vnode.context.$router.replace(ctx.value);
};
}
el.__qgoback = ctx;
el.addEventListener('click', ctx.goBack);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
el.__qgoback.value = binding.value;
}
},
unbind: function unbind (el) {
el.removeEventListener('click', el.__qgoback.goBack);
delete el.__qgoback;
}
}
function updateBinding$1 (el, selector) {
var
ctx = el.__qmove,
parent = el.parentNode;
if (!ctx.target) {
ctx.target = document.querySelector(selector);
}
if (ctx.target) {
if (parent !== ctx.target) {
ctx.target.appendChild(el);
}
}
else if (parent) {
parent.removeChild(el);
}
}
var move = {
name: 'move',
bind: function bind (el, ref) {
var value = ref.value;
el.__qmove = {};
},
update: function update (el, ref) {
var oldValue = ref.oldValue;
var value = ref.value;
if (oldValue !== value) {
el.__qmove.target = document.querySelector(value);
updateBinding$1(el, value);
}
},
inserted: function inserted (el, ref) {
var value = ref.value;
updateBinding$1(el, value);
},
unbind: function unbind (el) {
var parent = el.parentNode;
if (parent) {
parent.removeChild(el);
}
delete el.__qmove;
}
}
function updateBinding$2 (el, binding) {
var ctx = el.__qscrollfire;
if (typeof binding.value !== 'function') {
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll);
console.error('v-scroll-fire requires a function as parameter', el);
return
}
ctx.handler = binding.value;
if (typeof binding.oldValue !== 'function') {
ctx.scrollTarget.addEventListener('scroll', ctx.scroll, listenOpts.passive);
ctx.scroll();
}
}
var scrollFire = {
name: 'scroll-fire',
bind: function bind (el, binding) {
var ctx = {
scroll: debounce(function () {
var containerBottom, elementBottom, fire;
if (ctx.scrollTarget === window) {
elementBottom = el.getBoundingClientRect().bottom;
fire = elementBottom < viewport().height;
}
else {
containerBottom = offset(ctx.scrollTarget).top + height(ctx.scrollTarget);
elementBottom = offset(el).top + height(el);
fire = elementBottom < containerBottom;
}
if (fire) {
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll, listenOpts.passive);
ctx.handler(el);
}
}, 25)
};
el.__qscrollfire = ctx;
},
inserted: function inserted (el, binding) {
var ctx = el.__qscrollfire;
ctx.scrollTarget = getScrollTarget(el);
updateBinding$2(el, binding);
},
update: function update (el, binding) {
if (binding.value !== binding.oldValue) {
updateBinding$2(el, binding);
}
},
unbind: function unbind (el) {
var ctx = el.__qscrollfire;
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll, listenOpts.passive);
delete el.__qscrollfire;
}
}
function updateBinding$3 (el, binding) {
var ctx = el.__qscroll;
if (typeof binding.value !== 'function') {
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll, listenOpts.passive);
console.error('v-scroll requires a function as parameter', el);
return
}
ctx.handler = binding.value;
if (typeof binding.oldValue !== 'function') {
ctx.scrollTarget.addEventListener('scroll', ctx.scroll, listenOpts.passive);
}
}
var scroll$1 = {
name: 'scroll',
bind: function bind (el, binding) {
var ctx = {
scroll: function scroll () {
ctx.handler(getScrollPosition(ctx.scrollTarget));
}
};
el.__qscroll = ctx;
},
inserted: function inserted (el, binding) {
var ctx = el.__qscroll;
ctx.scrollTarget = getScrollTarget(el);
updateBinding$3(el, binding);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
updateBinding$3(el, binding);
}
},
unbind: function unbind (el) {
var ctx = el.__qscroll;
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll, listenOpts.passive);
delete el.__qscroll;
}
}
function updateBinding$4 (el, binding) {
var ctx = el.__qtouchhold;
ctx.duration = parseInt(binding.arg, 10) || 800;
if (binding.oldValue !== binding.value) {
ctx.handler = binding.value;
}
}
var touchHold = {
name: 'touch-hold',
bind: function bind (el, binding) {
var
mouse = !binding.modifiers.noMouse,
stopPropagation = binding.modifiers.stop,
preventDefault = binding.modifiers.prevent;
var ctx = {
mouseStart: function mouseStart (evt) {
if (leftClick(evt)) {
document.addEventListener('mousemove', ctx.mouseAbort);
document.addEventListener('mouseup', ctx.mouseAbort);
ctx.start(evt);
}
},
mouseAbort: function mouseAbort (evt) {
document.removeEventListener('mousemove', ctx.mouseAbort);
document.removeEventListener('mouseup', ctx.mouseAbort);
ctx.abort(evt);
},
start: function start (evt) {
var startTime = new Date().getTime();
stopPropagation && evt.stopPropagation();
preventDefault && evt.preventDefault();
ctx.timer = setTimeout(function () {
if (mouse) {
document.removeEventListener('mousemove', ctx.mouseAbort);
document.removeEventListener('mouseup', ctx.mouseAbort);
}
ctx.handler({
evt: evt,
position: position(evt),
duration: new Date().getTime() - startTime
});
}, ctx.duration);
},
abort: function abort (evt) {
clearTimeout(ctx.timer);
ctx.timer = null;
}
};
el.__qtouchhold = ctx;
updateBinding$4(el, binding);
if (mouse) {
el.addEventListener('mousedown', ctx.mouseStart);
}
el.addEventListener('touchstart', ctx.start);
el.addEventListener('touchmove', ctx.abort);
el.addEventListener('touchend', ctx.abort);
},
update: function update (el, binding) {
updateBinding$4(el, binding);
},
unbind: function unbind (el, binding) {
var ctx = el.__qtouchhold;
el.removeEventListener('touchstart', ctx.start);
el.removeEventListener('touchend', ctx.abort);
el.removeEventListener('touchmove', ctx.abort);
el.removeEventListener('mousedown', ctx.mouseStart);
document.removeEventListener('mousemove', ctx.mouseAbort);
document.removeEventListener('mouseup', ctx.mouseAbort);
delete el.__qtouchhold;
}
}
var directives = Object.freeze({
BackToTop: backToTop,
CloseOverlay: closeOverlay,
GoBack: goBack,
Move: move,
Ripple: Ripple,
ScrollFire: scrollFire,
Scroll: scroll$1,
TouchHold: touchHold,
TouchPan: TouchPan,
TouchSwipe: TouchSwipe
});
function modalFn (Component, Vue$$1) {
return function (props) {
var node = document.createElement('div');
document.body.appendChild(node);
return new Promise(function (resolve, reject) {
var vm = new Vue$$1({
el: node,
data: function data () {
return { props: props }
},
render: function (h) { return h(Component, {
props: props,
ref: 'modal',
on: {
ok: function (data) {
resolve(data);
vm.$destroy();
},
cancel: function () {
reject(new Error());
vm.$destroy();
}
}
}); },
mounted: function mounted () {
this.$refs.modal.show();
}
});
})
}
}
var actionSheet = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
$q.actionSheet = modalFn(QActionSheet, Vue$$1);
}
}
function getPrimaryHex () {
var tempDiv = document.createElement('div');
tempDiv.style.height = '10px';
tempDiv.style.position = 'absolute';
tempDiv.style.top = '-100000px';
tempDiv.className = 'bg-primary';
document.body.appendChild(tempDiv);
var primaryColor = window.getComputedStyle(tempDiv).getPropertyValue('background-color');
document.body.removeChild(tempDiv);
var rgb = primaryColor.match(/\d+/g);
return ("#" + (rgbToHex(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]))))
}
function setColor (hexColor) {
// http://stackoverflow.com/a/33193739
var metaTag = document.createElement('meta');
if (Platform.is.winphone) {
metaTag.setAttribute('name', 'msapplication-navbutton-color');
}
else if (Platform.is.safari) {
metaTag.setAttribute('name', 'apple-mobile-web-app-status-bar-style');
}
// Chrome, Firefox OS, Opera, Vivaldi
else {
metaTag.setAttribute('name', 'theme-color');
}
metaTag.setAttribute('content', hexColor);
document.getElementsByTagName('head')[0].appendChild(metaTag);
}
var addressbarColor = {
set: function set (hexColor) {
if (!Platform.is.mobile || Platform.is.cordova || isSSR) {
return
}
if (!Platform.is.winphone && !Platform.is.safari && !Platform.is.webkit && !Platform.is.vivaldi) {
return
}
ready(function () {
setColor(hexColor || getPrimaryHex());
});
}
}
var appFullscreen = {
isCapable: false,
isActive: false,
__prefixes: {},
request: function request (target) {
if (this.isCapable && !this.isActive) {
target = target || document.documentElement;
target[this.__prefixes.request]();
}
},
exit: function exit () {
if (this.isCapable && this.isActive) {
document[this.__prefixes.exit]();
}
},
toggle: function toggle (target) {
if (this.isActive) {
this.exit();
}
else {
this.request(target);
}
},
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
$q.fullscreen = this;
return
}
var request = [
'requestFullscreen',
'msRequestFullscreen', 'mozRequestFullScreen', 'webkitRequestFullscreen'
].find(function (request) { return document.documentElement[request]; });
this.isCapable = request !== undefined;
if (!this.isCapable) {
// it means the browser does NOT support it
return
}
var exit = [
'exitFullscreen',
'msExitFullscreen', 'mozCancelFullScreen', 'webkitExitFullscreen'
].find(function (exit) { return document[exit]; });
this.__prefixes = {
request: request,
exit: exit
};
this.isActive = (document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement ||
document.msFullscreenElement) !== undefined
;[
'onfullscreenchange',
'MSFullscreenChange', 'onmozfullscreenchange', 'onwebkitfullscreenchange'
].forEach(function (evt) {
document[evt] = function () {
this$1.isActive = !this$1.isActive;
};
});
Vue$$1.util.defineReactive({}, 'isActive', this);
$q.fullscreen = this;
}
}
var appVisibility = {
appVisible: false,
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
this.appVisible = $q.appVisible = true;
return
}
var prop, evt;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
prop = 'hidden';
evt = 'visibilitychange';
}
else if (typeof document.msHidden !== 'undefined') {
prop = 'msHidden';
evt = 'msvisibilitychange';
}
else if (typeof document.webkitHidden !== 'undefined') {
prop = 'webkitHidden';
evt = 'webkitvisibilitychange';
}
var update = function () {
this$1.appVisible = $q.appVisible = !document[prop];
};
update();
if (evt && typeof document[prop] !== 'undefined') {
Vue$$1.util.defineReactive({}, 'appVisible', $q);
document.addEventListener(evt, update, false);
}
}
}
function encode (string) {
return encodeURIComponent(string)
}
function decode (string) {
return decodeURIComponent(string)
}
function stringifyCookieValue (value) {
return encode(value === Object(value) ? JSON.stringify(value) : '' + value)
}
function read (string) {
if (string === '') {
return string
}
if (string.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
string = string.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
string = decode(string.replace(/\+/g, ' '));
try {
string = JSON.parse(string);
}
catch (e) {}
return string
}
function set (key, val, opts) {
if ( opts === void 0 ) opts = {};
var time = opts.expires;
if (typeof opts.expires === 'number') {
time = new Date();
time.setMilliseconds(time.getMilliseconds() + opts.expires * 864e+5);
}
document.cookie = [
encode(key), '=', stringifyCookieValue(val),
time ? '; expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
opts.path ? '; path=' + opts.path : '',
opts.domain ? '; domain=' + opts.domain : '',
opts.secure ? '; secure' : ''
].join('');
}
function get (key) {
var
result = key ? undefined : {},
cookies = document.cookie ? document.cookie.split('; ') : [],
i = 0,
l = cookies.length,
parts,
name,
cookie;
for (; i < l; i++) {
parts = cookies[i].split('=');
name = decode(parts.shift());
cookie = parts.join('=');
if (!key) {
result[name] = cookie;
}
else if (key === name) {
result = read(cookie);
break
}
}
return result
}
function remove (key, options) {
set(key, '', extend(true, {}, options, {
expires: -1
}));
}
function has (key) {
return get(key) !== undefined
}
var cookies = {
get: get,
set: set,
has: has,
remove: remove,
all: function () { return get(); },
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
var noop = function () {};
this.get = noop;
this.set = noop;
this.has = noop;
this.remove = noop;
this.all = noop;
}
$q.cookies = this;
}
}
var dialog = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
$q.dialog = isSSR
? function () { return new Promise(); }
: modalFn(QDialog, Vue$$1);
}
}
var vm;
var timeout;
var props = {};
var staticClass = 'q-loading animate-fade fullscreen column flex-center z-max';
var Loading = {
isActive: false,
show: function show (ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var delay = ref.delay; if ( delay === void 0 ) delay = 500;
var message = ref.message; if ( message === void 0 ) message = false;
var spinnerSize = ref.spinnerSize; if ( spinnerSize === void 0 ) spinnerSize = 80;
var spinnerColor = ref.spinnerColor; if ( spinnerColor === void 0 ) spinnerColor = 'white';
var messageColor = ref.messageColor; if ( messageColor === void 0 ) messageColor = 'white';
var spinner = ref.spinner; if ( spinner === void 0 ) spinner = QSpinner;
var customClass = ref.customClass; if ( customClass === void 0 ) customClass = false;
if (isSSR) { return }
props.spinner = spinner;
props.message = message;
props.spinnerSize = spinnerSize;
props.spinnerColor = spinnerColor;
props.messageColor = messageColor;
if (typeof customClass === 'string') {
props.customClass = customClass.trim();
}
if (this.isActive) {
vm && vm.$forceUpdate();
return
}
timeout = setTimeout(function () {
timeout = null;
var node = document.createElement('div');
document.body.appendChild(node);
document.body.classList.add('with-loading');
vm = new this$1.__Vue({
name: 'q-loading',
el: node,
render: function render (h) {
return h('div', {
staticClass: staticClass,
'class': props.customClass
}, [
h(props.spinner, {
props: {
color: props.spinnerColor,
size: props.spinnerSize
}
}),
message
? h('div', {
'class': ("text-" + (props.messageColor)),
domProps: {
innerHTML: props.message
}
})
: null
])
}
});
}, delay);
this.isActive = true;
},
hide: function hide () {
if (!this.isActive) {
return
}
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
else {
vm.$destroy();
document.body.classList.remove('with-loading');
document.body.removeChild(vm.$el);
vm = null;
}
this.isActive = false;
},
__Vue: null,
__installed: false,
install: function install (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
$q.loading = Loading;
this.__Vue = Vue$$1;
}
};
var positionList = [
'top-left', 'top-right',
'bottom-left', 'bottom-right',
'top', 'bottom', 'left', 'right', 'center'
];
function init (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
var node = document.createElement('div');
document.body.appendChild(node);
this.__vm = new Vue$$1({
name: 'q-notifications',
data: {
notifs: {
center: [],
left: [],
right: [],
top: [],
'top-left': [],
'top-right': [],
bottom: [],
'bottom-left': [],
'bottom-right': []
}
},
methods: {
add: function add (config) {
var this$1 = this;
if (!config) {
console.error('Notify: parameter required');
return false
}
var notif;
if (typeof config === 'string') {
notif = {
message: config,
position: 'bottom'
};
}
else {
notif = clone(config);
}
if (notif.position) {
if (!positionList.includes(notif.position)) {
console.error(("Notify: wrong position: " + (notif.position)));
return false
}
}
else {
notif.position = 'bottom';
}
notif.__uid = uid();
if (notif.timeout === void 0) {
notif.timeout = 5000;
}
var close = function () {
this$1.remove(notif);
};
if (notif.actions) {
notif.actions = config.actions.map(function (item) {
var
handler = item.handler,
action = clone(item);
action.handler = typeof handler === 'function'
? function () {
handler();
close();
}
: function () { return close(); };
return action
});
}
if (notif.closeBtn) {
var btn = [{
closeBtn: true,
label: notif.closeBtn,
handler: close
}];
notif.actions = notif.actions
? notif.actions.concat(btn)
: btn;
}
if (notif.timeout) {
notif.__timeout = setTimeout(function () {
close();
}, notif.timeout + /* show duration */ 1000);
}
var action = notif.position.indexOf('top') > -1 ? 'unshift' : 'push';
this.notifs[notif.position][action](notif);
return close
},
remove: function remove (notif) {
if (notif.__timeout) { clearTimeout(notif.__timeout); }
var index = this.notifs[notif.position].indexOf(notif);
if (index !== -1) {
var ref = this.$refs[("notif_" + (notif.__uid))];
if (ref && ref.$el) {
var el = ref.$el;
el.style.left = (el.offsetLeft) + "px";
el.style.width = getComputedStyle(el).width;
}
this.notifs[notif.position].splice(index, 1);
if (typeof notif.onDismiss === 'function') {
notif.onDismiss();
}
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', { staticClass: 'q-notifications' }, positionList.map(function (pos) {
var
vert = ['left', 'center', 'right'].includes(pos) ? 'center' : (pos.indexOf('top') > -1 ? 'top' : 'bottom'),
align = pos.indexOf('left') > -1 ? 'start' : (pos.indexOf('right') > -1 ? 'end' : 'center'),
classes = ['left', 'right'].includes(pos) ? ("items-" + (pos === 'left' ? 'start' : 'end') + " justify-center") : (pos === 'center' ? 'flex-center' : ("items-" + align));
return h('transition-group', {
key: pos,
staticClass: ("q-notification-list q-notification-list-" + vert + " fixed column " + classes),
tag: 'div',
props: {
name: ("q-notification-" + pos),
mode: 'out-in'
}
}, this$1.notifs[pos].map(function (notif) {
return h(QAlert, {
ref: ("notif_" + (notif.__uid)),
key: notif.__uid,
staticClass: 'q-notification',
props: notif
}, [ notif.message ])
}))
}))
}
});
this.__vm.$mount(node);
$q.notify = this.create.bind(this);
}
var notify = {
create: function create (opts) {
var this$1 = this;
if (isSSR) {
return
}
if (this.__vm !== void 0) {
return this.__vm.add(opts)
}
ready(function () {
setTimeout(function () {
this$1.create(opts);
});
});
},
__installed: false,
install: function install (args) {
var this$1 = this;
if (this.__installed) { return }
this.__installed = true;
if (!isSSR) {
ready(function () {
init.call(this$1, args);
});
}
}
}
function encode$1 (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
}
if (typeof value === 'boolean') {
return '__q_bool|' + (value ? '1' : '0')
}
if (typeof value === 'string') {
return '__q_strn|' + value
}
if (typeof value === 'function') {
return '__q_strn|' + value.toString()
}
if (value === Object(value)) {
return '__q_objt|' + JSON.stringify(value)
}
// hmm, we don't know what to do with it,
// so just return it as is
return value
}
function decode$1 (value) {
var type, length, source;
length = value.length;
if (length < 9) {
// then it wasn't encoded by us
return value
}
type = value.substr(0, 8);
source = value.substring(9);
switch (type) {
case '__q_date':
return new Date(source)
case '__q_expr':
return new RegExp(source)
case '__q_numb':
return Number(source)
case '__q_bool':
return Boolean(source === '1')
case '__q_strn':
return '' + source
case '__q_objt':
return JSON.parse(source)
default:
// hmm, we reached here, we don't know the type,
// then it means it wasn't encoded by us, so just
// return whatever value it is
return value
}
}
function getEmptyStorage () {
var fn = function () { return null; };
return {
has: fn,
get: {
length: fn,
item: fn,
index: fn,
all: fn
},
set: fn,
remove: fn,
clear: fn,
isEmpty: fn
}
}
function getStorage (type) {
var
webStorage = window[type + 'Storage'],
get = function (key) {
var item = webStorage.getItem(key);
return item
? decode$1(item)
: null
};
return {
has: function (key) { return webStorage.getItem(key) !== null; },
get: {
length: function () { return webStorage.length; },
item: get,
index: function (index) {
if (index < webStorage.length) {
return get(webStorage.key(index))
}
},
all: function () {
var result = {}, key, len = webStorage.length;
for (var i = 0; i < len; i++) {
key = webStorage.key(i);
result[key] = get(key);
}
return result
}
},
set: function (key, value) { webStorage.setItem(key, encode$1(value)); },
remove: function (key) { webStorage.removeItem(key); },
clear: function () { webStorage.clear(); },
isEmpty: function () { return webStorage.length === 0; }
}
}
var LocalStorage = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if ($q.platform.has.webStorage) {
var storage = getStorage('local');
$q.localStorage = storage;
extend(true, this, storage);
}
else {
$q.localStorage = getEmptyStorage();
}
}
};
var SessionStorage = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if ($q.platform.has.webStorage) {
var storage = getStorage('session');
$q.sessionStorage = storage;
extend(true, this, storage);
}
else {
$q.sessionStorage = getEmptyStorage();
}
}
};
var plugins = Object.freeze({
ActionSheet: actionSheet,
AddressbarColor: addressbarColor,
AppFullscreen: appFullscreen,
AppVisibility: appVisibility,
Cookies: cookies,
Dialog: dialog,
Loading: Loading,
Notify: notify,
Platform: Platform,
LocalStorage: LocalStorage,
SessionStorage: SessionStorage
});
function openUrl (url, reject) {
if (Platform.is.cordova && navigator && navigator.app) {
return navigator.app.loadUrl(url, {
openExternal: true
})
}
var win = window.open(url, '_blank');
if (win) {
win.focus();
return win
}
else {
reject();
}
}
function noop () {}
var utils = Object.freeze({
animate: animate,
clone: clone,
colors: colors,
date: date,
debounce: debounce,
frameDebounce: frameDebounce,
dom: dom,
easing: easing,
event: event,
extend: extend,
filter: filter,
format: format,
noop: noop,
openURL: openUrl,
scroll: scroll,
throttle: throttle,
uid: uid
});
if (Vue === void 0) {
console.error('[ Quasar ] Vue is required to run. Please add a script tag for it before loading Quasar.');
}
else {
Vue.use({ install: install }, {
components: components,
directives: directives,
plugins: plugins
});
}
var index_umd = {
version: version,
theme: "ios",
i18n: i18n,
icons: icons,
components: components,
directives: directives,
plugins: plugins,
utils: utils
}
return index_umd;
})));
|
src/page/notifications-demo.js | knledg/react-webpack-skeleton | import React from 'react';
import { Page, Panel, Button, eventBus, Alert, Breadcrumbs } from 'react-blur-admin';
import { Link } from 'react-router';
import {Row, Col} from 'react-flex-proto';
export class NotificationsDemo extends React.Component {
renderBreadcrumbs() {
return (
<Breadcrumbs>
<Link to='/'>
Home
</Link>
Notifications Demo
</Breadcrumbs>
);
}
render() {
return (
<Page actionBar={this.renderBreadcrumbs()} title='Notifications Demo'>
<Panel title='Message Notifications'>
<Row>
<Col grow={false}>
<Button type='success' onClick={e => eventBus.addNotification('success', 'You have been successful')} />
</Col>
<Col grow={false}>
<Button type='warning' onClick={e => eventBus.addNotification('warning', 'You have been warned')} />
</Col>
<Col grow={false}>
<Button type='danger' onClick={e => eventBus.addNotification('error', 'You have been errored')} />
</Col>
<Col grow={false}>
<Button type='info' onClick={e => eventBus.addNotification('info', 'You have been informed', {title: 'And titled'})} />
</Col>
</Row>
</Panel>
<Row>
<Col>
<Panel title='Alert Bar Notifications (Non-closable)'>
<Alert type='success'>Yay! You did the thing!</Alert>
<Alert type='info'>This alert is informative!</Alert>
<Alert type='warning'>Oh no, you're about to do a bad thing!</Alert>
<Alert type='danger'>*gasp*! You did a bad thing!</Alert>
</Panel>
</Col>
<Col>
<Panel title='Alert Bar Notifications (Closable)'>
<Alert isDismissible={true} type='success'>Yay! You did the thing!</Alert>
<Alert isDismissible={true} type='info'>This alert is informative!</Alert>
<Alert isDismissible={true} type='warning'>Oh no, you're about to do a bad thing!</Alert>
<Alert isDismissible={true} type='danger'>*gasp*! You did a bad thing!</Alert>
</Panel>
</Col>
</Row>
</Page>
);
}
}
|
templates/rubix/redux/redux-seed/src/routes/Home2.js | jeffthemaximum/Teachers-Dont-Pay-Jeff | import React from 'react';
import { connect } from 'react-redux';
import actions from '../redux/actions';
import {
Row,
Col,
Grid,
Panel,
PanelBody,
PanelContainer,
} from '@sketchpixy/rubix';
@connect((state) => state)
export default class Home extends React.Component {
static fetchData(store) {
return store.dispatch(actions.getGreeting('Greetings from Rubix :)'));
}
render() {
return (
<PanelContainer>
<Panel>
<PanelBody>
<Grid>
<Row>
<Col xs={12}>
<p>{this.props.greetings.hello}</p>
</Col>
</Row>
</Grid>
</PanelBody>
</Panel>
</PanelContainer>
);
}
}
|
components/SocialMediaList.js | turntwogg/esports-aggregator | import React from 'react';
import {
FaFacebook,
FaTwitter,
FaInstagram,
FaYoutube,
FaTwitch,
} from 'react-icons/fa';
import RaisedBox from './RaisedBox';
const SocialMediaListItem = ({ href, label, icon }) => (
<li className="social-media-list-item">
<RaisedBox>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="social-media-list-link"
aria-label={label}
title={label}
>
{icon}
</a>
</RaisedBox>
<style jsx>{`
.social-media-list-item {
line-height: 1;
}
.social-media-list-item + .social-media-list-item {
margin-left: 4px;
}
.social-media-list-link {
display: flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
padding: 4px;
opacity: 0.7;
transition: 250ms ease-out opacity;
}
.social-media-list-link:hover {
opacity: 1;
}
`}</style>
</li>
);
const SocialMediaList = ({
facebook,
twitter,
instagram,
youtube,
twitch,
...rest
}) => (
<ul className="social-media-list" {...rest}>
{facebook && (
<SocialMediaListItem
href={
facebook.includes('facebook.com')
? facebook
: `https://facebook.com/${facebook}`
}
label="Facebook"
icon={<FaFacebook />}
/>
)}
{twitter && (
<SocialMediaListItem
href={
twitter.includes('twitter.com')
? twitter
: `https://twitter.com/${twitter}`
}
label="Twitter"
icon={<FaTwitter />}
/>
)}
{instagram && (
<SocialMediaListItem
href={
instagram.includes('instagram.com')
? instagram
: `https://instagram.com/${instagram}`
}
label="Instagram"
icon={<FaInstagram />}
/>
)}
{youtube && (
<SocialMediaListItem
href={
youtube.includes('youtube.com')
? youtube
: `https://youtube.com/${youtube}`
}
label="YouTube"
icon={<FaYoutube />}
/>
)}
{twitch && (
<SocialMediaListItem
href={
twitch.includes('twitch.tv') ? twitch : `https://twitch.tv/${twitch}`
}
label="Twitch"
icon={<FaTwitch />}
/>
)}
<style jsx>{`
.social-media-list {
display: flex;
margin: 0;
}
`}</style>
</ul>
);
export default SocialMediaList;
|
app/components/Notifications/__tests__/Notifications-test.js | TailorDev/franklin | import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
// see: https://github.com/mochajs/mocha/issues/1847
const { describe, it } = global;
import Notifications from '../presenter';
import MessageBox from '../MessageBox';
describe('<Notifications />', () => {
it('renders nothing if no messages', () => {
const wrapper = shallow(
<Notifications messages={[]} onMessageBoxClose={() => {}} />
);
expect(wrapper.find('.message-boxes')).to.have.length(1);
expect(wrapper.find('.message-box')).to.have.length(0);
});
it('wraps a leveld message box', () => {
const messages = [
{
content: 'foo',
level: 'error',
count: 1,
},
];
const wrapper = mount(
<Notifications messages={messages} onMessageBoxClose={() => {}} />
);
expect(wrapper.find('.message-boxes')).to.have.length(1);
expect(wrapper.find(MessageBox)).to.have.length(1);
expect(wrapper.find('.message-box.error')).to.have.length(1);
expect(wrapper.find('.message-box.error').html()).to.contain('<p>foo</p>');
});
it('wraps many leveld message boxes', () => {
const messages = [
{
content: 'foo',
level: 'warning',
count: 1,
},
{
content: 'bar',
level: 'success',
count: 1,
},
{
content: 'lol',
level: 'info',
count: 1,
},
];
const wrapper = mount(
<Notifications messages={messages} onMessageBoxClose={() => {}} />
);
expect(wrapper.find('.message-boxes')).to.have.length(1);
expect(wrapper.find(MessageBox)).to.have.length(3);
expect(wrapper.find('.message-box.warning')).to.have.length(1);
expect(wrapper.find('.message-box.success')).to.have.length(1);
expect(wrapper.find('.message-box.info')).to.have.length(1);
expect(wrapper.find('.message-box.warning').html()).to.contain(
'<p>foo</p>'
);
expect(wrapper.find('.message-box.success').html()).to.contain(
'<p>bar</p>'
);
expect(wrapper.find('.message-box.info').html()).to.contain('<p>lol</p>');
});
it('calls close message box handler', () => {
const spy = sinon.spy();
const messages = [
{
content: 'foo',
level: 'warning',
count: 1,
},
{
content: 'bar',
level: 'success',
count: 1,
},
{
content: 'lol',
level: 'info',
count: 1,
},
];
const wrapper = mount(
<Notifications messages={messages} onMessageBoxClose={spy} />
);
// Close the info message
wrapper
.find('.message-box.info')
.children('.close-button')
.simulate('click');
expect(spy.calledOnce).to.be.true;
// Close the warning message
wrapper
.find('.message-box.warning')
.children('.close-button')
.simulate('click');
expect(spy.calledTwice).to.be.true;
// Close the success message
wrapper
.find('.message-box.success')
.children('.close-button')
.simulate('click');
expect(spy.calledThrice).to.be.true;
// Check that the handler is called with proper arguments
expect(spy.withArgs(0).calledOnce).to.be.true;
expect(spy.withArgs(1).calledOnce).to.be.true;
expect(spy.withArgs(2).calledOnce).to.be.true;
});
});
|
src/svg-icons/notification/do-not-disturb-alt.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationDoNotDisturbAlt = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z"/>
</SvgIcon>
);
NotificationDoNotDisturbAlt = pure(NotificationDoNotDisturbAlt);
NotificationDoNotDisturbAlt.displayName = 'NotificationDoNotDisturbAlt';
NotificationDoNotDisturbAlt.muiName = 'SvgIcon';
export default NotificationDoNotDisturbAlt;
|
src/svg-icons/notification/enhanced-encryption.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationEnhancedEncryption = (props) => (
<SvgIcon {...props}>
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H8.9V6zM16 16h-3v3h-2v-3H8v-2h3v-3h2v3h3v2z"/>
</SvgIcon>
);
NotificationEnhancedEncryption = pure(NotificationEnhancedEncryption);
NotificationEnhancedEncryption.displayName = 'NotificationEnhancedEncryption';
NotificationEnhancedEncryption.muiName = 'SvgIcon';
export default NotificationEnhancedEncryption;
|
frontend/src/components/print/print-react/renderingDependencies.js | usu/ecamp3 | import React from 'react'
import wrap from './minimalHalJsonVuex.js'
import createI18n from './i18n.js'
import documents from './documents/index.js'
import { pdf } from '@react-pdf/renderer'
export default { React, wrap, createI18n, pdf, documents }
|
app/javascript/mastodon/features/notifications/components/notification.js | rainyday/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage, defineMessages } from 'react-intl';
import { HotKeys } from 'react-hotkeys';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me } from 'mastodon/initial_state';
import StatusContainer from 'mastodon/containers/status_container';
import AccountContainer from 'mastodon/containers/account_container';
import FollowRequestContainer from '../containers/follow_request_container';
import Icon from 'mastodon/components/icon';
import Permalink from 'mastodon/components/permalink';
const messages = defineMessages({
favourite: { id: 'notification.favourite', defaultMessage: '{name} favourited your status' },
follow: { id: 'notification.follow', defaultMessage: '{name} followed you' },
ownPoll: { id: 'notification.own_poll', defaultMessage: 'Your poll has ended' },
poll: { id: 'notification.poll', defaultMessage: 'A poll you have voted in has ended' },
reblog: { id: 'notification.reblog', defaultMessage: '{name} boosted your status' },
});
const notificationForScreenReader = (intl, message, timestamp) => {
const output = [message];
output.push(intl.formatDate(timestamp, { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }));
return output.join(', ');
};
export default @injectIntl
class Notification extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
hidden: PropTypes.bool,
onMoveUp: PropTypes.func.isRequired,
onMoveDown: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onFavourite: PropTypes.func.isRequired,
onReblog: PropTypes.func.isRequired,
onToggleHidden: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
intl: PropTypes.object.isRequired,
getScrollPosition: PropTypes.func,
updateScrollBottom: PropTypes.func,
cacheMediaWidth: PropTypes.func,
cachedMediaWidth: PropTypes.number,
};
handleMoveUp = () => {
const { notification, onMoveUp } = this.props;
onMoveUp(notification.get('id'));
}
handleMoveDown = () => {
const { notification, onMoveDown } = this.props;
onMoveDown(notification.get('id'));
}
handleOpen = () => {
const { notification } = this.props;
if (notification.get('status')) {
this.context.router.history.push(`/statuses/${notification.get('status')}`);
} else {
this.handleOpenProfile();
}
}
handleOpenProfile = () => {
const { notification } = this.props;
this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`);
}
handleMention = e => {
e.preventDefault();
const { notification, onMention } = this.props;
onMention(notification.get('account'), this.context.router.history);
}
handleHotkeyFavourite = () => {
const { status } = this.props;
if (status) this.props.onFavourite(status);
}
handleHotkeyBoost = e => {
const { status } = this.props;
if (status) this.props.onReblog(status, e);
}
handleHotkeyToggleHidden = () => {
const { status } = this.props;
if (status) this.props.onToggleHidden(status);
}
getHandlers () {
return {
reply: this.handleMention,
favourite: this.handleHotkeyFavourite,
boost: this.handleHotkeyBoost,
mention: this.handleMention,
open: this.handleOpen,
openProfile: this.handleOpenProfile,
moveUp: this.handleMoveUp,
moveDown: this.handleMoveDown,
toggleHidden: this.handleHotkeyToggleHidden,
};
}
renderFollow (notification, account, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-follow focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.follow, { name: account.get('acct') }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='user-plus' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</span>
</div>
<AccountContainer id={account.get('id')} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderFollowRequest (notification, account, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-follow-request focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.follow_request', defaultMessage: '{name} has requested to follow you' }, { name: account.get('acct') }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='user' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.follow_request' defaultMessage='{name} has requested to follow you' values={{ name: link }} />
</span>
</div>
<FollowRequestContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderMention (notification) {
return (
<StatusContainer
id={notification.get('status')}
withDismiss
hidden={this.props.hidden}
onMoveDown={this.handleMoveDown}
onMoveUp={this.handleMoveUp}
contextType='notifications'
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
);
}
renderFavourite (notification, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-favourite focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.favourite, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='star' className='star-icon' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={notification.get('account')}
muted
withDismiss
hidden={!!this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
renderReblog (notification, link) {
const { intl } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-reblog focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.reblog, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='retweet' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={notification.get('account')}
muted
withDismiss
hidden={this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
renderPoll (notification, account) {
const { intl } = this.props;
const ownPoll = me === account.get('id');
const message = ownPoll ? intl.formatMessage(messages.ownPoll) : intl.formatMessage(messages.poll);
return (
<HotKeys handlers={this.getHandlers()}>
<div className='notification notification-poll focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, message, notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='tasks' fixedWidth />
</div>
<span title={notification.get('created_at')}>
{ownPoll ? (
<FormattedMessage id='notification.own_poll' defaultMessage='Your poll has ended' />
) : (
<FormattedMessage id='notification.poll' defaultMessage='A poll you have voted in has ended' />
)}
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={account}
muted
withDismiss
hidden={this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayNameHtml = { __html: account.get('display_name_html') };
const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(notification, account, link);
case 'follow_request':
return this.renderFollowRequest(notification, account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
case 'poll':
return this.renderPoll(notification, account);
}
return null;
}
}
|
src/containers/DevTools.js | wmaurer/frontend_pizza_react_redux | import React from 'react';
// Exported from redux-devtools
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
// createDevTools takes a monitor and produces a DevTools component
const DevTools = createDevTools(
// Monitors are individually adjustable with props.
// Consult their repositories to learn about those props.
// Here, we put LogMonitor inside a DockMonitor.
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'>
<LogMonitor theme='tomorrow' />
</DockMonitor>
);
export default DevTools;
|
ajax/libs/react-native-web/0.17.5/exports/View/index.js | cdnjs/cdnjs | function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
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; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import * as React from 'react';
import createElement from '../createElement';
import css from '../StyleSheet/css';
import * as forwardedProps from '../../modules/forwardedProps';
import pick from '../../modules/pick';
import useElementLayout from '../../modules/useElementLayout';
import useMergeRefs from '../../modules/useMergeRefs';
import usePlatformMethods from '../../modules/usePlatformMethods';
import useResponderEvents from '../../modules/useResponderEvents';
import StyleSheet from '../StyleSheet';
import TextAncestorContext from '../Text/TextAncestorContext';
var forwardPropsList = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, forwardedProps.defaultProps), forwardedProps.accessibilityProps), forwardedProps.clickProps), forwardedProps.focusProps), forwardedProps.keyboardProps), forwardedProps.mouseProps), forwardedProps.touchProps), forwardedProps.styleProps), {}, {
href: true,
lang: true,
onScroll: true,
onWheel: true,
pointerEvents: true
});
var pickProps = function pickProps(props) {
return pick(props, forwardPropsList);
};
var View = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) {
var hrefAttrs = props.hrefAttrs,
onLayout = props.onLayout,
onMoveShouldSetResponder = props.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture,
onResponderEnd = props.onResponderEnd,
onResponderGrant = props.onResponderGrant,
onResponderMove = props.onResponderMove,
onResponderReject = props.onResponderReject,
onResponderRelease = props.onResponderRelease,
onResponderStart = props.onResponderStart,
onResponderTerminate = props.onResponderTerminate,
onResponderTerminationRequest = props.onResponderTerminationRequest,
onScrollShouldSetResponder = props.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = props.onStartShouldSetResponder,
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture;
if (process.env.NODE_ENV !== 'production') {
React.Children.toArray(props.children).forEach(function (item) {
if (typeof item === 'string') {
console.error("Unexpected text node: " + item + ". A text node cannot be a child of a <View>.");
}
});
}
var hasTextAncestor = React.useContext(TextAncestorContext);
var hostRef = React.useRef(null);
useElementLayout(hostRef, onLayout);
useResponderEvents(hostRef, {
onMoveShouldSetResponder: onMoveShouldSetResponder,
onMoveShouldSetResponderCapture: onMoveShouldSetResponderCapture,
onResponderEnd: onResponderEnd,
onResponderGrant: onResponderGrant,
onResponderMove: onResponderMove,
onResponderReject: onResponderReject,
onResponderRelease: onResponderRelease,
onResponderStart: onResponderStart,
onResponderTerminate: onResponderTerminate,
onResponderTerminationRequest: onResponderTerminationRequest,
onScrollShouldSetResponder: onScrollShouldSetResponder,
onScrollShouldSetResponderCapture: onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder: onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture: onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder: onStartShouldSetResponder,
onStartShouldSetResponderCapture: onStartShouldSetResponderCapture
});
var component = 'div';
var style = StyleSheet.compose(hasTextAncestor && styles.inline, props.style);
var supportedProps = pickProps(props);
supportedProps.classList = classList;
supportedProps.style = style;
if (props.href != null) {
component = 'a';
if (hrefAttrs != null) {
var download = hrefAttrs.download,
rel = hrefAttrs.rel,
target = hrefAttrs.target;
if (download != null) {
supportedProps.download = download;
}
if (rel != null) {
supportedProps.rel = rel;
}
if (typeof target === 'string') {
supportedProps.target = target.charAt(0) !== '_' ? '_' + target : target;
}
}
}
var platformMethodsRef = usePlatformMethods(supportedProps);
var setRef = useMergeRefs(hostRef, platformMethodsRef, forwardedRef);
supportedProps.ref = setRef;
return createElement(component, supportedProps);
});
View.displayName = 'View';
var classes = css.create({
view: {
alignItems: 'stretch',
border: '0 solid black',
boxSizing: 'border-box',
display: 'flex',
flexBasis: 'auto',
flexDirection: 'column',
flexShrink: 0,
margin: 0,
minHeight: 0,
minWidth: 0,
padding: 0,
position: 'relative',
zIndex: 0
}
});
var classList = [classes.view];
var styles = StyleSheet.create({
inline: {
display: 'inline-flex'
}
});
export default View; |
source/common/components/HomePage/HomePage.js | shery15/react | import React from 'react';
import { Link } from 'react-router';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
const HomePage = ({
userId,
onSubmitUserId,
onChangeUserId
}) => {
return (
<div>
<TextField
hintText="Please Key in your Github User Id."
onChange={onChangeUserId}
/>
<RaisedButton label="Submit" onClick={onSubmitUserId(userId)} primary />
<Link
to={{
pathname: '/result',
query: { userId }
}}
/>
</div>
);
// return (
// <div>
// </div>
// );
};
export default HomePage;
|
src/components/Menu.js | tgdn/react-dropdown | import React from 'react'
class DropdownMenu extends React.Component {
render() {
const {children} = this.props
return (
<div className='Dropdown__menu'>
{children}
</div>
)
}
}
export {DropdownMenu}
|
src/test/containersSpec/ChannelData.spec.js | badT/Chatson | import React from 'react';
import { mount } from 'enzyme';
import chai, { expect } from 'chai';
import chaiEnzyme from 'chai-enzyme';
import sinon from 'sinon';
chai.use(chaiEnzyme());
import ConnectedChannelData from '../../containers/ChannelData/index';
import configureStore from '../../store/configureStore';
const store = configureStore();
describe('<ChannelData />', () => {
sinon.spy(ConnectedChannelData.prototype, 'componentDidMount');
sinon.spy(ConnectedChannelData.prototype, 'render');
it('should render message data', () => {
const wrapper = mount(<ConnectedChannelData store={store} />);
expect(wrapper.find('.msg-data')).to.have.length(3);
});
it('should call componentDidMount function', () => {
expect(ConnectedChannelData.prototype.componentDidMount.calledOnce).to.equal(true);
});
it('should call render function', () => {
expect(ConnectedChannelData.prototype.render.calledOnce).to.equal(true);
});
it('should set lastMsg state', () => {
const wrapper = mount(<ConnectedChannelData store={store} />);
expect(wrapper.state().lastMsg).to.not.exist;
wrapper.setState({ lastMsg: 'blumpyPals' });
expect(wrapper.state().lastMsg).to.equal('blumpyPals');
});
});
|
app/reactions/client/methods/setReaction.js | inoio/Rocket.Chat | import { Meteor } from 'meteor/meteor';
import _ from 'underscore';
import { Messages, Rooms, Subscriptions, EmojiCustom } from '../../../models';
import { callbacks } from '../../../callbacks';
import { emoji } from '../../../emoji';
Meteor.methods({
setReaction(reaction, messageId) {
if (!Meteor.userId()) {
throw new Meteor.Error(203, 'User_logged_out');
}
const user = Meteor.user();
const message = Messages.findOne({ _id: messageId });
const room = Rooms.findOne({ _id: message.rid });
if (room.ro && !room.reactWhenReadOnly) {
if (!Array.isArray(room.unmuted) || room.unmuted.indexOf(user.username) === -1) {
return false;
}
}
if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1) {
return false;
}
if (!Subscriptions.findOne({ rid: message.rid })) {
return false;
}
if (message.private) {
return false;
}
if (!emoji.list[reaction] && EmojiCustom.findByNameOrAlias(reaction).count() === 0) {
return false;
}
if (message.reactions && message.reactions[reaction] && message.reactions[reaction].usernames.indexOf(user.username) !== -1) {
message.reactions[reaction].usernames.splice(message.reactions[reaction].usernames.indexOf(user.username), 1);
if (message.reactions[reaction].usernames.length === 0) {
delete message.reactions[reaction];
}
if (_.isEmpty(message.reactions)) {
delete message.reactions;
Messages.unsetReactions(messageId);
callbacks.run('unsetReaction', messageId, reaction);
} else {
Messages.setReactions(messageId, message.reactions);
callbacks.run('setReaction', messageId, reaction);
}
} else {
if (!message.reactions) {
message.reactions = {};
}
if (!message.reactions[reaction]) {
message.reactions[reaction] = {
usernames: [],
};
}
message.reactions[reaction].usernames.push(user.username);
Messages.setReactions(messageId, message.reactions);
callbacks.run('setReaction', messageId, reaction);
}
},
});
|
src/routes/message/MessageContainer.js | nambawan/g-old | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Message from '../../components/Message';
import Box from '../../components/Box';
import { getMessage, getMessageUpdates } from '../../reducers';
import { createMessage } from '../../actions/message';
import List from '../../components/List';
import ListItem from '../../components/ListItem';
import MessageChannel from './MessageChannel';
import MessageForm from '../../components/MessageForm';
class MessageContainer extends React.Component {
static propTypes = {
message: PropTypes.shape({
subject: PropTypes.string,
messageObject: PropTypes.shape({}),
sender: PropTypes.shape({}),
}),
messageUpdates: PropTypes.shape({}).isRequired,
createMessage: PropTypes.func.isRequired,
};
static defaultProps = {
message: null,
};
constructor(props) {
super(props);
this.state = { openMessages: [] };
this.sendReply = this.sendReply.bind(this);
}
sendReply(values) {
const { message } = this.props;
const { subject, sender, parentId, id } = message;
this.props.createMessage({
parentId: parentId || id,
recipientType: 'USER',
messageType: 'COMMUNICATION',
recipients: [sender.id],
subject: { de: `Re: ${subject}` },
communication: {
textHtml: values.text,
replyable: true,
},
});
}
renderMessages(messageList) {
return (
<div style={{ maxWidth: '35em', width: '100%' }}>
<List>
{messageList &&
messageList.map(msg => (
<ListItem
onClick={() =>
this.setState({
openMessages: this.state.openMessages.find(
mId => mId === msg.id,
)
? this.state.openMessages.filter(mId => mId !== msg.id)
: this.state.openMessages.concat([msg.id]),
})
}
>
<Message
createdAt={msg.createdAt}
preview={!this.state.openMessages.find(mId => mId === msg.id)}
subject={msg.subject}
content={msg.messageObject && msg.messageObject.content}
sender={msg.sender}
/>
</ListItem>
))}
</List>
</div>
);
}
render() {
const {
message: { messageObject, parentId, id },
messageUpdates,
} = this.props;
return (
<Box tag="article" column pad align padding="medium">
<MessageChannel id={parentId || id} messageId={id} />
{messageObject &&
messageObject.replyable && (
<MessageForm updates={messageUpdates} onSend={this.sendReply} />
)
/* <div
style={{
width: '100%',
maxWidth: '35em',
paddingTop: '2em',
borderTop: '2px solid #eee',
}}
>
<FormValidation
submit={this.sendReply}
validations={{ text: { args: { required: true } } }}
data={{ text: '' }}
>
{({ values, onSubmit, handleValueChanges, errorMessages }) => (
<Box column>
<FormField label="Reply" error={errorMessages.textError}>
<Textarea
disabled={messageUpdates.pending}
name="text"
useCacheForDOMMeasurements
value={values.text}
onChange={handleValueChanges}
minRows={2}
/>
</FormField>
<Button
primary
disabled={messageUpdates.pending}
onClick={onSubmit}
label={<FormattedMessage {...messages.send} />}
/>
</Box>
)}
</FormValidation>
</div>
) */
}
</Box>
);
}
}
const mapStateToProps = (state, { id }) => ({
message: getMessage(state, id),
messageUpdates: getMessageUpdates(state),
});
const mapDispatch = {
createMessage,
};
export default connect(mapStateToProps, mapDispatch)(MessageContainer);
|
.storybook/config.js | Sashkan/ft_youtube | import { configure } from '@storybook/react';
function loadStories() {
require('../stories');
}
configure(loadStories, module);
|
ajax/libs/react-native-web/0.14.6/cjs/exports/Switch/index.js | cdnjs/cdnjs | "use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _multiplyStyleLengthValue = _interopRequireDefault(require("../../modules/multiplyStyleLengthValue"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var emptyObject = {};
var thumbDefaultBoxShadow = '0px 1px 3px rgba(0,0,0,0.5)';
var thumbFocusedBoxShadow = thumbDefaultBoxShadow + ", 0 0 0 10px rgba(0,0,0,0.1)";
var Switch = (0, React.forwardRef)(function (props, forwardedRef) {
var accessibilityLabel = props.accessibilityLabel,
_props$activeThumbCol = props.activeThumbColor,
activeThumbColor = _props$activeThumbCol === void 0 ? '#009688' : _props$activeThumbCol,
_props$activeTrackCol = props.activeTrackColor,
activeTrackColor = _props$activeTrackCol === void 0 ? '#A3D3CF' : _props$activeTrackCol,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
onValueChange = props.onValueChange,
_props$style = props.style,
style = _props$style === void 0 ? emptyObject : _props$style,
_props$thumbColor = props.thumbColor,
thumbColor = _props$thumbColor === void 0 ? '#FAFAFA' : _props$thumbColor,
_props$trackColor = props.trackColor,
trackColor = _props$trackColor === void 0 ? '#939393' : _props$trackColor,
_props$value = props.value,
value = _props$value === void 0 ? false : _props$value,
other = _objectWithoutPropertiesLoose(props, ["accessibilityLabel", "activeThumbColor", "activeTrackColor", "disabled", "onValueChange", "style", "thumbColor", "trackColor", "value"]);
var thumbRef = (0, React.useRef)(null);
function handleChange(event) {
if (onValueChange != null) {
onValueChange(event.nativeEvent.target.checked);
}
}
function handleFocusState(event) {
var isFocused = event.nativeEvent.type === 'focus';
var boxShadow = isFocused ? thumbFocusedBoxShadow : thumbDefaultBoxShadow;
if (thumbRef.current != null) {
thumbRef.current.style.boxShadow = boxShadow;
}
}
var _StyleSheet$flatten = _StyleSheet.default.flatten(style),
styleHeight = _StyleSheet$flatten.height,
styleWidth = _StyleSheet$flatten.width;
var height = styleHeight || 20;
var minWidth = (0, _multiplyStyleLengthValue.default)(height, 2);
var width = styleWidth > minWidth ? styleWidth : minWidth;
var trackBorderRadius = (0, _multiplyStyleLengthValue.default)(height, 0.5);
var trackCurrentColor = function () {
if (value === true) {
if (trackColor != null && typeof trackColor === 'object') {
return trackColor.true;
} else {
return activeTrackColor;
}
} else {
if (trackColor != null && typeof trackColor === 'object') {
return trackColor.false;
} else {
return trackColor;
}
}
}();
var thumbCurrentColor = value ? activeThumbColor : thumbColor;
var thumbHeight = height;
var thumbWidth = thumbHeight;
var rootStyle = [styles.root, style, disabled && styles.cursorDefault, {
height: height,
width: width
}];
var trackStyle = [styles.track, {
backgroundColor: disabled ? '#D5D5D5' : trackCurrentColor,
borderRadius: trackBorderRadius
}];
var thumbStyle = [styles.thumb, value && styles.thumbActive, {
backgroundColor: disabled ? '#BDBDBD' : thumbCurrentColor,
height: thumbHeight,
marginStart: value ? (0, _multiplyStyleLengthValue.default)(thumbWidth, -1) : 0,
width: thumbWidth
}];
var nativeControl = (0, _createElement.default)('input', {
accessibilityLabel: accessibilityLabel,
checked: value,
disabled: disabled,
onBlur: handleFocusState,
onChange: handleChange,
onFocus: handleFocusState,
ref: forwardedRef,
style: [styles.nativeControl, styles.cursorInherit],
type: 'checkbox'
});
return React.createElement(_View.default, _extends({}, other, {
style: rootStyle
}), React.createElement(_View.default, {
style: trackStyle
}), React.createElement(_View.default, {
ref: thumbRef,
style: thumbStyle
}), nativeControl);
});
Switch.displayName = 'Switch';
var styles = _StyleSheet.default.create({
root: {
cursor: 'pointer',
userSelect: 'none'
},
cursorDefault: {
cursor: 'default'
},
cursorInherit: {
cursor: 'inherit'
},
track: _objectSpread({}, _StyleSheet.default.absoluteFillObject, {
height: '70%',
margin: 'auto',
transitionDuration: '0.1s',
width: '100%'
}),
thumb: {
alignSelf: 'flex-start',
borderRadius: '100%',
boxShadow: thumbDefaultBoxShadow,
start: '0%',
transform: [{
translateZ: 0
}],
transitionDuration: '0.1s'
},
thumbActive: {
start: '100%'
},
nativeControl: _objectSpread({}, _StyleSheet.default.absoluteFillObject, {
height: '100%',
margin: 0,
opacity: 0,
padding: 0,
width: '100%'
})
});
var _default = Switch;
exports.default = _default;
module.exports = exports.default; |
app/scripts/controllers/activate_ctrl.js | Coding/m.coding.net | /**
* Created by wenki on 18/07/2015.
*/
var ACTIVATE_ROUTE = (function(){
function refreshCaptcha(){
$('img.captcha').attr('src', API_DOMAIN + '/api/getCaptcha?code=' + Math.random());
}
function changeStyle(){
var controls = new Array('email','captcha');
if ($("#activate").length != 0){
controls = new Array('password','confirm-password');
}
var flag = true;
for (var i = controls.length - 1; i >= 0; i--) {
var value = $.trim($('#' + controls[i]).val());
if (value == ''){
flag = false;
}
};
var elem_btn = $('.btn-activate');
if (flag){
elem_btn.removeAttr('disabled');
elem_btn.css('color','#ffffff');
}else{
elem_btn.attr('disabled','disabled');
elem_btn.css('color','rgba(255,255,255,0.5)');
}
}
function userActivate(){
$('form.activate').submit(function(e) {
e.preventDefault();
var email = $.trim($("#email").val()),
j_captcha = $.trim($("#captcha").val());
$.ajax({
url: API_DOMAIN + '/api/activate?email='+email+'&j_captcha='+j_captcha,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function(data) {
if (data.code == 0) {
router.run.call(router, '/login');
alert(' 已经发送邮件。');
}
if (data.msg) {
refreshCaptcha();
for(var key in data.msg) {
alert(data.msg[key]);
}
}
},
error: function() {
alert('Failed to activate');
}
});
});
$('#email').on('input',changeStyle);
$('#captcha').on('input',changeStyle);
$('img.captcha').on('click',refreshCaptcha);
bindClearInput('email');
bindClearInput('j_captcha');
}
function activate(email, key){
$('form#activate #email').val(email);
$('form#activate #email_hidden').val(email);
$('form#activate #key').val(key);
$.ajax({
url: API_DOMAIN + '/api/beforeactivate?confirm_password=&email='+email+'&key='+key+'&password=',
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function(data) {
if (data.code == 1) {
router.run.call(router, '/');
}
if (data.msg) {
for(var key in data.msg) {
alert(data.msg[key]);
}
}
},
error: function() {
alert('Failed to beforeactivate');
}
});
$('form#activate').submit(function(e) {
e.preventDefault();
var $email = $('input[name="email"]'),
$key = $('input[name="key"]'),
$password = $('input[name="password"]'),
$confirm_password = $('input[name="confirm_password"]'),
hash_password = CryptoJS.SHA1($password.val()),
hash_confirm_password = CryptoJS.SHA1($confirm_password.val()),
post_data = 'email=' + $.trim($email.val()) + '&key='
+ $key.val() + '&password=' + hash_password + '&confirm_password=' + hash_confirm_password;
$.ajax({
url: API_DOMAIN + '/api/activate',
type: 'POST',
dataType: 'json',
data: post_data,
xhrFields: {
withCredentials: true
},
success: function(data) {
if (data.code == 0) {
router.run.call(router, '/');
}
if (data.msg) {
for(var key in data.msg) {
alert(data.msg[key]);
}
}
},
error: function() {
alert('Failed to activate');
}
});
});
$('#password').on('input',changeStyle);
$('#confirm-password').on('input',changeStyle);
bindClearInput('password');
bindClearInput('confirm_password');
}
function remove_template(){
$('template').remove();
}
return {
template_url: '/views/activate.html',
context: '.container',
before_enter: function(email, key){
if (router.current_user) {
location.href = '/';
}
},
on_enter: function(email, key){
if (typeof email != 'undefined'){
$('div.slogon').after($('#activate-template').html());
remove_template();
activate(email,key);
}else{
var html = $('#user-activate-template').html();
$('div.slogon').after(html);
remove_template();
userActivate();
}
}
}
})();
|
ajax/libs/plotly.js/1.39.2/plotly-finance.min.js | jonobr1/cdnjs | /**
* plotly.js (finance - minified) v1.39.2
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){return function(){return function t(e,r,n){function a(o,l){if(!r[o]){if(!e[o]){var s="function"==typeof require&&require;if(!l&&s)return s(o,!0);if(i)return i(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[o]={exports:{}};e[o][0].call(u.exports,function(t){var r=e[o][1][t];return a(r||t)},u,u.exports,t,e,r,n)}return r[o].exports}for(var i="function"==typeof require&&require,o=0;o<n.length;o++)a(n[o]);return a}}()({1:[function(t,e,r){"use strict";var n=t("../src/lib"),a={"X,X div":"direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;","X input,X button":"font-family:'Open Sans', verdana, arial, sans-serif;","X input:focus,X button:focus":"outline:none;","X a":"text-decoration:none;","X a:hover":"text-decoration:none;","X .crisp":"shape-rendering:crispEdges;","X .user-select-none":"-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;","X svg":"overflow:hidden;","X svg a":"fill:#447adb;","X svg a:hover":"fill:#3c6dc5;","X .main-svg":"position:absolute;top:0;left:0;pointer-events:none;","X .main-svg .draglayer":"pointer-events:all;","X .cursor-default":"cursor:default;","X .cursor-pointer":"cursor:pointer;","X .cursor-crosshair":"cursor:crosshair;","X .cursor-move":"cursor:move;","X .cursor-col-resize":"cursor:col-resize;","X .cursor-row-resize":"cursor:row-resize;","X .cursor-ns-resize":"cursor:ns-resize;","X .cursor-ew-resize":"cursor:ew-resize;","X .cursor-sw-resize":"cursor:sw-resize;","X .cursor-s-resize":"cursor:s-resize;","X .cursor-se-resize":"cursor:se-resize;","X .cursor-w-resize":"cursor:w-resize;","X .cursor-e-resize":"cursor:e-resize;","X .cursor-nw-resize":"cursor:nw-resize;","X .cursor-n-resize":"cursor:n-resize;","X .cursor-ne-resize":"cursor:ne-resize;","X .cursor-grab":"cursor:-webkit-grab;cursor:grab;","X .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;","X:hover .modebar--hover":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","X [data-title]:before,X [data-title]:after":"position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;","X [data-title]:hover:before,X [data-title]:hover:after":"display:block;opacity:1;","X [data-title]:before":"content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;","X [data-title]:after":"content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;","X .select-outline":"fill:none;stroke-width:1;shape-rendering:crispEdges;","X .select-outline-1":"stroke:white;","X .select-outline-2":"stroke:black;stroke-dasharray:2px 2px;",Y:"font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;","Y p":"margin:0;","Y .notifier-note":"min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;","Y .notifier-close":"color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;","Y .notifier-close:hover":"color:#444;text-decoration:none;cursor:pointer;"};for(var i in a){var o=i.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");n.addStyleRule(o,a[i])}},{"../src/lib":163}],2:[function(t,e,r){"use strict";e.exports={undo:{width:857.1,height:1e3,path:"m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z",transform:"matrix(1 0 0 -1 0 850)"},home:{width:928.6,height:1e3,path:"m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z",transform:"matrix(1 0 0 -1 0 850)"},"camera-retro":{width:1e3,height:1e3,path:"m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z",transform:"matrix(1 0 0 -1 0 850)"},zoombox:{width:1e3,height:1e3,path:"m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z",transform:"matrix(1 0 0 -1 0 850)"},pan:{width:1e3,height:1e3,path:"m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z",transform:"matrix(1 0 0 -1 0 850)"},zoom_plus:{width:1e3,height:1e3,path:"m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z",transform:"matrix(1 0 0 -1 0 850)"},zoom_minus:{width:1e3,height:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",transform:"matrix(1 0 0 -1 0 850)"},autoscale:{width:1e3,height:1e3,path:"m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z",transform:"matrix(1 0 0 -1 0 850)"},tooltip_basic:{width:1500,height:1e3,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",transform:"matrix(1 0 0 -1 0 850)"},tooltip_compare:{width:1125,height:1e3,path:"m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z",transform:"matrix(1 0 0 -1 0 850)"},plotlylogo:{width:1542,height:1e3,path:"m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z",transform:"matrix(1 0 0 -1 0 850)"},"z-axis":{width:1e3,height:1e3,path:"m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z",transform:"matrix(1 0 0 -1 0 850)"},"3d_rotate":{width:1e3,height:1e3,path:"m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z",transform:"matrix(1 0 0 -1 0 850)"},camera:{width:1e3,height:1e3,path:"m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z",transform:"matrix(1 0 0 -1 0 850)"},movie:{width:1e3,height:1e3,path:"m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z",transform:"matrix(1 0 0 -1 0 850)"},question:{width:857.1,height:1e3,path:"m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z",transform:"matrix(1 0 0 -1 0 850)"},disk:{width:857.1,height:1e3,path:"m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z",transform:"matrix(1 0 0 -1 0 850)"},lasso:{width:1031,height:1e3,path:"m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z",transform:"matrix(1 0 0 -1 0 850)"},selectbox:{width:1e3,height:1e3,path:"m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z",transform:"matrix(1 0 0 -1 0 850)"},spikeline:{width:1e3,height:1e3,path:"M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z",transform:"matrix(1.5 0 0 -1.5 0 850)"}}},{}],3:[function(t,e,r){"use strict";e.exports=t("../src/traces/bar")},{"../src/traces/bar":261}],4:[function(t,e,r){"use strict";e.exports=t("../src/traces/candlestick")},{"../src/traces/candlestick":279}],5:[function(t,e,r){"use strict";e.exports=t("../src/core")},{"../src/core":148}],6:[function(t,e,r){"use strict";e.exports=t("../src/traces/histogram")},{"../src/traces/histogram":290}],7:[function(t,e,r){"use strict";var n=t("./core");n.register([t("./bar"),t("./histogram"),t("./pie"),t("./ohlc"),t("./candlestick")]),e.exports=n},{"./bar":3,"./candlestick":4,"./core":5,"./histogram":6,"./ohlc":8,"./pie":9}],8:[function(t,e,r){"use strict";e.exports=t("../src/traces/ohlc")},{"../src/traces/ohlc":296}],9:[function(t,e,r){"use strict";e.exports=t("../src/traces/pie")},{"../src/traces/pie":307}],10:[function(t,e,r){!function(){var t={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},a=this.document;function i(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(a)try{n(a.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(t,e){s.call(this,t,e+"")},l.setAttributeNS=function(t,e,r){c.call(this,t,e,r+"")},u.setProperty=function(t,e,r){f.call(this,t,e+"",r)}}function d(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}function p(t){return null===t?NaN:+t}function h(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n<a;){var i=n+a>>>1;t(e[i],r)<0?n=i+1:a=i}return n},right:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n<a;){var i=n+a>>>1;t(e[i],r)>0?a=i:n=i+1}return n}}}t.ascending=d,t.descending=function(t,e){return e<t?-1:e>t?1:e>=t?0:NaN},t.min=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a<i;)if(null!=(n=t[a])&&n>=n){r=n;break}for(;++a<i;)null!=(n=t[a])&&r>n&&(r=n)}else{for(;++a<i;)if(null!=(n=e.call(t,t[a],a))&&n>=n){r=n;break}for(;++a<i;)null!=(n=e.call(t,t[a],a))&&r>n&&(r=n)}return r},t.max=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a<i;)if(null!=(n=t[a])&&n>=n){r=n;break}for(;++a<i;)null!=(n=t[a])&&n>r&&(r=n)}else{for(;++a<i;)if(null!=(n=e.call(t,t[a],a))&&n>=n){r=n;break}for(;++a<i;)null!=(n=e.call(t,t[a],a))&&n>r&&(r=n)}return r},t.extent=function(t,e){var r,n,a,i=-1,o=t.length;if(1===arguments.length){for(;++i<o;)if(null!=(n=t[i])&&n>=n){r=a=n;break}for(;++i<o;)null!=(n=t[i])&&(r>n&&(r=n),a<n&&(a=n))}else{for(;++i<o;)if(null!=(n=e.call(t,t[i],i))&&n>=n){r=a=n;break}for(;++i<o;)null!=(n=e.call(t,t[i],i))&&(r>n&&(r=n),a<n&&(a=n))}return[r,a]},t.sum=function(t,e){var r,n=0,a=t.length,i=-1;if(1===arguments.length)for(;++i<a;)h(r=+t[i])&&(n+=r);else for(;++i<a;)h(r=+e.call(t,t[i],i))&&(n+=r);return n},t.mean=function(t,e){var r,n=0,a=t.length,i=-1,o=a;if(1===arguments.length)for(;++i<a;)h(r=p(t[i]))?n+=r:--o;else for(;++i<a;)h(r=p(e.call(t,t[i],i)))?n+=r:--o;if(o)return n/o},t.quantile=function(t,e){var r=(t.length-1)*e+1,n=Math.floor(r),a=+t[n-1],i=r-n;return i?a+i*(t[n]-a):a},t.median=function(e,r){var n,a=[],i=e.length,o=-1;if(1===arguments.length)for(;++o<i;)h(n=p(e[o]))&&a.push(n);else for(;++o<i;)h(n=p(r.call(e,e[o],o)))&&a.push(n);if(a.length)return t.quantile(a.sort(d),.5)},t.variance=function(t,e){var r,n,a=t.length,i=0,o=0,l=-1,s=0;if(1===arguments.length)for(;++l<a;)h(r=p(t[l]))&&(o+=(n=r-i)*(r-(i+=n/++s)));else for(;++l<a;)h(r=p(e.call(t,t[l],l)))&&(o+=(n=r-i)*(r-(i+=n/++s)));if(s>1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var y=g(d);function v(t){return t.length}t.bisectLeft=y.left,t.bisect=t.bisectRight=y.right,t.bisector=function(t){return g(1===t.length?function(e,r){return d(t(e),r)}:t)},t.shuffle=function(t,e,r){(i=arguments.length)<3&&(r=t.length,i<2&&(e=0));for(var n,a,i=r-e;i;)a=Math.random()*i--|0,n=t[i+e],t[i+e]=t[a+e],t[a+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],a=new Array(r<0?0:r);e<r;)a[e]=[n,n=t[++e]];return a},t.transpose=function(e){if(!(i=e.length))return[];for(var r=-1,n=t.min(e,v),a=new Array(n);++r<n;)for(var i,o=-1,l=a[r]=new Array(i);++o<i;)l[o]=e[o][r];return a},t.zip=function(){return t.transpose(arguments)},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},t.merge=function(t){for(var e,r,n,a=t.length,i=-1,o=0;++i<a;)o+=t[i].length;for(r=new Array(o);--a>=0;)for(e=(n=t[a]).length;--e>=0;)r[--o]=n[e];return r};var m=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,a=[],i=function(t){var e=1;for(;t*e%1;)e*=10;return e}(m(r)),o=-1;if(t*=i,e*=i,(r*=i)<0)for(;(n=t+r*++o)>e;)a.push(n/i);else for(;(n=t+r*++o)<e;)a.push(n/i);return a},t.map=function(t,e){var r=new b;if(t instanceof b)t.forEach(function(t,e){r.set(t,e)});else if(Array.isArray(t)){var n,a=-1,i=t.length;if(1===arguments.length)for(;++a<i;)r.set(a,t[a]);else for(;++a<i;)r.set(e.call(t,n=t[a],a),n)}else for(var o in t)r.set(o,t[o]);return r};var _="__proto__",w="\0";function k(t){return(t+="")===_||t[0]===w?w+t:t}function M(t){return(t+="")[0]===w?t.slice(1):t}function T(t){return k(t)in this._}function A(t){return(t=k(t))in this._&&delete this._[t]}function L(){var t=[];for(var e in this._)t.push(M(e));return t}function C(){var t=0;for(var e in this._)++t;return t}function S(){for(var t in this._)return!1;return!0}function O(){this._=Object.create(null)}function P(t){return t}function D(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function z(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=E.length;r<n;++r){var a=E[r]+e;if(a in t)return a}}x(b,{has:T,get:function(t){return this._[k(t)]},set:function(t,e){return this._[k(t)]=e},remove:A,keys:L,values:function(){var t=[];for(var e in this._)t.push(this._[e]);return t},entries:function(){var t=[];for(var e in this._)t.push({key:M(e),value:this._[e]});return t},size:C,empty:S,forEach:function(t){for(var e in this._)t.call(this,M(e),this._[e])}}),t.nest=function(){var e,r,n={},a=[],i=[];function o(t,i,l){if(l>=a.length)return r?r.call(n,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,p=i.length,h=a[l++],g=new b;++d<p;)(f=g.get(s=h(c=i[d])))?f.push(c):g.set(s,[c]);return t?(c=t(),u=function(e,r){c.set(e,o(t,r,l))}):(c={},u=function(e,r){c[e]=o(t,r,l)}),g.forEach(u),c}return n.map=function(t,e){return o(e,t,0)},n.entries=function(e){return function t(e,r){if(r>=a.length)return e;var n=[],o=i[r++];return e.forEach(function(e,a){n.push({key:e,values:t(a,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return a.push(t),n},n.sortKeys=function(t){return i[a.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new O;if(t)for(var r=0,n=t.length;r<n;++r)e.add(t[r]);return e},x(O,{has:T,add:function(t){return this._[k(t+="")]=!0,t},remove:A,values:L,size:C,empty:S,forEach:function(t){for(var e in this._)t.call(this,M(e))}}),t.behavior={},t.rebind=function(t,e){for(var r,n=1,a=arguments.length;++n<a;)t[r=arguments[n]]=D(t,e,e[r]);return t};var E=["webkit","ms","moz","Moz","o","O"];function I(){}function N(){}function R(t){var e=[],r=new b;function n(){for(var r,n=e,a=-1,i=n.length;++a<i;)(r=n[a].on)&&r.apply(this,arguments);return t}return n.on=function(n,a){var i,o=r.get(n);return arguments.length<2?o&&o.on:(o&&(o.on=null,e=e.slice(0,i=e.indexOf(o)).concat(e.slice(i+1)),r.remove(n)),a&&e.push(r.set(n,{on:a})),t)},n}function F(){t.event.preventDefault()}function j(){for(var e,r=t.event;e=r.sourceEvent;)r=e;return r}function B(e){for(var r=new N,n=0,a=arguments.length;++n<a;)r[arguments[n]]=R(r);return r.of=function(n,a){return function(i){try{var o=i.sourceEvent=t.event;i.target=e,t.event=i,r[i.type].apply(n,a)}finally{t.event=o}}},r}t.dispatch=function(){for(var t=new N,e=-1,r=arguments.length;++e<r;)t[arguments[e]]=R(t);return t},N.prototype.on=function(t,e){var r=t.indexOf("."),n="";if(r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(H,"\\$&")};var H=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function V(t){return q(t,X),t}var U=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},Y=function(t,e){var r=t.matches||t[z(t,"matchesSelector")];return(Y=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(U=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(t){return"function"==typeof t?t:function(){return U(t,this)}}function W(t){return"function"==typeof t?t:function(){return G(t,this)}}X.select=function(t){var e,r,n,a,i=[];t=Z(t);for(var o=-1,l=this.length;++o<l;){i.push(e=[]),e.parentNode=(n=this[o]).parentNode;for(var s=-1,c=n.length;++s<c;)(a=n[s])?(e.push(r=t.call(a,a.__data__,s,o)),r&&"__data__"in a&&(r.__data__=a.__data__)):e.push(null)}return V(i)},X.selectAll=function(t){var e,r,a=[];t=W(t);for(var i=-1,o=this.length;++i<o;)for(var l=this[i],s=-1,c=l.length;++s<c;)(r=l[s])&&(a.push(e=n(t.call(r,r.__data__,s,i))),e.parentNode=r);return V(a)};var Q="http://www.w3.org/1999/xhtml",J={svg:"http://www.w3.org/2000/svg",xhtml:Q,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function $(e,r){return e=t.ns.qualify(e),null==r?e.local?function(){this.removeAttributeNS(e.space,e.local)}:function(){this.removeAttribute(e)}:"function"==typeof r?e.local?function(){var t=r.apply(this,arguments);null==t?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,t)}:function(){var t=r.apply(this,arguments);null==t?this.removeAttribute(e):this.setAttribute(e,t)}:e.local?function(){this.setAttributeNS(e.space,e.local,r)}:function(){this.setAttribute(e,r)}}function K(t){return t.trim().replace(/\s+/g," ")}function tt(e){return new RegExp("(?:^|\\s+)"+t.requote(e)+"(?:\\s+|$)","g")}function et(t){return(t+"").trim().split(/^|\s+/)}function rt(t,e){var r=(t=et(t).map(nt)).length;return"function"==typeof e?function(){for(var n=-1,a=e.apply(this,arguments);++n<r;)t[n](this,a)}:function(){for(var n=-1;++n<r;)t[n](this,e)}}function nt(t){var e=tt(t);return function(r,n){if(a=r.classList)return n?a.add(t):a.remove(t);var a=r.getAttribute("class")||"";n?(e.lastIndex=0,e.test(a)||r.setAttribute("class",K(a+" "+t))):r.setAttribute("class",K(a.replace(e," ")))}}function at(t,e,r){return null==e?function(){this.style.removeProperty(t)}:"function"==typeof e?function(){var n=e.apply(this,arguments);null==n?this.style.removeProperty(t):this.style.setProperty(t,n,r)}:function(){this.style.setProperty(t,e,r)}}function it(t,e){return null==e?function(){delete this[t]}:"function"==typeof e?function(){var r=e.apply(this,arguments);null==r?delete this[t]:this[t]=r}:function(){this[t]=e}}function ot(e){return"function"==typeof e?e:(e=t.ns.qualify(e)).local?function(){return this.ownerDocument.createElementNS(e.space,e.local)}:function(){var t=this.ownerDocument,r=this.namespaceURI;return r===Q&&t.documentElement.namespaceURI===Q?t.createElement(e):t.createElementNS(r,e)}}function lt(){var t=this.parentNode;t&&t.removeChild(this)}function st(t){return{__data__:t}}function ct(t){return function(){return Y(this,t)}}function ut(t,e){for(var r=0,n=t.length;r<n;r++)for(var a,i=t[r],o=0,l=i.length;o<l;o++)(a=i[o])&&e(a,o,r);return t}function ft(t){return q(t,dt),t}t.ns={prefix:J,qualify:function(t){var e=t.indexOf(":"),r=t;return e>=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),J.hasOwnProperty(r)?{space:J[r],local:t}:t}},X.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each($(r,e[r]));return this}return this.each($(e,r))},X.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,a=-1;if(e=r.classList){for(;++a<n;)if(!e.contains(t[a]))return!1}else for(e=r.getAttribute("class");++a<n;)if(!tt(t[a]).test(e))return!1;return!0}for(e in t)this.each(rt(e,t[e]));return this}return this.each(rt(t,e))},X.style=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=""),t)this.each(at(r,t[r],e));return this}if(n<2){var a=this.node();return o(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(at(t,e,r))},X.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(it(e,t[e]));return this}return this.each(it(t,e))},X.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},X.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},X.append=function(t){return t=ot(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},X.insert=function(t,e){return t=ot(t),e=Z(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},X.remove=function(){return this.each(lt)},X.data=function(t,e){var r,n,a=-1,i=this.length;if(!arguments.length){for(t=new Array(i=(r=this[0]).length);++a<i;)(n=r[a])&&(t[a]=n.__data__);return t}function o(t,r){var n,a,i,o=t.length,u=r.length,f=Math.min(o,u),d=new Array(u),p=new Array(u),h=new Array(o);if(e){var g,y=new b,v=new Array(o);for(n=-1;++n<o;)(a=t[n])&&(y.has(g=e.call(a,a.__data__,n))?h[n]=a:y.set(g,a),v[n]=g);for(n=-1;++n<u;)(a=y.get(g=e.call(r,i=r[n],n)))?!0!==a&&(d[n]=a,a.__data__=i):p[n]=st(i),y.set(g,!0);for(n=-1;++n<o;)n in v&&!0!==y.get(v[n])&&(h[n]=t[n])}else{for(n=-1;++n<f;)a=t[n],i=r[n],a?(a.__data__=i,d[n]=a):p[n]=st(i);for(;n<u;++n)p[n]=st(r[n]);for(;n<o;++n)h[n]=t[n]}p.update=d,p.parentNode=d.parentNode=h.parentNode=t.parentNode,l.push(p),s.push(d),c.push(h)}var l=ft([]),s=V([]),c=V([]);if("function"==typeof t)for(;++a<i;)o(r=this[a],t.call(r,r.parentNode.__data__,a));else for(;++a<i;)o(r=this[a],t);return s.enter=function(){return l},s.exit=function(){return c},s},X.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")},X.filter=function(t){var e,r,n,a=[];"function"!=typeof t&&(t=ct(t));for(var i=0,o=this.length;i<o;i++){a.push(e=[]),e.parentNode=(r=this[i]).parentNode;for(var l=0,s=r.length;l<s;l++)(n=r[l])&&t.call(n,n.__data__,l,i)&&e.push(n)}return V(a)},X.order=function(){for(var t=-1,e=this.length;++t<e;)for(var r,n=this[t],a=n.length-1,i=n[a];--a>=0;)(r=n[a])&&(i&&i!==r.nextSibling&&i.parentNode.insertBefore(r,i),i=r);return this},X.sort=function(t){t=function(t){arguments.length||(t=d);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e<r;)this[e].sort(t);return this.order()},X.each=function(t){return ut(this,function(e,r,n){t.call(e,e.__data__,r,n)})},X.call=function(t){var e=n(arguments);return t.apply(e[0]=this,e),this},X.empty=function(){return!this.node()},X.node=function(){for(var t=0,e=this.length;t<e;t++)for(var r=this[t],n=0,a=r.length;n<a;n++){var i=r[n];if(i)return i}return null},X.size=function(){var t=0;return ut(this,function(){++t}),t};var dt=[];function pt(e,r,a){var i="__on"+e,o=e.indexOf("."),l=gt;o>0&&(e=e.slice(0,o));var s=ht.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=yt),o?r?function(){var t=l(r,n(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=r}:c:r?I:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(r=a.match(n)){var i=this[a];this.removeEventListener(r[1],i,i.$),delete this[a]}}}t.selection.enter=ft,t.selection.enter.prototype=dt,dt.append=X.append,dt.empty=X.empty,dt.node=X.node,dt.call=X.call,dt.size=X.size,dt.select=function(t){for(var e,r,n,a,i,o=[],l=-1,s=this.length;++l<s;){n=(a=this[l]).update,o.push(e=[]),e.parentNode=a.parentNode;for(var c=-1,u=a.length;++c<u;)(i=a[c])?(e.push(n[c]=r=t.call(a.parentNode,i.__data__,c,l)),r.__data__=i.__data__):e.push(null)}return V(o)},dt.insert=function(t,e){var r,n,a;return arguments.length<2&&(r=this,e=function(t,e,i){var o,l=r[i].update,s=l.length;for(i!=a&&(a=i,n=0),e>=n&&(n=e+1);!(o=l[n])&&++n<s;);return o}),X.insert.call(this,t,e)},t.select=function(t){var e;return"string"==typeof t?(e=[U(t,a)]).parentNode=a.documentElement:(e=[t]).parentNode=i(t),V([e])},t.selectAll=function(t){var e;return"string"==typeof t?(e=n(G(t,a))).parentNode=a.documentElement:(e=n(t)).parentNode=null,V([e])},X.on=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=!1),t)this.each(pt(r,t[r],e));return this}if(n<2)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(pt(t,e,r))};var ht=t.map({mouseenter:"mouseover",mouseleave:"mouseout"});function gt(e,r){return function(n){var a=t.event;t.event=n,r[0]=this.__data__;try{e.apply(this,r)}finally{t.event=a}}}function yt(t,e){var r=gt(t,e);return function(t){var e=t.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||r.call(this,t)}}a&&ht.forEach(function(t){"on"+t in a&&ht.remove(t)});var vt,mt=0;function xt(e){var r=".dragsuppress-"+ ++mt,n="click"+r,a=t.select(o(e)).on("touchmove"+r,F).on("dragstart"+r,F).on("selectstart"+r,F);if(null==vt&&(vt=!("onselectstart"in e)&&z(e.style,"userSelect")),vt){var l=i(e).style,s=l[vt];l[vt]="none"}return function(t){if(a.on(r,null),vt&&(l[vt]=s),t){var e=function(){a.on(n,null)};a.on(n,function(){F(),e()},!0),setTimeout(e,0)}}}t.mouse=function(t){return _t(t,j())};var bt=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;function _t(e,r){r.changedTouches&&(r=r.changedTouches[0]);var n=e.ownerSVGElement||e;if(n.createSVGPoint){var a=n.createSVGPoint();if(bt<0){var i=o(e);if(i.scrollX||i.scrollY){var l=(n=t.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important"))[0][0].getScreenCTM();bt=!(l.f||l.e),n.remove()}}return bt?(a.x=r.pageX,a.y=r.pageY):(a.x=r.clientX,a.y=r.clientY),[(a=a.matrixTransform(e.getScreenCTM().inverse())).x,a.y]}var s=e.getBoundingClientRect();return[r.clientX-s.left-e.clientLeft,r.clientY-s.top-e.clientTop]}function wt(){return t.event.changedTouches[0].identifier}t.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=j().changedTouches),e)for(var n,a=0,i=e.length;a<i;++a)if((n=e[a]).identifier===r)return _t(t,n)},t.behavior.drag=function(){var e=B(i,"drag","dragstart","dragend"),r=null,n=l(I,t.mouse,o,"mousemove","mouseup"),a=l(wt,t.touch,P,"touchmove","touchend");function i(){this.on("mousedown.drag",n).on("touchstart.drag",a)}function l(n,a,i,o,l){return function(){var s,c=t.event.target.correspondingElement||t.event.target,u=this.parentNode,f=e.of(this,arguments),d=0,p=n(),h=".drag"+(null==p?"":"-"+p),g=t.select(i(c)).on(o+h,function(){var t,e,r=a(u,p);if(!r)return;t=r[0]-v[0],e=r[1]-v[1],d|=t|e,v=r,f({type:"drag",x:r[0]+s[0],y:r[1]+s[1],dx:t,dy:e})}).on(l+h,function(){if(!a(u,p))return;g.on(o+h,null).on(l+h,null),y(d),f({type:"dragend"})}),y=xt(c),v=a(u,p);s=r?[(s=r.apply(this,arguments)).x-v[0],s.y-v[1]]:[0,0],f({type:"dragstart"})}}return i.origin=function(t){return arguments.length?(r=t,i):r},t.rebind(i,e,"on")},t.touches=function(t,e){return arguments.length<2&&(e=j().touches),e?n(e).map(function(e){var r=_t(t,e);return r.identifier=e.identifier,r}):[]};var kt=1e-6,Mt=kt*kt,Tt=Math.PI,At=2*Tt,Lt=At-kt,Ct=Tt/2,St=Tt/180,Ot=180/Tt;function Pt(t){return t>0?1:t<0?-1:0}function Dt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function zt(t){return t>1?0:t<-1?Tt:Math.acos(t)}function Et(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function It(t){return((t=Math.exp(t))+1/t)/2}function Nt(t){return(t=Math.sin(t/2))*t}var Rt=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,a=t[0],i=t[1],o=t[2],l=e[0],s=e[1],c=e[2],u=l-a,f=s-i,d=u*u+f*f;if(d<Mt)n=Math.log(c/o)/Rt,r=function(t){return[a+t*u,i+t*f,o*Math.exp(Rt*t*n)]};else{var p=Math.sqrt(d),h=(c*c-o*o+4*d)/(2*o*2*p),g=(c*c-o*o-4*d)/(2*c*2*p),y=Math.log(Math.sqrt(h*h+1)-h),v=Math.log(Math.sqrt(g*g+1)-g);n=(v-y)/Rt,r=function(t){var e,r=t*n,l=It(y),s=o/(2*p)*(l*(e=Rt*r+y,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(y));return[a+s*u,i+s*f,o*l/It(Rt*r+y)]}}return r.duration=1e3*n,r},t.behavior.zoom=function(){var e,r,n,i,l,s,c,u,f,d={x:0,y:0,k:1},p=[960,500],h=Bt,g=250,y=0,v="mousedown.zoom",m="mousemove.zoom",x="mouseup.zoom",b="touchstart.zoom",_=B(w,"zoomstart","zoom","zoomend");function w(t){t.on(v,P).on(jt+".zoom",z).on("dblclick.zoom",E).on(b,D)}function k(t){return[(t[0]-d.x)/d.k,(t[1]-d.y)/d.k]}function M(t){d.k=Math.max(h[0],Math.min(h[1],t))}function T(t,e){e=function(t){return[t[0]*d.k+d.x,t[1]*d.k+d.y]}(e),d.x+=t[0]-e[0],d.y+=t[1]-e[1]}function A(e,n,a,i){e.__chart__={x:d.x,y:d.y,k:d.k},M(Math.pow(2,i)),T(r=n,a),e=t.select(e),g>0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(t){return(t-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(t){return(t-d.y)/d.k}).map(u.invert))}function C(t){y++||t({type:"zoomstart"})}function S(t){L(),t({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function O(t){--y||(t({type:"zoomend"}),r=null)}function P(){var e=this,r=_.of(e,arguments),n=0,a=t.select(o(e)).on(m,function(){n=1,T(t.mouse(e),i),S(r)}).on(x,function(){a.on(m,null).on(x,null),l(n),O(r)}),i=k(t.mouse(e)),l=xt(e);fl.call(e),C(r)}function D(){var e,r=this,n=_.of(r,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(r),p=xt(r);function h(){var n=t.touches(r);return e=d.k,n.forEach(function(t){t.identifier in a&&(a[t.identifier]=k(t))}),n}function g(){var e=t.event.target;t.select(e).on(s,y).on(c,m),u.push(e);for(var n=t.event.changedTouches,o=0,f=n.length;o<f;++o)a[n[o].identifier]=null;var p=h(),g=Date.now();if(1===p.length){if(g-l<500){var v=p[0];A(r,v,a[v.identifier],Math.floor(Math.log(d.k)/Math.LN2)+1),F()}l=g}else if(p.length>1){v=p[0];var x=p[1],b=v[0]-x[0],_=v[1]-x[1];i=b*b+_*_}}function y(){var o,s,c,u,f=t.touches(r);fl.call(r);for(var d=0,p=f.length;d<p;++d,u=null)if(c=f[d],u=a[c.identifier]){if(s)break;o=c,s=u}if(u){var h=(h=c[0]-o[0])*h+(h=c[1]-o[1])*h,g=i&&Math.sqrt(h/i);o=[(o[0]+c[0])/2,(o[1]+c[1])/2],s=[(s[0]+u[0])/2,(s[1]+u[1])/2],M(g*e)}l=null,T(o,s),S(n)}function m(){if(t.event.touches.length){for(var e=t.event.changedTouches,r=0,i=e.length;r<i;++r)delete a[e[r].identifier];for(var l in a)return void h()}t.selectAll(u).on(o,null),f.on(v,P).on(b,D),p(),O(n)}g(),C(n),f.on(v,null).on(b,g)}function z(){var a=_.of(this,arguments);i?clearTimeout(i):(fl.call(this),e=k(r=n||t.mouse(this)),C(a)),i=setTimeout(function(){i=null,O(a)},50),F(),M(Math.pow(2,.002*Ft())*d.k),T(r,e),S(a)}function E(){var e=t.mouse(this),r=Math.log(d.k)/Math.LN2;A(this,e,k(e),t.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}return jt||(jt="onwheel"in a?(Ft=function(){return-t.event.deltaY*(t.event.deltaMode?120:1)},"wheel"):"onmousewheel"in a?(Ft=function(){return t.event.wheelDelta},"mousewheel"):(Ft=function(){return-t.event.detail},"MozMousePixelScroll")),w.event=function(e){e.each(function(){var e=_.of(this,arguments),n=d;hl?t.select(this).transition().each("start.zoom",function(){d=this.__chart__||{x:0,y:0,k:1},C(e)}).tween("zoom:zoom",function(){var a=p[0],i=p[1],o=r?r[0]:a/2,l=r?r[1]:i/2,s=t.interpolateZoom([(o-d.x)/d.k,(l-d.y)/d.k,a/d.k],[(o-n.x)/n.k,(l-n.y)/n.k,a/n.k]);return function(t){var r=s(t),n=a/r[2];this.__chart__=d={x:o-r[0]*n,y:l-r[1]*n,k:n},S(e)}}).each("interrupt.zoom",function(){O(e)}).each("end.zoom",function(){O(e)}):(this.__chart__=d,C(e),S(e),O(e))})},w.translate=function(t){return arguments.length?(d={x:+t[0],y:+t[1],k:d.k},L(),w):[d.x,d.y]},w.scale=function(t){return arguments.length?(d={x:d.x,y:d.y,k:null},M(+t),L(),w):d.k},w.scaleExtent=function(t){return arguments.length?(h=null==t?Bt:[+t[0],+t[1]],w):h},w.center=function(t){return arguments.length?(n=t&&[+t[0],+t[1]],w):n},w.size=function(t){return arguments.length?(p=t&&[+t[0],+t[1]],w):p},w.duration=function(t){return arguments.length?(g=+t,w):g},w.x=function(t){return arguments.length?(c=t,s=t.copy(),d={x:0,y:0,k:1},w):c},w.y=function(t){return arguments.length?(f=t,u=t.copy(),d={x:0,y:0,k:1},w):f},t.rebind(w,_,"on")};var Ft,jt,Bt=[0,1/0];function Ht(){}function qt(t,e,r){return this instanceof qt?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof qt?new qt(t.h,t.s,t.l):ue(""+t,fe,qt):new qt(t,e,r)}t.color=Ht,Ht.prototype.toString=function(){return this.rgb()+""},t.hsl=qt;var Vt=qt.prototype=new Ht;function Ut(t,e,r){var n,a;function i(t){return Math.round(255*function(t){return t>360?t-=360:t<0&&(t+=360),t<60?n+(a-n)*t/60:t<180?a:t<240?n+(a-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(a=r<=.5?r*(1+e):r+e-r*e),new ie(i(t+120),i(t),i(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Zt?e.l:(e=de((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}Vt.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,this.l/t)},Vt.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,t*this.l)},Vt.rgb=function(){return Ut(this.h,this.s,this.l)},t.hcl=Gt;var Yt=Gt.prototype=new Ht;function Xt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Zt(r,Math.cos(t*=St)*e,Math.sin(t)*e)}function Zt(t,e,r){return this instanceof Zt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Zt?new Zt(t.l,t.a,t.b):t instanceof Gt?Xt(t.h,t.c,t.l):de((t=ie(t)).r,t.g,t.b):new Zt(t,e,r)}Yt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Wt*(arguments.length?t:1)))},Yt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Wt*(arguments.length?t:1)))},Yt.rgb=function(){return Xt(this.h,this.c,this.l).rgb()},t.lab=Zt;var Wt=18,Qt=.95047,Jt=1,$t=1.08883,Kt=Zt.prototype=new Ht;function te(t,e,r){var n=(t+16)/116,a=n+e/500,i=n-r/200;return new ie(ae(3.2404542*(a=re(a)*Qt)-1.5371385*(n=re(n)*Jt)-.4985314*(i=re(i)*$t)),ae(-.969266*a+1.8760108*n+.041556*i),ae(.0556434*a-.2040259*n+1.0572252*i))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Ot,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ae(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ie(t,e,r){return this instanceof ie?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ie?new ie(t.r,t.g,t.b):ue(""+t,ie,Ut):new ie(t,e,r)}function oe(t){return new ie(t>>16,t>>8&255,255&t)}function le(t){return oe(t)+""}Kt.brighter=function(t){return new Zt(Math.min(100,this.l+Wt*(arguments.length?t:1)),this.a,this.b)},Kt.darker=function(t){return new Zt(Math.max(0,this.l-Wt*(arguments.length?t:1)),this.a,this.b)},Kt.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ie;var se=ie.prototype=new Ht;function ce(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ue(t,e,r){var n,a,i,o=0,l=0,s=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(a=n[2].split(","),n[1]){case"hsl":return r(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return e(he(a[0]),he(a[1]),he(a[2]))}return(i=ge.get(t))?e(i.r,i.g,i.b):(null==t||"#"!==t.charAt(0)||isNaN(i=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===t.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),e(o,l,s))}function fe(t,e,r){var n,a,i=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),n=t==o?(e-r)/l+(e<r?6:0):e==o?(r-t)/l+2:(t-e)/l+4,n*=60):(n=NaN,a=s>0&&s<1?0:n),new qt(n,a,s)}function de(t,e,r){var n=ne((.4124564*(t=pe(t))+.3575761*(e=pe(e))+.1804375*(r=pe(r)))/Qt),a=ne((.2126729*t+.7151522*e+.072175*r)/Jt);return Zt(116*a-16,500*(n-a),200*(a-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function pe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function he(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}se.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,a=30;return e||r||n?(e&&e<a&&(e=a),r&&r<a&&(r=a),n&&n<a&&(n=a),new ie(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new ie(a,a,a)},se.darker=function(t){return new ie((t=Math.pow(.7,arguments.length?t:1))*this.r,t*this.g,t*this.b)},se.hsl=function(){return fe(this.r,this.g,this.b)},se.toString=function(){return"#"+ce(this.r)+ce(this.g)+ce(this.b)};var ge=t.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});function ye(t){return"function"==typeof t?t:function(){return t}}function ve(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),me(e,r,t,n)}}function me(e,r,a,i){var o={},l=t.dispatch("beforesend","progress","load","error"),s={},c=new XMLHttpRequest,u=null;function f(){var t,e=c.status;if(!e&&function(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}(c)||e>=200&&e<300||304===e){try{t=a.call(o,c)}catch(t){return void l.error.call(o,t)}l.load.call(o,t)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var r=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(u=t,o):u},o.response=function(t){return a=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(t,n,a){if(2===arguments.length&&"function"==typeof n&&(a=n,n=null),c.open(t,e,!0),null==r||"accept"in s||(s.accept=r+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=r&&c.overrideMimeType&&c.overrideMimeType(r),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(t){a(null,t)}),l.beforesend.call(o,c),c.send(null==n?null:n),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(i))}ge.forEach(function(t,e){ge.set(t,oe(e))}),t.functor=ye,t.xhr=ve(P),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function a(t,r,n){arguments.length<3&&(n=r,r=null);var a=me(t,e,null==r?i:o(r),n);return a.row=function(t){return arguments.length?a.response(null==(r=t)?i:o(t)):r},a}function i(t){return a.parse(t.responseText)}function o(t){return function(e){return a.parse(e.responseText,t)}}function l(e){return e.map(s).join(t)}function s(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return a.parse=function(t,e){var r;return a.parseRows(t,function(t,n){if(r)return r(t,n-1);var a=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(a(t),r)}:a})},a.parseRows=function(t,e){var r,a,i={},o={},l=[],s=t.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++<s;)if(34===t.charCodeAt(r)){if(34!==t.charCodeAt(r+1))break;++r}return c=r+2,13===(l=t.charCodeAt(r+1))?(a=!0,10===t.charCodeAt(r+2)&&++c):10===l&&(a=!0),t.slice(e+1,r).replace(/""/g,'"')}for(;c<s;){var l,u=1;if(10===(l=t.charCodeAt(c++)))a=!0;else if(13===l)a=!0,10===t.charCodeAt(c)&&(++c,++u);else if(l!==n)continue;return t.slice(e,c-u)}return t.slice(e)}for(;(r=f())!==o;){for(var d=[];r!==i&&r!==o;)d.push(r),r=f();e&&null==(d=e(d,u++))||l.push(d)}return l},a.format=function(e){if(Array.isArray(e[0]))return a.formatRows(e);var r=new O,n=[];return e.forEach(function(t){for(var e in t)r.has(e)||n.push(r.add(e))}),[n.map(s).join(t)].concat(e.map(function(e){return n.map(function(t){return s(e[t])}).join(t)})).join("\n")},a.formatRows=function(t){return t.map(l).join("\n")},a},t.csv=t.dsv(",","text/csv"),t.tsv=t.dsv("\t","text/tab-separated-values");var xe,be,_e,we,ke=this[z(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};function Me(t,e,r){var n=arguments.length;n<2&&(e=0),n<3&&(r=Date.now());var a={c:t,t:r+e,n:null};return be?be.n=a:xe=a,be=a,_e||(we=clearTimeout(we),_e=1,ke(Te)),a}function Te(){var t=Ae(),e=Le()-t;e>24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),_e=0):(_e=1,ke(Te))}function Ae(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Le(){for(var t,e=xe,r=1/0;e;)e.c?(e.t<r&&(r=e.t),e=(t=e).n):e=t?t.n=e.n:xe=e.n;return be=t,r}function Ce(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}t.timer=function(){Me.apply(this,arguments)},t.timer.flush=function(){Ae(),Le()},t.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var Se=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(function(t,e){var r=Math.pow(10,3*m(8-e));return{scale:e>8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ce(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Se[8+n/3]};var Oe=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pe=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Ce(e,r))).toFixed(Math.max(0,Math.min(20,Ce(e*(1+1e-15),r))))}});function De(t){return t+""}var ze=t.time={},Ee=Date;function Ie(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Ie.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){Ne.setUTCDate.apply(this._,arguments)},setDay:function(){Ne.setUTCDay.apply(this._,arguments)},setFullYear:function(){Ne.setUTCFullYear.apply(this._,arguments)},setHours:function(){Ne.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Ne.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Ne.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Ne.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Ne.setUTCSeconds.apply(this._,arguments)},setTime:function(){Ne.setTime.apply(this._,arguments)}};var Ne=Date.prototype;function Re(t,e,r){function n(e){var r=t(e),n=i(r,1);return e-r<n-e?r:n}function a(r){return e(r=t(new Ee(r-1)),1),r}function i(t,r){return e(t=new Ee(+t),r),t}function o(t,n,i){var o=a(t),l=[];if(i>1)for(;o<n;)r(o)%i||l.push(new Date(+o)),e(o,1);else for(;o<n;)l.push(new Date(+o)),e(o,1);return l}t.floor=t,t.round=n,t.ceil=a,t.offset=i,t.range=o;var l=t.utc=Fe(t);return l.floor=l,l.round=Fe(n),l.ceil=Fe(a),l.offset=Fe(i),l.range=function(t,e,r){try{Ee=Ie;var n=new Ie;return n._=t,o(n,e,r)}finally{Ee=Date}},t}function Fe(t){return function(e,r){try{Ee=Ie;var n=new Ie;return n._=e,t(n,r)._}finally{Ee=Date}}}ze.year=Re(function(t){return(t=ze.day(t)).setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),ze.years=ze.year.range,ze.years.utc=ze.year.utc.range,ze.day=Re(function(t){var e=new Ee(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),ze.days=ze.day.range,ze.days.utc=ze.day.utc.range,ze.dayOfYear=function(t){var e=ze.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=ze[t]=Re(function(t){return(t=ze.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=ze.year(t).getDay();return Math.floor((ze.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});ze[t+"s"]=r.range,ze[t+"s"].utc=r.utc.range,ze[t+"OfYear"]=function(t){var r=ze.year(t).getDay();return Math.floor((ze.dayOfYear(t)+(r+e)%7)/7)}}),ze.week=ze.sunday,ze.weeks=ze.sunday.range,ze.weeks.utc=ze.sunday.utc.range,ze.weekOfYear=ze.sundayOfYear;var je={"-":"",_:" ",0:"0"},Be=/^\s*\d+/,He=/^%/;function qe(t,e,r){var n=t<0?"-":"",a=(n?-t:t)+"",i=a.length;return n+(i<r?new Array(r-i+1).join(e)+a:a)}function Ve(e){return new RegExp("^(?:"+e.map(t.requote).join("|")+")","i")}function Ue(t){for(var e=new b,r=-1,n=t.length;++r<n;)e.set(t[r].toLowerCase(),r);return e}function Ge(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function Ye(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r));return n?(t.U=+n[0],r+n[0].length):-1}function Xe(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r));return n?(t.W=+n[0],r+n[0].length):-1}function Ze(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function We(t,e,r){Be.lastIndex=0;var n,a=Be.exec(e.slice(r,r+2));return a?(t.y=(n=+a[0])+(n>68?1900:2e3),r+a[0].length):-1}function Qe(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Je(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Ke(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ar(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=m(e)/60|0,a=m(e)%60;return r+qe(n,"0",2)+qe(a,"0",2)}function ir(t,e,r){He.lastIndex=0;var n=He.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r<e;)t[r][0]=this(t[r][0]);return function(e){for(var r=0,n=t[r];!n[1](e);)n=t[++r];return n[0](e)}}t.locale=function(e){return{numberFormat:function(e){var r=e.decimal,n=e.thousands,a=e.grouping,i=e.currency,o=a&&n?function(t,e){for(var r=t.length,i=[],o=0,l=a[0],s=0;r>0&&l>0&&(s+l+1>e&&(l=Math.max(1,e-s)),i.push(t.substring(r-=l,r+l)),!((s+=l+1)>e));)l=a[o=(o+1)%a.length];return i.reverse().join(n)}:P;return function(e){var n=Oe.exec(e),a=n[1]||" ",l=n[2]||">",s=n[3]||"-",c=n[4]||"",u=n[5],f=+n[6],d=n[7],p=n[8],h=n[9],g=1,y="",v="",m=!1,x=!0;switch(p&&(p=+p.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),h){case"n":d=!0,h="g";break;case"%":g=100,v="%",h="f";break;case"p":g=100,v="%",h="r";break;case"b":case"o":case"x":case"X":"#"===c&&(y="0"+h.toLowerCase());case"c":x=!1;case"d":m=!0,p=0;break;case"s":g=-1,h="r"}"$"===c&&(y=i[0],v=i[1]),"r"!=h||p||(h="g"),null!=p&&("g"==h?p=Math.max(1,Math.min(21,p)):"e"!=h&&"f"!=h||(p=Math.max(0,Math.min(20,p)))),h=Pe.get(h)||De;var b=u&&d;return function(e){var n=v;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,p);e=c.scale(e),n=c.symbol+v}else e*=g;var _,w,k=(e=h(e,p)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=r+e.substring(k+1);!u&&d&&(_=o(_,1/0));var T=y.length+_.length+w.length+(b?0:i.length),A=T<f?new Array(T=f-T+1).join(a):"";return b&&(_=o(A+_,A.length?f-w.length:1/0)),i+=y,e=_+w,("<"===l?i+e+A:">"===l?A+i+e:"^"===l?A.substring(0,T>>=1)+i+e+A.substring(T):i+(b?e:A+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(t){var e=t.length;function r(r){for(var n,a,i,o=[],l=-1,s=0;++l<e;)37===t.charCodeAt(l)&&(o.push(t.slice(s,l)),null!=(a=je[n=t.charAt(++l)])&&(n=t.charAt(++l)),(i=_[n])&&(n=i(r,null==a?"e"===n?" ":"0":a)),o.push(n),s=l+1);return o.push(t.slice(s,l)),o.join("")}return r.parse=function(e){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null};if(f(r,t,e,0)!=e.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var n=null!=r.Z&&Ee!==Ie,a=new(n?Ie:Ee);return"j"in r?a.setFullYear(r.y,0,r.j):"W"in r||"U"in r?("w"in r||(r.w="W"in r?1:0),a.setFullYear(r.y,0,1),a.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(a.getDay()+5)%7:r.w+7*r.U-(a.getDay()+6)%7)):a.setFullYear(r.y,r.m,r.d),a.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L),n?a._:a},r.toString=function(){return t},r}function f(t,e,r,n){for(var a,i,o,l=0,s=e.length,c=r.length;l<s;){if(n>=c)return-1;if(37===(a=e.charCodeAt(l++))){if(o=e.charAt(l++),!(i=w[o in je?e.charAt(l++):o])||(n=i(t,r,n))<0)return-1}else if(a!=r.charCodeAt(n++))return-1}return n}u.utc=function(t){var e=u(t);function r(t){try{var r=new(Ee=Ie);return r._=t,e(r)}finally{Ee=Date}}return r.parse=function(t){try{Ee=Ie;var r=e.parse(t);return r&&r._}finally{Ee=Date}},r.toString=e.toString,r},u.multi=u.utc.multi=or;var d=t.map(),p=Ve(o),h=Ue(o),g=Ve(l),y=Ue(l),v=Ve(s),m=Ue(s),x=Ve(c),b=Ue(c);i.forEach(function(t,e){d.set(t.toLowerCase(),e)});var _={a:function(t){return l[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:u(r),d:function(t,e){return qe(t.getDate(),e,2)},e:function(t,e){return qe(t.getDate(),e,2)},H:function(t,e){return qe(t.getHours(),e,2)},I:function(t,e){return qe(t.getHours()%12||12,e,2)},j:function(t,e){return qe(1+ze.dayOfYear(t),e,3)},L:function(t,e){return qe(t.getMilliseconds(),e,3)},m:function(t,e){return qe(t.getMonth()+1,e,2)},M:function(t,e){return qe(t.getMinutes(),e,2)},p:function(t){return i[+(t.getHours()>=12)]},S:function(t,e){return qe(t.getSeconds(),e,2)},U:function(t,e){return qe(ze.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return qe(ze.mondayOfYear(t),e,2)},x:u(n),X:u(a),y:function(t,e){return qe(t.getFullYear()%100,e,2)},Y:function(t,e){return qe(t.getFullYear()%1e4,e,4)},Z:ar,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=y.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){p.lastIndex=0;var n=p.exec(e.slice(r));return n?(t.w=h.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){v.lastIndex=0;var n=v.exec(e.slice(r));return n?(t.m=m.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return f(t,_.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Ke,L:nr,m:Je,M:er,p:function(t,e,r){var n=d.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Ye,w:Ge,W:Xe,x:function(t,e,r){return f(t,_.x.toString(),e,r)},X:function(t,e,r){return f(t,_.X.toString(),e,r)},y:We,Y:Ze,Z:Qe,"%":ir};return u}(e)}};var lr=t.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function sr(){}t.format=lr.numberFormat,t.geo={},sr.prototype={s:0,t:0,add:function(t){ur(t,this.t,cr),ur(cr.s,this.s,this),this.s?this.t+=cr.t:this.s=cr.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cr=new sr;function ur(t,e,r){var n=r.s=t+e,a=n-t,i=n-a;r.t=t-i+(e-a)}function fr(t,e){t&&pr.hasOwnProperty(t.type)&&pr[t.type](t,e)}t.geo.stream=function(t,e){t&&dr.hasOwnProperty(t.type)?dr[t.type](t,e):fr(t,e)};var dr={Feature:function(t,e){fr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,a=r.length;++n<a;)fr(r[n].geometry,e)}},pr={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var r=t.coordinates,n=-1,a=r.length;++n<a;)t=r[n],e.point(t[0],t[1],t[2])},LineString:function(t,e){hr(t.coordinates,e,0)},MultiLineString:function(t,e){for(var r=t.coordinates,n=-1,a=r.length;++n<a;)hr(r[n],e,0)},Polygon:function(t,e){gr(t.coordinates,e)},MultiPolygon:function(t,e){for(var r=t.coordinates,n=-1,a=r.length;++n<a;)gr(r[n],e)},GeometryCollection:function(t,e){for(var r=t.geometries,n=-1,a=r.length;++n<a;)fr(r[n],e)}};function hr(t,e,r){var n,a=-1,i=t.length-r;for(e.lineStart();++a<i;)n=t[a],e.point(n[0],n[1],n[2]);e.lineEnd()}function gr(t,e){var r=-1,n=t.length;for(e.polygonStart();++r<n;)hr(t[r],e,1);e.polygonEnd()}t.geo.area=function(e){return yr=0,t.geo.stream(e,Sr),yr};var yr,vr,mr,xr,br,_r,wr,kr,Mr,Tr,Ar,Lr,Cr=new sr,Sr={sphere:function(){yr+=4*Tt},point:I,lineStart:I,lineEnd:I,polygonStart:function(){Cr.reset(),Sr.lineStart=Or},polygonEnd:function(){var t=2*Cr;yr+=t<0?4*Tt+t:t,Sr.lineStart=Sr.lineEnd=Sr.point=I}};function Or(){var t,e,r,n,a;function i(t,e){e=e*St/2+Tt/4;var i=(t*=St)-r,o=i>=0?1:-1,l=o*i,s=Math.cos(e),c=Math.sin(e),u=a*c,f=n*s+u*Math.cos(l),d=u*o*Math.sin(l);Cr.add(Math.atan2(d,f)),r=t,n=s,a=c}Sr.point=function(o,l){Sr.point=i,r=(t=o)*St,n=Math.cos(l=(e=l)*St/2+Tt/4),a=Math.sin(l)},Sr.lineEnd=function(){i(t,e)}}function Pr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Dr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function zr(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Er(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Ir(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Nr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Rr(t){return[Math.atan2(t[1],t[0]),Et(t[2])]}function Fr(t,e){return m(t[0]-e[0])<kt&&m(t[1]-e[1])<kt}t.geo.bounds=function(){var e,r,n,a,i,o,l,s,c,u,f,d={point:p,lineStart:g,lineEnd:y,polygonStart:function(){d.point=v,d.lineStart=x,d.lineEnd=b,c=0,Sr.polygonStart()},polygonEnd:function(){Sr.polygonEnd(),d.point=p,d.lineStart=g,d.lineEnd=y,Cr<0?(e=-(n=180),r=-(a=90)):c>kt?a=90:c<-kt&&(r=-90),f[0]=e,f[1]=n}};function p(t,i){u.push(f=[e=t,n=t]),i<r&&(r=i),i>a&&(a=i)}function h(t,o){var l=Pr([t*St,o*St]);if(s){var c=zr(s,l),u=zr([c[1],-c[0],0],c);Nr(u),u=Rr(u);var f=t-i,d=f>0?1:-1,h=u[0]*Ot*d,g=m(f)>180;if(g^(d*i<h&&h<d*t))(y=u[1]*Ot)>a&&(a=y);else if(g^(d*i<(h=(h+360)%360-180)&&h<d*t)){var y;(y=-u[1]*Ot)<r&&(r=y)}else o<r&&(r=o),o>a&&(a=o);g?t<i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(t<e&&(e=t),t>n&&(n=t)):t>i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else p(t,o);s=l,i=t}function g(){d.point=h}function y(){f[0]=e,f[1]=n,d.point=p,s=null}function v(t,e){if(s){var r=t-i;c+=m(r)>180?r+(r>0?360:-360):r}else o=t,l=e;Sr.point(t,e),h(t,e)}function x(){Sr.lineStart()}function b(){v(o,l),Sr.lineEnd(),m(c)>kt&&(e=-(n=180)),f[0]=e,f[1]=n,s=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function k(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}return function(i){if(a=n=-(e=r=1/0),u=[],t.geo.stream(i,d),c=u.length){u.sort(w);for(var o=1,l=[g=u[0]];o<c;++o)k((p=u[o])[0],g)||k(p[1],g)?(_(g[0],p[1])>_(g[0],g[1])&&(g[1]=p[1]),_(p[0],g[1])>_(g[0],g[1])&&(g[0]=p[0])):l.push(g=p);for(var s,c,p,h=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=p,++o)p=l[o],(s=_(g[1],p[0]))>h&&(h=s,e=p[0],n=g[1])}return u=f=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,a]]}}(),t.geo.centroid=function(e){vr=mr=xr=br=_r=wr=kr=Mr=Tr=Ar=Lr=0,t.geo.stream(e,jr);var r=Tr,n=Ar,a=Lr,i=r*r+n*n+a*a;return i<Mt&&(r=wr,n=kr,a=Mr,mr<kt&&(r=xr,n=br,a=_r),(i=r*r+n*n+a*a)<Mt)?[NaN,NaN]:[Math.atan2(n,r)*Ot,Et(a/Math.sqrt(i))*Ot]};var jr={sphere:I,point:Br,lineStart:qr,lineEnd:Vr,polygonStart:function(){jr.lineStart=Ur},polygonEnd:function(){jr.lineStart=qr}};function Br(t,e){t*=St;var r=Math.cos(e*=St);Hr(r*Math.cos(t),r*Math.sin(t),Math.sin(e))}function Hr(t,e,r){xr+=(t-xr)/++vr,br+=(e-br)/vr,_r+=(r-_r)/vr}function qr(){var t,e,r;function n(n,a){n*=St;var i=Math.cos(a*=St),o=i*Math.cos(n),l=i*Math.sin(n),s=Math.sin(a),c=Math.atan2(Math.sqrt((c=e*s-r*l)*c+(c=r*o-t*s)*c+(c=t*l-e*o)*c),t*o+e*l+r*s);mr+=c,wr+=c*(t+(t=o)),kr+=c*(e+(e=l)),Mr+=c*(r+(r=s)),Hr(t,e,r)}jr.point=function(a,i){a*=St;var o=Math.cos(i*=St);t=o*Math.cos(a),e=o*Math.sin(a),r=Math.sin(i),jr.point=n,Hr(t,e,r)}}function Vr(){jr.point=Br}function Ur(){var t,e,r,n,a;function i(t,e){t*=St;var i=Math.cos(e*=St),o=i*Math.cos(t),l=i*Math.sin(t),s=Math.sin(e),c=n*s-a*l,u=a*o-r*s,f=r*l-n*o,d=Math.sqrt(c*c+u*u+f*f),p=r*o+n*l+a*s,h=d&&-zt(p)/d,g=Math.atan2(d,p);Tr+=h*c,Ar+=h*u,Lr+=h*f,mr+=g,wr+=g*(r+(r=o)),kr+=g*(n+(n=l)),Mr+=g*(a+(a=s)),Hr(r,n,a)}jr.point=function(o,l){t=o,e=l,jr.point=i,o*=St;var s=Math.cos(l*=St);r=s*Math.cos(o),n=s*Math.sin(o),a=Math.sin(l),Hr(r,n,a)},jr.lineEnd=function(){i(t,e),jr.lineEnd=Vr,jr.point=Br}}function Gr(t,e){function r(r,n){return r=t(r,n),e(r[0],r[1])}return t.invert&&e.invert&&(r.invert=function(r,n){return(r=e.invert(r,n))&&t.invert(r[0],r[1])}),r}function Yr(){return!0}function Xr(t,e,r,n,a){var i=[],o=[];if(t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,r=t[0],n=t[e];if(Fr(r,n)){a.lineStart();for(var l=0;l<e;++l)a.point((r=t[l])[0],r[1]);a.lineEnd()}else{var s=new Wr(r,t,null,!0),c=new Wr(r,null,s,!1);s.o=c,i.push(s),o.push(c),s=new Wr(n,t,null,!1),c=new Wr(n,null,s,!0),s.o=c,i.push(s),o.push(c)}}}),o.sort(e),Zr(i),Zr(o),i.length){for(var l=0,s=r,c=o.length;l<c;++l)o[l].e=s=!s;for(var u,f,d=i[0];;){for(var p=d,h=!0;p.v;)if((p=p.n)===d)return;u=p.z,a.lineStart();do{if(p.v=p.o.v=!0,p.e){if(h)for(l=0,c=u.length;l<c;++l)a.point((f=u[l])[0],f[1]);else n(p.x,p.n.x,1,a);p=p.n}else{if(h)for(l=(u=p.p.z).length-1;l>=0;--l)a.point((f=u[l])[0],f[1]);else n(p.x,p.p.x,-1,a);p=p.p}u=(p=p.o).z,h=!h}while(!p.v);a.lineEnd()}}}function Zr(t){if(e=t.length){for(var e,r,n=0,a=t[0];++n<e;)a.n=r=t[n],r.p=a,a=r;a.n=r=t[0],r.p=a}}function Wr(t,e,r,n){this.x=t,this.z=e,this.o=r,this.e=n,this.v=!1,this.n=this.p=null}function Qr(e,r,n,a){return function(i,o){var l,s=r(o),c=i.invert(a[0],a[1]),u={point:f,lineStart:p,lineEnd:h,polygonStart:function(){u.point=b,u.lineStart=_,u.lineEnd=w,l=[],g=[]},polygonEnd:function(){u.point=f,u.lineStart=p,u.lineEnd=h,l=t.merge(l);var e=function(t,e){var r=t[0],n=t[1],a=[Math.sin(r),-Math.cos(r),0],i=0,o=0;Cr.reset();for(var l=0,s=e.length;l<s;++l){var c=e[l],u=c.length;if(u)for(var f=c[0],d=f[0],p=f[1]/2+Tt/4,h=Math.sin(p),g=Math.cos(p),y=1;;){y===u&&(y=0);var v=(t=c[y])[0],m=t[1]/2+Tt/4,x=Math.sin(m),b=Math.cos(m),_=v-d,w=_>=0?1:-1,k=w*_,M=k>Tt,T=h*x;if(Cr.add(Math.atan2(T*w*Math.sin(k),g*b+T*Math.cos(k))),i+=M?_+w*At:_,M^d>=r^v>=r){var A=zr(Pr(f),Pr(t));Nr(A);var L=zr(a,A);Nr(L);var C=(M^_>=0?-1:1)*Et(L[2]);(n>C||n===C&&(A[0]||A[1]))&&(o+=M^_>=0?1:-1)}if(!y++)break;d=v,h=x,g=b,f=t}}return(i<-kt||i<kt&&Cr<-kt)^1&o}(c,g);l.length?(x||(o.polygonStart(),x=!0),Xr(l,Kr,e,n,o)):e&&(x||(o.polygonStart(),x=!0),o.lineStart(),n(null,null,1,o),o.lineEnd()),x&&(o.polygonEnd(),x=!1),l=g=null},sphere:function(){o.polygonStart(),o.lineStart(),n(null,null,1,o),o.lineEnd(),o.polygonEnd()}};function f(t,r){var n=i(t,r);e(t=n[0],r=n[1])&&o.point(t,r)}function d(t,e){var r=i(t,e);s.point(r[0],r[1])}function p(){u.point=d,s.lineStart()}function h(){u.point=f,s.lineEnd()}var g,y,v=$r(),m=r(v),x=!1;function b(t,e){y.push([t,e]);var r=i(t,e);m.point(r[0],r[1])}function _(){m.lineStart(),y=[]}function w(){b(y[0][0],y[0][1]),m.lineEnd();var t,e=m.clean(),r=v.buffer(),n=r.length;if(y.pop(),g.push(y),y=null,n)if(1&e){var a,i=-1;if((n=(t=r[0]).length-1)>0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i<n;)o.point((a=t[i])[0],a[1]);o.lineEnd()}}else n>1&&2&e&&r.push(r.pop().concat(r.shift())),l.push(r.filter(Jr))}return u}}function Jr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:I,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Kr(t,e){return((t=t.x)[0]<0?t[1]-Ct-kt:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-kt:Ct-e[1])}var tn=Qr(Yr,function(t){var e,r=NaN,n=NaN,a=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(i,o){var l=i>0?Tt:-Tt,s=m(i-r);m(s-Tt)<kt?(t.point(r,n=(n+o)/2>0?Ct:-Ct),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),t.point(i,n),e=0):a!==l&&s>=Tt&&(m(r-a)<kt&&(r-=a*kt),m(i-l)<kt&&(i-=l*kt),n=function(t,e,r,n){var a,i,o=Math.sin(t-r);return m(o)>kt?Math.atan((Math.sin(e)*(i=Math.cos(n))*Math.sin(r)-Math.sin(n)*(a=Math.cos(e))*Math.sin(t))/(a*i*o)):(e+n)/2}(r,n,i,o),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),e=0),t.point(r=i,n=o),a=l},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var a;if(null==t)a=r*Ct,n.point(-Tt,a),n.point(0,a),n.point(Tt,a),n.point(Tt,0),n.point(Tt,-a),n.point(0,-a),n.point(-Tt,-a),n.point(-Tt,0),n.point(-Tt,a);else if(m(t[0]-e[0])>kt){var i=t[0]<e[0]?Tt:-Tt;a=r*i/2,n.point(-i,a),n.point(0,a),n.point(i,a)}else n.point(e[0],e[1])},[-Tt,-Tt/2]);function en(t,e,r,n){return function(a){var i,o=a.a,l=a.b,s=o.x,c=o.y,u=0,f=1,d=l.x-s,p=l.y-c;if(i=t-s,d||!(i>0)){if(i/=d,d<0){if(i<u)return;i<f&&(f=i)}else if(d>0){if(i>f)return;i>u&&(u=i)}if(i=r-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i<u)return;i<f&&(f=i)}if(i=e-c,p||!(i>0)){if(i/=p,p<0){if(i<u)return;i<f&&(f=i)}else if(p>0){if(i>f)return;i>u&&(u=i)}if(i=n-c,p||!(i<0)){if(i/=p,p<0){if(i>f)return;i>u&&(u=i)}else if(p>0){if(i<u)return;i<f&&(f=i)}return u>0&&(a.a={x:s+u*d,y:c+u*p}),f<1&&(a.b={x:s+f*d,y:c+f*p}),a}}}}}}var rn=1e9;function nn(e,r,n,a){return function(s){var c,u,f,d,p,h,g,y,v,m,x,b=s,_=$r(),w=en(e,r,n,a),k={point:A,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,v=!1,g=y=NaN},lineEnd:function(){c&&(L(d,p),h&&v&&_.rejoin(),c.push(_.buffer()));k.point=A,v&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var r=function(t){for(var e=0,r=u.length,n=t[1],a=0;a<r;++a)for(var i,o=1,l=u[a],s=l.length,c=l[0];o<s;++o)i=l[o],c[1]<=n?i[1]>n&&Dt(c,i,t)>0&&++e:i[1]<=n&&Dt(c,i,t)<0&&--e,c=i;return 0!==e}([e,a]),n=x&&r,i=c.length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Xr(c,o,r,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:n,u>1?a:r)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function T(t,i){return e<=t&&t<=n&&r<=i&&i<=a}function A(t,e){T(t,e)&&s.point(t,e)}function L(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(u&&f.push([t,e]),m)d=t,p=e,h=r,m=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&v)s.point(t,e);else{var n={a:{x:g,y:y},b:{x:t,y:e}};w(n)?(v||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),x=!1):r&&(s.lineStart(),s.point(t,e),x=!1)}g=t,y=e,v=r}return k};function i(t,a){return m(t[0]-e)<kt?a>0?0:3:m(t[0]-n)<kt?a>0?2:1:m(t[1]-r)<kt?a>0?1:0:a>0?3:2}function o(t,e){return l(t.x,e.x)}function l(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=Sn(t),a=n(e,r);return a.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},a}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,a=1+r*(2*n-r),i=Math.sqrt(a)/n;function o(t,e){var r=Math.sqrt(a-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),i-r*Math.cos(t)]}return o.invert=function(t,e){var r=i-e;return[Math.atan2(t,r)/n,Et((a-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,a,i,o={stream:function(t){return a&&(a.valid=!1),(a=i(t)).valid=!0,a},extent:function(l){return arguments.length?(i=nn(t=+l[0][0],e=+l[0][1],r=+l[1][0],n=+l[1][1]),a&&(a.valid=!1,a=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,r){e=[t,r]}};function c(t){var i=t[0],o=t[1];return e=null,r(i,o),e||(n(i,o),e)||a(i,o),e}return c.invert=function(t){var e=i.scale(),r=i.translate(),n=(t[0]-r[0])/e,a=(t[1]-r[1])/e;return(a>=.12&&a<.234&&n>=-.425&&n<-.214?o:a>=.166&&a<.234&&n>=-.214&&n<-.115?l:i).invert(t)},c.stream=function(t){var e=i.stream(t),r=o.stream(t),n=l.stream(t);return{point:function(t,a){e.point(t,a),r.point(t,a),n.point(t,a)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},c.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),l.precision(t),c):i.precision()},c.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),l.scale(t),c.translate(i.translate())):i.scale()},c.translate=function(t){if(!arguments.length)return i.translate();var e=i.scale(),u=+t[0],f=+t[1];return r=i.translate(t).clipExtent([[u-.455*e,f-.238*e],[u+.455*e,f+.238*e]]).stream(s).point,n=o.translate([u-.307*e,f+.201*e]).clipExtent([[u-.425*e+kt,f+.12*e+kt],[u-.214*e-kt,f+.234*e-kt]]).stream(s).point,a=l.translate([u-.205*e,f+.212*e]).clipExtent([[u-.214*e+kt,f+.166*e+kt],[u-.115*e-kt,f+.234*e-kt]]).stream(s).point,c},c.scale(1070)};var ln,sn,cn,un,fn,dn,pn={point:I,lineStart:I,lineEnd:I,polygonStart:function(){sn=0,pn.lineStart=hn},polygonEnd:function(){pn.lineStart=pn.lineEnd=pn.point=I,ln+=m(sn/2)}};function hn(){var t,e,r,n;function a(t,e){sn+=n*t-r*e,r=t,n=e}pn.point=function(i,o){pn.point=a,t=r=i,e=n=o},pn.lineEnd=function(){a(t,e)}}var gn={point:function(t,e){t<cn&&(cn=t);t>fn&&(fn=t);e<un&&(un=e);e>dn&&(dn=e)},lineStart:I,lineEnd:I,polygonStart:I,polygonEnd:I};function yn(){var t=vn(4.5),e=[],r={point:n,lineStart:function(){r.point=a},lineEnd:o,polygonStart:function(){r.lineEnd=l},polygonEnd:function(){r.lineEnd=o,r.point=n},pointRadius:function(e){return t=vn(e),r},result:function(){if(e.length){var t=e.join("");return e=[],t}}};function n(r,n){e.push("M",r,",",n,t)}function a(t,n){e.push("M",t,",",n),r.point=i}function i(t,r){e.push("L",t,",",r)}function o(){r.point=n}function l(){e.push("Z")}return r}function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,xn={point:bn,lineStart:_n,lineEnd:wn,polygonStart:function(){xn.lineStart=kn},polygonEnd:function(){xn.point=bn,xn.lineStart=_n,xn.lineEnd=wn}};function bn(t,e){xr+=t,br+=e,++_r}function _n(){var t,e;function r(r,n){var a=r-t,i=n-e,o=Math.sqrt(a*a+i*i);wr+=o*(t+r)/2,kr+=o*(e+n)/2,Mr+=o,bn(t=r,e=n)}xn.point=function(n,a){xn.point=r,bn(t=n,e=a)}}function wn(){xn.point=bn}function kn(){var t,e,r,n;function a(t,e){var a=t-r,i=e-n,o=Math.sqrt(a*a+i*i);wr+=o*(r+t)/2,kr+=o*(n+e)/2,Mr+=o,Tr+=(o=n*t-r*e)*(r+t),Ar+=o*(n+e),Lr+=3*o,bn(r=t,n=e)}xn.point=function(i,o){xn.point=a,bn(t=r=i,e=n=o)},xn.lineEnd=function(){a(t,e)}}function Mn(t){var e=4.5,r={point:n,lineStart:function(){r.point=a},lineEnd:o,polygonStart:function(){r.lineEnd=l},polygonEnd:function(){r.lineEnd=o,r.point=n},pointRadius:function(t){return e=t,r},result:I};function n(r,n){t.moveTo(r+e,n),t.arc(r,n,e,0,At)}function a(e,n){t.moveTo(e,n),r.point=i}function i(e,r){t.lineTo(e,r)}function o(){r.point=n}function l(){t.closePath()}return r}function Tn(t){var e=.5,r=Math.cos(30*St),n=16;function a(e){return(n?function(e){var r,a,o,l,s,c,u,f,d,p,h,g,y={point:v,lineStart:m,lineEnd:b,polygonStart:function(){e.polygonStart(),y.lineStart=_},polygonEnd:function(){e.polygonEnd(),y.lineStart=m}};function v(r,n){r=t(r,n),e.point(r[0],r[1])}function m(){f=NaN,y.point=x,e.lineStart()}function x(r,a){var o=Pr([r,a]),l=t(r,a);i(f,d,u,p,h,g,f=l[0],d=l[1],u=r,p=o[0],h=o[1],g=o[2],n,e),e.point(f,d)}function b(){y.point=v,e.lineEnd()}function _(){m(),y.point=w,y.lineEnd=k}function w(t,e){x(r=t,e),a=f,o=d,l=p,s=h,c=g,y.point=x}function k(){i(f,d,u,p,h,g,a,o,r,l,s,c,n,e),y.lineEnd=b,b()}return y}:function(e){return Ln(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function i(n,a,o,l,s,c,u,f,d,p,h,g,y,v){var x=u-n,b=f-a,_=x*x+b*b;if(_>4*e&&y--){var w=l+p,k=s+h,M=c+g,T=Math.sqrt(w*w+k*k+M*M),A=Math.asin(M/=T),L=m(m(M)-1)<kt||m(o-d)<kt?(o+d)/2:Math.atan2(k,w),C=t(L,A),S=C[0],O=C[1],P=S-n,D=O-a,z=b*P-x*D;(z*z/_>e||m((x*P+b*D)/_-.5)>.3||l*p+s*h+c*g<r)&&(i(n,a,o,l,s,c,S,O,L,w/=T,k/=T,M,y,v),v.point(S,O),i(S,O,L,w,k,M,u,f,d,p,h,g,y,v))}}return a.precision=function(t){return arguments.length?(n=(e=t*t)>0&&16,a):Math.sqrt(e)},a}function An(t){this.stream=t}function Ln(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Cn(t){return Sn(function(){return t})()}function Sn(e){var r,n,a,i,o,l,s=Tn(function(t,e){return[(t=r(t,e))[0]*c+i,o-t[1]*c]}),c=150,u=480,f=250,d=0,p=0,h=0,g=0,y=0,v=tn,x=P,b=null,_=null;function w(t){return[(t=a(t[0]*St,t[1]*St))[0]*c+i,o-t[1]*c]}function k(t){return(t=a.invert((t[0]-i)/c,(o-t[1])/c))&&[t[0]*Ot,t[1]*Ot]}function M(){a=Gr(n=zn(h,g,y),r);var t=r(d,p);return i=u-t[0]*c,o=f+t[1]*c,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(t){return l&&(l.valid=!1),(l=On(v(n,s(x(t))))).valid=!0,l},w.clipAngle=function(t){return arguments.length?(v=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=m(e)>kt;return Qr(a,function(t){var e,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var p,h=[f,d],g=a(f,d),y=r?g?0:o(f,d):g?o(f+(f<0?Tt:-Tt),d):0;if(!e&&(c=s=g)&&t.lineStart(),g!==s&&(p=i(e,h),(Fr(e,p)||Fr(h,p))&&(h[0]+=kt,h[1]+=kt,g=a(h[0],h[1]))),g!==s)u=0,g?(t.lineStart(),p=i(h,e),t.point(p[0],p[1])):(p=i(e,h),t.point(p[0],p[1]),t.lineEnd()),e=p;else if(n&&e&&r^g){var v;y&l||!(v=i(h,e,!0))||(u=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1])))}!g||e&&Fr(e,h)||t.point(h[0],h[1]),e=h,s=g,l=y},lineEnd:function(){s&&t.lineEnd(),e=null},clean:function(){return u|(c&&s)<<1}}},Rn(t,6*St),r?[0,-t]:[-Tt,t-Tt]);function a(t,r){return Math.cos(t)*Math.cos(r)>e}function i(t,r,n){var a=[1,0,0],i=zr(Pr(t),Pr(r)),o=Dr(i,i),l=i[0],s=o-l*l;if(!s)return!n&&t;var c=e*o/s,u=-e*l/s,f=zr(a,i),d=Ir(a,c);Er(d,Ir(i,u));var p=f,h=Dr(d,p),g=Dr(p,p),y=h*h-g*(Dr(d,d)-1);if(!(y<0)){var v=Math.sqrt(y),x=Ir(p,(-h-v)/g);if(Er(x,d),x=Rr(x),!n)return x;var b,_=t[0],w=r[0],k=t[1],M=r[1];w<_&&(b=_,_=w,w=b);var T=w-_,A=m(T-Tt)<kt;if(!A&&M<k&&(b=k,k=M,M=b),A||T<kt?A?k+M>0^x[1]<(m(x[0]-_)<kt?k:M):k<=x[1]&&x[1]<=M:T>Tt^(_<=x[0]&&x[0]<=w)){var L=Ir(p,(-h+v)/g);return Er(L,d),[x,Rr(L)]}}}function o(e,n){var a=r?t:Tt-t,i=0;return e<-a?i|=1:e>a&&(i|=2),n<-a?i|=4:n>a&&(i|=8),i}}((b=+t)*St),T()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):P,T()):_},w.scale=function(t){return arguments.length?(c=+t,M()):c},w.translate=function(t){return arguments.length?(u=+t[0],f=+t[1],M()):[u,f]},w.center=function(t){return arguments.length?(d=t[0]%360*St,p=t[1]%360*St,M()):[d*Ot,p*Ot]},w.rotate=function(t){return arguments.length?(h=t[0]%360*St,g=t[1]%360*St,y=t.length>2?t[2]%360*St:0,M()):[h*Ot,g*Ot,y*Ot]},t.rebind(w,s,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&k,M()}}function On(t){return Ln(t,function(e,r){t.point(e*St,r*St)})}function Pn(t,e){return[t,e]}function Dn(t,e){return[t>Tt?t-At:t<-Tt?t+At:t,e]}function zn(t,e,r){return t?e||r?Gr(In(t),Nn(e,r)):In(t):e||r?Nn(e,r):Dn}function En(t){return function(e,r){return[(e+=t)>Tt?e-At:e<-Tt?e+At:e,r]}}function In(t){var e=En(t);return e.invert=En(-t),e}function Nn(t,e){var r=Math.cos(t),n=Math.sin(t),a=Math.cos(e),i=Math.sin(e);function o(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,c=Math.sin(e),u=c*r+l*n;return[Math.atan2(s*a-u*i,l*r-c*n),Et(u*a+s*i)]}return o.invert=function(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,c=Math.sin(e),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*r+u*n),Et(u*r-l*n)]},o}function Rn(t,e){var r=Math.cos(t),n=Math.sin(t);return function(a,i,o,l){var s=o*e;null!=a?(a=Fn(r,a),i=Fn(r,i),(o>0?a<i:a>i)&&(a+=o*At)):(a=t+o*At,i=t-.5*s);for(var c,u=a;o>0?u>i:u<i;u-=s)l.point((c=Rr([r,-n*Math.cos(u),-n*Math.sin(u)]))[0],c[1])}}function Fn(t,e){var r=Pr(e);r[0]-=t,Nr(r);var n=zt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-kt)%(2*Math.PI)}function jn(e,r,n){var a=t.range(e,r-kt,n).concat(r);return function(t){return a.map(function(e){return[t,e]})}}function Bn(e,r,n){var a=t.range(e,r-kt,n).concat(r);return function(t){return a.map(function(e){return[e,t]})}}function Hn(t){return t.source}function qn(t){return t.target}t.geo.path=function(){var e,r,n,a,i,o=4.5;function l(e){return e&&("function"==typeof o&&a.pointRadius(+o.apply(this,arguments)),i&&i.valid||(i=n(a)),t.geo.stream(e,i)),a.result()}function s(){return i=null,l}return l.area=function(e){return ln=0,t.geo.stream(e,n(pn)),ln},l.centroid=function(e){return xr=br=_r=wr=kr=Mr=Tr=Ar=Lr=0,t.geo.stream(e,n(xn)),Lr?[Tr/Lr,Ar/Lr]:Mr?[wr/Mr,kr/Mr]:_r?[xr/_r,br/_r]:[NaN,NaN]},l.bounds=function(e){return fn=dn=-(cn=un=1/0),t.geo.stream(e,n(gn)),[[cn,un],[fn,dn]]},l.projection=function(t){return arguments.length?(n=(e=t)?t.stream||(r=t,a=Tn(function(t,e){return r([t*Ot,e*Ot])}),function(t){return On(a(t))}):P,s()):e;var r,a},l.context=function(t){return arguments.length?(a=null==(r=t)?new yn:new Mn(t),"function"!=typeof o&&a.pointRadius(o),s()):r},l.pointRadius=function(t){return arguments.length?(o="function"==typeof t?t:(a.pointRadius(+t),+t),l):o},l.projection(t.geo.albersUsa()).context(null)},t.geo.transform=function(t){return{stream:function(e){var r=new An(e);for(var n in t)r[n]=t[n];return r}}},An.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},t.geo.projection=Cn,t.geo.projectionMutator=Sn,(t.geo.equirectangular=function(){return Cn(Pn)}).raw=Pn.invert=Pn,t.geo.rotation=function(t){function e(e){return(e=t(e[0]*St,e[1]*St))[0]*=Ot,e[1]*=Ot,e}return t=zn(t[0]%360*St,t[1]*St,t.length>2?t[2]*St:0),e.invert=function(e){return(e=t.invert(e[0]*St,e[1]*St))[0]*=Ot,e[1]*=Ot,e},e},Dn.invert=Pn,t.geo.circle=function(){var t,e,r=[0,0],n=6;function a(){var t="function"==typeof r?r.apply(this,arguments):r,n=zn(-t[0]*St,-t[1]*St,0).invert,a=[];return e(null,null,1,{point:function(t,e){a.push(t=n(t,e)),t[0]*=Ot,t[1]*=Ot}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(t){return arguments.length?(r=t,a):r},a.angle=function(r){return arguments.length?(e=Rn((t=+r)*St,n*St),a):t},a.precision=function(r){return arguments.length?(e=Rn(t*St,(n=+r)*St),a):n},a.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*St,a=t[1]*St,i=e[1]*St,o=Math.sin(n),l=Math.cos(n),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-s*f*l)*r),s*u+c*f*l)},t.geo.graticule=function(){var e,r,n,a,i,o,l,s,c,u,f,d,p=10,h=p,g=90,y=360,v=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,n,g).map(f).concat(t.range(Math.ceil(s/y)*y,l,y).map(d)).concat(t.range(Math.ceil(r/p)*p,e,p).filter(function(t){return m(t%g)>kt}).map(c)).concat(t.range(Math.ceil(o/h)*h,i,h).filter(function(t){return m(t%y)>kt}).map(u))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(n).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(a=+t[0][0],n=+t[1][0],s=+t[0][1],l=+t[1][1],a>n&&(t=a,a=n,n=t),s>l&&(t=s,s=l,l=t),x.precision(v)):[[a,s],[n,l]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],r>e&&(t=r,r=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(v)):[[r,o],[e,i]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],y=+t[1],x):[g,y]},x.minorStep=function(t){return arguments.length?(p=+t[0],h=+t[1],x):[p,h]},x.precision=function(t){return arguments.length?(v=+t,c=jn(o,i,90),u=Bn(r,e,v),f=jn(s,l,90),d=Bn(a,n,v),x):v},x.majorExtent([[-180,-90+kt],[180,90-kt]]).minorExtent([[-180,-80-kt],[180,80+kt]])},t.geo.greatArc=function(){var e,r,n=Hn,a=qn;function i(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||a.apply(this,arguments))},i.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,i):n},i.target=function(t){return arguments.length?(a=t,r="function"==typeof t?null:t,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(t,e){return r=t[0]*St,n=t[1]*St,a=e[0]*St,i=e[1]*St,o=Math.cos(n),l=Math.sin(n),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(r),f=o*Math.sin(r),d=s*Math.cos(a),p=s*Math.sin(a),h=2*Math.asin(Math.sqrt(Nt(i-n)+o*s*Nt(a-r))),g=1/Math.sin(h),(y=h?function(t){var e=Math.sin(t*=h)*g,r=Math.sin(h-t)*g,n=r*u+e*d,a=r*f+e*p,i=r*l+e*c;return[Math.atan2(a,n)*Ot,Math.atan2(i,Math.sqrt(n*n+a*a))*Ot]}:function(){return[r*Ot,n*Ot]}).distance=h,y;var r,n,a,i,o,l,s,c,u,f,d,p,h,g,y},t.geo.length=function(e){return mn=0,t.geo.stream(e,Vn),mn};var Vn={sphere:I,point:I,lineStart:function(){var t,e,r;function n(n,a){var i=Math.sin(a*=St),o=Math.cos(a),l=m((n*=St)-t),s=Math.cos(l);mn+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=r*i-e*o*s)*l),e*i+r*o*s),t=n,e=i,r=o}Vn.point=function(a,i){t=a*St,e=Math.sin(i*=St),r=Math.cos(i),Vn.point=n},Vn.lineEnd=function(){Vn.point=Vn.lineEnd=I}},lineEnd:I,polygonStart:I,polygonEnd:I};function Un(t,e){function r(e,r){var n=Math.cos(e),a=Math.cos(r),i=t(n*a);return[i*a*Math.sin(e),i*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),a=e(n),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(t*i,n*o),Math.asin(n&&r*i/n)]},r}var Gn=Un(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return Cn(Gn)}).raw=Gn;var Yn=Un(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},P);function Xn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},a=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),i=r*Math.pow(n(t),a)/a;if(!a)return Qn;function o(t,e){i>0?e<-Ct+kt&&(e=-Ct+kt):e>Ct-kt&&(e=Ct-kt);var r=i/Math.pow(n(e),a);return[r*Math.sin(a*t),i-r*Math.cos(a*t)]}return o.invert=function(t,e){var r=i-e,n=Pt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(i/n,1/a))-Ct]},o}function Zn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),a=r/n+t;if(m(n)<kt)return Pn;function i(t,e){var r=a-e;return[r*Math.sin(n*t),a-r*Math.cos(n*t)]}return i.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,a-Pt(n)*Math.sqrt(t*t+r*r)]},i}(t.geo.azimuthalEquidistant=function(){return Cn(Yn)}).raw=Yn,(t.geo.conicConformal=function(){return an(Xn)}).raw=Xn,(t.geo.conicEquidistant=function(){return an(Zn)}).raw=Zn;var Wn=Un(function(t){return 1/t},Math.atan);function Qn(t,e){return[t,Math.log(Math.tan(Tt/4+e/2))]}function Jn(t){var e,r=Cn(t),n=r.scale,a=r.translate,i=r.clipExtent;return r.scale=function(){var t=n.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.translate=function(){var t=a.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.clipExtent=function(t){var o=i.apply(r,arguments);if(o===r){if(e=null==t){var l=Tt*n(),s=a();i([[s[0]-l,s[1]-l],[s[0]+l,s[1]+l]])}}else e&&(o=null);return o},r.clipExtent(null)}(t.geo.gnomonic=function(){return Cn(Wn)}).raw=Wn,Qn.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Ct]},(t.geo.mercator=function(){return Jn(Qn)}).raw=Qn;var $n=Un(function(){return 1},Math.asin);(t.geo.orthographic=function(){return Cn($n)}).raw=$n;var Kn=Un(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});function ta(t,e){return[Math.log(Math.tan(Tt/4+e/2)),-t]}function ea(t){return t[0]}function ra(t){return t[1]}function na(t){for(var e=t.length,r=[0,1],n=2,a=2;a<e;a++){for(;n>1&&Dt(t[r[n-2]],t[r[n-1]],t[a])<=0;)--n;r[n++]=a}return r.slice(0,n)}function aa(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return Cn(Kn)}).raw=Kn,ta.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(t.geo.transverseMercator=function(){var t=Jn(ta),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=ta,t.geom={},t.geom.hull=function(t){var e=ea,r=ra;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,a=ye(e),i=ye(r),o=t.length,l=[],s=[];for(n=0;n<o;n++)l.push([+a.call(this,t[n],n),+i.call(this,t[n],n),n]);for(l.sort(aa),n=0;n<o;n++)s.push([l[n][0],-l[n][1]]);var c=na(l),u=na(s),f=u[0]===c[0],d=u[u.length-1]===c[c.length-1],p=[];for(n=c.length-1;n>=0;--n)p.push(t[l[c[n]][2]]);for(n=+f;n<u.length-d;++n)p.push(t[l[u[n]][2]]);return p}return n.x=function(t){return arguments.length?(e=t,n):e},n.y=function(t){return arguments.length?(r=t,n):r},n},t.geom.polygon=function(t){return q(t,ia),t};var ia=t.geom.polygon.prototype=[];function oa(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function la(t,e,r,n){var a=t[0],i=r[0],o=e[0]-a,l=n[0]-i,s=t[1],c=r[1],u=e[1]-s,f=n[1]-c,d=(l*(s-c)-f*(a-i))/(f*o-l*u);return[a+d*o,s+d*u]}function sa(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}ia.area=function(){for(var t,e=-1,r=this.length,n=this[r-1],a=0;++e<r;)t=n,n=this[e],a+=t[1]*n[0]-t[0]*n[1];return.5*a},ia.centroid=function(t){var e,r,n=-1,a=this.length,i=0,o=0,l=this[a-1];for(arguments.length||(t=-1/(6*this.area()));++n<a;)e=l,l=this[n],r=e[0]*l[1]-l[0]*e[1],i+=(e[0]+l[0])*r,o+=(e[1]+l[1])*r;return[i*t,o*t]},ia.clip=function(t){for(var e,r,n,a,i,o,l=sa(t),s=-1,c=this.length-sa(this),u=this[c-1];++s<c;){for(e=t.slice(),t.length=0,a=this[s],i=e[(n=e.length-l)-1],r=-1;++r<n;)oa(o=e[r],u,a)?(oa(i,u,a)||t.push(la(i,o,u,a)),t.push(o)):oa(i,u,a)&&t.push(la(i,o,u,a)),i=o;l&&t.push(t[0]),u=a}return t};var ca,ua,fa,da,pa,ha=[],ga=[];function ya(){Ea(this),this.edge=this.site=this.circle=null}function va(t){var e=ha.pop()||new ya;return e.site=t,e}function ma(t){La(t),fa.remove(t),ha.push(t),Ea(t)}function xa(t){var e=t.circle,r=e.x,n=e.cy,a={x:r,y:n},i=t.P,o=t.N,l=[t];ma(t);for(var s=i;s.circle&&m(r-s.circle.x)<kt&&m(n-s.circle.cy)<kt;)i=s.P,l.unshift(s),ma(s),s=i;l.unshift(s),La(s);for(var c=o;c.circle&&m(r-c.circle.x)<kt&&m(n-c.circle.cy)<kt;)o=c.N,l.push(c),ma(c),c=o;l.push(c),La(c);var u,f=l.length;for(u=1;u<f;++u)c=l[u],s=l[u-1],Pa(c.edge,s.site,c.site,a);s=l[0],(c=l[f-1]).edge=Oa(s.site,c.site,null,a),Aa(s),Aa(c)}function ba(t){for(var e,r,n,a,i=t.x,o=t.y,l=fa._;l;)if((n=_a(l,o)-i)>kt)l=l.L;else{if(!((a=i-wa(l,o))>kt)){n>-kt?(e=l.P,r=l):a>-kt?(e=l,r=l.N):e=r=l;break}if(!l.R){e=l;break}l=l.R}var s=va(t);if(fa.insert(e,s),e||r){if(e===r)return La(e),r=va(e.site),fa.insert(s,r),s.edge=r.edge=Oa(e.site,s.site),Aa(e),void Aa(r);if(r){La(e),La(r);var c=e.site,u=c.x,f=c.y,d=t.x-u,p=t.y-f,h=r.site,g=h.x-u,y=h.y-f,v=2*(d*y-p*g),m=d*d+p*p,x=g*g+y*y,b={x:(y*m-p*x)/v+u,y:(d*x-g*m)/v+f};Pa(r.edge,c,h,b),s.edge=Oa(c,t,null,b),r.edge=Oa(t,h,null,b),Aa(e),Aa(r)}else s.edge=Oa(e.site,s.site)}}function _a(t,e){var r=t.site,n=r.x,a=r.y,i=a-e;if(!i)return n;var o=t.P;if(!o)return-1/0;var l=(r=o.site).x,s=r.y,c=s-e;if(!c)return l;var u=l-n,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+n:(n+l)/2}function wa(t,e){var r=t.N;if(r)return _a(r,e);var n=t.site;return n.y===e?n.x:1/0}function ka(t){this.site=t,this.edges=[]}function Ma(t,e){return e.angle-t.angle}function Ta(){Ea(this),this.x=this.y=this.arc=this.site=this.cy=null}function Aa(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,a=t.site,i=r.site;if(n!==i){var o=a.x,l=a.y,s=n.x-o,c=n.y-l,u=i.x-o,f=2*(s*(y=i.y-l)-c*u);if(!(f>=-Mt)){var d=s*s+c*c,p=u*u+y*y,h=(y*d-c*p)/f,g=(s*p-u*d)/f,y=g+l,v=ga.pop()||new Ta;v.arc=t,v.site=a,v.x=h+o,v.y=y+Math.sqrt(h*h+g*g),v.cy=y,t.circle=v;for(var m=null,x=pa._;x;)if(v.y<x.y||v.y===x.y&&v.x<=x.x){if(!x.L){m=x.P;break}x=x.L}else{if(!x.R){m=x;break}x=x.R}pa.insert(m,v),m||(da=v)}}}}function La(t){var e=t.circle;e&&(e.P||(da=e.N),pa.remove(e),ga.push(e),Ea(e),t.circle=null)}function Ca(t,e){var r=t.b;if(r)return!0;var n,a,i=t.a,o=e[0][0],l=e[1][0],s=e[0][1],c=e[1][1],u=t.l,f=t.r,d=u.x,p=u.y,h=f.x,g=f.y,y=(d+h)/2,v=(p+g)/2;if(g===p){if(y<o||y>=l)return;if(d>h){if(i){if(i.y>=c)return}else i={x:y,y:s};r={x:y,y:c}}else{if(i){if(i.y<s)return}else i={x:y,y:c};r={x:y,y:s}}}else if(a=v-(n=(d-h)/(g-p))*y,n<-1||n>1)if(d>h){if(i){if(i.y>=c)return}else i={x:(s-a)/n,y:s};r={x:(c-a)/n,y:c}}else{if(i){if(i.y<s)return}else i={x:(c-a)/n,y:c};r={x:(s-a)/n,y:s}}else if(p<g){if(i){if(i.x>=l)return}else i={x:o,y:n*o+a};r={x:l,y:n*l+a}}else{if(i){if(i.x<o)return}else i={x:l,y:n*l+a};r={x:o,y:n*o+a}}return t.a=i,t.b=r,!0}function Sa(t,e){this.l=t,this.r=e,this.a=this.b=null}function Oa(t,e,r,n){var a=new Sa(t,e);return ca.push(a),r&&Pa(a,t,e,r),n&&Pa(a,e,t,n),ua[t.i].edges.push(new Da(a,t,e)),ua[e.i].edges.push(new Da(a,e,t)),a}function Pa(t,e,r,n){t.a||t.b?t.l===r?t.b=n:t.a=n:(t.a=n,t.l=e,t.r=r)}function Da(t,e,r){var n=t.a,a=t.b;this.edge=t,this.site=e,this.angle=r?Math.atan2(r.y-e.y,r.x-e.x):t.l===e?Math.atan2(a.x-n.x,n.y-a.y):Math.atan2(n.x-a.x,a.y-n.y)}function za(){this._=null}function Ea(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function Ia(t,e){var r=e,n=e.R,a=r.U;a?a.L===r?a.L=n:a.R=n:t._=n,n.U=a,r.U=n,r.R=n.L,r.R&&(r.R.U=r),n.L=r}function Na(t,e){var r=e,n=e.L,a=r.U;a?a.L===r?a.L=n:a.R=n:t._=n,n.U=a,r.U=n,r.L=n.R,r.L&&(r.L.U=r),n.R=r}function Ra(t){for(;t.L;)t=t.L;return t}function Fa(t,e){var r,n,a,i=t.sort(ja).pop();for(ca=[],ua=new Array(t.length),fa=new za,pa=new za;;)if(a=da,i&&(!a||i.y<a.y||i.y===a.y&&i.x<a.x))i.x===r&&i.y===n||(ua[i.i]=new ka(i),ba(i),r=i.x,n=i.y),i=t.pop();else{if(!a)break;xa(a.arc)}e&&(function(t){for(var e,r=ca,n=en(t[0][0],t[0][1],t[1][0],t[1][1]),a=r.length;a--;)(!Ca(e=r[a],t)||!n(e)||m(e.a.x-e.b.x)<kt&&m(e.a.y-e.b.y)<kt)&&(e.a=e.b=null,r.splice(a,1))}(e),function(t){for(var e,r,n,a,i,o,l,s,c,u,f=t[0][0],d=t[1][0],p=t[0][1],h=t[1][1],g=ua,y=g.length;y--;)if((i=g[y])&&i.prepare())for(s=(l=i.edges).length,o=0;o<s;)n=(u=l[o].end()).x,a=u.y,e=(c=l[++o%s].start()).x,r=c.y,(m(n-e)>kt||m(a-r)>kt)&&(l.splice(o,0,new Da((v=i.site,x=u,b=m(n-f)<kt&&h-a>kt?{x:f,y:m(e-f)<kt?r:h}:m(a-h)<kt&&d-n>kt?{x:m(r-h)<kt?e:d,y:h}:m(n-d)<kt&&a-p>kt?{x:d,y:m(e-d)<kt?r:p}:m(a-p)<kt&&n-f>kt?{x:m(r-p)<kt?e:f,y:p}:null,_=void 0,_=new Sa(v,null),_.a=x,_.b=b,ca.push(_),_),i.site,null)),++s);var v,x,b,_}(e));var o={cells:ua,edges:ca};return fa=pa=ca=ua=null,o}function ja(t,e){return e.y-t.y||e.x-t.x}ka.prototype.prepare=function(){for(var t,e=this.edges,r=e.length;r--;)(t=e[r].edge).b&&t.a||e.splice(r,1);return e.sort(Ma),e.length},Da.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},za.prototype={insert:function(t,e){var r,n,a;if(t){if(e.P=t,e.N=t.N,t.N&&(t.N.P=e),t.N=e,t.R){for(t=t.R;t.L;)t=t.L;t.L=e}else t.R=e;r=t}else this._?(t=Ra(this._),e.P=null,e.N=t,t.P=t.L=e,r=t):(e.P=e.N=null,this._=e,r=null);for(e.L=e.R=null,e.U=r,e.C=!0,t=e;r&&r.C;)r===(n=r.U).L?(a=n.R)&&a.C?(r.C=a.C=!1,n.C=!0,t=n):(t===r.R&&(Ia(this,r),r=(t=r).U),r.C=!1,n.C=!0,Na(this,n)):(a=n.L)&&a.C?(r.C=a.C=!1,n.C=!0,t=n):(t===r.L&&(Na(this,r),r=(t=r).U),r.C=!1,n.C=!0,Ia(this,n)),r=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var e,r,n,a=t.U,i=t.L,o=t.R;if(r=i?o?Ra(o):i:o,a?a.L===t?a.L=r:a.R=r:this._=r,i&&o?(n=r.C,r.C=t.C,r.L=i,i.U=r,r!==o?(a=r.U,r.U=t.U,t=r.R,a.L=t,r.R=o,o.U=r):(r.U=a,a=r,t=r.R)):(n=t.C,t=r),t&&(t.U=a),!n)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===a.L){if((e=a.R).C&&(e.C=!1,a.C=!0,Ia(this,a),e=a.R),e.L&&e.L.C||e.R&&e.R.C){e.R&&e.R.C||(e.L.C=!1,e.C=!0,Na(this,e),e=a.R),e.C=a.C,a.C=e.R.C=!1,Ia(this,a),t=this._;break}}else if((e=a.L).C&&(e.C=!1,a.C=!0,Na(this,a),e=a.L),e.L&&e.L.C||e.R&&e.R.C){e.L&&e.L.C||(e.R.C=!1,e.C=!0,Ia(this,e),e=a.L),e.C=a.C,a.C=e.L.C=!1,Na(this,a),t=this._;break}e.C=!0,t=a,a=a.U}while(!t.C);t&&(t.C=!1)}}},t.geom.voronoi=function(t){var e=ea,r=ra,n=e,a=r,i=Ba;if(t)return o(t);function o(t){var e=new Array(t.length),r=i[0][0],n=i[0][1],a=i[1][0],o=i[1][1];return Fa(l(t),i).cells.forEach(function(i,l){var s=i.edges,c=i.site;(e[l]=s.length?s.map(function(t){var e=t.start();return[e.x,e.y]}):c.x>=r&&c.x<=a&&c.y>=n&&c.y<=o?[[r,o],[a,o],[a,n],[r,n]]:[]).point=t[l]}),e}function l(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/kt)*kt,y:Math.round(a(t,e)/kt)*kt,i:e}})}return o.links=function(t){return Fa(l(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Fa(l(t)).cells.forEach(function(r,n){for(var a,i,o,l,s=r.site,c=r.edges.sort(Ma),u=-1,f=c.length,d=c[f-1].edge,p=d.l===s?d.r:d.l;++u<f;)d,a=p,p=(d=c[u].edge).l===s?d.r:d.l,n<a.i&&n<p.i&&(o=a,l=p,((i=s).x-l.x)*(o.y-i.y)-(i.x-o.x)*(l.y-i.y)<0)&&e.push([t[n],t[a.i],t[p.i]])}),e},o.x=function(t){return arguments.length?(n=ye(e=t),o):e},o.y=function(t){return arguments.length?(a=ye(r=t),o):r},o.clipExtent=function(t){return arguments.length?(i=null==t?Ba:t,o):i===Ba?null:i},o.size=function(t){return arguments.length?o.clipExtent(t&&[[0,0],t]):i===Ba?null:i&&i[1]},o};var Ba=[[-1e6,-1e6],[1e6,1e6]];function Ha(t){return t.x}function qa(t){return t.y}function Va(e,r){e=t.rgb(e),r=t.rgb(r);var n=e.r,a=e.g,i=e.b,o=r.r-n,l=r.g-a,s=r.b-i;return function(t){return"#"+ce(Math.round(n+o*t))+ce(Math.round(a+l*t))+ce(Math.round(i+s*t))}}function Ua(t,e){var r,n={},a={};for(r in t)r in e?n[r]=Wa(t[r],e[r]):a[r]=t[r];for(r in e)r in t||(a[r]=e[r]);return function(t){for(r in n)a[r]=n[r](t);return a}}function Ga(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function Ya(t,e){var r,n,a,i=Xa.lastIndex=Za.lastIndex=0,o=-1,l=[],s=[];for(t+="",e+="";(r=Xa.exec(t))&&(n=Za.exec(e));)(a=n.index)>i&&(a=e.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(r=r[0])===(n=n[0])?l[o]?l[o]+=n:l[++o]=n:(l[++o]=null,s.push({i:o,x:Ga(r,n)})),i=Za.lastIndex;return i<e.length&&(a=e.slice(i),l[o]?l[o]+=a:l[++o]=a),l.length<2?s[0]?(e=s[0].x,function(t){return e(t)+""}):function(){return e}:(e=s.length,function(t){for(var r,n=0;n<e;++n)l[(r=s[n]).i]=r.x(t);return l.join("")})}t.geom.delaunay=function(e){return t.geom.voronoi().triangles(e)},t.geom.quadtree=function(t,e,r,n,a){var i,o=ea,l=ra;if(i=arguments.length)return o=Ha,l=qa,3===i&&(a=r,n=e,r=e=0),s(t);function s(t){var s,c,u,f,d,p,h,g,y,v=ye(o),x=ye(l);if(null!=e)p=e,h=r,g=n,y=a;else if(g=y=-(p=h=1/0),c=[],u=[],d=t.length,i)for(f=0;f<d;++f)(s=t[f]).x<p&&(p=s.x),s.y<h&&(h=s.y),s.x>g&&(g=s.x),s.y>y&&(y=s.y),c.push(s.x),u.push(s.y);else for(f=0;f<d;++f){var b=+v(s=t[f],f),_=+x(s,f);b<p&&(p=b),_<h&&(h=_),b>g&&(g=b),_>y&&(y=_),c.push(b),u.push(_)}var w=g-p,k=y-h;function M(t,e,r,n,a,i,o,l){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var s=t.x,c=t.y;if(null!=s)if(m(s-r)+m(c-n)<.01)T(t,e,r,n,a,i,o,l);else{var u=t.point;t.x=t.y=t.point=null,T(t,u,s,c,a,i,o,l),T(t,e,r,n,a,i,o,l)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,a,i,o,l)}function T(t,e,r,n,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=r>=s,f=n>=c,d=f<<1|u;t.leaf=!1,u?a=s:o=s,f?i=c:l=c,M(t=t.nodes[d]||(t.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(A,t,+v(t,++f),+x(t,f),p,h,g,y)}}),e,r,n,a,i,o,l)}w>k?y=h+w:g=p+k;var A={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(A,t,+v(t,++f),+x(t,f),p,h,g,y)}};if(A.visit=function(t){!function t(e,r,n,a,i,o){if(!e(r,n,a,i,o)){var l=.5*(n+i),s=.5*(a+o),c=r.nodes;c[0]&&t(e,c[0],n,a,l,s),c[1]&&t(e,c[1],l,a,i,s),c[2]&&t(e,c[2],n,s,l,o),c[3]&&t(e,c[3],l,s,i,o)}}(t,A,p,h,g,y)},A.find=function(t){return function(t,e,r,n,a,i,o){var l,s=1/0;return function t(c,u,f,d,p){if(!(u>i||f>o||d<n||p<a)){if(h=c.point){var h,g=e-c.x,y=r-c.y,v=g*g+y*y;if(v<s){var m=Math.sqrt(s=v);n=e-m,a=r-m,i=e+m,o=r+m,l=h}}for(var x=c.nodes,b=.5*(u+d),_=.5*(f+p),w=(r>=_)<<1|e>=b,k=w+4;w<k;++w)if(c=x[3&w])switch(3&w){case 0:t(c,u,f,b,_);break;case 1:t(c,b,f,d,_);break;case 2:t(c,u,_,b,p);break;case 3:t(c,b,_,d,p)}}}(t,n,a,i,o),l}(A,t[0],t[1],p,h,g,y)},f=-1,null==e){for(;++f<d;)M(A,t[f],c[f],u[f],p,h,g,y);--f}else t.forEach(A.add);return c=u=t=s=null,A}return s.x=function(t){return arguments.length?(o=t,s):o},s.y=function(t){return arguments.length?(l=t,s):l},s.extent=function(t){return arguments.length?(null==t?e=r=n=a=null:(e=+t[0][0],r=+t[0][1],n=+t[1][0],a=+t[1][1]),s):null==e?null:[[e,r],[n,a]]},s.size=function(t){return arguments.length?(null==t?e=r=n=a=null:(e=r=0,n=+t[0],a=+t[1]),s):null==e?null:[n-e,a-r]},s},t.interpolateRgb=Va,t.interpolateObject=Ua,t.interpolateNumber=Ga,t.interpolateString=Ya;var Xa=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Za=new RegExp(Xa.source,"g");function Wa(e,r){for(var n,a=t.interpolators.length;--a>=0&&!(n=t.interpolators[a](e,r)););return n}function Qa(t,e){var r,n=[],a=[],i=t.length,o=e.length,l=Math.min(t.length,e.length);for(r=0;r<l;++r)n.push(Wa(t[r],e[r]));for(;r<i;++r)a[r]=t[r];for(;r<o;++r)a[r]=e[r];return function(t){for(r=0;r<l;++r)a[r]=n[r](t);return a}}t.interpolate=Wa,t.interpolators=[function(t,e){var r=typeof e;return("string"===r?ge.has(e.toLowerCase())||/^(#|rgb\(|hsl\()/i.test(e)?Va:Ya:e instanceof Ht?Va:Array.isArray(e)?Qa:"object"===r&&isNaN(e)?Ua:Ga)(t,e)}],t.interpolateArray=Qa;var Ja=function(){return P},$a=t.map({linear:Ja,poly:function(t){return function(e){return Math.pow(e,t)}},quad:function(){return ri},cubic:function(){return ni},sin:function(){return ii},exp:function(){return oi},circle:function(){return li},elastic:function(t,e){var r;arguments.length<2&&(e=.45);arguments.length?r=e/At*Math.asin(1/t):(t=1,r=e/4);return function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*At/e)}},back:function(t){t||(t=1.70158);return function(e){return e*e*((t+1)*e-t)}},bounce:function(){return si}}),Ka=t.map({in:P,out:ti,"in-out":ei,"out-in":function(t){return ei(ti(t))}});function ti(t){return function(e){return 1-t(1-e)}}function ei(t){return function(e){return.5*(e<.5?t(2*e):2-t(2-2*e))}}function ri(t){return t*t}function ni(t){return t*t*t}function ai(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ii(t){return 1-Math.cos(t*Ct)}function oi(t){return Math.pow(2,10*(t-1))}function li(t){return 1-Math.sqrt(1-t*t)}function si(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function ci(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function ui(t){var e,r,n,a=[t.a,t.b],i=[t.c,t.d],o=di(a),l=fi(a,i),s=di(((e=i)[0]+=(n=-l)*(r=a)[0],e[1]+=n*r[1],e))||0;a[0]*i[1]<i[0]*a[1]&&(a[0]*=-1,a[1]*=-1,o*=-1,l*=-1),this.rotate=(o?Math.atan2(a[1],a[0]):Math.atan2(-i[0],i[1]))*Ot,this.translate=[t.e,t.f],this.scale=[o,s],this.skew=s?Math.atan2(l,s)*Ot:0}function fi(t,e){return t[0]*e[0]+t[1]*e[1]}function di(t){var e=Math.sqrt(fi(t,t));return e&&(t[0]/=e,t[1]/=e),e}t.ease=function(t){var e,n=t.indexOf("-"),a=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1):"in";return a=$a.get(a)||Ja,i=Ka.get(i)||P,e=i(a.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,a=e.c,i=e.l,o=r.h-n,l=r.c-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.c:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Xt(n+o*t,a+l*t,i+s*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,a=e.s,i=e.l,o=r.h-n,l=r.s-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.s:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Ut(n+o*t,a+l*t,i+s*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,a=e.a,i=e.b,o=r.l-n,l=r.a-a,s=r.b-i;return function(t){return te(n+o*t,a+l*t,i+s*t)+""}},t.interpolateRound=ci,t.transform=function(e){var r=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new ui(e?e.matrix:pi)})(e)},ui.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var pi={a:1,b:0,c:0,d:1,e:0,f:0};function hi(t){return t.length?t.pop()+",":""}function gi(e,r){var n=[],a=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push("translate(",null,",",null,")");n.push({i:a-4,x:Ga(t[0],e[0])},{i:a-2,x:Ga(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,a),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(hi(r)+"rotate(",null,")")-2,x:Ga(t,e)})):e&&r.push(hi(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,a),function(t,e,r,n){t!==e?n.push({i:r.push(hi(r)+"skewX(",null,")")-2,x:Ga(t,e)}):e&&r.push(hi(r)+"skewX("+e+")")}(e.skew,r.skew,n,a),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push(hi(r)+"scale(",null,",",null,")");n.push({i:a-4,x:Ga(t[0],e[0])},{i:a-2,x:Ga(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(hi(r)+"scale("+e+")")}(e.scale,r.scale,n,a),e=r=null,function(t){for(var e,r=-1,i=a.length;++r<i;)n[(e=a[r]).i]=e.x(t);return n.join("")}}function yi(t,e){return e=(e-=t=+t)||1/e,function(r){return(r-t)/e}}function vi(t,e){return e=(e-=t=+t)||1/e,function(r){return Math.max(0,Math.min(1,(r-t)/e))}}function mi(t){for(var e=t.source,r=t.target,n=function(t,e){if(t===e)return t;var r=xi(t),n=xi(e),a=r.pop(),i=n.pop(),o=null;for(;a===i;)o=a,a=r.pop(),i=n.pop();return o}(e,r),a=[e];e!==n;)e=e.parent,a.push(e);for(var i=a.length;r!==n;)a.splice(i,0,r),r=r.parent;return a}function xi(t){for(var e=[],r=t.parent;null!=r;)e.push(t),t=r,r=r.parent;return e.push(t),e}function bi(t){t.fixed|=2}function _i(t){t.fixed&=-7}function wi(t){t.fixed|=4,t.px=t.x,t.py=t.y}function ki(t){t.fixed&=-5}t.interpolateTransform=gi,t.layout={},t.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++r<n;)e.push(mi(t[r]));return e}},t.layout.chord=function(){var e,r,n,a,i,o,l,s={},c=0;function u(){var s,u,d,p,h,g={},y=[],v=t.range(a),m=[];for(e=[],r=[],s=0,p=-1;++p<a;){for(u=0,h=-1;++h<a;)u+=n[p][h];y.push(u),m.push(t.range(a)),s+=u}for(i&&v.sort(function(t,e){return i(y[t],y[e])}),o&&m.forEach(function(t,e){t.sort(function(t,r){return o(n[e][t],n[e][r])})}),s=(At-c*a)/s,u=0,p=-1;++p<a;){for(d=u,h=-1;++h<a;){var x=v[p],b=m[x][h],_=n[x][b],w=u,k=u+=_*s;g[x+"-"+b]={index:x,subindex:b,startAngle:w,endAngle:k,value:_}}r[x]={index:x,startAngle:d,endAngle:u,value:y[x]},u+=c}for(p=-1;++p<a;)for(h=p-1;++h<a;){var M=g[p+"-"+h],T=g[h+"-"+p];(M.value||T.value)&&e.push(M.value<T.value?{source:T,target:M}:{source:M,target:T})}l&&f()}function f(){e.sort(function(t,e){return l((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}return s.matrix=function(t){return arguments.length?(a=(n=t)&&n.length,e=r=null,s):n},s.padding=function(t){return arguments.length?(c=t,e=r=null,s):c},s.sortGroups=function(t){return arguments.length?(i=t,e=r=null,s):i},s.sortSubgroups=function(t){return arguments.length?(o=t,e=null,s):o},s.sortChords=function(t){return arguments.length?(l=t,e&&f(),s):l},s.chords=function(){return e||u(),e},s.groups=function(){return r||u(),r},s},t.layout.force=function(){var e,r,n,a,i,o,l={},s=t.dispatch("start","tick","end"),c=[1,1],u=.9,f=Mi,d=Ti,p=-30,h=Ai,g=.1,y=.64,v=[],m=[];function x(t){return function(e,r,n,a){if(e.point!==t){var i=e.cx-t.x,o=e.cy-t.y,l=a-r,s=i*i+o*o;if(l*l/y<s){if(s<h){var c=e.charge/s;t.px-=i*c,t.py-=o*c}return!0}if(e.point&&s&&s<h){c=e.pointCharge/s;t.px-=i*c,t.py-=o*c}}return!e.charge}}function b(e){e.px=t.event.x,e.py=t.event.y,l.resume()}return l.tick=function(){if((n*=.99)<.005)return e=null,s.end({type:"end",alpha:n=0}),!0;var r,l,f,d,h,y,b,_,w,k=v.length,M=m.length;for(l=0;l<M;++l)d=(f=m[l]).source,(y=(_=(h=f.target).x-d.x)*_+(w=h.y-d.y)*w)&&(_*=y=n*i[l]*((y=Math.sqrt(y))-a[l])/y,w*=y,h.x-=_*(b=d.weight+h.weight?d.weight/(d.weight+h.weight):.5),h.y-=w*b,d.x+=_*(b=1-b),d.y+=w*b);if((b=n*g)&&(_=c[0]/2,w=c[1]/2,l=-1,b))for(;++l<k;)(f=v[l]).x+=(_-f.x)*b,f.y+=(w-f.y)*b;if(p)for(!function t(e,r,n){var a=0,i=0;e.charge=0;if(!e.leaf)for(var o,l=e.nodes,s=l.length,c=-1;++c<s;)null!=(o=l[c])&&(t(o,r,n),e.charge+=o.charge,a+=o.charge*o.cx,i+=o.charge*o.cy);if(e.point){e.leaf||(e.point.x+=Math.random()-.5,e.point.y+=Math.random()-.5);var u=r*n[e.point.index];e.charge+=e.pointCharge=u,a+=u*e.point.x,i+=u*e.point.y}e.cx=a/e.charge;e.cy=i/e.charge}(r=t.geom.quadtree(v),n,o),l=-1;++l<k;)(f=v[l]).fixed||r.visit(x(f));for(l=-1;++l<k;)(f=v[l]).fixed?(f.x=f.px,f.y=f.py):(f.x-=(f.px-(f.px=f.x))*u,f.y-=(f.py-(f.py=f.y))*u);s.tick({type:"tick",alpha:n})},l.nodes=function(t){return arguments.length?(v=t,l):v},l.links=function(t){return arguments.length?(m=t,l):m},l.size=function(t){return arguments.length?(c=t,l):c},l.linkDistance=function(t){return arguments.length?(f="function"==typeof t?t:+t,l):f},l.distance=l.linkDistance,l.linkStrength=function(t){return arguments.length?(d="function"==typeof t?t:+t,l):d},l.friction=function(t){return arguments.length?(u=+t,l):u},l.charge=function(t){return arguments.length?(p="function"==typeof t?t:+t,l):p},l.chargeDistance=function(t){return arguments.length?(h=t*t,l):Math.sqrt(h)},l.gravity=function(t){return arguments.length?(g=+t,l):g},l.theta=function(t){return arguments.length?(y=t*t,l):Math.sqrt(y)},l.alpha=function(t){return arguments.length?(t=+t,n?t>0?n=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:n=0})):t>0&&(s.start({type:"start",alpha:n=t}),e=Me(l.tick)),l):n},l.start=function(){var t,e,r,n=v.length,s=m.length,u=c[0],h=c[1];for(t=0;t<n;++t)(r=v[t]).index=t,r.weight=0;for(t=0;t<s;++t)"number"==typeof(r=m[t]).source&&(r.source=v[r.source]),"number"==typeof r.target&&(r.target=v[r.target]),++r.source.weight,++r.target.weight;for(t=0;t<n;++t)r=v[t],isNaN(r.x)&&(r.x=g("x",u)),isNaN(r.y)&&(r.y=g("y",h)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(a=[],"function"==typeof f)for(t=0;t<s;++t)a[t]=+f.call(this,m[t],t);else for(t=0;t<s;++t)a[t]=f;if(i=[],"function"==typeof d)for(t=0;t<s;++t)i[t]=+d.call(this,m[t],t);else for(t=0;t<s;++t)i[t]=d;if(o=[],"function"==typeof p)for(t=0;t<n;++t)o[t]=+p.call(this,v[t],t);else for(t=0;t<n;++t)o[t]=p;function g(r,a){if(!e){for(e=new Array(n),c=0;c<n;++c)e[c]=[];for(c=0;c<s;++c){var i=m[c];e[i.source.index].push(i.target),e[i.target.index].push(i.source)}}for(var o,l=e[t],c=-1,u=l.length;++c<u;)if(!isNaN(o=l[c][r]))return o;return Math.random()*a}return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){if(r||(r=t.behavior.drag().origin(P).on("dragstart.force",bi).on("drag.force",b).on("dragend.force",_i)),!arguments.length)return r;this.on("mouseover.force",wi).on("mouseout.force",ki).call(r)},t.rebind(l,s,"on")};var Mi=20,Ti=1,Ai=1/0;function Li(e,r){return t.rebind(e,r,"sort","children","value"),e.nodes=e,e.links=zi,e}function Ci(t,e){for(var r=[t];null!=(t=r.pop());)if(e(t),(a=t.children)&&(n=a.length))for(var n,a;--n>=0;)r.push(a[n])}function Si(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(i=t.children)&&(a=i.length))for(var a,i,o=-1;++o<a;)r.push(i[o]);for(;null!=(t=n.pop());)e(t)}function Oi(t){return t.children}function Pi(t){return t.value}function Di(t,e){return e.value-t.value}function zi(e){return t.merge(e.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}t.layout.hierarchy=function(){var t=Di,e=Oi,r=Pi;function n(a){var i,o=[a],l=[];for(a.depth=0;null!=(i=o.pop());)if(l.push(i),(c=e.call(n,i,i.depth))&&(s=c.length)){for(var s,c,u;--s>=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;r&&(i.value=0),i.children=c}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Si(a,function(e){var n,a;t&&(n=e.children)&&n.sort(t),r&&(a=e.parent)&&(a.value+=e.value)}),l}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Ci(t,function(t){t.children&&(t.value=0)}),Si(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var a=e.call(this,t,n);return function t(e,r,n,a){var i=e.children;if(e.x=r,e.y=e.depth*a,e.dx=n,e.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(n=e.value?n/e.value:0;++c<o;)t(l=i[c],r,s=l.value*n,a),r+=s}}(a[0],0,r[0],r[1]/function t(e){var r=e.children,n=0;if(r&&(a=r.length))for(var a,i=-1;++i<a;)n=Math.max(n,t(r[i]));return 1+n}(a[0])),a}return n.size=function(t){return arguments.length?(r=t,n):r},Li(n,e)},t.layout.pie=function(){var e=Number,r=Ei,n=0,a=At,i=0;function o(l){var s,c=l.length,u=l.map(function(t,r){return+e.call(o,t,r)}),f=+("function"==typeof n?n.apply(this,arguments):n),d=("function"==typeof a?a.apply(this,arguments):a)-f,p=Math.min(Math.abs(d)/c,+("function"==typeof i?i.apply(this,arguments):i)),h=p*(d<0?-1:1),g=t.sum(u),y=g?(d-c*h)/g:0,v=t.range(c),m=[];return null!=r&&v.sort(r===Ei?function(t,e){return u[e]-u[t]}:function(t,e){return r(l[t],l[e])}),v.forEach(function(t){m[t]={data:l[t],value:s=u[t],startAngle:f,endAngle:f+=s*y+h,padAngle:p}}),m}return o.value=function(t){return arguments.length?(e=t,o):e},o.sort=function(t){return arguments.length?(r=t,o):r},o.startAngle=function(t){return arguments.length?(n=t,o):n},o.endAngle=function(t){return arguments.length?(a=t,o):a},o.padAngle=function(t){return arguments.length?(i=t,o):i},o};var Ei={};function Ii(t){return t.x}function Ni(t){return t.y}function Ri(t,e,r){t.y0=e,t.y=r}t.layout.stack=function(){var e=P,r=Bi,n=Hi,a=Ri,i=Ii,o=Ni;function l(s,c){if(!(p=s.length))return s;var u=s.map(function(t,r){return e.call(l,t,r)}),f=u.map(function(t){return t.map(function(t,e){return[i.call(l,t,e),o.call(l,t,e)]})}),d=r.call(l,f,c);u=t.permute(u,d),f=t.permute(f,d);var p,h,g,y,v=n.call(l,f,c),m=u[0].length;for(g=0;g<m;++g)for(a.call(l,u[0][g],y=v[g],f[0][g][1]),h=1;h<p;++h)a.call(l,u[h][g],y+=f[h-1][g][1],f[h][g][1]);return s}return l.values=function(t){return arguments.length?(e=t,l):e},l.order=function(t){return arguments.length?(r="function"==typeof t?t:Fi.get(t)||Bi,l):r},l.offset=function(t){return arguments.length?(n="function"==typeof t?t:ji.get(t)||Hi,l):n},l.x=function(t){return arguments.length?(i=t,l):i},l.y=function(t){return arguments.length?(o=t,l):o},l.out=function(t){return arguments.length?(a=t,l):a},l};var Fi=t.map({"inside-out":function(e){var r,n,a=e.length,i=e.map(qi),o=e.map(Vi),l=t.range(a).sort(function(t,e){return i[t]-i[e]}),s=0,c=0,u=[],f=[];for(r=0;r<a;++r)n=l[r],s<c?(s+=o[n],u.push(n)):(c+=o[n],f.push(n));return f.reverse().concat(u)},reverse:function(e){return t.range(e.length).reverse()},default:Bi}),ji=t.map({silhouette:function(t){var e,r,n,a=t.length,i=t[0].length,o=[],l=0,s=[];for(r=0;r<i;++r){for(e=0,n=0;e<a;e++)n+=t[e][r][1];n>l&&(l=n),o.push(n)}for(r=0;r<i;++r)s[r]=(l-o[r])/2;return s},wiggle:function(t){var e,r,n,a,i,o,l,s,c,u=t.length,f=t[0],d=f.length,p=[];for(p[0]=s=c=0,r=1;r<d;++r){for(e=0,a=0;e<u;++e)a+=t[e][r][1];for(e=0,i=0,l=f[r][0]-f[r-1][0];e<u;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*l);n<e;++n)o+=(t[n][r][1]-t[n][r-1][1])/l;i+=o*t[e][r][1]}p[r]=s-=a?i/a*l:0,s<c&&(c=s)}for(r=0;r<d;++r)p[r]-=c;return p},expand:function(t){var e,r,n,a=t.length,i=t[0].length,o=1/a,l=[];for(r=0;r<i;++r){for(e=0,n=0;e<a;e++)n+=t[e][r][1];if(n)for(e=0;e<a;e++)t[e][r][1]/=n;else for(e=0;e<a;e++)t[e][r][1]=o}for(r=0;r<i;++r)l[r]=0;return l},zero:Hi});function Bi(e){return t.range(e.length)}function Hi(t){for(var e=-1,r=t[0].length,n=[];++e<r;)n[e]=0;return n}function qi(t){for(var e,r=1,n=0,a=t[0][1],i=t.length;r<i;++r)(e=t[r][1])>a&&(n=r,a=e);return n}function Vi(t){return t.reduce(Ui,0)}function Ui(t,e){return t+e[1]}function Gi(t,e){return Yi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Yi(t,e){for(var r=-1,n=+t[0],a=(t[1]-n)/e,i=[];++r<=e;)i[r]=a*r+n;return i}function Xi(e){return[t.min(e),t.max(e)]}function Zi(t,e){return t.value-e.value}function Wi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Qi(t,e){t._pack_next=e,e._pack_prev=t}function Ji(t,e){var r=e.x-t.x,n=e.y-t.y,a=t.r+e.r;return.999*a*a>r*r+n*n}function $i(t){if((e=t.children)&&(s=e.length)){var e,r,n,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(e.forEach(Ki),(r=e[0]).x=-r.r,r.y=0,x(r),s>1&&((n=e[1]).x=n.r,n.y=0,x(n),s>2))for(eo(r,n,a=e[2]),x(a),Wi(r,a),r._pack_prev=a,Wi(a,n),n=r._pack_next,i=3;i<s;i++){eo(r,n,a=e[i]);var p=0,h=1,g=1;for(o=n._pack_next;o!==n;o=o._pack_next,h++)if(Ji(o,a)){p=1;break}if(1==p)for(l=r._pack_prev;l!==o._pack_prev&&!Ji(l,a);l=l._pack_prev,g++);p?(h<g||h==g&&n.r<r.r?Qi(r,n=o):Qi(r=l,n),i--):(Wi(r,a),n=a,x(a))}var y=(c+u)/2,v=(f+d)/2,m=0;for(i=0;i<s;i++)(a=e[i]).x-=y,a.y-=v,m=Math.max(m,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=m,e.forEach(to)}function x(t){c=Math.min(t.x-t.r,c),u=Math.max(t.x+t.r,u),f=Math.min(t.y-t.r,f),d=Math.max(t.y+t.r,d)}}function Ki(t){t._pack_next=t._pack_prev=t}function to(t){delete t._pack_next,delete t._pack_prev}function eo(t,e,r){var n=t.r+r.r,a=e.x-t.x,i=e.y-t.y;if(n&&(a||i)){var o=e.r+r.r,l=a*a+i*i,s=.5+((n*=n)-(o*=o))/(2*l),c=Math.sqrt(Math.max(0,2*o*(n+l)-(n-=l)*n-o*o))/(2*l);r.x=t.x+s*a+c*i,r.y=t.y+s*i-c*a}else r.x=t.x+n,r.y=t.y}function ro(t,e){return t.parent==e.parent?1:2}function no(t){var e=t.children;return e.length?e[0]:t.t}function ao(t){var e,r=t.children;return(e=r.length)?r[e-1]:t.t}function io(t,e,r){var n=r/(e.i-t.i);e.c-=n,e.s+=r,t.c+=n,e.z+=r,e.m+=r}function oo(t,e,r){return t.a.parent===e.parent?t.a:r}function lo(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function so(t,e){var r=t.x+e[3],n=t.y+e[0],a=t.dx-e[1]-e[3],i=t.dy-e[0]-e[2];return a<0&&(r+=a/2,a=0),i<0&&(n+=i/2,i=0),{x:r,y:n,dx:a,dy:i}}function co(t){var e=t[0],r=t[t.length-1];return e<r?[e,r]:[r,e]}function uo(t){return t.rangeExtent?t.rangeExtent():co(t.range())}function fo(t,e,r,n){var a=r(t[0],t[1]),i=n(e[0],e[1]);return function(t){return i(a(t))}}function po(t,e){var r,n=0,a=t.length-1,i=t[n],o=t[a];return o<i&&(r=n,n=a,a=r,r=i,i=o,o=r),t[n]=e.floor(i),t[a]=e.ceil(o),t}function ho(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:go}t.layout.histogram=function(){var e=!0,r=Number,n=Xi,a=Gi;function i(i,o){for(var l,s,c=[],u=i.map(r,this),f=n.call(this,u,o),d=a.call(this,f,u,o),p=(o=-1,u.length),h=d.length-1,g=e?1:1/p;++o<h;)(l=c[o]=[]).dx=d[o+1]-(l.x=d[o]),l.y=0;if(h>0)for(o=-1;++o<p;)(s=u[o])>=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,h)-1]).y+=g,l.push(i[o]));return c}return i.value=function(t){return arguments.length?(r=t,i):r},i.range=function(t){return arguments.length?(n=ye(t),i):n},i.bins=function(t){return arguments.length?(a="number"==typeof t?function(e){return Yi(e,t)}:ye(t),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Zi),n=0,a=[1,1];function i(t,i){var o=r.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Si(l,function(t){t.r=+u(t.value)}),Si(l,$i),n){var f=n*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Si(l,function(t){t.r+=f}),Si(l,$i),Si(l,function(t){t.r-=f})}return function t(e,r,n,a){var i=e.children;e.x=r+=a*e.x;e.y=n+=a*e.y;e.r*=a;if(i)for(var o=-1,l=i.length;++o<l;)t(i[o],r,n,a)}(l,s/2,c/2,e?1:1/Math.max(2*l.r/s,2*l.r/c)),o}return i.size=function(t){return arguments.length?(a=t,i):a},i.radius=function(t){return arguments.length?(e=null==t||"function"==typeof t?t:+t,i):e},i.padding=function(t){return arguments.length?(n=+t,i):n},Li(i,r)},t.layout.tree=function(){var e=t.layout.hierarchy().sort(null).value(null),r=ro,n=[1,1],a=null;function i(t,i){var c=e.call(this,t,i),u=c[0],f=function(t){var e,r={A:null,children:[t]},n=[r];for(;null!=(e=n.pop());)for(var a,i=e.children,o=0,l=i.length;o<l;++o)n.push((i[o]=a={_:i[o],parent:e,children:(a=i[o].children)&&a.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=a);return r.children[0]}(u);if(Si(f,o),f.parent.m=-f.z,Ci(f,l),a)Ci(u,s);else{var d=u,p=u,h=u;Ci(u,function(t){t.x<d.x&&(d=t),t.x>p.x&&(p=t),t.depth>h.depth&&(h=t)});var g=r(d,p)/2-d.x,y=n[0]/(p.x+r(p,d)/2+g),v=n[1]/(h.depth||1);Ci(u,function(t){t.x=(t.x+g)*y,t.y=t.depth*v})}return c}function o(t){var e=t.children,n=t.parent.children,a=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,a=t.children,i=a.length;for(;--i>=0;)(e=a[i]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var i=(e[0].z+e[e.length-1].z)/2;a?(t.z=a.z+r(t._,a._),t.m=t.z-i):t.z=i}else a&&(t.z=a.z+r(t._,a._));t.parent.A=function(t,e,n){if(e){for(var a,i=t,o=t,l=e,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=ao(l),i=no(i),l&&i;)s=no(s),(o=ao(o)).a=t,(a=l.z+f-i.z-c+r(l._,i._))>0&&(io(oo(l,t,n),t,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!ao(o)&&(o.t=l,o.m+=f-u),i&&!no(s)&&(s.t=i,s.m+=c-d,n=t)}return n}(t,a,t.parent.A||n[0])}function l(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function s(t){t.x*=n[0],t.y=t.depth*n[1]}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t)?s:null,i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null==(n=t)?null:s,i):a?n:null},Li(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=ro,n=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Si(c,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=l?u+=r(e,l):0,e.y=0,l=e)});var f=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(c),d=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(c),p=f.x-r(f,d)/2,h=d.x+r(d,f)/2;return Si(c,a?function(t){t.x=(t.x-c.x)*n[0],t.y=(c.y-t.y)*n[1]}:function(t){t.x=(t.x-p)/(h-p)*n[0],t.y=(1-(c.y?t.y/c.y:1))*n[1]}),s}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t),i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null!=(n=t),i):a?n:null},Li(i,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,a=[1,1],i=null,o=lo,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(t,e){for(var r,n,a=-1,i=t.length;++a<i;)n=(r=t[a]).value*(e<0?0:e),r.area=isNaN(n)||n<=0?0:n}function f(t){var e=t.children;if(e&&e.length){var r,n,a,i=o(t),l=[],c=e.slice(),d=1/0,g="slice"===s?i.dx:"dice"===s?i.dy:"slice-dice"===s?1&t.depth?i.dy:i.dx:Math.min(i.dx,i.dy);for(u(c,i.dx*i.dy/t.value),l.area=0;(a=c.length)>0;)l.push(r=c[a-1]),l.area+=r.area,"squarify"!==s||(n=p(l,g))<=d?(c.pop(),d=n):(l.area-=l.pop().area,h(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(h(l,g,i,!0),l.length=l.area=0),e.forEach(f)}}function d(t){var e=t.children;if(e&&e.length){var r,n=o(t),a=e.slice(),i=[];for(u(a,n.dx*n.dy/t.value),i.area=0;r=a.pop();)i.push(r),i.area+=r.area,null!=r.z&&(h(i,r.z?n.dx:n.dy,n,!a.length),i.length=i.area=0);e.forEach(d)}}function p(t,e){for(var r,n=t.area,a=0,i=1/0,o=-1,l=t.length;++o<l;)(r=t[o].area)&&(r<i&&(i=r),r>a&&(a=r));return e*=e,(n*=n)?Math.max(e*a*c/n,n/(e*i*c)):1/0}function h(t,e,r,a){var i,o=-1,l=t.length,s=r.x,c=r.y,u=e?n(t.area/e):0;if(e==r.dx){for((a||u>r.dy)&&(u=r.dy);++o<l;)(i=t[o]).x=s,i.y=c,i.dy=u,s+=i.dx=Math.min(r.x+r.dx-s,u?n(i.area/u):0);i.z=!0,i.dx+=r.x+r.dx-s,r.y+=u,r.dy-=u}else{for((a||u>r.dx)&&(u=r.dx);++o<l;)(i=t[o]).x=s,i.y=c,i.dx=u,c+=i.dy=Math.min(r.y+r.dy-c,u?n(i.area/u):0);i.z=!1,i.dy+=r.y+r.dy-c,r.x+=u,r.dx-=u}}function g(t){var n=e||r(t),i=n[0];return i.x=i.y=0,i.value?(i.dx=a[0],i.dy=a[1]):i.dx=i.dy=0,e&&r.revalue(i),u([i],i.dx*i.dy/i.value),(e?d:f)(i),l&&(e=n),n}return g.size=function(t){return arguments.length?(a=t,g):a},g.padding=function(t){if(!arguments.length)return i;function e(e){return so(e,t)}var r;return o=null==(i=t)?lo:"function"==(r=typeof t)?function(e){var r=t.call(g,e,e.depth);return null==r?lo(e):so(e,"number"==typeof r?[r,r,r,r]:r)}:"number"===r?(t=[t,t,t,t],e):e,g},g.round=function(t){return arguments.length?(n=t?Math.round:Number,g):n!=Number},g.sticky=function(t){return arguments.length?(l=t,e=null,g):l},g.ratio=function(t){return arguments.length?(c=t,g):c},g.mode=function(t){return arguments.length?(s=t+"",g):s},Li(g,r)},t.random={normal:function(t,e){var r=arguments.length;return r<2&&(e=1),r<1&&(t=0),function(){var r,n,a;do{a=(r=2*Math.random()-1)*r+(n=2*Math.random()-1)*n}while(!a||a>1);return t+e*r*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r<t;r++)e+=Math.random();return e}}},t.scale={};var go={floor:P,ceil:P};function yo(e,r,n,a){var i=[],o=[],l=0,s=Math.min(e.length,r.length)-1;for(e[s]<e[0]&&(e=e.slice().reverse(),r=r.slice().reverse());++l<=s;)i.push(n(e[l-1],e[l])),o.push(a(r[l-1],r[l]));return function(r){var n=t.bisect(e,r,1,s)-1;return o[n](i[n](r))}}function vo(e,r){return t.rebind(e,r,"range","rangeRound","interpolate","clamp")}function mo(t,e){return po(t,ho(xo(t,e)[2])),po(t,ho(xo(t,e)[2])),t}function xo(t,e){null==e&&(e=10);var r=co(t),n=r[1]-r[0],a=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),i=e/n*a;return i<=.15?a*=10:i<=.35?a*=5:i<=.75&&(a*=2),r[0]=Math.ceil(r[0]/a)*a,r[1]=Math.floor(r[1]/a)*a+.5*a,r[2]=a,r}function bo(e,r){return t.range.apply(t,xo(e,r))}function _o(e,r,n){var a=xo(e,r);if(n){var i=Oe.exec(n);if(i.shift(),"s"===i[8]){var o=t.formatPrefix(Math.max(m(a[0]),m(a[1])));return i[7]||(i[7]="."+ko(o.scale(a[2]))),i[8]="f",n=t.format(i.join("")),function(t){return n(o.scale(t))+o.symbol}}i[7]||(i[7]="."+function(t,e){var r=ko(e[2]);return t in wo?Math.abs(r-ko(Math.max(m(e[0]),m(e[1]))))+ +("e"!==t):r-2*("%"===t)}(i[8],a)),n=i.join("")}else n=",."+ko(a[2])+"f";return t.format(n)}t.scale.linear=function(){return function t(e,r,n,a){var i,o;function l(){var t=Math.min(e.length,r.length)>2?yo:fo,l=a?vi:yi;return i=t(e,r,l,n),o=t(r,e,l,Wa),s}function s(t){return i(t)}s.invert=function(t){return o(t)};s.domain=function(t){return arguments.length?(e=t.map(Number),l()):e};s.range=function(t){return arguments.length?(r=t,l()):r};s.rangeRound=function(t){return s.range(t).interpolate(ci)};s.clamp=function(t){return arguments.length?(a=t,l()):a};s.interpolate=function(t){return arguments.length?(n=t,l()):n};s.ticks=function(t){return bo(e,t)};s.tickFormat=function(t,r){return _o(e,t,r)};s.nice=function(t){return mo(e,t),l()};s.copy=function(){return t(e,r,n,a)};return l()}([0,1],[0,1],Wa,!1)};var wo={s:1,g:1,p:1,r:1,e:1};function ko(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,a,i){function o(t){return(a?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function l(t){return a?Math.pow(n,t):-Math.pow(n,-t)}function s(t){return r(o(t))}s.invert=function(t){return l(r.invert(t))};s.domain=function(t){return arguments.length?(a=t[0]>=0,r.domain((i=t.map(Number)).map(o)),s):i};s.base=function(t){return arguments.length?(n=+t,r.domain(i.map(o)),s):n};s.nice=function(){var t=po(i.map(o),a?Math:To);return r.domain(t),i=t.map(l),s};s.ticks=function(){var t=co(i),e=[],r=t[0],s=t[1],c=Math.floor(o(r)),u=Math.ceil(o(s)),f=n%1?2:n;if(isFinite(u-c)){if(a){for(;c<u;c++)for(var d=1;d<f;d++)e.push(l(c)*d);e.push(l(c))}else for(e.push(l(c));c++<u;)for(var d=f-1;d>0;d--)e.push(l(c)*d);for(c=0;e[c]<r;c++);for(u=e.length;e[u-1]>s;u--);e=e.slice(c,u)}return e};s.tickFormat=function(e,r){if(!arguments.length)return Mo;arguments.length<2?r=Mo:"function"!=typeof r&&(r=t.format(r));var a=Math.max(1,n*e/s.ticks().length);return function(t){var e=t/l(Math.round(o(t)));return e*n<n-.5&&(e*=n),e<=a?r(t):""}};s.copy=function(){return e(r.copy(),n,a,i)};return vo(s,r)}(t.scale.linear().domain([0,1]),10,!0,[1,10])};var Mo=t.format(".0e"),To={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};function Ao(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}t.scale.pow=function(){return function t(e,r,n){var a=Ao(r),i=Ao(1/r);function o(t){return e(a(t))}o.invert=function(t){return i(e.invert(t))};o.domain=function(t){return arguments.length?(e.domain((n=t.map(Number)).map(a)),o):n};o.ticks=function(t){return bo(n,t)};o.tickFormat=function(t,e){return _o(n,t,e)};o.nice=function(t){return o.domain(mo(n,t))};o.exponent=function(t){return arguments.length?(a=Ao(r=t),i=Ao(1/r),e.domain(n.map(a)),o):r};o.copy=function(){return t(e.copy(),r,n)};return vo(o,e)}(t.scale.linear(),1,[0,1])},t.scale.sqrt=function(){return t.scale.pow().exponent(.5)},t.scale.ordinal=function(){return function e(r,n){var a,i,o;function l(t){return i[((a.get(t)||("range"===n.t?a.set(t,r.push(t)):NaN))-1)%i.length]}function s(e,n){return t.range(r.length).map(function(t){return e+n*t})}l.domain=function(t){if(!arguments.length)return r;r=[],a=new b;for(var e,i=-1,o=t.length;++i<o;)a.has(e=t[i])||a.set(e,r.push(e));return l[n.t].apply(l,n.a)};l.range=function(t){return arguments.length?(i=t,o=0,n={t:"range",a:arguments},l):i};l.rangePoints=function(t,e){arguments.length<2&&(e=0);var a=t[0],c=t[1],u=r.length<2?(a=(a+c)/2,0):(c-a)/(r.length-1+e);return i=s(a+u*e/2,u),o=0,n={t:"rangePoints",a:arguments},l};l.rangeRoundPoints=function(t,e){arguments.length<2&&(e=0);var a=t[0],c=t[1],u=r.length<2?(a=c=Math.round((a+c)/2),0):(c-a)/(r.length-1+e)|0;return i=s(a+Math.round(u*e/2+(c-a-(r.length-1+e)*u)/2),u),o=0,n={t:"rangeRoundPoints",a:arguments},l};l.rangeBands=function(t,e,a){arguments.length<2&&(e=0),arguments.length<3&&(a=e);var c=t[1]<t[0],u=t[c-0],f=t[1-c],d=(f-u)/(r.length-e+2*a);return i=s(u+d*a,d),c&&i.reverse(),o=d*(1-e),n={t:"rangeBands",a:arguments},l};l.rangeRoundBands=function(t,e,a){arguments.length<2&&(e=0),arguments.length<3&&(a=e);var c=t[1]<t[0],u=t[c-0],f=t[1-c],d=Math.floor((f-u)/(r.length-e+2*a));return i=s(u+Math.round((f-u-(r.length-e)*d)/2),d),c&&i.reverse(),o=Math.round(d*(1-e)),n={t:"rangeRoundBands",a:arguments},l};l.rangeBand=function(){return o};l.rangeExtent=function(){return co(n.a[0])};l.copy=function(){return e(r,n)};return l.domain(r)}([],{t:"range",a:[[]]})},t.scale.category10=function(){return t.scale.ordinal().range(Lo)},t.scale.category20=function(){return t.scale.ordinal().range(Co)},t.scale.category20b=function(){return t.scale.ordinal().range(So)},t.scale.category20c=function(){return t.scale.ordinal().range(Oo)};var Lo=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(le),Co=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(le),So=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(le),Oo=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(le);function Po(){return 0}t.scale.quantile=function(){return function e(r,n){var a;function i(){var e=0,i=n.length;for(a=[];++e<i;)a[e-1]=t.quantile(r,e/i);return o}function o(e){if(!isNaN(e=+e))return n[t.bisect(a,e)]}o.domain=function(t){return arguments.length?(r=t.map(p).filter(h).sort(d),i()):r};o.range=function(t){return arguments.length?(n=t,i()):n};o.quantiles=function(){return a};o.invertExtent=function(t){return(t=n.indexOf(t))<0?[NaN,NaN]:[t>0?a[t-1]:r[0],t<a.length?a[t]:r[r.length-1]]};o.copy=function(){return e(r,n)};return i()}([],[])},t.scale.quantize=function(){return function t(e,r,n){var a,i;function o(t){return n[Math.max(0,Math.min(i,Math.floor(a*(t-e))))]}function l(){return a=n.length/(r-e),i=n.length-1,o}o.domain=function(t){return arguments.length?(e=+t[0],r=+t[t.length-1],l()):[e,r]};o.range=function(t){return arguments.length?(n=t,l()):n};o.invertExtent=function(t){return[t=(t=n.indexOf(t))<0?NaN:t/a+e,t+1/a]};o.copy=function(){return t(e,r,n)};return l()}(0,1,[0,1])},t.scale.threshold=function(){return function e(r,n){function a(e){if(e<=e)return n[t.bisect(r,e)]}a.domain=function(t){return arguments.length?(r=t,a):r};a.range=function(t){return arguments.length?(n=t,a):n};a.invertExtent=function(t){return t=n.indexOf(t),[r[t-1],r[t]]};a.copy=function(){return e(r,n)};return a}([.5],[0,1])},t.scale.identity=function(){return function t(e){function r(t){return+t}r.invert=r;r.domain=r.range=function(t){return arguments.length?(e=t.map(r),r):e};r.ticks=function(t){return bo(e,t)};r.tickFormat=function(t,r){return _o(e,t,r)};r.copy=function(){return t(e)};return r}([0,1])},t.svg={},t.svg.arc=function(){var t=zo,e=Eo,r=Po,n=Do,a=Io,i=No,o=Ro;function l(){var l=Math.max(0,+t.apply(this,arguments)),c=Math.max(0,+e.apply(this,arguments)),u=a.apply(this,arguments)-Ct,f=i.apply(this,arguments)-Ct,d=Math.abs(f-u),p=u>f?0:1;if(c<l&&(h=c,c=l,l=h),d>=Lt)return s(c,p)+(l?s(l,1-p):"")+"Z";var h,g,y,v,m,x,b,_,w,k,M,T,A=0,L=0,C=[];if((v=(+o.apply(this,arguments)||0)/2)&&(y=n===Do?Math.sqrt(l*l+c*c):+n.apply(this,arguments),p||(L*=-1),c&&(L=Et(y/c*Math.sin(v))),l&&(A=Et(y/l*Math.sin(v)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Tt?0:1;if(L&&Fo(m,x,b,_)===p^S){var O=(u+f)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-A),k=l*Math.sin(f-A),M=l*Math.cos(u+A),T=l*Math.sin(u+A);var P=Math.abs(u-f+2*A)<=Tt?0:1;if(A&&Fo(w,k,M,T)===1-p^P){var D=(u+f)/2;w=l*Math.cos(D),k=l*Math.sin(D),M=T=null}}else w=k=0;if(d>kt&&(h=Math.min(Math.abs(c-l)/2,+r.apply(this,arguments)))>.001){g=l<c^p?0:1;var z=h,E=h;if(d<Tt){var I=null==M?[w,k]:null==b?[m,x]:la([m,x],[M,T],[b,_],[w,k]),N=m-I[0],R=x-I[1],F=b-I[0],j=_-I[1],B=1/Math.sin(Math.acos((N*F+R*j)/(Math.sqrt(N*N+R*R)*Math.sqrt(F*F+j*j)))/2),H=Math.sqrt(I[0]*I[0]+I[1]*I[1]);E=Math.min(h,(l-H)/(B-1)),z=Math.min(h,(c-H)/(B+1))}if(null!=b){var q=jo(null==M?[w,k]:[M,T],[m,x],c,z,p),V=jo([b,_],[w,k],c,z,p);h===z?C.push("M",q[0],"A",z,",",z," 0 0,",g," ",q[1],"A",c,",",c," 0 ",1-p^Fo(q[1][0],q[1][1],V[1][0],V[1][1]),",",p," ",V[1],"A",z,",",z," 0 0,",g," ",V[0]):C.push("M",q[0],"A",z,",",z," 0 1,",g," ",V[0])}else C.push("M",m,",",x);if(null!=M){var U=jo([m,x],[M,T],l,-E,p),G=jo([w,k],null==b?[m,x]:[b,_],l,-E,p);h===E?C.push("L",G[0],"A",E,",",E," 0 0,",g," ",G[1],"A",l,",",l," 0 ",p^Fo(G[1][0],G[1][1],U[1][0],U[1][1]),",",1-p," ",U[1],"A",E,",",E," 0 0,",g," ",U[0]):C.push("L",G[0],"A",E,",",E," 0 0,",g," ",U[0])}else C.push("L",w,",",k)}else C.push("M",m,",",x),null!=b&&C.push("A",c,",",c," 0 ",S,",",p," ",b,",",_),C.push("L",w,",",k),null!=M&&C.push("A",l,",",l," 0 ",P,",",1-p," ",M,",",T);return C.push("Z"),C.join("")}function s(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}return l.innerRadius=function(e){return arguments.length?(t=ye(e),l):t},l.outerRadius=function(t){return arguments.length?(e=ye(t),l):e},l.cornerRadius=function(t){return arguments.length?(r=ye(t),l):r},l.padRadius=function(t){return arguments.length?(n=t==Do?Do:ye(t),l):n},l.startAngle=function(t){return arguments.length?(a=ye(t),l):a},l.endAngle=function(t){return arguments.length?(i=ye(t),l):i},l.padAngle=function(t){return arguments.length?(o=ye(t),l):o},l.centroid=function(){var r=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,n=(+a.apply(this,arguments)+ +i.apply(this,arguments))/2-Ct;return[Math.cos(n)*r,Math.sin(n)*r]},l};var Do="auto";function zo(t){return t.innerRadius}function Eo(t){return t.outerRadius}function Io(t){return t.startAngle}function No(t){return t.endAngle}function Ro(t){return t&&t.padAngle}function Fo(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function jo(t,e,r,n,a){var i=t[0]-e[0],o=t[1]-e[1],l=(a?n:-n)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=t[0]+s,f=t[1]+c,d=e[0]+s,p=e[1]+c,h=(u+d)/2,g=(f+p)/2,y=d-u,v=p-f,m=y*y+v*v,x=r-n,b=u*p-d*f,_=(v<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*v-y*_)/m,k=(-b*y-v*_)/m,M=(b*v+y*_)/m,T=(-b*y+v*_)/m,A=w-h,L=k-g,C=M-h,S=T-g;return A*A+L*L>C*C+S*S&&(w=M,k=T),[[w-s,k-c],[w*r/x,k*r/x]]}function Bo(t){var e=ea,r=ra,n=Yr,a=qo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=ye(e),p=ye(r);function h(){s.push("M",a(t(c),o))}for(;++u<f;)n.call(this,l=i[u],u)?c.push([+d.call(this,l,u),+p.call(this,l,u)]):c.length&&(h(),c=[]);return c.length&&h(),s.length?s.join(""):null}return l.x=function(t){return arguments.length?(e=t,l):e},l.y=function(t){return arguments.length?(r=t,l):r},l.defined=function(t){return arguments.length?(n=t,l):n},l.interpolate=function(t){return arguments.length?(i="function"==typeof t?a=t:(a=Ho.get(t)||qo).key,l):i},l.tension=function(t){return arguments.length?(o=t,l):o},l}t.svg.line=function(){return Bo(P)};var Ho=t.map({linear:qo,"linear-closed":Vo,step:function(t){var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];for(;++e<r;)a.push("H",(n[0]+(n=t[e])[0])/2,"V",n[1]);r>1&&a.push("H",n[0]);return a.join("")},"step-before":Uo,"step-after":Go,basis:Zo,"basis-open":function(t){if(t.length<4)return qo(t);var e,r=[],n=-1,a=t.length,i=[0],o=[0];for(;++n<3;)e=t[n],i.push(e[0]),o.push(e[1]);r.push(Wo($o,i)+","+Wo($o,o)),--n;for(;++n<a;)e=t[n],i.shift(),i.push(e[0]),o.shift(),o.push(e[1]),Ko(r,i,o);return r.join("")},"basis-closed":function(t){var e,r,n=-1,a=t.length,i=a+4,o=[],l=[];for(;++n<4;)r=t[n%a],o.push(r[0]),l.push(r[1]);e=[Wo($o,o),",",Wo($o,l)],--n;for(;++n<i;)r=t[n%a],o.shift(),o.push(r[0]),l.shift(),l.push(r[1]),Ko(e,o,l);return e.join("")},bundle:function(t,e){var r=t.length-1;if(r)for(var n,a,i=t[0][0],o=t[0][1],l=t[r][0]-i,s=t[r][1]-o,c=-1;++c<=r;)n=t[c],a=c/r,n[0]=e*n[0]+(1-e)*(i+a*l),n[1]=e*n[1]+(1-e)*(o+a*s);return Zo(t)},cardinal:function(t,e){return t.length<3?qo(t):t[0]+Yo(t,Xo(t,e))},"cardinal-open":function(t,e){return t.length<4?qo(t):t[1]+Yo(t.slice(1,-1),Xo(t,e))},"cardinal-closed":function(t,e){return t.length<3?Vo(t):t[0]+Yo((t.push(t[0]),t),Xo([t[t.length-2]].concat(t,[t[1]]),e))},monotone:function(t){return t.length<3?qo(t):t[0]+Yo(t,function(t){var e,r,n,a,i=[],o=function(t){var e=0,r=t.length-1,n=[],a=t[0],i=t[1],o=n[0]=tl(a,i);for(;++e<r;)n[e]=(o+(o=tl(a=i,i=t[e+1])))/2;return n[e]=o,n}(t),l=-1,s=t.length-1;for(;++l<s;)e=tl(t[l],t[l+1]),m(e)<kt?o[l]=o[l+1]=0:(r=o[l]/e,n=o[l+1]/e,(a=r*r+n*n)>9&&(a=3*e/Math.sqrt(a),o[l]=a*r,o[l+1]=a*n));l=-1;for(;++l<=s;)a=(t[Math.min(s,l+1)][0]-t[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(t))}});function qo(t){return t.length>1?t.join("L"):t+"Z"}function Vo(t){return t.join("L")+"Z"}function Uo(t){for(var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];++e<r;)a.push("V",(n=t[e])[1],"H",n[0]);return a.join("")}function Go(t){for(var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];++e<r;)a.push("H",(n=t[e])[0],"V",n[1]);return a.join("")}function Yo(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return qo(t);var r=t.length!=e.length,n="",a=t[0],i=t[1],o=e[0],l=o,s=1;if(r&&(n+="Q"+(i[0]-2*o[0]/3)+","+(i[1]-2*o[1]/3)+","+i[0]+","+i[1],a=t[1],s=2),e.length>1){l=e[1],i=t[s],s++,n+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;c<e.length;c++,s++)i=t[s],l=e[c],n+="S"+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1]}if(r){var u=t[s];n+="Q"+(i[0]+2*l[0]/3)+","+(i[1]+2*l[1]/3)+","+u[0]+","+u[1]}return n}function Xo(t,e){for(var r,n=[],a=(1-e)/2,i=t[0],o=t[1],l=1,s=t.length;++l<s;)r=i,i=o,o=t[l],n.push([a*(o[0]-r[0]),a*(o[1]-r[1])]);return n}function Zo(t){if(t.length<3)return qo(t);var e=1,r=t.length,n=t[0],a=n[0],i=n[1],o=[a,a,a,(n=t[1])[0]],l=[i,i,i,n[1]],s=[a,",",i,"L",Wo($o,o),",",Wo($o,l)];for(t.push(t[r-1]);++e<=r;)n=t[e],o.shift(),o.push(n[0]),l.shift(),l.push(n[1]),Ko(s,o,l);return t.pop(),s.push("L",n),s.join("")}function Wo(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}Ho.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Qo=[0,2/3,1/3,0],Jo=[0,1/3,2/3,0],$o=[0,1/6,2/3,1/6];function Ko(t,e,r){t.push("C",Wo(Qo,e),",",Wo(Qo,r),",",Wo(Jo,e),",",Wo(Jo,r),",",Wo($o,e),",",Wo($o,r))}function tl(t,e){return(e[1]-t[1])/(e[0]-t[0])}function el(t){for(var e,r,n,a=-1,i=t.length;++a<i;)r=(e=t[a])[0],n=e[1]-Ct,e[0]=r*Math.cos(n),e[1]=r*Math.sin(n);return t}function rl(t){var e=ea,r=ea,n=0,a=ra,i=Yr,o=qo,l=o.key,s=o,c="L",u=.7;function f(l){var f,d,p,h=[],g=[],y=[],v=-1,m=l.length,x=ye(e),b=ye(n),_=e===r?function(){return d}:ye(r),w=n===a?function(){return p}:ye(a);function k(){h.push("M",o(t(y),u),c,s(t(g.reverse()),u),"Z")}for(;++v<m;)i.call(this,f=l[v],v)?(g.push([d=+x.call(this,f,v),p=+b.call(this,f,v)]),y.push([+_.call(this,f,v),+w.call(this,f,v)])):g.length&&(k(),g=[],y=[]);return g.length&&k(),h.length?h.join(""):null}return f.x=function(t){return arguments.length?(e=r=t,f):r},f.x0=function(t){return arguments.length?(e=t,f):e},f.x1=function(t){return arguments.length?(r=t,f):r},f.y=function(t){return arguments.length?(n=a=t,f):a},f.y0=function(t){return arguments.length?(n=t,f):n},f.y1=function(t){return arguments.length?(a=t,f):a},f.defined=function(t){return arguments.length?(i=t,f):i},f.interpolate=function(t){return arguments.length?(l="function"==typeof t?o=t:(o=Ho.get(t)||qo).key,s=o.reverse||o,c=o.closed?"M":"L",f):l},f.tension=function(t){return arguments.length?(u=t,f):u},f}function nl(t){return t.radius}function al(t){return[t.x,t.y]}function il(){return 64}function ol(){return"circle"}function ll(t){var e=Math.sqrt(t/Tt);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}t.svg.line.radial=function(){var t=Bo(el);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Uo.reverse=Go,Go.reverse=Uo,t.svg.area=function(){return rl(P)},t.svg.area.radial=function(){var t=rl(el);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},t.svg.chord=function(){var t=Hn,e=qn,r=nl,n=Io,a=No;function i(r,n){var a,i,c=o(this,t,r,n),u=o(this,e,r,n);return"M"+c.p0+l(c.r,c.p1,c.a1-c.a0)+(i=u,(a=c).a0==i.a0&&a.a1==i.a1?s(c.r,c.p1,c.r,c.p0):s(c.r,c.p1,u.r,u.p0)+l(u.r,u.p1,u.a1-u.a0)+s(u.r,u.p1,c.r,c.p0))+"Z"}function o(t,e,i,o){var l=e.call(t,i,o),s=r.call(t,l,o),c=n.call(t,l,o)-Ct,u=a.call(t,l,o)-Ct;return{r:s,a0:c,a1:u,p0:[s*Math.cos(c),s*Math.sin(c)],p1:[s*Math.cos(u),s*Math.sin(u)]}}function l(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Tt)+",1 "+e}function s(t,e,r,n){return"Q 0,0 "+n}return i.radius=function(t){return arguments.length?(r=ye(t),i):r},i.source=function(e){return arguments.length?(t=ye(e),i):t},i.target=function(t){return arguments.length?(e=ye(t),i):e},i.startAngle=function(t){return arguments.length?(n=ye(t),i):n},i.endAngle=function(t){return arguments.length?(a=ye(t),i):a},i},t.svg.diagonal=function(){var t=Hn,e=qn,r=al;function n(n,a){var i=t.call(this,n,a),o=e.call(this,n,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(r))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return n.source=function(e){return arguments.length?(t=ye(e),n):t},n.target=function(t){return arguments.length?(e=ye(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=al,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=ol,e=il;function r(r,n){return(sl.get(t.call(this,r,n))||ll)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ye(e),r):t},r.size=function(t){return arguments.length?(e=ye(t),r):e},r};var sl=t.map({circle:ll,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*ul)),r=e*ul;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/cl),r=e*cl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/cl),r=e*cl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=sl.keys();var cl=Math.sqrt(3),ul=Math.tan(30*St);X.transition=function(t){for(var e,r,n=hl||++vl,a=bl(t),i=[],o=gl||{time:Date.now(),ease:ai,delay:0,duration:250},l=-1,s=this.length;++l<s;){i.push(e=[]);for(var c=this[l],u=-1,f=c.length;++u<f;)(r=c[u])&&_l(r,u,a,n,o),e.push(r)}return pl(i,a,n)},X.interrupt=function(t){return this.each(null==t?fl:dl(bl(t)))};var fl=dl(bl());function dl(t){return function(){var e,r,n;(e=this[t])&&(n=e[r=e.active])&&(n.timer.c=null,n.timer.t=NaN,--e.count?delete e[r]:delete this[t],e.active+=.5,n.event&&n.event.interrupt.call(this,this.__data__,n.index))}}function pl(t,e,r){return q(t,yl),t.namespace=e,t.id=r,t}var hl,gl,yl=[],vl=0;function ml(t,e,r,n){var a=t.id,i=t.namespace;return ut(t,"function"==typeof r?function(t,o,l){t[i][a].tween.set(e,n(r.call(t,t.__data__,o,l)))}:(r=n(r),function(t){t[i][a].tween.set(e,r)}))}function xl(t){return null==t&&(t=""),function(){this.textContent=t}}function bl(t){return null==t?"__transition__":"__transition_"+t+"__"}function _l(t,e,r,n,a){var i,o,l,s,c,u=t[r]||(t[r]={active:0,count:0}),f=u[n];function d(r){var a=u.active,d=u[a];for(var h in d&&(d.timer.c=null,d.timer.t=NaN,--u.count,delete u[a],d.event&&d.event.interrupt.call(t,t.__data__,d.index)),u)if(+h<n){var g=u[h];g.timer.c=null,g.timer.t=NaN,--u.count,delete u[h]}o.c=p,Me(function(){return o.c&&p(r||1)&&(o.c=null,o.t=NaN),1},0,i),u.active=n,f.event&&f.event.start.call(t,t.__data__,e),c=[],f.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&c.push(n)}),s=f.ease,l=f.duration}function p(a){for(var i=a/l,o=s(i),d=c.length;d>0;)c[--d].call(t,o);if(i>=1)return f.event&&f.event.end.call(t,t.__data__,e),--u.count?delete u[n]:delete t[r],1}f||(i=a.time,o=Me(function(t){var e=f.delay;if(o.t=e+i,e<=t)return d(t-e);o.c=d},0,i),f=u[n]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:e},a=null,++u.count)}yl.call=X.call,yl.empty=X.empty,yl.node=X.node,yl.size=X.size,t.transition=function(e,r){return e&&e.transition?hl?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=yl,yl.select=function(t){var e,r,n,a=this.id,i=this.namespace,o=[];t=Z(t);for(var l=-1,s=this.length;++l<s;){o.push(e=[]);for(var c=this[l],u=-1,f=c.length;++u<f;)(n=c[u])&&(r=t.call(n,n.__data__,u,l))?("__data__"in n&&(r.__data__=n.__data__),_l(r,u,i,a,n[i][a]),e.push(r)):e.push(null)}return pl(o,i,a)},yl.selectAll=function(t){var e,r,n,a,i,o=this.id,l=this.namespace,s=[];t=W(t);for(var c=-1,u=this.length;++c<u;)for(var f=this[c],d=-1,p=f.length;++d<p;)if(n=f[d]){i=n[l][o],r=t.call(n,n.__data__,d,c),s.push(e=[]);for(var h=-1,g=r.length;++h<g;)(a=r[h])&&_l(a,h,l,o,i),e.push(a)}return pl(s,l,o)},yl.filter=function(t){var e,r,n=[];"function"!=typeof t&&(t=ct(t));for(var a=0,i=this.length;a<i;a++){n.push(e=[]);for(var o,l=0,s=(o=this[a]).length;l<s;l++)(r=o[l])&&t.call(r,r.__data__,l,a)&&e.push(r)}return pl(n,this.namespace,this.id)},yl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):ut(this,null==e?function(e){e[n][r].tween.remove(t)}:function(a){a[n][r].tween.set(t,e)})},yl.attr=function(e,r){if(arguments.length<2){for(r in e)this.attr(r,e[r]);return this}var n="transform"==e?gi:Wa,a=t.ns.qualify(e);function i(){this.removeAttribute(a)}function o(){this.removeAttributeNS(a.space,a.local)}return ml(this,"attr."+e,r,a.local?function(t){return null==t?o:(t+="",function(){var e,r=this.getAttributeNS(a.space,a.local);return r!==t&&(e=n(r,t),function(t){this.setAttributeNS(a.space,a.local,e(t))})})}:function(t){return null==t?i:(t+="",function(){var e,r=this.getAttribute(a);return r!==t&&(e=n(r,t),function(t){this.setAttribute(a,e(t))})})})},yl.attrTween=function(e,r){var n=t.ns.qualify(e);return this.tween("attr."+e,n.local?function(t,e){var a=r.call(this,t,e,this.getAttributeNS(n.space,n.local));return a&&function(t){this.setAttributeNS(n.space,n.local,a(t))}}:function(t,e){var a=r.call(this,t,e,this.getAttribute(n));return a&&function(t){this.setAttribute(n,a(t))}})},yl.style=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=""),t)this.style(r,t[r],e);return this}r=""}function a(){this.style.removeProperty(t)}return ml(this,"style."+t,e,function(e){return null==e?a:(e+="",function(){var n,a=o(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(n=Wa(a,e),function(e){this.style.setProperty(t,n(e),r)})})})},yl.styleTween=function(t,e,r){return arguments.length<3&&(r=""),this.tween("style."+t,function(n,a){var i=e.call(this,n,a,o(this).getComputedStyle(this,null).getPropertyValue(t));return i&&function(e){this.style.setProperty(t,i(e),r)}})},yl.text=function(t){return ml(this,"text",t,xl)},yl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},yl.ease=function(e){var r=this.id,n=this.namespace;return arguments.length<1?this.node()[n][r].ease:("function"!=typeof e&&(e=t.ease.apply(t,arguments)),ut(this,function(t){t[n][r].ease=e}))},yl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:ut(this,"function"==typeof t?function(n,a,i){n[r][e].delay=+t.call(n,n.__data__,a,i)}:(t=+t,function(n){n[r][e].delay=t}))},yl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:ut(this,"function"==typeof t?function(n,a,i){n[r][e].duration=Math.max(1,t.call(n,n.__data__,a,i))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},yl.each=function(e,r){var n=this.id,a=this.namespace;if(arguments.length<2){var i=gl,o=hl;try{hl=n,ut(this,function(t,r,i){gl=t[a][n],e.call(t,t.__data__,r,i)})}finally{gl=i,hl=o}}else ut(this,function(i){var o=i[a][n];(o.event||(o.event=t.dispatch("start","end","interrupt"))).on(e,r)});return this},yl.transition=function(){for(var t,e,r,n=this.id,a=++vl,i=this.namespace,o=[],l=0,s=this.length;l<s;l++){o.push(t=[]);for(var c,u=0,f=(c=this[l]).length;u<f;u++)(e=c[u])&&_l(e,u,i,a,{time:(r=e[i][n]).time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration}),t.push(e)}return pl(o,i,a)},t.svg.axis=function(){var e,r=t.scale.linear(),a=wl,i=6,o=6,l=3,s=[10],c=null;function u(n){n.each(function(){var n,u=t.select(this),f=this.__chart__||r,d=this.__chart__=r.copy(),p=null==c?d.ticks?d.ticks.apply(d,s):d.domain():c,h=null==e?d.tickFormat?d.tickFormat.apply(d,s):P:e,g=u.selectAll(".tick").data(p,d),y=g.enter().insert("g",".domain").attr("class","tick").style("opacity",kt),v=t.transition(g.exit()).style("opacity",kt).remove(),m=t.transition(g.order()).style("opacity",1),x=Math.max(i,0)+l,b=uo(d),_=u.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),t.transition(_));y.append("line"),y.append("text");var k,M,T,A,L=y.select("line"),C=m.select("line"),S=g.select("text").text(h),O=y.select("text"),D=m.select("text"),z="top"===a||"left"===a?-1:1;if("bottom"===a||"top"===a?(n=Ml,k="x",T="y",M="x2",A="y2",S.attr("dy",z<0?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+z*o+"V0H"+b[1]+"V"+z*o)):(n=Tl,k="y",T="x",M="y2",A="x2",S.attr("dy",".32em").style("text-anchor",z<0?"end":"start"),w.attr("d","M"+z*o+","+b[0]+"H0V"+b[1]+"H"+z*o)),L.attr(A,z*i),O.attr(T,z*x),C.attr(M,0).attr(A,z*i),D.attr(k,0).attr(T,z*x),d.rangeBand){var E=d,I=E.rangeBand()/2;f=d=function(t){return E(t)+I}}else f.rangeBand?f=d:v.call(n,d,f);y.call(n,f,d),m.call(n,d,d)})}return u.scale=function(t){return arguments.length?(r=t,u):r},u.orient=function(t){return arguments.length?(a=t in kl?t+"":wl,u):a},u.ticks=function(){return arguments.length?(s=n(arguments),u):s},u.tickValues=function(t){return arguments.length?(c=t,u):c},u.tickFormat=function(t){return arguments.length?(e=t,u):e},u.tickSize=function(t){var e=arguments.length;return e?(i=+t,o=+arguments[e-1],u):i},u.innerTickSize=function(t){return arguments.length?(i=+t,u):i},u.outerTickSize=function(t){return arguments.length?(o=+t,u):o},u.tickPadding=function(t){return arguments.length?(l=+t,u):l},u.tickSubdivide=function(){return arguments.length&&u},u};var wl="bottom",kl={top:1,right:1,bottom:1,left:1};function Ml(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function Tl(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}t.svg.brush=function(){var e,r,n=B(d,"brushstart","brush","brushend"),a=null,i=null,l=[0,0],s=[0,0],c=!0,u=!0,f=Ll[0];function d(e){e.each(function(){var e=t.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",y).on("touchstart.brush",y),r=e.selectAll(".background").data([0]);r.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),e.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var n=e.selectAll(".resize").data(f,P);n.exit().remove(),n.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Al[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),n.style("display",d.empty()?"none":null);var o,l=t.transition(e),s=t.transition(r);a&&(o=uo(a),s.attr("x",o[0]).attr("width",o[1]-o[0]),h(l)),i&&(o=uo(i),s.attr("y",o[0]).attr("height",o[1]-o[0]),g(l)),p(l)})}function p(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+l[+/e$/.test(t)]+","+s[+/^s/.test(t)]+")"})}function h(t){t.select(".extent").attr("x",l[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",l[1]-l[0])}function g(t){t.select(".extent").attr("y",s[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function y(){var f,y,v=this,m=t.select(t.event.target),x=n.of(v,arguments),b=t.select(v),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),T=xt(v),A=t.mouse(v),L=t.select(o(v)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,A[0]-=l[1],A[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(A[0]+=l[1],A[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",D):L.on("mousemove.brush",O).on("mouseup.brush",D),b.interrupt().selectAll("*").interrupt(),M)A[0]=l[0]-A[0],A[1]=s[0]-A[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);y=[l[1-C]-A[0],s[1-S]-A[1]],A[0]=l[C],A[1]=s[S]}else t.event.altKey&&(f=A.slice());function O(){var e=t.mouse(v),r=!1;y&&(e[0]+=y[0],e[1]+=y[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),A[0]=l[+(e[0]<f[0])],A[1]=s[+(e[1]<f[1])]):f=null),w&&P(e,a,0)&&(h(b),r=!0),k&&P(e,i,1)&&(g(b),r=!0),r&&(p(b),x({type:"brush",mode:M?"move":"resize"}))}function P(t,n,a){var i,o,d=uo(n),p=d[0],h=d[1],g=A[a],y=a?s:l,v=y[1]-y[0];if(M&&(p-=g,h-=v+g),i=(a?u:c)?Math.max(p,Math.min(h,t[a])):t[a],M?o=(i+=g)+v:(f&&(g=Math.max(p,Math.min(h,2*f[a]-i))),g<i?(o=i,i=g):o=g),y[0]!=i||y[1]!=o)return a?r=null:e=null,y[0]=i,y[1]=o,!0}function D(){O(),b.style("pointer-events","all").selectAll(".resize").style("display",d.empty()?"none":null),t.select("body").style("cursor",null),L.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),T(),x({type:"brushend"})}b.style("pointer-events","none").selectAll(".resize").style("display",null),t.select("body").style("cursor",m.style("cursor")),x({type:"brushstart"}),O()}return d.event=function(a){a.each(function(){var a=n.of(this,arguments),i={x:l,y:s,i:e,j:r},o=this.__chart__||i;this.__chart__=i,hl?t.select(this).transition().each("start.brush",function(){e=o.i,r=o.j,l=o.x,s=o.y,a({type:"brushstart"})}).tween("brush:brush",function(){var t=Qa(l,i.x),n=Qa(s,i.y);return e=r=null,function(e){l=i.x=t(e),s=i.y=n(e),a({type:"brush",mode:"resize"})}}).each("end.brush",function(){e=i.i,r=i.j,a({type:"brush",mode:"resize"}),a({type:"brushend"})}):(a({type:"brushstart"}),a({type:"brush",mode:"resize"}),a({type:"brushend"}))})},d.x=function(t){return arguments.length?(f=Ll[!(a=t)<<1|!i],d):a},d.y=function(t){return arguments.length?(f=Ll[!a<<1|!(i=t)],d):i},d.clamp=function(t){return arguments.length?(a&&i?(c=!!t[0],u=!!t[1]):a?c=!!t:i&&(u=!!t),d):a&&i?[c,u]:a?c:i?u:null},d.extent=function(t){var n,o,c,u,f;return arguments.length?(a&&(n=t[0],o=t[1],i&&(n=n[0],o=o[0]),e=[n,o],a.invert&&(n=a(n),o=a(o)),o<n&&(f=n,n=o,o=f),n==l[0]&&o==l[1]||(l=[n,o])),i&&(c=t[0],u=t[1],a&&(c=c[1],u=u[1]),r=[c,u],i.invert&&(c=i(c),u=i(u)),u<c&&(f=c,c=u,u=f),c==s[0]&&u==s[1]||(s=[c,u])),d):(a&&(e?(n=e[0],o=e[1]):(n=l[0],o=l[1],a.invert&&(n=a.invert(n),o=a.invert(o)),o<n&&(f=n,n=o,o=f))),i&&(r?(c=r[0],u=r[1]):(c=s[0],u=s[1],i.invert&&(c=i.invert(c),u=i.invert(u)),u<c&&(f=c,c=u,u=f))),a&&i?[[n,c],[o,u]]:a?[n,o]:i&&[c,u])},d.clear=function(){return d.empty()||(l=[0,0],s=[0,0],e=r=null),d},d.empty=function(){return!!a&&l[0]==l[1]||!!i&&s[0]==s[1]},t.rebind(d,n,"on")};var Al={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Ll=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Cl=ze.format=lr.timeFormat,Sl=Cl.utc,Ol=Sl("%Y-%m-%dT%H:%M:%S.%LZ");function Pl(t){return t.toISOString()}function Dl(e,r,n){function a(t){return e(t)}function i(e,n){var a=(e[1]-e[0])/n,i=t.bisect(El,a);return i==El.length?[r.year,xo(e.map(function(t){return t/31536e6}),n)[2]]:i?r[a/El[i-1]<El[i]/a?i-1:i]:[Rl,xo(e,n)[2]]}return a.invert=function(t){return zl(e.invert(t))},a.domain=function(t){return arguments.length?(e.domain(t),a):e.domain().map(zl)},a.nice=function(t,e){var r=a.domain(),n=co(r),o=null==t?i(n,10):"number"==typeof t&&i(n,t);function l(r){return!isNaN(r)&&!t.range(r,zl(+r+1),e).length}return o&&(t=o[0],e=o[1]),a.domain(po(r,e>1?{floor:function(e){for(;l(e=t.floor(e));)e=zl(e-1);return e},ceil:function(e){for(;l(e=t.ceil(e));)e=zl(+e+1);return e}}:t))},a.ticks=function(t,e){var r=co(a.domain()),n=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],zl(+r[1]+1),e<1?1:e)},a.tickFormat=function(){return n},a.copy=function(){return Dl(e.copy(),r,n)},vo(a,e)}function zl(t){return new Date(t)}Cl.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Pl:Ol,Pl.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Pl.toString=Ol.toString,ze.second=Re(function(t){return new Ee(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),ze.seconds=ze.second.range,ze.seconds.utc=ze.second.utc.range,ze.minute=Re(function(t){return new Ee(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),ze.minutes=ze.minute.range,ze.minutes.utc=ze.minute.utc.range,ze.hour=Re(function(t){var e=t.getTimezoneOffset()/60;return new Ee(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),ze.hours=ze.hour.range,ze.hours.utc=ze.hour.utc.range,ze.month=Re(function(t){return(t=ze.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),ze.months=ze.month.range,ze.months.utc=ze.month.utc.range;var El=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Il=[[ze.second,1],[ze.second,5],[ze.second,15],[ze.second,30],[ze.minute,1],[ze.minute,5],[ze.minute,15],[ze.minute,30],[ze.hour,1],[ze.hour,3],[ze.hour,6],[ze.hour,12],[ze.day,1],[ze.day,2],[ze.week,1],[ze.month,1],[ze.month,3],[ze.year,1]],Nl=Cl.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Yr]]),Rl={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(zl)},floor:P,ceil:P};Il.year=ze.year,ze.scale=function(){return Dl(t.scale.linear(),Il,Nl)};var Fl=Il.map(function(t){return[t[0].utc,t[1]]}),jl=Sl.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Yr]]);function Bl(t){return JSON.parse(t.responseText)}function Hl(t){var e=a.createRange();return e.selectNode(a.body),e.createContextualFragment(t.responseText)}Fl.year=ze.year.utc,ze.scale.utc=function(){return Dl(t.scale.linear(),Fl,jl)},t.text=ve(function(t){return t.responseText}),t.json=function(t,e){return me(t,"application/json",Bl,e)},t.html=function(t,e){return me(t,"text/html",Hl,e)},t.xml=ve(function(t){return t.responseXML}),"object"==typeof e&&e.exports?e.exports=t:this.d3=t}()},{}],11:[function(t,e,r){(function(n,a){!function(t,n){"object"==typeof r&&"undefined"!=typeof e?e.exports=n():t.ES6Promise=n()}(this,function(){"use strict";function e(t){return"function"==typeof t}var r=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},i=0,o=void 0,l=void 0,s=function(t,e){g[i]=t,g[i+1]=e,2===(i+=2)&&(l?l(y):_())};var c="undefined"!=typeof window?window:void 0,u=c||{},f=u.MutationObserver||u.WebKitMutationObserver,d="undefined"==typeof self&&"undefined"!=typeof n&&"[object process]"==={}.toString.call(n),p="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function h(){var t=setTimeout;return function(){return t(y,1)}}var g=new Array(1e3);function y(){for(var t=0;t<i;t+=2){(0,g[t])(g[t+1]),g[t]=void 0,g[t+1]=void 0}i=0}var v,m,x,b,_=void 0;function w(t,e){var r=arguments,n=this,a=new this.constructor(T);void 0===a[M]&&q(a);var i,o=n._state;return o?(i=r[o-1],s(function(){return B(o,a,i,n._result)})):N(n,a,t,e),a}function k(t){if(t&&"object"==typeof t&&t.constructor===this)return t;var e=new this(T);return D(e,t),e}d?_=function(){return n.nextTick(y)}:f?(m=0,x=new f(y),b=document.createTextNode(""),x.observe(b,{characterData:!0}),_=function(){b.data=m=++m%2}):p?((v=new MessageChannel).port1.onmessage=y,_=function(){return v.port2.postMessage(0)}):_=void 0===c&&"function"==typeof t?function(){try{var e=t("vertx");return o=e.runOnLoop||e.runOnContext,function(){o(y)}}catch(t){return h()}}():h();var M=Math.random().toString(36).substring(16);function T(){}var A=void 0,L=1,C=2,S=new F;function O(t){try{return t.then}catch(t){return S.error=t,S}}function P(t,r,n){r.constructor===t.constructor&&n===w&&r.constructor.resolve===k?function(t,e){e._state===L?E(t,e._result):e._state===C?I(t,e._result):N(e,void 0,function(e){return D(t,e)},function(e){return I(t,e)})}(t,r):n===S?I(t,S.error):void 0===n?E(t,r):e(n)?function(t,e,r){s(function(t){var n=!1,a=function(t,e,r,n){try{t.call(e,r,n)}catch(t){return t}}(r,e,function(r){n||(n=!0,e!==r?D(t,r):E(t,r))},function(e){n||(n=!0,I(t,e))},t._label);!n&&a&&(n=!0,I(t,a))},t)}(t,r,n):E(t,r)}function D(t,e){var r;t===e?I(t,new TypeError("You cannot resolve a promise with itself")):"function"==typeof(r=e)||"object"==typeof r&&null!==r?P(t,e,O(e)):E(t,e)}function z(t){t._onerror&&t._onerror(t._result),R(t)}function E(t,e){t._state===A&&(t._result=e,t._state=L,0!==t._subscribers.length&&s(R,t))}function I(t,e){t._state===A&&(t._state=C,t._result=e,s(z,t))}function N(t,e,r,n){var a=t._subscribers,i=a.length;t._onerror=null,a[i]=e,a[i+L]=r,a[i+C]=n,0===i&&t._state&&s(R,t)}function R(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n=void 0,a=void 0,i=t._result,o=0;o<e.length;o+=3)n=e[o],a=e[o+r],n?B(r,n,a,i):a(i);t._subscribers.length=0}}function F(){this.error=null}var j=new F;function B(t,r,n,a){var i=e(n),o=void 0,l=void 0,s=void 0,c=void 0;if(i){if((o=function(t,e){try{return t(e)}catch(t){return j.error=t,j}}(n,a))===j?(c=!0,l=o.error,o=null):s=!0,r===o)return void I(r,new TypeError("A promises callback cannot return that same promise."))}else o=a,s=!0;r._state!==A||(i&&s?D(r,o):c?I(r,l):t===L?E(r,o):t===C&&I(r,o))}var H=0;function q(t){t[M]=H++,t._state=void 0,t._result=void 0,t._subscribers=[]}function V(t,e){this._instanceConstructor=t,this.promise=new t(T),this.promise[M]||q(this.promise),r(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?E(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&E(this.promise,this._result))):I(this.promise,new Error("Array Methods must be provided an Array"))}function U(t){this[M]=H++,this._result=this._state=void 0,this._subscribers=[],T!==t&&("function"!=typeof t&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof U?function(t,e){try{e(function(e){D(t,e)},function(e){I(t,e)})}catch(e){I(t,e)}}(this,t):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}function G(){var t=void 0;if("undefined"!=typeof a)t=a;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var e=t.Promise;if(e){var r=null;try{r=Object.prototype.toString.call(e.resolve())}catch(t){}if("[object Promise]"===r&&!e.cast)return}t.Promise=U}return V.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===A&&r<t;r++)this._eachEntry(e[r],r)},V.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===k){var a=O(t);if(a===w&&t._state!==A)this._settledAt(t._state,e,t._result);else if("function"!=typeof a)this._remaining--,this._result[e]=t;else if(r===U){var i=new r(T);P(i,t,a),this._willSettleAt(i,e)}else this._willSettleAt(new r(function(e){return e(t)}),e)}else this._willSettleAt(n(t),e)},V.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===A&&(this._remaining--,t===C?I(n,r):this._result[e]=r),0===this._remaining&&E(n,this._result)},V.prototype._willSettleAt=function(t,e){var r=this;N(t,void 0,function(t){return r._settledAt(L,e,t)},function(t){return r._settledAt(C,e,t)})},U.all=function(t){return new V(this,t).promise},U.race=function(t){var e=this;return r(t)?new e(function(r,n){for(var a=t.length,i=0;i<a;i++)e.resolve(t[i]).then(r,n)}):new e(function(t,e){return e(new TypeError("You must pass an array to race."))})},U.resolve=k,U.reject=function(t){var e=new this(T);return I(e,t),e},U._setScheduler=function(t){l=t},U._setAsap=function(t){s=t},U._asap=s,U.prototype={constructor:U,then:w,catch:function(t){return this.then(null,t)}},G(),U.polyfill=G,U.Promise=U,U})}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:27}],12:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function a(t){return"function"==typeof t}function i(t){return"object"==typeof t&&null!==t}function o(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,l,s,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var u=new Error('Uncaught, unspecified "error" event. ('+e+")");throw u.context=e,u}if(o(r=this._events[t]))return!1;if(a(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:l=Array.prototype.slice.call(arguments,1),r.apply(this,l)}else if(i(r))for(l=Array.prototype.slice.call(arguments,1),n=(c=r.slice()).length,s=0;s<n;s++)c[s].apply(this,l);return!0},n.prototype.addListener=function(t,e){var r;if(!a(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,a(e.listener)?e.listener:e),this._events[t]?i(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,i(this._events[t])&&!this._events[t].warned&&(r=o(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){if(!a(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var r,n,o,l;if(!a(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(o=(r=this._events[t]).length,n=-1,r===e||a(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(i(r)){for(l=o;l-- >0;)if(r[l]===e||r[l].listener&&r[l].listener===e){n=l;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(a(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?a(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(a(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],13:[function(t,e,r){"use strict";e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n<r;n++)if(((e=t.charCodeAt(n))<9||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1}},{}],14:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],a=e[2],i=e[3],o=r+r,l=n+n,s=a+a,c=r*o,u=n*o,f=n*l,d=a*o,p=a*l,h=a*s,g=i*o,y=i*l,v=i*s;return t[0]=1-f-h,t[1]=u+v,t[2]=d-y,t[3]=0,t[4]=u-v,t[5]=1-c-h,t[6]=p+g,t[7]=0,t[8]=d+y,t[9]=p-g,t[10]=1-c-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}},{}],15:[function(t,e,r){(function(r){"use strict";var n,a=t("is-browser");n="function"==typeof r.matchMedia?!r.matchMedia("(hover: none)").matches:a,e.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"is-browser":17}],16:[function(t,e,r){"use strict";var n=t("is-browser");e.exports=n&&function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){t=!1}return t}()},{"is-browser":17}],17:[function(t,e,r){e.exports=!0},{}],18:[function(t,e,r){var n={left:0,top:0};e.exports=function(t,e,r){e=e||t.currentTarget||t.srcElement,Array.isArray(r)||(r=[0,0]);var a=t.clientX||0,i=t.clientY||0,o=(l=e,l===window||l===document||l===document.body?n:l.getBoundingClientRect());var l;return r[0]=a-o.left,r[1]=i-o.top,r}},{}],19:[function(t,e,r){var n,a=t("./lib/build-log"),i=t("./lib/epsilon"),o=t("./lib/intersecter"),l=t("./lib/segment-chainer"),s=t("./lib/segment-selector"),c=t("./lib/geojson"),u=!1,f=i();function d(t,e,r){var a=n.segments(t),i=n.segments(e),o=r(n.combine(a,i));return n.polygon(o)}n={buildLog:function(t){return!0===t?u=a():!1===t&&(u=!1),!1!==u&&u.list},epsilon:function(t){return f.epsilon(t)},segments:function(t){var e=o(!0,f,u);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:o(!1,f,u).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:s.union(t.combined,u),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:s.intersect(t.combined,u),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:s.difference(t.combined,u),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:s.differenceRev(t.combined,u),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:s.xor(t.combined,u),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:l(t.segments,f,u),inverted:t.inverted}},polygonFromGeoJSON:function(t){return c.toPolygon(n,t)},polygonToGeoJSON:function(t){return c.fromPolygon(n,f,t)},union:function(t,e){return d(t,e,n.selectUnion)},intersect:function(t,e){return d(t,e,n.selectIntersect)},difference:function(t,e){return d(t,e,n.selectDifference)},differenceRev:function(t,e){return d(t,e,n.selectDifferenceRev)},xor:function(t,e){return d(t,e,n.selectXor)}},"object"==typeof window&&(window.PolyBool=n),e.exports=n},{"./lib/build-log":20,"./lib/epsilon":21,"./lib/geojson":22,"./lib/intersecter":23,"./lib/segment-chainer":25,"./lib/segment-selector":26}],20:[function(t,e,r){e.exports=function(){var t,e=0,r=!1;function n(e,r){return t.list.push({type:e,data:r?JSON.parse(JSON.stringify(r)):void 0}),t}return t={list:[],segmentId:function(){return e++},checkIntersection:function(t,e){return n("check",{seg1:t,seg2:e})},segmentChop:function(t,e){return n("div_seg",{seg:t,pt:e}),n("chop",{seg:t,pt:e})},statusRemove:function(t){return n("pop_seg",{seg:t})},segmentUpdate:function(t){return n("seg_update",{seg:t})},segmentNew:function(t,e){return n("new_seg",{seg:t,primary:e})},segmentRemove:function(t){return n("rem_seg",{seg:t})},tempStatus:function(t,e,r){return n("temp_status",{seg:t,above:e,below:r})},rewind:function(t){return n("rewind",{seg:t})},status:function(t,e,r){return n("status",{seg:t,above:e,below:r})},vert:function(e){return e===r?t:(r=e,n("vert",{x:e}))},log:function(t){return"string"!=typeof t&&(t=JSON.stringify(t,!1," ")),n("log",{txt:t})},reset:function(){return n("reset")},selected:function(t){return n("selected",{segs:t})},chainStart:function(t){return n("chain_start",{seg:t})},chainRemoveHead:function(t,e){return n("chain_rem_head",{index:t,pt:e})},chainRemoveTail:function(t,e){return n("chain_rem_tail",{index:t,pt:e})},chainNew:function(t,e){return n("chain_new",{pt1:t,pt2:e})},chainMatch:function(t){return n("chain_match",{index:t})},chainClose:function(t){return n("chain_close",{index:t})},chainAddHead:function(t,e){return n("chain_add_head",{index:t,pt:e})},chainAddTail:function(t,e){return n("chain_add_tail",{index:t,pt:e})},chainConnect:function(t,e){return n("chain_con",{index1:t,index2:e})},chainReverse:function(t){return n("chain_rev",{index:t})},chainJoin:function(t,e){return n("chain_join",{index1:t,index2:e})},done:function(){return n("done")}}}},{}],21:[function(t,e,r){e.exports=function(t){"number"!=typeof t&&(t=1e-10);var e={epsilon:function(e){return"number"==typeof e&&(t=e),t},pointAboveOrOnLine:function(e,r,n){var a=r[0],i=r[1],o=n[0],l=n[1],s=e[0];return(o-a)*(e[1]-i)-(l-i)*(s-a)>=-t},pointBetween:function(e,r,n){var a=e[1]-r[1],i=n[0]-r[0],o=e[0]-r[0],l=n[1]-r[1],s=o*i+a*l;return!(s<t||s-(i*i+l*l)>-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])<t},pointsSameY:function(e,r){return Math.abs(e[1]-r[1])<t},pointsSame:function(t,r){return e.pointsSameX(t,r)&&e.pointsSameY(t,r)},pointsCompare:function(t,r){return e.pointsSameX(t,r)?e.pointsSameY(t,r)?0:t[1]<r[1]?-1:1:t[0]<r[0]?-1:1},pointsCollinear:function(e,r,n){var a=e[0]-r[0],i=e[1]-r[1],o=r[0]-n[0],l=r[1]-n[1];return Math.abs(a*l-o*i)<t},linesIntersect:function(e,r,n,a){var i=r[0]-e[0],o=r[1]-e[1],l=a[0]-n[0],s=a[1]-n[1],c=i*s-o*l;if(Math.abs(c)<t)return!1;var u=e[0]-n[0],f=e[1]-n[1],d=(l*f-s*u)/c,p=(i*f-o*u)/c,h={alongA:0,alongB:0,pt:[e[0]+d*i,e[1]+d*o]};return h.alongA=d<=-t?-2:d<t?-1:d-1<=-t?0:d-1<t?1:2,h.alongB=p<=-t?-2:p<t?-1:p-1<=-t?0:p-1<t?1:2,h},pointInsideRegion:function(e,r){for(var n=e[0],a=e[1],i=r[r.length-1][0],o=r[r.length-1][1],l=!1,s=0;s<r.length;s++){var c=r[s][0],u=r[s][1];u-a>t!=o-a>t&&(i-c)*(a-u)/(o-u)+c-n>t&&(l=!l),i=c,o=u}return l}};return e}},{}],22:[function(t,e,r){var n={toPolygon:function(t,e){function r(e){if(e.length<=0)return t.segments({inverted:!1,regions:[]});function r(e){var r=e.slice(0,e.length-1);return t.segments({inverted:!1,regions:[r]})}for(var n=r(e[0]),a=1;a<e.length;a++)n=t.selectDifference(t.combine(n,r(e[a])));return n}if("Polygon"===e.type)return t.polygon(r(e.coordinates));if("MultiPolygon"===e.type){for(var n=t.segments({inverted:!1,regions:[]}),a=0;a<e.coordinates.length;a++)n=t.selectUnion(t.combine(n,r(e.coordinates[a])));return t.polygon(n)}throw new Error("PolyBool: Cannot convert GeoJSON object to PolyBool polygon")},fromPolygon:function(t,e,r){function n(t,r){return e.pointInsideRegion([.5*(t[0][0]+t[1][0]),.5*(t[0][1]+t[1][1])],r)}function a(t){return{region:t,children:[]}}r=t.polygon(t.segments(r));var i=a(null);function o(t,e){for(var r=0;r<t.children.length;r++){if(n(e,(l=t.children[r]).region))return void o(l,e)}var i=a(e);for(r=0;r<t.children.length;r++){var l;n((l=t.children[r]).region,e)&&(i.children.push(l),t.children.splice(r,1),r--)}t.children.push(i)}for(var l=0;l<r.regions.length;l++){var s=r.regions[l];s.length<3||o(i,s)}function c(t,e){for(var r=0,n=t[t.length-1][0],a=t[t.length-1][1],i=[],o=0;o<t.length;o++){var l=t[o][0],s=t[o][1];i.push([l,s]),r+=s*n-l*a,n=l,a=s}return r<0!==e&&i.reverse(),i.push([i[0][0],i[0][1]]),i}var u=[];function f(t){var e=[c(t.region,!1)];u.push(e);for(var r=0;r<t.children.length;r++)e.push(d(t.children[r]))}function d(t){for(var e=0;e<t.children.length;e++)f(t.children[e]);return c(t.region,!0)}for(l=0;l<i.children.length;l++)f(i.children[l]);return u.length<=0?{type:"Polygon",coordinates:[]}:1==u.length?{type:"Polygon",coordinates:u[0]}:{type:"MultiPolygon",coordinates:u}}};e.exports=n},{}],23:[function(t,e,r){var n=t("./linked-list");e.exports=function(t,e,r){function a(t,e,n){return{id:r?r.segmentId():-1,start:t,end:e,myFill:{above:n.myFill.above,below:n.myFill.below},otherFill:null}}var i=n.create();function o(t,r){i.insertBefore(t,function(n){return function(t,r,n,a,i,o){var l=e.pointsCompare(r,i);return 0!==l?l:e.pointsSame(n,o)?0:t!==a?t?1:-1:e.pointAboveOrOnLine(n,a?i:o,a?o:i)?1:-1}(t.isStart,t.pt,r,n.isStart,n.pt,n.other.pt)<0})}function l(t,e){var r=function(t,e){var r=n.node({isStart:!0,pt:t.start,seg:t,primary:e,other:null,status:null});return o(r,t.end),r}(t,e);return function(t,e,r){var a=n.node({isStart:!1,pt:e.end,seg:e,primary:r,other:t,status:null});t.other=a,o(a,t.pt)}(r,t,e),r}function s(t,e){var n=a(e,t.seg.end,t.seg);return function(t,e){r&&r.segmentChop(t.seg,e),t.other.remove(),t.seg.end=e,t.other.pt=e,o(t.other,t.pt)}(t,e),l(n,t.primary)}function c(a,o){var l=n.create();function c(t){return l.findTransition(function(r){var n,a,i,o,l,s;return n=t,a=r.ev,i=n.seg.start,o=n.seg.end,l=a.seg.start,s=a.seg.end,(e.pointsCollinear(i,l,s)?e.pointsCollinear(o,l,s)?1:e.pointAboveOrOnLine(o,l,s)?1:-1:e.pointAboveOrOnLine(i,l,s)?1:-1)>0})}function u(t,n){var a=t.seg,i=n.seg,o=a.start,l=a.end,c=i.start,u=i.end;r&&r.checkIntersection(a,i);var f=e.linesIntersect(o,l,c,u);if(!1===f){if(!e.pointsCollinear(o,l,c))return!1;if(e.pointsSame(o,u)||e.pointsSame(l,c))return!1;var d=e.pointsSame(o,c),p=e.pointsSame(l,u);if(d&&p)return n;var h=!d&&e.pointBetween(o,c,u),g=!p&&e.pointBetween(l,c,u);if(d)return g?s(n,l):s(t,u),n;h&&(p||(g?s(n,l):s(t,u)),s(n,o))}else 0===f.alongA&&(-1===f.alongB?s(t,c):0===f.alongB?s(t,f.pt):1===f.alongB&&s(t,u)),0===f.alongB&&(-1===f.alongA?s(n,o):0===f.alongA?s(n,f.pt):1===f.alongA&&s(n,l));return!1}for(var f=[];!i.isEmpty();){var d=i.getHead();if(r&&r.vert(d.pt[0]),d.isStart){r&&r.segmentNew(d.seg,d.primary);var p=c(d),h=p.before?p.before.ev:null,g=p.after?p.after.ev:null;function y(){if(h){var t=u(d,h);if(t)return t}return!!g&&u(d,g)}r&&r.tempStatus(d.seg,!!h&&h.seg,!!g&&g.seg);var v,m,x=y();if(x)t?(m=null===d.seg.myFill.below||d.seg.myFill.above!==d.seg.myFill.below)&&(x.seg.myFill.above=!x.seg.myFill.above):x.seg.otherFill=d.seg.myFill,r&&r.segmentUpdate(x.seg),d.other.remove(),d.remove();if(i.getHead()!==d){r&&r.rewind(d.seg);continue}t?(m=null===d.seg.myFill.below||d.seg.myFill.above!==d.seg.myFill.below,d.seg.myFill.below=g?g.seg.myFill.above:a,d.seg.myFill.above=m?!d.seg.myFill.below:d.seg.myFill.below):null===d.seg.otherFill&&(v=g?d.primary===g.primary?g.seg.otherFill.above:g.seg.myFill.above:d.primary?o:a,d.seg.otherFill={above:v,below:v}),r&&r.status(d.seg,!!h&&h.seg,!!g&&g.seg),d.other.status=p.insert(n.node({ev:d}))}else{var b=d.status;if(null===b)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(l.exists(b.prev)&&l.exists(b.next)&&u(b.prev.ev,b.next.ev),r&&r.statusRemove(b.ev.seg),b.remove(),!d.primary){var _=d.seg.myFill;d.seg.myFill=d.seg.otherFill,d.seg.otherFill=_}f.push(d.seg)}i.getHead().remove()}return r&&r.done(),f}return t?{addRegion:function(t){for(var n,a,i,o=t[t.length-1],s=0;s<t.length;s++){n=o,o=t[s];var c=e.pointsCompare(n,o);0!==c&&l((a=c<0?n:o,i=c<0?o:n,{id:r?r.segmentId():-1,start:a,end:i,myFill:{above:null,below:null},otherFill:null}),!0)}},calculate:function(t){return c(t,!1)}}:{calculate:function(t,e,r,n){return t.forEach(function(t){l(a(t.start,t.end,t),!0)}),r.forEach(function(t){l(a(t.start,t.end,t),!1)}),c(e,n)}}}},{"./linked-list":24}],24:[function(t,e,r){e.exports={create:function(){var t={root:{root:!0,next:null},exists:function(e){return null!==e&&e!==t.root},isEmpty:function(){return null===t.root.next},getHead:function(){return t.root.next},insertBefore:function(e,r){for(var n=t.root,a=t.root.next;null!==a;){if(r(a))return e.prev=a.prev,e.next=a,a.prev.next=e,void(a.prev=e);n=a,a=a.next}n.next=e,e.prev=n,e.next=null},findTransition:function(e){for(var r=t.root,n=t.root.next;null!==n&&!e(n);)r=n,n=n.next;return{before:r===t.root?null:r,after:n,insert:function(t){return t.prev=r,t.next=n,r.next=t,null!==n&&(n.prev=t),t}}}};return t},node:function(t){return t.prev=null,t.next=null,t.remove=function(){t.prev.next=t.next,t.next&&(t.next.prev=t.prev),t.prev=null,t.next=null},t}}},{}],25:[function(t,e,r){e.exports=function(t,e,r){var n=[],a=[];return t.forEach(function(t){var i=t.start,o=t.end;if(e.pointsSame(i,o))console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");else{r&&r.chainStart(t);for(var l={index:0,matches_head:!1,matches_pt1:!1},s={index:0,matches_head:!1,matches_pt1:!1},c=l,u=0;u<n.length;u++){var f=(y=n[u])[0],d=(y[1],y[y.length-1]);if(y[y.length-2],e.pointsSame(f,i)){if(M(u,!0,!0))break}else if(e.pointsSame(f,o)){if(M(u,!0,!1))break}else if(e.pointsSame(d,i)){if(M(u,!1,!0))break}else if(e.pointsSame(d,o)&&M(u,!1,!1))break}if(c===l)return n.push([i,o]),void(r&&r.chainNew(i,o));if(c===s){r&&r.chainMatch(l.index);var p=l.index,h=l.matches_pt1?o:i,g=l.matches_head,y=n[p],v=g?y[0]:y[y.length-1],m=g?y[1]:y[y.length-2],x=g?y[y.length-1]:y[0],b=g?y[y.length-2]:y[1];return e.pointsCollinear(m,v,h)&&(g?(r&&r.chainRemoveHead(l.index,h),y.shift()):(r&&r.chainRemoveTail(l.index,h),y.pop()),v=m),e.pointsSame(x,h)?(n.splice(p,1),e.pointsCollinear(b,x,v)&&(g?(r&&r.chainRemoveTail(l.index,v),y.pop()):(r&&r.chainRemoveHead(l.index,v),y.shift())),r&&r.chainClose(l.index),void a.push(y)):void(g?(r&&r.chainAddHead(l.index,h),y.unshift(h)):(r&&r.chainAddTail(l.index,h),y.push(h)))}var _=l.index,w=s.index;r&&r.chainConnect(_,w);var k=n[_].length<n[w].length;l.matches_head?s.matches_head?k?(T(_),A(_,w)):(T(w),A(w,_)):A(w,_):s.matches_head?A(_,w):k?(T(_),A(w,_)):(T(w),A(_,w))}function M(t,e,r){return c.index=t,c.matches_head=e,c.matches_pt1=r,c===l?(c=s,!1):(c=null,!0)}function T(t){r&&r.chainReverse(t),n[t].reverse()}function A(t,a){var i=n[t],o=n[a],l=i[i.length-1],s=i[i.length-2],c=o[0],u=o[1];e.pointsCollinear(s,l,c)&&(r&&r.chainRemoveTail(t,l),i.pop(),l=s),e.pointsCollinear(l,c,u)&&(r&&r.chainRemoveHead(a,c),o.shift()),r&&r.chainJoin(t,a),n[t]=i.concat(o),n.splice(a,1)}}),a}},{}],26:[function(t,e,r){function n(t,e,r){var n=[];return t.forEach(function(t){var a=(t.myFill.above?8:0)+(t.myFill.below?4:0)+(t.otherFill&&t.otherFill.above?2:0)+(t.otherFill&&t.otherFill.below?1:0);0!==e[a]&&n.push({id:r?r.segmentId():-1,start:t.start,end:t.end,myFill:{above:1===e[a],below:2===e[a]},otherFill:null})}),r&&r.selected(n),n}var a={union:function(t,e){return n(t,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],e)},intersect:function(t,e){return n(t,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],e)},difference:function(t,e){return n(t,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],e)},differenceRev:function(t,e){return n(t,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],e)},xor:function(t,e){return n(t,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],e)}};e.exports=a},{}],27:[function(t,e,r){var n,a,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function l(){throw new Error("clearTimeout has not been defined")}function s(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{a="function"==typeof clearTimeout?clearTimeout:l}catch(t){a=l}}();var c,u=[],f=!1,d=-1;function p(){f&&c&&(f=!1,c.length?u=c.concat(u):d=-1,u.length&&h())}function h(){if(!f){var t=s(p);f=!0;for(var e=u.length;e;){for(c=u,u=[];++d<e;)c&&c[d].run();d=-1,e=u.length}c=null,f=!1,function(t){if(a===clearTimeout)return clearTimeout(t);if((a===l||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(t);try{a(t)}catch(e){try{return a.call(null,t)}catch(e){return a.call(this,t)}}}(t)}}function g(t,e){this.fun=t,this.array=e}function y(){}i.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];u.push(new g(t,e)),1!==u.length||f||s(h)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=y,i.addListener=y,i.once=y,i.off=y,i.removeListener=y,i.removeAllListeners=y,i.emit=y,i.prependListener=y,i.prependOnceListener=y,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],28:[function(t,e,r){!function(t){var r=/^\s+/,n=/\s+$/,a=0,i=t.round,o=t.min,l=t.max,s=t.random;function c(e,s){if(s=s||{},(e=e||"")instanceof c)return e;if(!(this instanceof c))return new c(e,s);var u=function(e){var a={r:0,g:0,b:0},i=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof e&&(e=function(t){t=t.replace(r,"").replace(n,"").toLowerCase();var e,a=!1;if(L[t])t=L[t],a=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(e=B.rgb.exec(t))return{r:e[1],g:e[2],b:e[3]};if(e=B.rgba.exec(t))return{r:e[1],g:e[2],b:e[3],a:e[4]};if(e=B.hsl.exec(t))return{h:e[1],s:e[2],l:e[3]};if(e=B.hsla.exec(t))return{h:e[1],s:e[2],l:e[3],a:e[4]};if(e=B.hsv.exec(t))return{h:e[1],s:e[2],v:e[3]};if(e=B.hsva.exec(t))return{h:e[1],s:e[2],v:e[3],a:e[4]};if(e=B.hex8.exec(t))return{r:D(e[1]),g:D(e[2]),b:D(e[3]),a:N(e[4]),format:a?"name":"hex8"};if(e=B.hex6.exec(t))return{r:D(e[1]),g:D(e[2]),b:D(e[3]),format:a?"name":"hex"};if(e=B.hex4.exec(t))return{r:D(e[1]+""+e[1]),g:D(e[2]+""+e[2]),b:D(e[3]+""+e[3]),a:N(e[4]+""+e[4]),format:a?"name":"hex8"};if(e=B.hex3.exec(t))return{r:D(e[1]+""+e[1]),g:D(e[2]+""+e[2]),b:D(e[3]+""+e[3]),format:a?"name":"hex"};return!1}(e));"object"==typeof e&&(H(e.r)&&H(e.g)&&H(e.b)?(p=e.r,h=e.g,g=e.b,a={r:255*O(p,255),g:255*O(h,255),b:255*O(g,255)},f=!0,d="%"===String(e.r).substr(-1)?"prgb":"rgb"):H(e.h)&&H(e.s)&&H(e.v)?(s=E(e.s),c=E(e.v),a=function(e,r,n){e=6*O(e,360),r=O(r,100),n=O(n,100);var a=t.floor(e),i=e-a,o=n*(1-r),l=n*(1-i*r),s=n*(1-(1-i)*r),c=a%6;return{r:255*[n,l,o,o,s,n][c],g:255*[s,n,n,l,o,o][c],b:255*[o,o,s,n,n,l][c]}}(e.h,s,c),f=!0,d="hsv"):H(e.h)&&H(e.s)&&H(e.l)&&(s=E(e.s),u=E(e.l),a=function(t,e,r){var n,a,i;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=O(t,360),e=O(e,100),r=O(r,100),0===e)n=a=i=r;else{var l=r<.5?r*(1+e):r+e-r*e,s=2*r-l;n=o(s,l,t+1/3),a=o(s,l,t),i=o(s,l,t-1/3)}return{r:255*n,g:255*a,b:255*i}}(e.h,s,u),f=!0,d="hsl"),e.hasOwnProperty("a")&&(i=e.a));var p,h,g;return i=S(i),{ok:f,format:e.format||d,r:o(255,l(a.r,0)),g:o(255,l(a.g,0)),b:o(255,l(a.b,0)),a:i}}(e);this._originalInput=e,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=i(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=u.ok,this._tc_id=a++}function u(t,e,r){t=O(t,255),e=O(e,255),r=O(r,255);var n,a,i=l(t,e,r),s=o(t,e,r),c=(i+s)/2;if(i==s)n=a=0;else{var u=i-s;switch(a=c>.5?u/(2-i-s):u/(i+s),i){case t:n=(e-r)/u+(e<r?6:0);break;case e:n=(r-t)/u+2;break;case r:n=(t-e)/u+4}n/=6}return{h:n,s:a,l:c}}function f(t,e,r){t=O(t,255),e=O(e,255),r=O(r,255);var n,a,i=l(t,e,r),s=o(t,e,r),c=i,u=i-s;if(a=0===i?0:u/i,i==s)n=0;else{switch(i){case t:n=(e-r)/u+(e<r?6:0);break;case e:n=(r-t)/u+2;break;case r:n=(t-e)/u+4}n/=6}return{h:n,s:a,v:c}}function d(t,e,r,n){var a=[z(i(t).toString(16)),z(i(e).toString(16)),z(i(r).toString(16))];return n&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0):a.join("")}function p(t,e,r,n){return[z(I(n)),z(i(t).toString(16)),z(i(e).toString(16)),z(i(r).toString(16))].join("")}function h(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.s-=e/100,r.s=P(r.s),c(r)}function g(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.s+=e/100,r.s=P(r.s),c(r)}function y(t){return c(t).desaturate(100)}function v(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.l+=e/100,r.l=P(r.l),c(r)}function m(t,e){e=0===e?0:e||10;var r=c(t).toRgb();return r.r=l(0,o(255,r.r-i(-e/100*255))),r.g=l(0,o(255,r.g-i(-e/100*255))),r.b=l(0,o(255,r.b-i(-e/100*255))),c(r)}function x(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.l-=e/100,r.l=P(r.l),c(r)}function b(t,e){var r=c(t).toHsl(),n=(r.h+e)%360;return r.h=n<0?360+n:n,c(r)}function _(t){var e=c(t).toHsl();return e.h=(e.h+180)%360,c(e)}function w(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+120)%360,s:e.s,l:e.l}),c({h:(r+240)%360,s:e.s,l:e.l})]}function k(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+90)%360,s:e.s,l:e.l}),c({h:(r+180)%360,s:e.s,l:e.l}),c({h:(r+270)%360,s:e.s,l:e.l})]}function M(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+72)%360,s:e.s,l:e.l}),c({h:(r+216)%360,s:e.s,l:e.l})]}function T(t,e,r){e=e||6,r=r||30;var n=c(t).toHsl(),a=360/r,i=[c(t)];for(n.h=(n.h-(a*e>>1)+720)%360;--e;)n.h=(n.h+a)%360,i.push(c(n));return i}function A(t,e){e=e||6;for(var r=c(t).toHsv(),n=r.h,a=r.s,i=r.v,o=[],l=1/e;e--;)o.push(c({h:n,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,a=this.toRgb();return e=a.r/255,r=a.g/255,n=a.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=S(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=f(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=f(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=u(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=u(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return d(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[z(i(t).toString(16)),z(i(e).toString(16)),z(i(r).toString(16)),z(I(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*O(this._r,255))+"%",g:i(100*O(this._g,255))+"%",b:i(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*O(this._r,255))+"%, "+i(100*O(this._g,255))+"%, "+i(100*O(this._b,255))+"%)":"rgba("+i(100*O(this._r,255))+"%, "+i(100*O(this._g,255))+"%, "+i(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+p(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var a=c(t);r="#"+p(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(v,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(h,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(y,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:E(t[n]));t=r}return c(t,e)},c.equals=function(t,e){return!(!t||!e)&&c(t).toRgbString()==c(e).toRgbString()},c.random=function(){return c.fromRatio({r:s(),g:s(),b:s()})},c.mix=function(t,e,r){r=0===r?0:r||50;var n=c(t).toRgb(),a=c(e).toRgb(),i=r/100;return c({r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a})},c.readability=function(e,r){var n=c(e),a=c(r);return(t.max(n.getLuminance(),a.getLuminance())+.05)/(t.min(n.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(t,e,r){var n,a,i=c.readability(t,e);switch(a=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(t,e,r){var n,a,i,o,l=null,s=0;a=(r=r||{}).includeFallbackColors,i=r.level,o=r.size;for(var u=0;u<e.length;u++)(n=c.readability(t,e[u]))>s&&(s=n,l=c(e[u]));return c.isReadable(t,l,{level:i,size:o})||!a?l:(r.includeFallbackColors=!1,c.mostReadable(t,["#fff","#000"],r))};var L=c.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},C=c.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(L);function S(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function O(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=o(r,l(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function P(t){return o(1,l(0,t))}function D(t){return parseInt(t,16)}function z(t){return 1==t.length?"0"+t:""+t}function E(t){return t<=1&&(t=100*t+"%"),t}function I(e){return t.round(255*parseFloat(e)).toString(16)}function N(t){return D(t)/255}var R,F,j,B=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",j="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function H(t){return!!B.CSS_UNIT.exec(t)}"undefined"!=typeof e&&e.exports?e.exports=c:window.tinycolor=c}(Math)},{}],29:[function(t,e,r){"use strict";e.exports=[{path:"",backoff:0},{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0,noRotate:!0},{path:"M2,2V-2H-2V2Z",backoff:0,noRotate:!0}]},{}],30:[function(t,e,r){"use strict";var n=t("./arrow_paths"),a=t("../../plots/font_attributes"),i=t("../../plots/cartesian/constants"),o=t("../../plot_api/plot_template").templatedArray;e.exports=o("annotation",{visible:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},text:{valType:"string",editType:"calcIfAutorange+arraydraw"},textangle:{valType:"angle",dflt:0,editType:"calcIfAutorange+arraydraw"},font:a({editType:"calcIfAutorange+arraydraw",colorEditType:"arraydraw"}),width:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},height:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},align:{valType:"enumerated",values:["left","center","right"],dflt:"center",editType:"arraydraw"},valign:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle",editType:"arraydraw"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},borderpad:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},borderwidth:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},showarrow:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},arrowcolor:{valType:"color",editType:"arraydraw"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},startarrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},arrowside:{valType:"flaglist",flags:["end","start"],extras:["none"],dflt:"end",editType:"arraydraw"},arrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},startarrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},arrowwidth:{valType:"number",min:.1,editType:"calcIfAutorange+arraydraw"},standoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},startstandoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},ax:{valType:"any",editType:"calcIfAutorange+arraydraw"},ay:{valType:"any",editType:"calcIfAutorange+arraydraw"},axref:{valType:"enumerated",dflt:"pixel",values:["pixel",i.idRegex.x.toString()],editType:"calc"},ayref:{valType:"enumerated",dflt:"pixel",values:["pixel",i.idRegex.y.toString()],editType:"calc"},xref:{valType:"enumerated",values:["paper",i.idRegex.x.toString()],editType:"calc"},x:{valType:"any",editType:"calcIfAutorange+arraydraw"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},xshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},yref:{valType:"enumerated",values:["paper",i.idRegex.y.toString()],editType:"calc"},y:{valType:"any",editType:"calcIfAutorange+arraydraw"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},yshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},clicktoshow:{valType:"enumerated",values:[!1,"onoff","onout"],dflt:!1,editType:"arraydraw"},xclick:{valType:"any",editType:"arraydraw"},yclick:{valType:"any",editType:"arraydraw"},hovertext:{valType:"string",editType:"arraydraw"},hoverlabel:{bgcolor:{valType:"color",editType:"arraydraw"},bordercolor:{valType:"color",editType:"arraydraw"},font:a({editType:"arraydraw"}),editType:"arraydraw"},captureevents:{valType:"boolean",editType:"arraydraw"},editType:"calc",_deprecated:{ref:{valType:"string",editType:"calc"}}})},{"../../plot_api/plot_template":197,"../../plots/cartesian/constants":212,"../../plots/font_attributes":233,"./arrow_paths":29}],31:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("./draw").draw;function o(t){var e=t._fullLayout;n.filterVisible(e.annotations).forEach(function(e){var r,n,i,o,l=a.getFromId(t,e.xref),s=a.getFromId(t,e.yref),c=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;l&&l.autorange&&(r=c+e.xshift,n=c-e.xshift,i=u+e.xshift,o=u-e.xshift,e.axref===e.xref?(a.expand(l,[l.r2c(e.x)],{ppadplus:r,ppadminus:n}),a.expand(l,[l.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,o)})):(i=e.ax?i+e.ax:i,o=e.ax?o-e.ax:o,a.expand(l,[l.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,o)}))),s&&s.autorange&&(r=c-e.yshift,n=c+e.yshift,i=u-e.yshift,o=u+e.yshift,e.ayref===e.yref?(a.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),a.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,o)})):(i=e.ay?i+e.ay:i,o=e.ay?o-e.ay:o,a.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,o)})))})}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.annotations);if(r.length&&t._fullData.length){var l={};for(var s in r.forEach(function(t){l[t.xref]=1,l[t.yref]=1}),l){var c=a.getFromId(t,s);if(c&&c.autorange)return n.syncOrAsync([i,o],t)}}}},{"../../lib":163,"../../plots/cartesian/axes":207,"./draw":36}],32:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry"),i=t("../../plot_api/plot_template").arrayEditor;function o(t,e){var r,n,a,i,o,s,c,u=t._fullLayout.annotations,f=[],d=[],p=[],h=(e||[]).length;for(r=0;r<u.length;r++)if(i=(a=u[r]).clicktoshow){for(n=0;n<h;n++)if(s=(o=e[n]).xaxis,c=o.yaxis,s._id===a.xref&&c._id===a.yref&&s.d2r(o.x)===l(a._xclick,s)&&c.d2r(o.y)===l(a._yclick,c)){(a.visible?"onout"===i?d:p:f).push(r);break}n===h&&a.visible&&"onout"===i&&d.push(r)}return{on:f,off:d,explicitOff:p}}function l(t,e){return"log"===e.type?e.l2r(t):e.d2r(t)}e.exports={hasClickToShow:function(t,e){var r=o(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,l,s=o(t,e),c=s.on,u=s.off.concat(s.explicitOff),f={},d=t._fullLayout.annotations;if(!c.length&&!u.length)return;for(r=0;r<c.length;r++)(l=i(t.layout,"annotations",d[c[r]])).modifyItem("visible",!0),n.extendFlat(f,l.getUpdateObj());for(r=0;r<u.length;r++)(l=i(t.layout,"annotations",d[u[r]])).modifyItem("visible",!1),n.extendFlat(f,l.getUpdateObj());return a.call("update",t,{},f)}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../registry":247}],33:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../color");e.exports=function(t,e,r,i){i("opacity");var o=i("bgcolor"),l=i("bordercolor"),s=a.opacity(l);i("borderpad");var c=i("borderwidth"),u=i("showarrow");if(i("text",u?" ":r._dfltTitle.annotation),i("textangle"),n.coerceFont(i,"font",r.font),i("width"),i("align"),i("height")&&i("valign"),u){var f,d,p=i("arrowside");-1!==p.indexOf("end")&&(f=i("arrowhead"),d=i("arrowsize")),-1!==p.indexOf("start")&&(i("startarrowhead",f),i("startarrowsize",d)),i("arrowcolor",s?e.bordercolor:a.defaultLine),i("arrowwidth",2*(s&&c||1)),i("standoff"),i("startstandoff")}var h=i("hovertext"),g=r.hoverlabel||{};if(h){var y=i("hoverlabel.bgcolor",g.bgcolor||(a.opacity(o)?a.rgb(o):a.defaultLine)),v=i("hoverlabel.bordercolor",g.bordercolor||a.contrast(y));n.coerceFont(i,"hoverlabel.font",{family:g.font.family,size:g.font.size,color:g.font.color||v})}i("captureevents",!!h)}},{"../../lib":163,"../color":45}],34:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib/to_log_range");e.exports=function(t,e,r,i){e=e||{};var o="log"===r&&"linear"===e.type,l="linear"===r&&"log"===e.type;if(o||l)for(var s,c,u=t._fullLayout.annotations,f=e._id.charAt(0),d=0;d<u.length;d++)s=u[d],c="annotations["+d+"].",s[f+"ref"]===e._id&&p(f),s["a"+f+"ref"]===e._id&&p("a"+f);function p(t){var r=s[t],l=null;l=o?a(r,e.range):Math.pow(10,r),n(l)||(l=null),i(c+t,l)}}},{"../../lib/to_log_range":186,"fast-isnumeric":13}],35:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("./common_defaults"),l=t("./attributes");function s(t,e,r){function i(r,a){return n.coerce(t,e,l,r,a)}var s=i("visible"),c=i("clicktoshow");if(s||c){o(t,e,r,i);for(var u=e.showarrow,f=["x","y"],d=[-10,-30],p={_fullLayout:r},h=0;h<2;h++){var g=f[h],y=a.coerceRef(t,e,p,g,"","paper");if(a.coercePosition(e,p,i,y,g,.5),u){var v="a"+g,m=a.coerceRef(t,e,p,v,"pixel");"pixel"!==m&&m!==y&&(m=e[v]="pixel");var x="pixel"===m?d[h]:.4;a.coercePosition(e,p,i,m,v,x)}i(g+"anchor"),i(g+"shift")}if(n.noneOrAll(t,e,["x","y"]),u&&n.noneOrAll(t,e,["ax","ay"]),c){var b=i("xclick"),_=i("yclick");e._xclick=void 0===b?e.x:a.cleanPosition(b,p,e.xref),e._yclick=void 0===_?e.y:a.cleanPosition(_,p,e.yref)}}}e.exports=function(t,e){i(t,e,{name:"annotations",handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"./attributes":30,"./common_defaults":33}],36:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../plots/plots"),o=t("../../lib"),l=t("../../plots/cartesian/axes"),s=t("../color"),c=t("../drawing"),u=t("../fx"),f=t("../../lib/svg_text_utils"),d=t("../../lib/setcursor"),p=t("../dragelement"),h=t("../../plot_api/plot_template").arrayEditor,g=t("./draw_arrow_head");function y(t,e){var r=t._fullLayout.annotations[e]||{};v(t,r,e,!1,l.getFromId(t,r.xref),l.getFromId(t,r.yref))}function v(t,e,r,i,l,y){var v,m,x=t._fullLayout,b=t._fullLayout._size,_=t._context.edits;i?(v="annotation-"+i,m=i+".annotations"):(v="annotation",m="annotations");var w=h(t.layout,m,e),k=w.modifyBase,M=w.modifyItem,T=w.getUpdateObj;x._infolayer.selectAll("."+v+'[data-index="'+r+'"]').remove();var A="clip"+x._uid+"_ann"+r;if(e._input&&!1!==e.visible){var L={x:{},y:{}},C=+e.textangle||0,S=x._infolayer.append("g").classed(v,!0).attr("data-index",String(r)).style("opacity",e.opacity),O=S.append("g").classed("annotation-text-g",!0),P=_[e.showarrow?"annotationTail":"annotationPosition"],D=e.captureevents||_.annotationText||P,z=O.append("g").style("pointer-events",D?"all":null).call(d,"pointer").on("click",function(){t._dragging=!1;var a={index:r,annotation:e._input,fullAnnotation:e,event:n.event};i&&(a.subplotId=i),t.emit("plotly_clickannotation",a)});e.hovertext&&z.on("mouseover",function(){var r=e.hoverlabel,n=r.font,a=this.getBoundingClientRect(),i=t.getBoundingClientRect();u.loneHover({x0:a.left-i.left,x1:a.right-i.left,y:(a.top+a.bottom)/2-i.top,text:e.hovertext,color:r.bgcolor,borderColor:r.bordercolor,fontFamily:n.family,fontSize:n.size,fontColor:n.color},{container:x._hoverlayer.node(),outerContainer:x._paper.node(),gd:t})}).on("mouseout",function(){u.loneUnhover(x._hoverlayer.node())});var E=e.borderwidth,I=e.borderpad,N=E+I,R=z.append("rect").attr("class","bg").style("stroke-width",E+"px").call(s.stroke,e.bordercolor).call(s.fill,e.bgcolor),F=e.width||e.height,j=x._topclips.selectAll("#"+A).data(F?[0]:[]);j.enter().append("clipPath").classed("annclip",!0).attr("id",A).append("rect"),j.exit().remove();var B=e.font,H=z.append("text").classed("annotation-text",!0).text(e.text);_.annotationText?H.call(f.makeEditable,{delegate:z,gd:t}).call(q).on("edit",function(r){e.text=r,this.call(q),M("text",r),l&&l.autorange&&k(l._name+".autorange",!0),y&&y.autorange&&k(y._name+".autorange",!0),a.call("relayout",t,T())}):H.call(q)}else n.selectAll("#"+A).remove();function q(r){return r.call(c.font,B).attr({"text-anchor":{left:"start",right:"end"}[e.align]||"middle"}),f.convertToTspans(r,t,V),r}function V(){var r=H.selectAll("a");1===r.size()&&r.text()===H.text()&&z.insert("a",":first-child").attr({"xlink:xlink:href":r.attr("xlink:href"),"xlink:xlink:show":r.attr("xlink:show")}).style({cursor:"pointer"}).node().appendChild(R.node());var n=z.select(".annotation-text-math-group"),u=!n.empty(),h=c.bBox((u?n:H).node()),v=h.width,m=h.height,w=e.width||v,D=e.height||m,I=Math.round(w+2*N),B=Math.round(D+2*N);function q(t,e){return"auto"===e&&(e=t<1/3?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}e._w=w,e._h=D;for(var V=!1,U=["x","y"],G=0;G<U.length;G++){var Y,X,Z,W,Q,J=U[G],$=e[J+"ref"]||J,K=e["a"+J+"ref"],tt={x:l,y:y}[J],et=(C+("x"===J?0:-90))*Math.PI/180,rt=I*Math.cos(et),nt=B*Math.sin(et),at=Math.abs(rt)+Math.abs(nt),it=e[J+"anchor"],ot=e[J+"shift"]*("x"===J?1:-1),lt=L[J];if(tt){var st=tt.r2fraction(e[J]);if((t._dragging||!tt.autorange)&&(st<0||st>1)&&(K===$?((st=tt.r2fraction(e["a"+J]))<0||st>1)&&(V=!0):V=!0,V))continue;Y=tt._offset+tt.r2p(e[J]),W=.5}else"x"===J?(Z=e[J],Y=b.l+b.w*Z):(Z=1-e[J],Y=b.t+b.h*Z),W=e.showarrow?.5:Z;if(e.showarrow){lt.head=Y;var ct=e["a"+J];Q=rt*q(.5,e.xanchor)-nt*q(.5,e.yanchor),K===$?(lt.tail=tt._offset+tt.r2p(ct),X=Q):(lt.tail=Y+ct,X=Q+ct),lt.text=lt.tail+Q;var ut=x["x"===J?"width":"height"];if("paper"===$&&(lt.head=o.constrain(lt.head,1,ut-1)),"pixel"===K){var ft=-Math.max(lt.tail-3,lt.text),dt=Math.min(lt.tail+3,lt.text)-ut;ft>0?(lt.tail+=ft,lt.text+=ft):dt>0&&(lt.tail-=dt,lt.text-=dt)}lt.tail+=ot,lt.head+=ot}else X=Q=at*q(W,it),lt.text=Y+Q;lt.text+=ot,Q+=ot,X+=ot,e["_"+J+"padplus"]=at/2+X,e["_"+J+"padminus"]=at/2-X,e["_"+J+"size"]=at,e["_"+J+"shift"]=Q}if(V)z.remove();else{var pt=0,ht=0;if("left"!==e.align&&(pt=(w-v)*("center"===e.align?.5:1)),"top"!==e.valign&&(ht=(D-m)*("middle"===e.valign?.5:1)),u)n.select("svg").attr({x:N+pt-1,y:N+ht}).call(c.setClipUrl,F?A:null);else{var gt=N+ht-h.top,yt=N+pt-h.left;H.call(f.positionText,yt,gt).call(c.setClipUrl,F?A:null)}j.select("rect").call(c.setRect,N,N,w,D),R.call(c.setRect,E/2,E/2,I-E,B-E),z.call(c.setTranslate,Math.round(L.x.text-I/2),Math.round(L.y.text-B/2)),O.attr({transform:"rotate("+C+","+L.x.text+","+L.y.text+")"});var vt,mt=function(r,n){S.selectAll(".annotation-arrow-g").remove();var u=L.x.head,f=L.y.head,d=L.x.tail+r,h=L.y.tail+n,v=L.x.text+r,m=L.y.text+n,x=o.rotationXYMatrix(C,v,m),w=o.apply2DTransform(x),A=o.apply2DTransform2(x),P=+R.attr("width"),D=+R.attr("height"),E=v-.5*P,I=E+P,N=m-.5*D,F=N+D,j=[[E,N,E,F],[E,F,I,F],[I,F,I,N],[I,N,E,N]].map(A);if(!j.reduce(function(t,e){return t^!!o.segmentsIntersect(u,f,u+1e6,f+1e6,e[0],e[1],e[2],e[3])},!1)){j.forEach(function(t){var e=o.segmentsIntersect(d,h,u,f,t[0],t[1],t[2],t[3]);e&&(d=e.x,h=e.y)});var B=e.arrowwidth,H=e.arrowcolor,q=e.arrowside,V=S.append("g").style({opacity:s.opacity(H)}).classed("annotation-arrow-g",!0),U=V.append("path").attr("d","M"+d+","+h+"L"+u+","+f).style("stroke-width",B+"px").call(s.stroke,s.rgb(H));if(g(U,q,e),_.annotationPosition&&U.node().parentNode&&!i){var G=u,Y=f;if(e.standoff){var X=Math.sqrt(Math.pow(u-d,2)+Math.pow(f-h,2));G+=e.standoff*(d-u)/X,Y+=e.standoff*(h-f)/X}var Z,W,Q=V.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).classed("cursor-move",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-G)+","+(h-Y),transform:"translate("+G+","+Y+")"}).style("stroke-width",B+6+"px").call(s.stroke,"rgba(0,0,0,0)").call(s.fill,"rgba(0,0,0,0)");p.init({element:Q.node(),gd:t,prepFn:function(){var t=c.getTranslate(z);Z=t.x,W=t.y,l&&l.autorange&&k(l._name+".autorange",!0),y&&y.autorange&&k(y._name+".autorange",!0)},moveFn:function(t,r){var n=w(Z,W),a=n[0]+t,i=n[1]+r;z.call(c.setTranslate,a,i),M("x",l?l.p2r(l.r2p(e.x)+t):e.x+t/b.w),M("y",y?y.p2r(y.r2p(e.y)+r):e.y-r/b.h),e.axref===e.xref&&M("ax",l.p2r(l.r2p(e.ax)+t)),e.ayref===e.yref&&M("ay",y.p2r(y.r2p(e.ay)+r)),V.attr("transform","translate("+t+","+r+")"),O.attr({transform:"rotate("+C+","+a+","+i+")"})},doneFn:function(){a.call("relayout",t,T());var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(e.showarrow&&mt(0,0),P)p.init({element:z.node(),gd:t,prepFn:function(){vt=O.attr("transform")},moveFn:function(t,r){var n="pointer";if(e.showarrow)e.axref===e.xref?M("ax",l.p2r(l.r2p(e.ax)+t)):M("ax",e.ax+t),e.ayref===e.yref?M("ay",y.p2r(y.r2p(e.ay)+r)):M("ay",e.ay+r),mt(t,r);else{if(i)return;var a,o;if(l)a=l.p2r(l.r2p(e.x)+t);else{var s=e._xsize/b.w,c=e.x+(e._xshift-e.xshift)/b.w-s/2;a=p.align(c+t/b.w,s,0,1,e.xanchor)}if(y)o=y.p2r(y.r2p(e.y)+r);else{var u=e._ysize/b.h,f=e.y-(e._yshift+e.yshift)/b.h-u/2;o=p.align(f-r/b.h,u,0,1,e.yanchor)}M("x",a),M("y",o),l&&y||(n=p.getCursor(l?.5:a,y?.5:o,e.xanchor,e.yanchor))}O.attr({transform:"translate("+t+","+r+")"+vt}),d(z,n)},doneFn:function(){d(z),a.call("relayout",t,T());var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}e.exports={draw:function(t){var e=t._fullLayout;e._infolayer.selectAll(".annotation").remove();for(var r=0;r<e.annotations.length;r++)e.annotations[r].visible&&y(t,r);return i.previousPromises(t)},drawOne:y,drawRaw:v}},{"../../lib":163,"../../lib/setcursor":182,"../../lib/svg_text_utils":184,"../../plot_api/plot_template":197,"../../plots/cartesian/axes":207,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"../fx":87,"./draw_arrow_head":37,d3:10}],37:[function(t,e,r){"use strict";var n=t("d3"),a=t("../color"),i=t("./arrow_paths");e.exports=function(t,e,r){var o,l,s,c,u=t.node(),f=i[r.arrowhead||0],d=i[r.startarrowhead||0],p=(r.arrowwidth||1)*(r.arrowsize||1),h=(r.arrowwidth||1)*(r.startarrowsize||1),g=e.indexOf("start")>=0,y=e.indexOf("end")>=0,v=f.backoff*p+r.standoff,m=d.backoff*h+r.startstandoff;if("line"===u.nodeName){o={x:+t.attr("x1"),y:+t.attr("y1")},l={x:+t.attr("x2"),y:+t.attr("y2")};var x=o.x-l.x,b=o.y-l.y;if(c=(s=Math.atan2(b,x))+Math.PI,v&&m&&v+m>Math.sqrt(x*x+b*b))return void P();if(v){if(v*v>x*x+b*b)return void P();var _=v*Math.cos(s),w=v*Math.sin(s);l.x+=_,l.y+=w,t.attr({x2:l.x,y2:l.y})}if(m){if(m*m>x*x+b*b)return void P();var k=m*Math.cos(s),M=m*Math.sin(s);o.x-=k,o.y-=M,t.attr({x1:o.x,y1:o.y})}}else if("path"===u.nodeName){var T=u.getTotalLength(),A="";if(T<v+m)return void P();var L=u.getPointAtLength(0),C=u.getPointAtLength(.1);s=Math.atan2(L.y-C.y,L.x-C.x),o=u.getPointAtLength(Math.min(m,T)),A="0px,"+m+"px,";var S=u.getPointAtLength(T),O=u.getPointAtLength(T-.1);c=Math.atan2(S.y-O.y,S.x-O.x),l=u.getPointAtLength(Math.max(0,T-v)),A+=T-(A?m+v:v)+"px,"+T+"px",t.style("stroke-dasharray",A)}function P(){t.style("stroke-dasharray","0px,100px")}function D(e,i,o,l){e.path&&(e.noRotate&&(o=0),n.select(u.parentNode).append("path").attr({class:t.attr("class"),d:e.path,transform:"translate("+i.x+","+i.y+")"+(o?"rotate("+180*o/Math.PI+")":"")+"scale("+l+")"}).style({fill:a.rgb(r.arrowcolor),"stroke-width":0}))}g&&D(d,o,s,h),y&&D(f,l,c,p)}},{"../color":45,"./arrow_paths":29,d3:10}],38:[function(t,e,r){"use strict";var n=t("./draw"),a=t("./click");e.exports={moduleType:"component",name:"annotations",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("annotations"),calcAutorange:t("./calc_autorange"),draw:n.draw,drawOne:n.drawOne,drawRaw:n.drawRaw,hasClickToShow:a.hasClickToShow,onClick:a.onClick,convertCoords:t("./convert_coords")}},{"../../plots/cartesian/include_components":217,"./attributes":30,"./calc_autorange":31,"./click":32,"./convert_coords":34,"./defaults":35,"./draw":36}],39:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),a=t("../../plot_api/edit_types").overrideAll,i=t("../../plot_api/plot_template").templatedArray;e.exports=a(i("annotation",{visible:n.visible,x:{valType:"any"},y:{valType:"any"},z:{valType:"any"},ax:{valType:"number"},ay:{valType:"number"},xanchor:n.xanchor,xshift:n.xshift,yanchor:n.yanchor,yshift:n.yshift,text:n.text,textangle:n.textangle,font:n.font,width:n.width,height:n.height,opacity:n.opacity,align:n.align,valign:n.valign,bgcolor:n.bgcolor,bordercolor:n.bordercolor,borderpad:n.borderpad,borderwidth:n.borderwidth,showarrow:n.showarrow,arrowcolor:n.arrowcolor,arrowhead:n.arrowhead,startarrowhead:n.startarrowhead,arrowside:n.arrowside,arrowsize:n.arrowsize,startarrowsize:n.startarrowsize,arrowwidth:n.arrowwidth,standoff:n.standoff,startstandoff:n.startstandoff,hovertext:n.hovertext,hoverlabel:n.hoverlabel,captureevents:n.captureevents}),"calc","from-root")},{"../../plot_api/edit_types":190,"../../plot_api/plot_template":197,"../annotations/attributes":30}],40:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes");function i(t,e){var r=e.fullSceneLayout.domain,i=e.fullLayout._size,o={pdata:null,type:"linear",autorange:!1,range:[-1/0,1/0]};t._xa={},n.extendFlat(t._xa,o),a.setConvert(t._xa),t._xa._offset=i.l+r.x[0]*i.w,t._xa.l2p=function(){return.5*(1+t._pdata[0]/t._pdata[3])*i.w*(r.x[1]-r.x[0])},t._ya={},n.extendFlat(t._ya,o),a.setConvert(t._ya),t._ya._offset=i.t+(1-r.y[1])*i.h,t._ya.l2p=function(){return.5*(1-t._pdata[1]/t._pdata[3])*i.h*(r.y[1]-r.y[0])}}e.exports=function(t){for(var e=t.fullSceneLayout.annotations,r=0;r<e.length;r++)i(e[r],t);t.fullLayout._infolayer.selectAll(".annotation-"+t.id).remove()}},{"../../lib":163,"../../plots/cartesian/axes":207}],41:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("../annotations/common_defaults"),l=t("./attributes");function s(t,e,r,i){function s(r,a){return n.coerce(t,e,l,r,a)}function c(t){var n=t+"axis",i={_fullLayout:{}};return i._fullLayout[n]=r[n],a.coercePosition(e,i,s,t,t,.5)}s("visible")&&(o(t,e,i.fullLayout,s),c("x"),c("y"),c("z"),n.noneOrAll(t,e,["x","y","z"]),e.xref="x",e.yref="y",e.zref="z",s("xanchor"),s("yanchor"),s("xshift"),s("yshift"),e.showarrow&&(e.axref="pixel",e.ayref="pixel",s("ax",-10),s("ay",-30),n.noneOrAll(t,e,["ax","ay"])))}e.exports=function(t,e,r){i(t,e,{name:"annotations",handleItemDefaults:s,fullLayout:r.fullLayout})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"../annotations/common_defaults":33,"./attributes":39}],42:[function(t,e,r){"use strict";var n=t("../annotations/draw").drawRaw,a=t("../../plots/gl3d/project"),i=["x","y","z"];e.exports=function(t){for(var e=t.fullSceneLayout,r=t.dataScale,o=e.annotations,l=0;l<o.length;l++){for(var s=o[l],c=!1,u=0;u<3;u++){var f=i[u],d=s[f],p=e[f+"axis"].r2fraction(d);if(p<0||p>1){c=!0;break}}c?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+l+'"]').remove():(s._pdata=a(t.glplot.cameraParams,[e.xaxis.r2l(s.x)*r[0],e.yaxis.r2l(s.y)*r[1],e.zaxis.r2l(s.z)*r[2]]),n(t.graphDiv,s,l,t.id,s._xa,s._ya))}}},{"../../plots/gl3d/project":236,"../annotations/draw":36}],43:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib");e.exports={moduleType:"component",name:"annotations3d",schema:{subplots:{scene:{annotations:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),includeBasePlot:function(t,e){var r=n.subplotsRegistry.gl3d;if(!r)return;for(var i=r.attrRegex,o=Object.keys(t),l=0;l<o.length;l++){var s=o[l];i.test(s)&&(t[s].annotations||[]).length&&(a.pushUnique(e._basePlotModules,r),a.pushUnique(e._subplots.gl3d,s))}},convert:t("./convert"),draw:t("./draw")}},{"../../lib":163,"../../registry":247,"./attributes":39,"./convert":40,"./defaults":41,"./draw":42}],44:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.borderLine="#BEC8D9",r.lightFraction=1e3/11},{}],45:[function(t,e,r){"use strict";var n=t("tinycolor2"),a=t("fast-isnumeric"),i=e.exports={},o=t("./attributes");i.defaults=o.defaults;var l=i.defaultLine=o.defaultLine;i.lightLine=o.lightLine;var s=i.background=o.background;function c(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o<n.length;o++){if(!n[o].length)return t;if(n[o]=Number(n[o]),!(n[o]>=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var l=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+l+", "+n[3]+")":"rgb("+l+")"}i.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},i.rgb=function(t){return i.tinyRGB(n(t))},i.opacity=function(t){return t?n(t).getAlpha():0},i.addOpacity=function(t,e){var r=n(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},i.combine=function(t,e){var r=n(t).toRgb();if(1===r.a)return n(t).toRgbString();var a=n(e||s).toRgb(),i=1===a.a?a:{r:255*(1-a.a)+a.r*a.a,g:255*(1-a.a)+a.g*a.a,b:255*(1-a.a)+a.b*a.a},o={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return n(o).toRgbString()},i.contrast=function(t,e,r){var a=n(t);return 1!==a.getAlpha()&&(a=n(i.combine(t,s))),(a.isDark()?e?a.lighten(e):s:r?a.darken(r):l).toString()},i.stroke=function(t,e){var r=n(e);t.style({stroke:i.tinyRGB(r),"stroke-opacity":r.getAlpha()})},i.fill=function(t,e){var r=n(e);t.style({fill:i.tinyRGB(r),"fill-opacity":r.getAlpha()})},i.clean=function(t){if(t&&"object"==typeof t){var e,r,n,a,o=Object.keys(t);for(e=0;e<o.length;e++)if(a=t[n=o[e]],"color"===n.substr(n.length-5))if(Array.isArray(a))for(r=0;r<a.length;r++)a[r]=c(a[r]);else t[n]=c(a);else if("colorscale"===n.substr(n.length-10)&&Array.isArray(a))for(r=0;r<a.length;r++)Array.isArray(a[r])&&(a[r][1]=c(a[r][1]));else if(Array.isArray(a)){var l=a[0];if(!Array.isArray(l)&&l&&"object"==typeof l)for(r=0;r<a.length;r++)i.clean(a[r])}else a&&"object"==typeof a&&i.clean(a)}}},{"./attributes":44,"fast-isnumeric":13,tinycolor2:28}],46:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/layout_attributes"),a=t("../../plots/font_attributes"),i=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll;e.exports=o({thicknessmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"pixels"},thickness:{valType:"number",min:0,dflt:30},lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",dflt:1.02,min:-2,max:3},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},xpad:{valType:"number",min:0,dflt:10},y:{valType:"number",dflt:.5,min:-2,max:3},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle"},ypad:{valType:"number",min:0,dflt:10},outlinecolor:n.linecolor,outlinewidth:n.linewidth,bordercolor:n.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},tickmode:n.tickmode,nticks:n.nticks,tick0:n.tick0,dtick:n.dtick,tickvals:n.tickvals,ticktext:n.ticktext,ticks:i({},n.ticks,{dflt:""}),ticklen:n.ticklen,tickwidth:n.tickwidth,tickcolor:n.tickcolor,showticklabels:n.showticklabels,tickfont:a({}),tickangle:n.tickangle,tickformat:n.tickformat,tickformatstops:n.tickformatstops,tickprefix:n.tickprefix,showtickprefix:n.showtickprefix,ticksuffix:n.ticksuffix,showticksuffix:n.showticksuffix,separatethousands:n.separatethousands,exponentformat:n.exponentformat,showexponent:n.showexponent,title:{valType:"string"},titlefont:a({}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}},"colorbars","from-root")},{"../../lib/extend":157,"../../plot_api/edit_types":190,"../../plots/cartesian/layout_attributes":219,"../../plots/font_attributes":233}],47:[function(t,e,r){"use strict";var n=t("../colorscale"),a=t("./draw");e.exports=function(t,e,r){if("function"==typeof r)return r(t,e);var i=e[0].trace,o="cb"+i.uid,l=r.container,s=l?i[l]:i;if(t._fullLayout._infolayer.selectAll("."+o).remove(),s&&s.showscale){var c=s[r.min],u=s[r.max],f=e[0].t.cb=a(t,o),d=n.makeColorScaleFunc(n.extractScale(s.colorscale,c,u),{noNumericCheck:!0});f.fillcolor(d).filllevels({start:c,end:u,size:(u-c)/254}).options(s.colorbar)()}}},{"../colorscale":60,"./draw":50}],48:[function(t,e,r){"use strict";e.exports={cn:{colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"}}},{}],49:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plot_api/plot_template"),i=t("../../plots/cartesian/tick_value_defaults"),o=t("../../plots/cartesian/tick_mark_defaults"),l=t("../../plots/cartesian/tick_label_defaults"),s=t("./attributes");e.exports=function(t,e,r){var c=a.newContainer(e,"colorbar"),u=t.colorbar||{};function f(t,e){return n.coerce(u,c,s,t,e)}var d=f("thicknessmode");f("thickness","fraction"===d?30/(r.width-r.margin.l-r.margin.r):30);var p=f("lenmode");f("len","fraction"===p?1:r.height-r.margin.t-r.margin.b),f("x"),f("xanchor"),f("xpad"),f("y"),f("yanchor"),f("ypad"),n.noneOrAll(u,c,["x","y"]),f("outlinecolor"),f("outlinewidth"),f("bordercolor"),f("borderwidth"),f("bgcolor"),i(u,c,f,"linear");var h={outerTicks:!1,font:r.font};l(u,c,f,"linear",h),o(u,c,f,"linear",h),f("title",r._dfltTitle.colorbar),n.coerceFont(f,"titlefont",r.font),f("titleside")}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/cartesian/tick_label_defaults":226,"../../plots/cartesian/tick_mark_defaults":227,"../../plots/cartesian/tick_value_defaults":228,"./attributes":46}],50:[function(t,e,r){"use strict";var n=t("d3"),a=t("tinycolor2"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../plots/cartesian/axes"),s=t("../dragelement"),c=t("../../lib"),u=t("../../lib/extend").extendFlat,f=t("../../lib/setcursor"),d=t("../drawing"),p=t("../color"),h=t("../titles"),g=t("../../lib/svg_text_utils"),y=t("../../constants/alignment"),v=y.LINE_SPACING,m=y.FROM_TL,x=y.FROM_BR,b=t("../../plots/cartesian/axis_defaults"),_=t("../../plots/cartesian/position_defaults"),w=t("../../plots/cartesian/layout_attributes"),k=t("./attributes"),M=t("./constants").cn;e.exports=function(t,e){var r={};function y(){var k=t._fullLayout,A=k._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var L,C,S=n.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),O=[],P=[],D="function"==typeof r.line.color?r.line.color:function(){return r.line.color},z="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},E=r.levels.end+r.levels.size/100,I=r.levels.size,N=1.001*S[0]-.001*S[1],R=1.001*S[1]-.001*S[0];for(C=0;C<1e5&&(L=r.levels.start+C*I,!(I>0?L>=E:L<=E));C++)L>N&&L<R&&O.push(L);if("function"==typeof r.fillcolor)if(r.filllevels)for(E=r.filllevels.end+r.filllevels.size/100,I=r.filllevels.size,C=0;C<1e5&&(L=r.filllevels.start+C*I,!(I>0?L>=E:L<=E));C++)L>S[0]&&L<S[1]&&P.push(L);else(P=O.map(function(t){return t-r.levels.size/2})).push(P[P.length-1]+r.levels.size);else r.fillcolor&&"string"==typeof r.fillcolor&&(P=[0]);r.levels.size<0&&(O.reverse(),P.reverse());var F,j=A.h,B=A.w,H=Math.round(r.thickness*("fraction"===r.thicknessmode?B:1)),q=H/A.w,V=Math.round(r.len*("fraction"===r.lenmode?j:1)),U=V/A.h,G=r.xpad/A.w,Y=(r.borderwidth+r.outlinewidth)/2,X=r.ypad/A.h,Z=Math.round(r.x*A.w+r.xpad),W=r.x-q*({middle:.5,right:1}[r.xanchor]||0),Q=r.y+U*(({top:-.5,bottom:.5}[r.yanchor]||0)-.5),J=Math.round(A.h*(1-Q)),$=J-V,K={type:"linear",range:S,tickmode:r.tickmode,nticks:r.nticks,tick0:r.tick0,dtick:r.dtick,tickvals:r.tickvals,ticktext:r.ticktext,ticks:r.ticks,ticklen:r.ticklen,tickwidth:r.tickwidth,tickcolor:r.tickcolor,showticklabels:r.showticklabels,tickfont:r.tickfont,tickangle:r.tickangle,tickformat:r.tickformat,exponentformat:r.exponentformat,separatethousands:r.separatethousands,showexponent:r.showexponent,showtickprefix:r.showtickprefix,tickprefix:r.tickprefix,showticksuffix:r.showticksuffix,ticksuffix:r.ticksuffix,title:r.title,titlefont:r.titlefont,showline:!0,anchor:"free",position:1},tt={type:"linear",_id:"y"+e},et={letter:"y",font:k.font,noHover:!0,calendar:k.calendar};if(b(K,tt,yt,et,k),_(K,tt,yt,et),tt.position=r.x+G+q,y.axis=tt,-1!==["top","bottom"].indexOf(r.titleside)&&(tt.titleside=r.titleside,tt.titlex=r.x+G,tt.titley=Q+("top"===r.titleside?U-X:X)),r.line.color&&"auto"===r.tickmode){tt.tickmode="linear",tt.tick0=r.levels.start;var rt=r.levels.size,nt=c.constrain((J-$)/50,4,15)+1,at=(S[1]-S[0])/((r.nticks||nt)*rt);if(at>1){var it=Math.pow(10,Math.floor(Math.log(at)/Math.LN10));rt*=it*c.roundUp(at/it,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(tt.tick0=0)}tt.dtick=rt}tt.domain=[Q+X,Q+U-X],tt.setScale();var ot=c.ensureSingle(k._infolayer,"g",e,function(t){t.classed(M.colorbar,!0).each(function(){var t=n.select(this);t.append("rect").classed(M.cbbg,!0),t.append("g").classed(M.cbfills,!0),t.append("g").classed(M.cblines,!0),t.append("g").classed(M.cbaxis,!0).classed(M.crisp,!0),t.append("g").classed(M.cbtitleunshift,!0).append("g").classed(M.cbtitle,!0),t.append("rect").classed(M.cboutline,!0),t.select(".cbtitle").datum(0)})});ot.attr("transform","translate("+Math.round(A.l)+","+Math.round(A.t)+")");var lt=ot.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(A.l)+",-"+Math.round(A.t)+")");tt._axislayer=ot.select(".cbaxis");var st=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var ct,ut=A.l+(r.x+G)*A.w,ft=tt.titlefont.size;ct="top"===r.titleside?(1-(Q+U-X))*A.h+A.t+3+.75*ft:(1-(Q+X))*A.h+A.t-3-.25*ft,vt(tt._id+"title",{attributes:{x:ut,y:ct,"text-anchor":"start"}})}var dt,pt,ht,gt=c.syncOrAsync([i.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var e=ot.select(".cbtitle"),i=e.select("text"),o=[-r.outlinewidth/2,r.outlinewidth/2],s=e.select(".h"+tt._id+"title-math-group").node(),u=15.6;if(i.node()&&(u=parseInt(i.node().style.fontSize,10)*v),s?(st=d.bBox(s).height)>u&&(o[1]-=(st-u)/2):i.node()&&!i.classed(M.jsPlaceholder)&&(st=d.bBox(i.node()).height),st){if(st+=5,"top"===r.titleside)tt.domain[1]-=st/A.h,o[1]*=-1;else{tt.domain[0]+=st/A.h;var f=g.lineCount(i);o[1]+=(1-f)*u}e.attr("transform","translate("+o+")"),tt.setScale()}}ot.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(A.h*(1-tt.domain[1]))+")"),tt._axislayer.attr("transform","translate(0,"+Math.round(-A.t)+")");var p=ot.select(".cbfills").selectAll("rect.cbfill").data(P);p.enter().append("rect").classed(M.cbfill,!0).style("stroke","none"),p.exit().remove(),p.each(function(t,e){var r=[0===e?S[0]:(P[e]+P[e-1])/2,e===P.length-1?S[1]:(P[e]+P[e+1])/2].map(tt.c2p).map(Math.round);e!==P.length-1&&(r[1]+=r[1]>r[0]?1:-1);var i=z(t).replace("e-",""),o=a(i).toHexString();n.select(this).attr({x:Z,width:Math.max(H,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var h=ot.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?O:[]);return h.enter().append("path").classed(M.cbline,!0),h.exit().remove(),h.each(function(t){n.select(this).attr("d","M"+Z+","+(Math.round(tt.c2p(t))+r.line.width/2%1)+"h"+H).call(d.lineGroupStyle,r.line.width,D(t),r.line.dash)}),tt._axislayer.selectAll("g."+tt._id+"tick,path").remove(),tt._pos=Z+H+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),tt.side="right",c.syncOrAsync([function(){return l.doTicksSingle(t,tt,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var e=tt.titlefont.size,a=tt._offset+tt._length/2,i=A.l+(tt.position||0)*A.w+("right"===tt.side?10+e*(tt.showticklabels?1:.5):-10-e*(tt.showticklabels?.5:0));vt("h"+tt._id+"title",{avoid:{selection:n.select(t).selectAll("g."+tt._id+"tick"),side:r.titleside,offsetLeft:A.l,offsetTop:0,maxShift:k.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},i.previousPromises,function(){var n=H+r.outlinewidth/2+d.bBox(tt._axislayer.node()).width;if((F=lt.select("text")).node()&&!F.classed(M.jsPlaceholder)){var a,o=lt.select(".h"+tt._id+"title-math-group").node();a=o&&-1!==["top","bottom"].indexOf(r.titleside)?d.bBox(o).width:d.bBox(lt.node()).right-Z-A.l,n=Math.max(n,a)}var l=2*r.xpad+n+r.borderwidth+r.outlinewidth/2,s=J-$;ot.select(".cbbg").attr({x:Z-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:$-Y,width:Math.max(l,2),height:Math.max(s+2*Y,2)}).call(p.fill,r.bgcolor).call(p.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),ot.selectAll(".cboutline").attr({x:Z,y:$+r.ypad+("top"===r.titleside?st:0),width:Math.max(H,2),height:Math.max(s-2*r.ypad-st,2)}).call(p.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*l;ot.attr("transform","translate("+(A.l-c)+","+A.t+")");var u={},f=m[r.yanchor],h=x[r.yanchor];"pixels"===r.lenmode?(u.y=r.y,u.t=s*f,u.b=s*h):(u.t=u.b=0,u.yt=r.y+r.len*f,u.yb=r.y-r.len*h);var g=m[r.xanchor],y=x[r.xanchor];if("pixels"===r.thicknessmode)u.x=r.x,u.l=l*g,u.r=l*y;else{var v=l-H;u.l=v*g,u.r=v*y,u.xl=r.x-r.thickness*g,u.xr=r.x+r.thickness*y}i.autoMargin(t,e,u)}],t);if(gt&>.then&&(t._promises||[]).push(gt),t._context.edits.colorbarPosition)s.init({element:ot.node(),gd:t,prepFn:function(){dt=ot.attr("transform"),f(ot)},moveFn:function(t,e){ot.attr("transform",dt+" translate("+t+","+e+")"),pt=s.align(W+t/A.w,q,0,1,r.xanchor),ht=s.align(Q-e/A.h,U,0,1,r.yanchor);var n=s.getCursor(pt,ht,r.xanchor,r.yanchor);f(ot,n)},doneFn:function(){f(ot),void 0!==pt&&void 0!==ht&&o.call("restyle",t,{"colorbar.x":pt,"colorbar.y":ht},T().index)}});return gt}function yt(t,e){return c.coerce(K,tt,w,t,e)}function vt(e,r){var n=T(),a="colorbar.title",i=n._module.colorbar.container;i&&(a=i+"."+a);var o={propContainer:tt,propName:a,traceIndex:n.index,placeholder:k._dfltTitle.colorbar,containerGroup:ot.select(".cbtitle")},l="h"===e.charAt(0)?e.substr(1):"h"+e;ot.selectAll("."+l+",."+l+"-math-group").remove(),h.draw(t,e,u(o,r||{}))}k._infolayer.selectAll("g."+e).remove()}function T(){var r,n,a=e.substr(2);for(r=0;r<t._fullData.length;r++)if((n=t._fullData[r]).uid===a)return n}return Object.keys(k).forEach(function(t){r[t]=null}),r.fillcolor=null,r.line={color:null,width:null,dash:null},r.levels={start:null,end:null,size:null},r.filllevels=null,Object.keys(r).forEach(function(t){y[t]=function(e){return arguments.length?(r[t]=c.isPlainObject(r[t])?c.extendFlat(r[t],e):e,y):r[t]}}),y.options=function(t){return Object.keys(t).forEach(function(e){"function"==typeof y[e]&&y[e](t[e])}),y},y._opts=r,y}},{"../../constants/alignment":143,"../../lib":163,"../../lib/extend":157,"../../lib/setcursor":182,"../../lib/svg_text_utils":184,"../../plots/cartesian/axes":207,"../../plots/cartesian/axis_defaults":209,"../../plots/cartesian/layout_attributes":219,"../../plots/cartesian/position_defaults":222,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"../titles":136,"./attributes":46,"./constants":48,d3:10,tinycolor2:28}],51:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){return n.isPlainObject(t.colorbar)}},{"../../lib":163}],52:[function(t,e,r){"use strict";var n=t("./scales.js");Object.keys(n);function a(t){return"`"+t+"`"}e.exports=function(t,e){t=t||"";var r,i=(e=e||{}).cLetter||"c",o=("onlyIfNumerical"in e?e.onlyIfNumerical:Boolean(t),"noScale"in e?e.noScale:"marker.line"===t),l="showScaleDflt"in e?e.showScaleDflt:"z"===i,s="string"==typeof e.colorscaleDflt?n[e.colorscaleDflt]:null,c=e.editTypeOverride||"",u=t?t+".":"";"colorAttr"in e?(r=e.colorAttr,e.colorAttr):a(u+(r={z:"z",c:"color"}[i]));var f=i+"auto",d=i+"min",p=i+"max",h=(a(u+d),a(u+p),{});h[d]=h[p]=void 0;var g={};g[f]=!1;var y={};return"color"===r&&(y.color={valType:"color",arrayOk:!0,editType:c||"style"}),y[f]={valType:"boolean",dflt:!0,editType:"calc",impliedEdits:h},y[d]={valType:"number",dflt:null,editType:c||"plot",impliedEdits:g},y[p]={valType:"number",dflt:null,editType:c||"plot",impliedEdits:g},y.colorscale={valType:"colorscale",editType:"calc",dflt:s,impliedEdits:{autocolorscale:!1}},y.autocolorscale={valType:"boolean",dflt:!1!==e.autoColorDflt,editType:"calc",impliedEdits:{colorscale:void 0}},y.reversescale={valType:"boolean",dflt:!1,editType:"calc"},o||(y.showscale={valType:"boolean",dflt:l,editType:"calc"}),y}},{"./scales.js":64}],53:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./scales"),i=t("./flip_scale");e.exports=function(t,e,r,o){var l=t,s=t._input,c=t._fullInput,u=t.updateStyle;function f(e,n,a){void 0===a&&(a=n),u?u(t._input,r?r+"."+e:e,n):s[e]=n,l[e]=a,c&&t!==t._fullInput&&(u?u(t._fullInput,r?r+"."+e:e,a):c[e]=a)}r&&(l=n.nestedProperty(l,r).get(),s=n.nestedProperty(s,r).get(),c=n.nestedProperty(c,r).get()||{});var d=o+"auto",p=o+"min",h=o+"max",g=l[d],y=l[p],v=l[h],m=l.colorscale;!1===g&&void 0!==y||(y=n.aggNums(Math.min,null,e)),!1===g&&void 0!==v||(v=n.aggNums(Math.max,null,e)),y===v&&(y-=.5,v+=.5),f(p,y),f(h,v),f(d,!1!==g||void 0===y&&void 0===v),l.autocolorscale&&(f("colorscale",m=y*v<0?a.RdBu:y>=0?a.Reds:a.Blues,l.reversescale?i(m):m),s.autocolorscale||f("autocolorscale",!1))}},{"../../lib":163,"./flip_scale":57,"./scales":64}],54:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":64}],55:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),l=t("./is_valid_scale"),s=t("./flip_scale");e.exports=function(t,e,r,c,u){var f,d=u.prefix,p=u.cLetter,h=d.slice(0,d.length-1),g=d?a.nestedProperty(t,h).get()||{}:t,y=d?a.nestedProperty(e,h).get()||{}:e,v=g[p+"min"],m=g[p+"max"],x=g.colorscale;c(d+p+"auto",!(n(v)&&n(m)&&v<m)),c(d+p+"min"),c(d+p+"max"),void 0!==x&&(f=!l(x)),c(d+"autocolorscale",f);var b,_=c(d+"colorscale");(c(d+"reversescale")&&(y.colorscale=s(_)),"marker.line."!==d)&&(d&&(b=i(g)),c(d+"showscale",b)&&o(g,y,r))}},{"../../lib":163,"../colorbar/defaults":49,"../colorbar/has_colorbar":51,"./flip_scale":57,"./is_valid_scale":61,"fast-isnumeric":13}],56:[function(t,e,r){"use strict";e.exports=function(t,e,r){for(var n=t.length,a=new Array(n),i=new Array(n),o=0;o<n;o++){var l=t[o];a[o]=e+l[0]*(r-e),i[o]=l[1]}return{domain:a,range:i}}},{}],57:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),a=r-1,i=0;a>=0;a--,i++)e=t[a],n[i]=[1-e[0],e[1]];return n}},{}],58:[function(t,e,r){"use strict";var n=t("./scales"),a=t("./default_scale"),i=t("./is_valid_scale_array");e.exports=function(t,e){if(e||(e=a),!t)return e;function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return"string"==typeof t&&(r(),"string"==typeof t&&r()),i(t)?t:e}},{"./default_scale":54,"./is_valid_scale_array":62,"./scales":64}],59:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("./is_valid_scale");e.exports=function(t,e){var r=e?a.nestedProperty(t,e).get()||{}:t,o=r.color,l=!1;if(a.isArrayOrTypedArray(o))for(var s=0;s<o.length;s++)if(n(o[s])){l=!0;break}return a.isPlainObject(r)&&(l||!0===r.showscale||n(r.cmin)&&n(r.cmax)||i(r.colorscale)||a.isPlainObject(r.colorbar))}},{"../../lib":163,"./is_valid_scale":61,"fast-isnumeric":13}],60:[function(t,e,r){"use strict";r.scales=t("./scales"),r.defaultScale=t("./default_scale"),r.attributes=t("./attributes"),r.handleDefaults=t("./defaults"),r.calc=t("./calc"),r.hasColorscale=t("./has_colorscale"),r.isValidScale=t("./is_valid_scale"),r.getScale=t("./get_scale"),r.flipScale=t("./flip_scale"),r.extractScale=t("./extract_scale"),r.makeColorScaleFunc=t("./make_color_scale_func")},{"./attributes":52,"./calc":53,"./default_scale":54,"./defaults":55,"./extract_scale":56,"./flip_scale":57,"./get_scale":58,"./has_colorscale":59,"./is_valid_scale":61,"./make_color_scale_func":63,"./scales":64}],61:[function(t,e,r){"use strict";var n=t("./scales"),a=t("./is_valid_scale_array");e.exports=function(t){return void 0!==n[t]||a(t)}},{"./is_valid_scale_array":62,"./scales":64}],62:[function(t,e,r){"use strict";var n=t("tinycolor2");e.exports=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r<t.length;r++){var a=t[r];if(2!==a.length||+a[0]<e||!n(a[1]).isValid())return!1;e=+a[0]}return!0}},{tinycolor2:28}],63:[function(t,e,r){"use strict";var n=t("d3"),a=t("tinycolor2"),i=t("fast-isnumeric"),o=t("../color");function l(t){var e={r:t[0],g:t[1],b:t[2],a:t[3]};return a(e).toRgbString()}e.exports=function(t,e){e=e||{};for(var r=t.domain,s=t.range,c=s.length,u=new Array(c),f=0;f<c;f++){var d=a(s[f]).toRgb();u[f]=[d.r,d.g,d.b,d.a]}var p,h=n.scale.linear().domain(r).range(u).clamp(!0),g=e.noNumericCheck,y=e.returnArray;return(p=g&&y?h:g?function(t){return l(h(t))}:y?function(t){return i(t)?h(t):a(t).isValid()?t:o.defaultLine}:function(t){return i(t)?l(h(t)):a(t).isValid()?t:o.defaultLine}).domain=h.domain,p.range=function(){return s},p}},{"../color":45,d3:10,"fast-isnumeric":13,tinycolor2:28}],64:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]}},{}],65:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,a){var i=(t-r)/(n-r),o=i+e/(n-r),l=(i+o)/2;return"left"===a||"bottom"===a?i:"center"===a||"middle"===a?l:"right"===a||"top"===a?o:i<2/3-l?i:o>4/3-l?o:l}},{}],66:[function(t,e,r){"use strict";var n=t("../../lib"),a=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,i){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===i?0:"middle"===i?1:"top"===i?2:n.constrain(Math.floor(3*e),0,2),a[e][t]}},{"../../lib":163}],67:[function(t,e,r){"use strict";var n=t("mouse-event-offset"),a=t("has-hover"),i=t("has-passive-events"),o=t("../../registry"),l=t("../../lib"),s=t("../../plots/cartesian/constants"),c=t("../../constants/interactions"),u=e.exports={};u.align=t("./align"),u.getCursor=t("./cursor");var f=t("./unhover");function d(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function p(t){return n(t.changedTouches?t.changedTouches[0]:t,document.body)}u.unhover=f.wrapped,u.unhoverRaw=f.raw,u.init=function(t){var e,r,n,f,h,g,y,v,m=t.gd,x=1,b=c.DBLCLICKDELAY,_=t.element;m._mouseDownTime||(m._mouseDownTime=0),_.style.pointerEvents="all",_.onmousedown=k,i?(_._ontouchstart&&_.removeEventListener("touchstart",_._ontouchstart),_._ontouchstart=k,_.addEventListener("touchstart",k,{passive:!1})):_.ontouchstart=k;var w=t.clampFn||function(t,e,r){return Math.abs(t)<r&&(t=0),Math.abs(e)<r&&(e=0),[t,e]};function k(i){i.preventDefault(),m._dragged=!1,m._dragging=!0;var o=p(i);e=o[0],r=o[1],y=i.target,g=i,v=2===i.buttons||i.ctrlKey,(n=(new Date).getTime())-m._mouseDownTime<b?x+=1:(x=1,m._mouseDownTime=n),t.prepFn&&t.prepFn(i,e,r),a&&!v?(h=d()).style.cursor=window.getComputedStyle(_).cursor:a||(h=document,f=window.getComputedStyle(document.documentElement).cursor,document.documentElement.style.cursor=window.getComputedStyle(_).cursor),document.addEventListener("mousemove",M),document.addEventListener("mouseup",T),document.addEventListener("touchmove",M),document.addEventListener("touchend",T)}function M(n){n.preventDefault();var a=p(n),i=t.minDrag||s.MINDRAG,o=w(a[0]-e,a[1]-r,i),l=o[0],c=o[1];(l||c)&&(m._dragged=!0,u.unhover(m)),m._dragged&&t.moveFn&&!v&&t.moveFn(l,c)}function T(e){if(document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",T),document.removeEventListener("touchmove",M),document.removeEventListener("touchend",T),e.preventDefault(),a?l.removeElement(h):f&&(h.documentElement.style.cursor=f,f=null),m._dragging){if(m._dragging=!1,(new Date).getTime()-m._mouseDownTime>b&&(x=Math.max(x-1,1)),m._dragged)t.doneFn&&t.doneFn();else if(t.clickFn&&t.clickFn(x,g),!v){var r;try{r=new MouseEvent("click",e)}catch(t){var n=p(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}y.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&o.call("plot",t)}(m),m._dragged=!1}else m._dragged=!1}},u.coverSlip=d},{"../../constants/interactions":144,"../../lib":163,"../../plots/cartesian/constants":212,"../../registry":247,"./align":65,"./cursor":66,"./unhover":68,"has-hover":15,"has-passive-events":16,"mouse-event-offset":18}],68:[function(t,e,r){"use strict";var n=t("../../lib/events"),a=t("../../lib/throttle"),i=t("../../lib/get_graph_div"),o=t("../fx/constants"),l=e.exports={};l.wrapped=function(t,e,r){(t=i(t))._fullLayout&&a.clear(t._fullLayout._uid+o.HOVERID),l.raw(t,e,r)},l.raw=function(t,e){var r=t._fullLayout,a=t._hoverdata;e||(e={}),e.target&&!1===n.triggerHandler(t,"plotly_beforehover",e)||(r._hoverlayer.selectAll("g").remove(),r._hoverlayer.selectAll("line").remove(),r._hoverlayer.selectAll("circle").remove(),t._hoverdata=void 0,e.target&&a&&t.emit("plotly_unhover",{event:e,points:a}))}},{"../../lib/events":156,"../../lib/get_graph_div":161,"../../lib/throttle":185,"../fx/constants":82}],69:[function(t,e,r){"use strict";r.dash={valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},{}],70:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("tinycolor2"),o=t("../../registry"),l=t("../color"),s=t("../colorscale"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),d=t("../../constants/alignment").LINE_SPACING,p=t("../../constants/interactions").DESELECTDIM,h=t("../../traces/scatter/subtypes"),g=t("../../traces/scatter/make_bubble_size_func"),y=e.exports={};y.font=function(t,e,r,n){c.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(l.fill,n)},y.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},y.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},y.setRect=function(t,e,r,n,a){t.call(y.setPosition,e,r).call(y.setSize,n,a)},y.translatePoint=function(t,e,r,n){var i=r.c2p(t.x),o=n.c2p(t.y);return!!(a(i)&&a(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",i).attr("y",o):e.attr("transform","translate("+i+","+o+")"),!0)},y.translatePoints=function(t,e,r){t.each(function(t){var a=n.select(this);y.translatePoint(t,a,e,r)})},y.hideOutsideRangePoint=function(t,e,r,n,a,i){e.attr("display",r.isPtWithinRange(t,a)&&n.isPtWithinRange(t,i)?null:"none")},y.hideOutsideRangePoints=function(t,e){if(e._hasClipOnAxisFalse){var r=e.xaxis,a=e.yaxis;t.each(function(e){var i=e[0].trace,o=i.xcalendar,l=i.ycalendar,s="bar"===i.type?".bartext":".point,.textpoint";t.selectAll(s).each(function(t){y.hideOutsideRangePoint(t,n.select(this),r,a,o,l)})})}},y.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:e<1?1:Math.round(e):r||0},y.singleLineStyle=function(t,e,r,n,a){e.style("fill","none");var i=(((t||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,s=a||i.dash||"";l.stroke(e,n||i.color),y.dashLine(e,s,o)},y.lineGroupStyle=function(t,e,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=e||i.width||0,s=a||i.dash||"";n.select(this).call(l.stroke,r||i.color).call(y.dashLine,s,o)})},y.dashLine=function(t,e,r){r=+r||0,e=y.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},y.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},y.singleFillStyle=function(t){var e=(((n.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;e&&t.call(l.fill,e)},y.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=n.select(this);try{r.call(l.fill,e[0].trace.fillcolor)}catch(e){c.error(e,t),r.remove()}})};var v=t("./symbol_defs");y.symbolNames=[],y.symbolFuncs=[],y.symbolNeedLines={},y.symbolNoDot={},y.symbolNoFill={},y.symbolList=[],Object.keys(v).forEach(function(t){var e=v[t];y.symbolList=y.symbolList.concat([e.n,t,e.n+100,t+"-open"]),y.symbolNames[e.n]=t,y.symbolFuncs[e.n]=e.f,e.needLine&&(y.symbolNeedLines[e.n]=!0),e.noDot?y.symbolNoDot[e.n]=!0:y.symbolList=y.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(y.symbolNoFill[e.n]=!0)});var m=y.symbolNames.length,x="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function b(t,e){var r=t%100;return y.symbolFuncs[r](e)+(t>=200?x:"")}y.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=y.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=m||t>=400?0:Math.floor(Math.max(t,0))};var _={x1:1,x2:0,y1:0,y2:0},w={x1:0,x2:0,y1:1,y2:0};y.gradient=function(t,e,r,a,o,s){var u=e._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+o+s],c.identity);u.exit().remove(),u.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=n.select(this);"horizontal"===a?t.attr(_):"vertical"===a&&t.attr(w),t.attr("id",r);var e=i(o),c=i(s);t.append("stop").attr({offset:"0%","stop-color":l.tinyRGB(c),"stop-opacity":c.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":l.tinyRGB(e),"stop-opacity":e.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},y.initGradients=function(t){c.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},y.pointStyle=function(t,e,r){if(t.size()){var a=y.makePointStyleFns(e);t.each(function(t){y.singlePointStyle(t,n.select(this),e,a,r)})}},y.singlePointStyle=function(t,e,r,n,a){var i=r.marker,o=i.line;if(e.style("opacity",n.selectedOpacityFn?n.selectedOpacityFn(t):void 0===t.mo?i.opacity:t.mo),n.ms2mrc){var s;s="various"===t.ms||"various"===i.size?3:n.ms2mrc(t.ms),t.mrc=s,n.selectedSizeFn&&(s=t.mrc=n.selectedSizeFn(t));var u=y.symbolNumber(t.mx||i.symbol)||0;t.om=u%200>=100,e.attr("d",b(u,s))}var f,d,p,h=!1;if(t.so)p=o.outlierwidth,d=o.outliercolor,f=i.outliercolor;else{var g=(o||{}).width;p=(t.mlw+1||g+1||(t.trace?(t.trace.marker.line||{}).width:0)+1)-1||0,d="mlc"in t?t.mlcc=n.lineScale(t.mlc):c.isArrayOrTypedArray(o.color)?l.defaultLine:o.color,c.isArrayOrTypedArray(i.color)&&(f=l.defaultLine,h=!0),f="mc"in t?t.mcc=n.markerScale(t.mc):i.color||"rgba(0,0,0,0)",n.selectedColorFn&&(f=n.selectedColorFn(t))}if(t.om)e.call(l.stroke,f).style({"stroke-width":(p||1)+"px",fill:"none"});else{e.style("stroke-width",p+"px");var v=i.gradient,m=t.mgt;if(m?h=!0:m=v&&v.type,m&&"none"!==m){var x=t.mgc;x?h=!0:x=v.color;var _="g"+a._fullLayout._uid+"-"+r.uid;h&&(_+="-"+t.i),e.call(y.gradient,a,_,m,f,x)}else e.call(l.fill,f);p&&e.call(l.stroke,d)}},y.makePointStyleFns=function(t){var e={},r=t.marker;return e.markerScale=y.tryColorscale(r,""),e.lineScale=y.tryColorscale(r,"line"),o.traceIs(t,"symbols")&&(e.ms2mrc=h.isBubble(t)?g(t):function(){return(r.size||6)/2}),t.selectedpoints&&c.extendFlat(e,y.makeSelectedPointStyleFns(t)),e},y.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},a=t.marker||{},i=r.marker||{},l=n.marker||{},s=a.opacity,u=i.opacity,f=l.opacity,d=void 0!==u,h=void 0!==f;(c.isArrayOrTypedArray(s)||d||h)&&(e.selectedOpacityFn=function(t){var e=void 0===t.mo?a.opacity:t.mo;return t.selected?d?u:e:h?f:p*e});var g=a.color,y=i.color,v=l.color;(y||v)&&(e.selectedColorFn=function(t){var e=t.mcc||g;return t.selected?y||e:v||e});var m=a.size,x=i.size,b=l.size,_=void 0!==x,w=void 0!==b;return o.traceIs(t,"symbols")&&(_||w)&&(e.selectedSizeFn=function(t){var e=t.mrc||m/2;return t.selected?_?x/2:e:w?b/2:e}),e},y.makeSelectedTextStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},a=t.textfont||{},i=r.textfont||{},o=n.textfont||{},s=a.color,c=i.color,u=o.color;return e.selectedTextColorFn=function(t){var e=t.tc||s;return t.selected?c||e:u||(c?e:l.addOpacity(e,p))},e},y.selectedPointStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=y.makeSelectedPointStyleFns(e),a=e.marker||{},i=[];r.selectedOpacityFn&&i.push(function(t,e){t.style("opacity",r.selectedOpacityFn(e))}),r.selectedColorFn&&i.push(function(t,e){l.fill(t,r.selectedColorFn(e))}),r.selectedSizeFn&&i.push(function(t,e){var n=e.mx||a.symbol||0,i=r.selectedSizeFn(e);t.attr("d",b(y.symbolNumber(n),i)),e.mrc2=i}),i.length&&t.each(function(t){for(var e=n.select(this),r=0;r<i.length;r++)i[r](e,t)})}},y.tryColorscale=function(t,e){var r=e?c.nestedProperty(t,e).get():t;if(r){var n=r.colorscale,a=r.color;if(n&&c.isArrayOrTypedArray(a))return s.makeColorScaleFunc(s.extractScale(n,r.cmin,r.cmax))}return c.identity};var k={start:1,end:-1,middle:0,bottom:1,top:-1};function M(t,e,r,a){var i=n.select(t.node().parentNode),o=-1!==e.indexOf("top")?"top":-1!==e.indexOf("bottom")?"bottom":"middle",l=-1!==e.indexOf("left")?"end":-1!==e.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(u.lineCount(t)-1)*d+1,f=k[l]*s,p=.75*r+k[o]*s+(k[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+f+","+p+")")}function T(t,e){var r=t.ts||e.textfont.size;return a(r)&&r>0?r:0}y.textPointStyle=function(t,e,r){if(t.size()){var a;if(e.selectedpoints){var i=y.makeSelectedTextStyleFns(e);a=i.selectedTextColorFn}t.each(function(t){var i=n.select(this),o=c.extractOption(t,e,"tx","text");if(o||0===o){var l=t.tp||e.textposition,s=T(t,e),f=a?a(t):t.tc||e.textfont.color;i.call(y.font,t.tf||e.textfont.family,s,f).text(o).call(u.convertToTspans,r).call(M,l,s,t.mrc)}else i.remove()})}},y.selectedTextStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=y.makeSelectedTextStyleFns(e);t.each(function(t){var a=n.select(this),i=r.selectedTextColorFn(t),o=t.tp||e.textposition,s=T(t,e);l.fill(a,i),M(a,o,s,t.mrc2||t.mrc)})}};var A=.5;function L(t,e,r,a){var i=t[0]-e[0],o=t[1]-e[1],l=r[0]-e[0],s=r[1]-e[1],c=Math.pow(i*i+o*o,A/2),u=Math.pow(l*l+s*s,A/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,p=3*u*(c+u),h=3*c*(c+u);return[[n.round(e[0]+(p&&f/p),2),n.round(e[1]+(p&&d/p),2)],[n.round(e[0]-(h&&f/h),2),n.round(e[1]-(h&&d/h),2)]]}y.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],a=[];for(r=1;r<t.length-1;r++)a.push(L(t[r-1],t[r],t[r+1],e));for(n+="Q"+a[0][0]+" "+t[1],r=2;r<t.length-1;r++)n+="C"+a[r-2][1]+" "+a[r-1][0]+" "+t[r];return n+="Q"+a[t.length-3][1]+" "+t[t.length-1]},y.smoothclosed=function(t,e){if(t.length<3)return"M"+t.join("L")+"Z";var r,n="M"+t[0],a=t.length-1,i=[L(t[a],t[0],t[1],e)];for(r=1;r<a;r++)i.push(L(t[r-1],t[r],t[r+1],e));for(i.push(L(t[a-1],t[a],t[0],e)),r=1;r<=a;r++)n+="C"+i[r-1][1]+" "+i[r][0]+" "+t[r];return n+="C"+i[a][1]+" "+i[0][0]+" "+t[0]+"Z"};var C={hv:function(t,e){return"H"+n.round(e[0],2)+"V"+n.round(e[1],2)},vh:function(t,e){return"V"+n.round(e[1],2)+"H"+n.round(e[0],2)},hvh:function(t,e){return"H"+n.round((t[0]+e[0])/2,2)+"V"+n.round(e[1],2)+"H"+n.round(e[0],2)},vhv:function(t,e){return"V"+n.round((t[1]+e[1])/2,2)+"H"+n.round(e[0],2)+"V"+n.round(e[1],2)}},S=function(t,e){return"L"+n.round(e[0],2)+","+n.round(e[1],2)};y.steps=function(t){var e=C[t]||S;return function(t){for(var r="M"+n.round(t[0][0],2)+","+n.round(t[0][1],2),a=1;a<t.length;a++)r+=e(t[a-1],t[a]);return r}},y.makeTester=function(){var t=c.ensureSingleById(n.select("body"),"svg","js-plotly-tester",function(t){t.attr(f.svgAttrs).style({position:"absolute",left:"-10000px",top:"-10000px",width:"9000px",height:"9000px","z-index":"1"})}),e=c.ensureSingle(t,"path","js-reference-point",function(t){t.attr("d","M0,0H1V1H0Z").style({"stroke-width":0,fill:"black"})});y.tester=t,y.testref=e},y.savedBBoxes={};var O=0;function P(t){var e=t.getAttribute("data-unformatted");if(null!==e)return e+t.getAttribute("data-math")+t.getAttribute("text-anchor")+t.getAttribute("style")}y.bBox=function(t,e,r){var a,i,o;if(r||(r=P(t)),r){if(a=y.savedBBoxes[r])return c.extendFlat({},a)}else if(1===t.childNodes.length){var l=t.childNodes[0];if(r=P(l)){var s=+l.getAttribute("x")||0,f=+l.getAttribute("y")||0,d=l.getAttribute("transform");if(!d){var p=y.bBox(l,!1,r);return s&&(p.left+=s,p.right+=s),f&&(p.top+=f,p.bottom+=f),p}if(r+="~"+s+"~"+f+"~"+d,a=y.savedBBoxes[r])return c.extendFlat({},a)}}e?i=t:(o=y.tester.node(),i=t.cloneNode(!0),o.appendChild(i)),n.select(i).attr("transform",null).call(u.positionText,0,0);var h=i.getBoundingClientRect(),g=y.testref.node().getBoundingClientRect();e||o.removeChild(i);var v={height:h.height,width:h.width,left:h.left-g.left,top:h.top-g.top,right:h.right-g.left,bottom:h.bottom-g.top};return O>=1e4&&(y.savedBBoxes={},O=0),r&&(y.savedBBoxes[r]=v),O++,c.extendFlat({},v)},y.setClipUrl=function(t,e){if(e){if(void 0===y.baseUrl){var r=n.select("base");r.size()&&r.attr("href")?y.baseUrl=window.location.href.split("#")[0]:y.baseUrl=""}t.attr("clip-path","url("+y.baseUrl+"#"+e+")")}else t.attr("clip-path",null)},y.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},y.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||0,r=r||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+e+", "+r+")").trim(),t[a]("transform",i),i},y.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},y.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||1,r=r||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+e+", "+r+")").trim(),t[a]("transform",i),i};var D=/\s*sc.*/;y.setPointGroupScale=function(t,e,r){if(e=e||1,r=r||1,t){var n=1===e&&1===r?"":" scale("+e+","+r+")";t.each(function(){var t=(this.getAttribute("transform")||"").replace(D,"");t=(t+=n).trim(),this.setAttribute("transform",t)})}};var z=/translate\([^)]*\)\s*$/;y.setTextPointsScale=function(t,e,r){t&&t.each(function(){var t,a=n.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(z);t=1===e&&1===r?[]:["translate("+o+","+l+")","scale("+e+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})}},{"../../constants/alignment":143,"../../constants/interactions":144,"../../constants/xmlns_namespaces":147,"../../lib":163,"../../lib/svg_text_utils":184,"../../registry":247,"../../traces/scatter/make_bubble_size_func":330,"../../traces/scatter/subtypes":336,"../color":45,"../colorscale":60,"./symbol_defs":71,d3:10,"fast-isnumeric":13,tinycolor2:28}],71:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,a="l"+e+",-"+e,i="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+a+i+a+i+o+i+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+","+n.round(t/2,2)+"H"+e+"L0,-"+n.round(t,2)+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+",-"+n.round(t/2,2)+"H"+e+"L0,"+n.round(t,2)+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M"+n.round(t/2,2)+",-"+e+"V"+e+"L-"+n.round(t,2)+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+n.round(t/2,2)+",-"+e+"V"+e+"L"+n.round(t,2)+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),a=n.round(-t,2),i=n.round(-.309*t,2);return"M"+e+","+i+"L"+r+","+n.round(.809*t,2)+"H-"+r+"L-"+e+","+i+"L0,"+a+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),a=n.round(t*Math.sqrt(3)/2,2);return"M"+a+",-"+r+"V"+r+"L0,"+e+"L-"+a+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),a=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+a+"H"+r+"L"+e+",0L"+r+",-"+a+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),a=n.round(.951*e,2),i=n.round(.363*e,2),o=n.round(.588*e,2),l=n.round(-e,2),s=n.round(-.309*e,2),c=n.round(.118*e,2),u=n.round(.809*e,2);return"M"+r+","+s+"H"+a+"L"+i+","+c+"L"+o+","+u+"L0,"+n.round(.382*e,2)+"L-"+o+","+u+"L-"+i+","+c+"L-"+a+","+s+"H-"+r+"L0,"+l+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),a=n.round(.76*t,2);return"M-"+a+",0l-"+r+",-"+e+"h"+a+"l"+r+",-"+e+"l"+r+","+e+"h"+a+"l-"+r+","+e+"l"+r+","+e+"h-"+a+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+a+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),a=n.round(1.6*t,2),i=n.round(4*t,2),o="A "+i+","+i+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+a+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),a=n.round(1.6*t,2),i=n.round(4*t,2),o="A "+i+","+i+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+a+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),a="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+a+"-"+e+","+e+a+e+","+e+a+e+",-"+e+a+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),a="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+a+"0,"+e+a+e+",0"+a+"0,-"+e+a+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0,noFill:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0,noFill:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M-"+e+","+a+"L0,0M"+e+","+a+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M-"+e+",-"+a+"L0,0M"+e+",-"+a+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M"+a+","+e+"L0,0M"+a+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M-"+a+","+e+"L0,0M-"+a+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0,noFill:!0}}},{d3:10}],72:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}}},{}],73:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../registry"),i=t("../../plots/cartesian/axes"),o=t("./compute_error");function l(t,e,r,a){var l=e["error_"+a]||{},s=[];if(l.visible&&-1!==["linear","log"].indexOf(r.type)){for(var c=o(l),u=0;u<t.length;u++){var f=t[u],d=f[a];if(n(r.c2l(d))){var p=c(d,u);if(n(p[0])&&n(p[1])){var h=f[a+"s"]=d-p[0],g=f[a+"h"]=d+p[1];s.push(h,g)}}}i.expand(r,s,{padded:!0})}}e.exports=function(t){for(var e=t.calcdata,r=0;r<e.length;r++){var n=e[r],o=n[0].trace;if(a.traceIs(o,"errorBarsOK")){var s=i.getFromId(t,o.xaxis),c=i.getFromId(t,o.yaxis);l(n,o,s,"x"),l(n,o,c,"y")}}}},{"../../plots/cartesian/axes":207,"../../registry":247,"./compute_error":74,"fast-isnumeric":13}],74:[function(t,e,r){"use strict";function n(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}e.exports=function(t){var e=t.type,r=t.symmetric;if("data"===e){var a=t.array||[];if(r)return function(t,e){var r=+a[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+a[e],n=+i[e];return isNaN(r)&&isNaN(n)?[NaN,NaN]:[n||0,r||0]}}var o=n(e,t.value),l=n(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=o(t);return[e,e]}:function(t){return[l(t),o(t)]}}},{}],75:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../registry"),i=t("../../lib"),o=t("../../plot_api/plot_template"),l=t("./attributes");e.exports=function(t,e,r,s){var c="error_"+s.axis,u=o.newContainer(e,c),f=t[c]||{};function d(t,e){return i.coerce(f,u,l,t,e)}if(!1!==d("visible",void 0!==f.array||void 0!==f.value||"sqrt"===f.type)){var p=d("type","array"in f?"data":"percent"),h=!0;"sqrt"!==p&&(h=d("symmetric",!(("data"===p?"arrayminus":"valueminus")in f))),"data"===p?(d("array"),d("traceref"),h||(d("arrayminus"),d("tracerefminus"))):"percent"!==p&&"constant"!==p||(d("value"),h||d("valueminus"));var g="copy_"+s.inherit+"style";if(s.inherit)(e["error_"+s.inherit]||{}).visible&&d(g,!(f.color||n(f.thickness)||n(f.width)));s.inherit&&u[g]||(d("color",r),d("thickness"),d("width",a.traceIs(e,"gl3d")?0:4))}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../registry":247,"./attributes":72,"fast-isnumeric":13}],76:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plot_api/edit_types").overrideAll,i=t("./attributes"),o={error_x:n.extendFlat({},i),error_y:n.extendFlat({},i)};delete o.error_x.copy_zstyle,delete o.error_y.copy_zstyle,delete o.error_y.copy_ystyle;var l={error_x:n.extendFlat({},i),error_y:n.extendFlat({},i),error_z:n.extendFlat({},i)};delete l.error_x.copy_ystyle,delete l.error_y.copy_ystyle,delete l.error_z.copy_ystyle,delete l.error_z.copy_zstyle,e.exports={moduleType:"component",name:"errorbars",schema:{traces:{scatter:o,bar:o,histogram:o,scatter3d:a(l,"calc","nested"),scattergl:a(o,"calc","nested")}},supplyDefaults:t("./defaults"),calc:t("./calc"),makeComputeError:t("./compute_error"),plot:t("./plot"),style:t("./style"),hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}}},{"../../lib":163,"../../plot_api/edit_types":190,"./attributes":72,"./calc":73,"./compute_error":74,"./defaults":75,"./plot":77,"./style":78}],77:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../drawing"),o=t("../../traces/scatter/subtypes");e.exports=function(t,e,r){var l=e.xaxis,s=e.yaxis,c=r&&r.duration>0;t.each(function(t){var u,f=t[0].trace,d=f.error_x||{},p=f.error_y||{};f.ids&&(u=function(t){return t.id});var h=o.hasMarkers(f)&&f.marker.maxdisplayed>0;p.visible||d.visible||(t=[]);var g=n.select(this).selectAll("g.errorbar").data(t,u);if(g.exit().remove(),t.length){d.visible||g.selectAll("path.xerror").remove(),p.visible||g.selectAll("path.yerror").remove(),g.style("opacity",1);var y=g.enter().append("g").classed("errorbar",!0);c&&y.style("opacity",0).transition().duration(r.duration).style("opacity",1),i.setClipUrl(g,e.layerClipId),g.each(function(t){var e=n.select(this),i=function(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0)));void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0)));return n}(t,l,s);if(!h||t.vis){var o,u=e.select("path.yerror");if(p.visible&&a(i.x)&&a(i.yh)&&a(i.ys)){var f=p.width;o="M"+(i.x-f)+","+i.yh+"h"+2*f+"m-"+f+",0V"+i.ys,i.noYS||(o+="m-"+f+",0h"+2*f),!u.size()?u=e.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0):c&&(u=u.transition().duration(r.duration).ease(r.easing)),u.attr("d",o)}else u.remove();var g=e.select("path.xerror");if(d.visible&&a(i.y)&&a(i.xh)&&a(i.xs)){var y=(d.copy_ystyle?p:d).width;o="M"+i.xh+","+(i.y-y)+"v"+2*y+"m0,-"+y+"H"+i.xs,i.noXS||(o+="m0,-"+y+"v"+2*y),!g.size()?g=e.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0):c&&(g=g.transition().duration(r.duration).ease(r.easing)),g.attr("d",o)}else g.remove()}})}})}},{"../../traces/scatter/subtypes":336,"../drawing":70,d3:10,"fast-isnumeric":13}],78:[function(t,e,r){"use strict";var n=t("d3"),a=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},i=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(a.stroke,r.color),i.copy_ystyle&&(i=r),o.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(a.stroke,i.color)})}},{"../color":45,d3:10}],79:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes");e.exports={hoverlabel:{bgcolor:{valType:"color",arrayOk:!0,editType:"none"},bordercolor:{valType:"color",arrayOk:!0,editType:"none"},font:n({arrayOk:!0,editType:"none"}),namelength:{valType:"integer",min:-1,arrayOk:!0,editType:"none"},editType:"calc"}}},{"../../plots/font_attributes":233}],80:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry");function i(t,e,r,a){a=a||n.identity,Array.isArray(t)&&(e[0][r]=a(t))}e.exports=function(t){var e=t.calcdata,r=t._fullLayout;function o(t){return function(e){return n.coerceHoverinfo({hoverinfo:e},{_module:t._module},r)}}for(var l=0;l<e.length;l++){var s=e[l],c=s[0].trace;if(!a.traceIs(c,"pie")){var u=a.traceIs(c,"2dMap")?i:n.fillArray;u(c.hoverinfo,s,"hi",o(c)),c.hoverlabel&&(u(c.hoverlabel.bgcolor,s,"hbg"),u(c.hoverlabel.bordercolor,s,"hbc"),u(c.hoverlabel.font.size,s,"hts"),u(c.hoverlabel.font.color,s,"htc"),u(c.hoverlabel.font.family,s,"htf"),u(c.hoverlabel.namelength,s,"hnl"))}}}},{"../../lib":163,"../../registry":247}],81:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./hover").hover;e.exports=function(t,e,r){var i=n.getComponentMethod("annotations","onClick")(t,t._hoverdata);function o(){t.emit("plotly_click",{points:t._hoverdata,event:e})}void 0!==r&&a(t,e,r,!0),t._hoverdata&&e&&e.target&&(i&&i.then?i.then(o):o(),e.stopImmediatePropagation&&e.stopImmediatePropagation())}},{"../../registry":247,"./hover":85}],82:[function(t,e,r){"use strict";e.exports={YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,HOVERID:"-hover"}},{}],83:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./attributes"),i=t("./hoverlabel_defaults");e.exports=function(t,e,r,o){i(t,e,function(r,i){return n.coerce(t,e,a,r,i)},o.hoverlabel)}},{"../../lib":163,"./attributes":79,"./hoverlabel_defaults":86}],84:[function(t,e,r){"use strict";var n=t("../../lib");r.getSubplot=function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},r.isTraceInSubplots=function(t,e){if("splom"===t.type){for(var n=t.xaxes||[],a=t.yaxes||[],i=0;i<n.length;i++)for(var o=0;o<a.length;o++)if(-1!==e.indexOf(n[i]+a[o]))return!0;return!1}return-1!==e.indexOf(r.getSubplot(t))},r.flat=function(t,e){for(var r=new Array(t.length),n=0;n<t.length;n++)r[n]=e;return r},r.p2c=function(t,e){for(var r=new Array(t.length),n=0;n<t.length;n++)r[n]=t[n].p2c(e);return r},r.getDistanceFunction=function(t,e,n,a){return"closest"===t?a||r.quadrature(e,n):"x"===t?e:n},r.getClosest=function(t,e,r){if(!1!==r.index)r.index>=0&&r.index<t.length?r.distance=0:r.index=!1;else for(var n=0;n<t.length;n++){var a=e(t[n]);a<=r.distance&&(r.index=n,r.distance=a)}return r},r.inbox=function(t,e,r){return t*e<0||0===t?r:1/0},r.quadrature=function(t,e){return function(r){var n=t(r),a=e(r);return Math.sqrt(n*n+a*a)}},r.makeEventData=function(t,e,n){var a="index"in t?t.index:t.pointNumber,i={data:e._input,fullData:e,curveNumber:e.index,pointNumber:a};if(e._indexToPoints){var o=e._indexToPoints[a];1===o.length?i.pointIndex=o[0]:i.pointIndices=o}else i.pointIndex=a;return e._module.eventData?i=e._module.eventData(i,t,e,n,a):("xVal"in t?i.x=t.xVal:"x"in t&&(i.x=t.x),"yVal"in t?i.y=t.yVal:"y"in t&&(i.y=t.y),t.xa&&(i.xaxis=t.xa),t.ya&&(i.yaxis=t.ya),void 0!==t.zLabelVal&&(i.z=t.zLabelVal)),r.appendArrayPointValue(i,e,a),i},r.appendArrayPointValue=function(t,e,r){var a=e._arrayAttrs;if(a)for(var l=0;l<a.length;l++){var s=a[l],c=i(s);if(void 0===t[c]){var u=o(n.nestedProperty(e,s).get(),r);void 0!==u&&(t[c]=u)}}},r.appendArrayMultiPointValues=function(t,e,r){var a=e._arrayAttrs;if(a)for(var l=0;l<a.length;l++){var s=a[l],c=i(s);if(void 0===t[c]){for(var u=n.nestedProperty(e,s).get(),f=new Array(r.length),d=0;d<r.length;d++)f[d]=o(u,r[d]);t[c]=f}}};var a={ids:"id",locations:"location",labels:"label",values:"value","marker.colors":"color"};function i(t){return a[t]||t}function o(t,e){return Array.isArray(e)?Array.isArray(t)&&Array.isArray(t[e[0]])?t[e[0]][e[1]]:void 0:t[e]}},{"../../lib":163}],85:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("tinycolor2"),o=t("../../lib"),l=t("../../lib/events"),s=t("../../lib/svg_text_utils"),c=t("../../lib/override_cursor"),u=t("../drawing"),f=t("../color"),d=t("../dragelement"),p=t("../../plots/cartesian/axes"),h=t("../../registry"),g=t("./helpers"),y=t("./constants"),v=y.YANGLE,m=Math.PI*v/180,x=1/Math.sin(m),b=Math.cos(m),_=Math.sin(m),w=y.HOVERARROWSIZE,k=y.HOVERTEXTPAD;function M(t,e,r){var a=e.hovermode,i=e.rotateLabels,l=e.bgColor,c=e.container,d=e.outerContainer,p=e.commonLabelOpts||{},h=e.fontFamily||y.HOVERFONT,g=e.fontSize||y.HOVERFONTSIZE,m=t[0],x=m.xa,b=m.ya,_="y"===a?"yLabel":"xLabel",M=m[_],T=(String(M)||"").split(" ")[0],A=d.node().getBoundingClientRect(),L=A.top,C=A.width,S=A.height,O=void 0!==M&&m.distance<=e.hoverdistance&&("x"===a||"y"===a);if(O){var P,D,z=!0;for(P=0;P<t.length;P++){z&&void 0===t[P].zLabel&&(z=!1),D=t[P].hoverinfo||t[P].trace.hoverinfo;var E=Array.isArray(D)?D:D.split("+");if(-1===E.indexOf("all")&&-1===E.indexOf(a)){O=!1;break}}z&&(O=!1)}var I=c.selectAll("g.axistext").data(O?[0]:[]);I.enter().append("g").classed("axistext",!0),I.exit().remove(),I.each(function(){var e=n.select(this),i=o.ensureSingle(e,"path","",function(t){t.style({"stroke-width":"1px"})}),l=o.ensureSingle(e,"text","",function(t){t.attr("data-notex",1)}),c=p.bgcolor||f.defaultLine,d=p.bordercolor||f.contrast(c);i.style({fill:c,stroke:d}),l.text(M).call(u.font,p.font.family||h,p.font.size||g,p.font.color||f.background).call(s.positionText,0,0).call(s.convertToTspans,r),e.attr("transform","");var y=l.node().getBoundingClientRect();if("x"===a){l.attr("text-anchor","middle").call(s.positionText,0,"top"===x.side?L-y.bottom-w-k:L-y.top+w+k);var v="top"===x.side?"-":"";i.attr("d","M0,0L"+w+","+v+w+"H"+(k+y.width/2)+"v"+v+(2*k+y.height)+"H-"+(k+y.width/2)+"V"+v+w+"H-"+w+"Z"),e.attr("transform","translate("+(x._offset+(m.x0+m.x1)/2)+","+(b._offset+("top"===x.side?0:b._length))+")")}else{l.attr("text-anchor","right"===b.side?"start":"end").call(s.positionText,("right"===b.side?1:-1)*(k+w),L-y.top-y.height/2);var A="right"===b.side?"":"-";i.attr("d","M0,0L"+A+w+","+w+"V"+(k+y.height/2)+"h"+A+(2*k+y.width)+"V-"+(k+y.height/2)+"H"+A+w+"V-"+w+"Z"),e.attr("transform","translate("+(x._offset+("right"===b.side?x._length:0))+","+(b._offset+(m.y0+m.y1)/2)+")")}t=t.filter(function(t){return void 0!==t.zLabelVal||(t[_]||"").split(" ")[0]===T})});var N=c.selectAll("g.hovertext").data(t,function(t){return[t.trace.index,t.index,t.x0,t.y0,t.name,t.attr,t.xa,t.ya||""].join(",")});return N.enter().append("g").classed("hovertext",!0).each(function(){var t=n.select(this);t.append("rect").call(f.fill,f.addOpacity(l,.8)),t.append("text").classed("name",!0),t.append("path").style("stroke-width","1px"),t.append("text").classed("nums",!0).call(u.font,h,g)}),N.exit().remove(),N.each(function(t){var e=n.select(this).attr("transform",""),o="",c="",d=f.opacity(t.color)?t.color:f.defaultLine,p=f.combine(d,l),y=t.borderColor||f.contrast(p);if(void 0!==t.nameOverride&&(t.name=t.nameOverride),t.name){o=s.plainText(t.name||"");var m=Math.round(t.nameLength);m>-1&&o.length>m&&(o=m>3?o.substr(0,m-3)+"...":o.substr(0,m))}void 0!==t.zLabel?(void 0!==t.xLabel&&(c+="x: "+t.xLabel+"<br>"),void 0!==t.yLabel&&(c+="y: "+t.yLabel+"<br>"),c+=(c?"z: ":"")+t.zLabel):O&&t[a+"Label"]===M?c=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(c=t.yLabel):c=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",!t.text&&0!==t.text||Array.isArray(t.text)||(c+=(c?"<br>":"")+t.text),void 0!==t.extraText&&(c+=(c?"<br>":"")+t.extraText),""===c&&(""===o&&e.remove(),c=o);var x=e.select("text.nums").call(u.font,t.fontFamily||h,t.fontSize||g,t.fontColor||y).text(c).attr("data-notex",1).call(s.positionText,0,0).call(s.convertToTspans,r),b=e.select("text.name"),_=0;o&&o!==c?(b.call(u.font,t.fontFamily||h,t.fontSize||g,p).text(o).attr("data-notex",1).call(s.positionText,0,0).call(s.convertToTspans,r),_=b.node().getBoundingClientRect().width+2*k):(b.remove(),e.select("rect").remove()),e.select("path").style({fill:p,stroke:y});var T,A,P=x.node().getBoundingClientRect(),D=t.xa._offset+(t.x0+t.x1)/2,z=t.ya._offset+(t.y0+t.y1)/2,E=Math.abs(t.x1-t.x0),I=Math.abs(t.y1-t.y0),N=P.width+w+k+_;t.ty0=L-P.top,t.bx=P.width+2*k,t.by=P.height+2*k,t.anchor="start",t.txwidth=P.width,t.tx2width=_,t.offset=0,i?(t.pos=D,T=z+I/2+N<=S,A=z-I/2-N>=0,"top"!==t.idealAlign&&T||!A?T?(z+=I/2,t.anchor="start"):t.anchor="middle":(z-=I/2,t.anchor="end")):(t.pos=z,T=D+E/2+N<=C,A=D-E/2-N>=0,"left"!==t.idealAlign&&T||!A?T?(D+=E/2,t.anchor="start"):t.anchor="middle":(D-=E/2,t.anchor="end")),x.attr("text-anchor",t.anchor),_&&b.attr("text-anchor",t.anchor),e.attr("transform","translate("+D+","+z+")"+(i?"rotate("+v+")":""))}),N}function T(t,e){t.each(function(t){var r=n.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(w+k),c=l+o*(t.txwidth+k),f=0,d=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,c+=t.txwidth/2+k),e&&(d*=-_,f=t.offset*b),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(d-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*w+f)+","+(w+d)+"v"+(t.by/2-w)+"h"+a*t.bx+"v-"+t.by+"H"+(a*w+f)+"V"+(d-w)+"Z"),i.call(s.positionText,l+f,d+t.ty0-t.by/2+k),t.tx2width&&(r.select("text.name").call(s.positionText,c+o*k+f,d+t.ty0-t.by/2+k),r.select("rect").call(u.setRect,c+(o-1)*t.tx2width/2+f,d-t.by/2-1,t.tx2width,t.by+2))}})}function A(t,e){var r=t.index,n=t.trace||{},a=t.cd[0],i=t.cd[r]||{},l=Array.isArray(r)?function(t,e){return o.castOption(a,r,t)||o.extractOption({},n,"",e)}:function(t,e){return o.extractOption(i,n,t,e)};function s(e,r,n){var a=l(r,n);a&&(t[e]=a)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=o.constrain(t.x0,0,t.xa._length),t.x1=o.constrain(t.x1,0,t.xa._length),t.y0=o.constrain(t.y0,0,t.ya._length),t.y1=o.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:p.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:p.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var c=p.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+c+" / -"+p.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+c,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=p.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+p.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var f=t.hoverinfo||t.trace.hoverinfo;return"all"!==f&&(-1===(f=Array.isArray(f)?f:f.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===f.indexOf("y")&&(t.yLabel=void 0),-1===f.indexOf("z")&&(t.zLabel=void 0),-1===f.indexOf("text")&&(t.text=void 0),-1===f.indexOf("name")&&(t.name=void 0)),t}function L(t,e){var r,n,a=e.container,o=e.fullLayout,l=e.event,s=!!t.hLinePoint,c=!!t.vLinePoint;if(a.selectAll(".spikeline").remove(),c||s){var d=f.combine(o.plot_bgcolor,o.paper_bgcolor);if(s){var p,h,g=t.hLinePoint;r=g&&g.xa,"cursor"===(n=g&&g.ya).spikesnap?(p=l.pointerX,h=l.pointerY):(p=r._offset+g.x,h=n._offset+g.y);var y,v,m=i.readability(g.color,d)<1.5?f.contrast(d):g.color,x=n.spikemode,b=n.spikethickness,_=n.spikecolor||m,w=n._boundingBox,k=(w.left+w.right)/2<p?w.right:w.left;-1===x.indexOf("toaxis")&&-1===x.indexOf("across")||(-1!==x.indexOf("toaxis")&&(y=k,v=p),-1!==x.indexOf("across")&&(y=n._counterSpan[0],v=n._counterSpan[1]),a.insert("line",":first-child").attr({x1:y,x2:v,y1:h,y2:h,"stroke-width":b,stroke:_,"stroke-dasharray":u.dashStyle(n.spikedash,b)}).classed("spikeline",!0).classed("crisp",!0),a.insert("line",":first-child").attr({x1:y,x2:v,y1:h,y2:h,"stroke-width":b+2,stroke:d}).classed("spikeline",!0).classed("crisp",!0)),-1!==x.indexOf("marker")&&a.insert("circle",":first-child").attr({cx:k+("right"!==n.side?b:-b),cy:h,r:b,fill:_}).classed("spikeline",!0)}if(c){var M,T,A=t.vLinePoint;r=A&&A.xa,n=A&&A.ya,"cursor"===r.spikesnap?(M=l.pointerX,T=l.pointerY):(M=r._offset+A.x,T=n._offset+A.y);var L,C,S=i.readability(A.color,d)<1.5?f.contrast(d):A.color,O=r.spikemode,P=r.spikethickness,D=r.spikecolor||S,z=r._boundingBox,E=(z.top+z.bottom)/2<T?z.bottom:z.top;-1===O.indexOf("toaxis")&&-1===O.indexOf("across")||(-1!==O.indexOf("toaxis")&&(L=E,C=T),-1!==O.indexOf("across")&&(L=r._counterSpan[0],C=r._counterSpan[1]),a.insert("line",":first-child").attr({x1:M,x2:M,y1:L,y2:C,"stroke-width":P,stroke:D,"stroke-dasharray":u.dashStyle(r.spikedash,P)}).classed("spikeline",!0).classed("crisp",!0),a.insert("line",":first-child").attr({x1:M,x2:M,y1:L,y2:C,"stroke-width":P+2,stroke:d}).classed("spikeline",!0).classed("crisp",!0)),-1!==O.indexOf("marker")&&a.insert("circle",":first-child").attr({cx:M,cy:E-("top"!==r.side?P:-P),r:P,fill:D}).classed("spikeline",!0)}}}function C(t,e){return!e||(e.vLinePoint!==t._spikepoints.vLinePoint||e.hLinePoint!==t._spikepoints.hLinePoint)}r.hover=function(t,e,r,i){t=o.getGraphDiv(t),o.throttle(t._fullLayout._uid+y.HOVERID,y.HOVERMINTIME,function(){!function(t,e,r,i){r||(r="xy");var s=Array.isArray(r)?r:[r],u=t._fullLayout,y=u._plots||[],v=y[r],m=u._has("cartesian");if(v){var b=v.overlays.map(function(t){return t.id});s=s.concat(b)}for(var _=s.length,w=new Array(_),k=new Array(_),S=!1,O=0;O<_;O++){var P=s[O],D=y[P];if(D)S=!0,w[O]=p.getFromId(t,D.xaxis._id),k[O]=p.getFromId(t,D.yaxis._id);else{var z=u[P]._subplot;w[O]=z.xaxis,k[O]=z.yaxis}}var E=e.hovermode||u.hovermode;E&&!S&&(E="closest");if(-1===["x","y","closest"].indexOf(E)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return d.unhoverRaw(t,e);var I,N,R,F,j,B,H,q,V,U,G,Y,X,Z=-1===u.hoverdistance?1/0:u.hoverdistance,W=-1===u.spikedistance?1/0:u.spikedistance,Q=[],J=[],$={hLinePoint:null,vLinePoint:null};if(Array.isArray(e))for(E="array",R=0;R<e.length;R++)"skip"!==(j=t.calcdata[e[R].curveNumber||0])[0].trace.hoverinfo&&J.push(j);else{for(F=0;F<t.calcdata.length;F++)j=t.calcdata[F],"skip"!==(B=j[0].trace).hoverinfo&&g.isTraceInSubplots(B,s)&&J.push(j);var K,tt,et=!e.target;if(et)K="xpx"in e?e.xpx:w[0]._length/2,tt="ypx"in e?e.ypx:k[0]._length/2;else{if(!1===l.triggerHandler(t,"plotly_beforehover",e))return;var rt=e.target.getBoundingClientRect();if(K=e.clientX-rt.left,tt=e.clientY-rt.top,K<0||K>w[0]._length||tt<0||tt>k[0]._length)return d.unhoverRaw(t,e)}if(e.pointerX=K+w[0]._offset,e.pointerY=tt+k[0]._offset,I="xval"in e?g.flat(s,e.xval):g.p2c(w,K),N="yval"in e?g.flat(s,e.yval):g.p2c(k,tt),!a(I[0])||!a(N[0]))return o.warn("Fx.hover failed",e,t),d.unhoverRaw(t,e)}var nt=1/0;for(F=0;F<J.length;F++)if((j=J[F])&&j[0]&&j[0].trace&&!0===j[0].trace.visible&&(B=j[0].trace,-1===["carpet","contourcarpet"].indexOf(B._module.name))){if("splom"===B.type?H=s[q=0]:(H=g.getSubplot(B),q=s.indexOf(H)),V=E,Y={cd:j,trace:B,xa:w[q],ya:k[q],maxHoverDistance:Z,maxSpikeDistance:W,index:!1,distance:Math.min(nt,Z),spikeDistance:1/0,xSpike:void 0,ySpike:void 0,color:f.defaultLine,name:B.name,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},u[H]&&(Y.subplot=u[H]._subplot),X=Q.length,"array"===V){var at=e[F];"pointNumber"in at?(Y.index=at.pointNumber,V="closest"):(V="","xval"in at&&(U=at.xval,V="x"),"yval"in at&&(G=at.yval,V=V?"closest":"y"))}else U=I[q],G=N[q];if(0!==Z)if(B._module&&B._module.hoverPoints){var it=B._module.hoverPoints(Y,U,G,V,u._hoverlayer);if(it)for(var ot,lt=0;lt<it.length;lt++)ot=it[lt],a(ot.x0)&&a(ot.y0)&&Q.push(A(ot,E))}else o.log("Unrecognized trace type in hover:",B);if("closest"===E&&Q.length>X&&(Q.splice(0,X),nt=Q[0].distance),m&&0!==W&&0===Q.length){Y.distance=W,Y.index=!1;var st=B._module.hoverPoints(Y,U,G,"closest",u._hoverlayer);if(st&&(st=st.filter(function(t){return t.spikeDistance<=W})),st&&st.length){var ct,ut=st.filter(function(t){return t.xa.showspikes});if(ut.length){var ft=ut[0];a(ft.x0)&&a(ft.y0)&&(ct=gt(ft),(!$.vLinePoint||$.vLinePoint.spikeDistance>ct.spikeDistance)&&($.vLinePoint=ct))}var dt=st.filter(function(t){return t.ya.showspikes});if(dt.length){var pt=dt[0];a(pt.x0)&&a(pt.y0)&&(ct=gt(pt),(!$.hLinePoint||$.hLinePoint.spikeDistance>ct.spikeDistance)&&($.hLinePoint=ct))}}}}function ht(t,e){for(var r,n=null,a=1/0,i=0;i<t.length;i++)(r=t[i].spikeDistance)<a&&r<=e&&(n=t[i],a=r);return n}function gt(t){return t?{xa:t.xa,ya:t.ya,x:void 0!==t.xSpike?t.xSpike:(t.x0+t.x1)/2,y:void 0!==t.ySpike?t.ySpike:(t.y0+t.y1)/2,distance:t.distance,spikeDistance:t.spikeDistance,curveNumber:t.trace.index,color:t.color,pointNumber:t.index}:null}var yt={fullLayout:u,container:u._hoverlayer,outerContainer:u._paperdiv,event:e},vt=t._spikepoints,mt={vLinePoint:$.vLinePoint,hLinePoint:$.hLinePoint};if(t._spikepoints=mt,m&&0!==W&&0!==Q.length){var xt=Q.filter(function(t){return t.ya.showspikes}),bt=ht(xt,W);$.hLinePoint=gt(bt);var _t=Q.filter(function(t){return t.xa.showspikes}),wt=ht(_t,W);$.vLinePoint=gt(wt)}if(0===Q.length){var kt=d.unhoverRaw(t,e);return!m||null===$.hLinePoint&&null===$.vLinePoint||C(vt)&&L($,yt),kt}m&&C(vt)&&L($,yt);Q.sort(function(t,e){return t.distance-e.distance});var Mt=t._hoverdata,Tt=[];for(R=0;R<Q.length;R++){var At=Q[R];Tt.push(g.makeEventData(At,At.trace,At.cd))}t._hoverdata=Tt;var Lt="y"===E&&J.length>1,Ct=f.combine(u.plot_bgcolor||f.background,u.paper_bgcolor),St={hovermode:E,rotateLabels:Lt,bgColor:Ct,container:u._hoverlayer,outerContainer:u._paperdiv,commonLabelOpts:u.hoverlabel,hoverdistance:u.hoverdistance},Ot=M(Q,St,t);if(function(t,e,r){var n,a,i,o,l,s,c,u=0,f=t.map(function(t,n){var a=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===a._id.charAt(0)?x:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function d(t){var e=t[0],r=t[t.length-1];if(a=e.pmin-e.pos-e.dp+e.size,i=r.pos+r.dp+r.size-e.pmax,a>.01){for(l=t.length-1;l>=0;l--)t[l].dp+=a;n=!1}if(!(i<.01)){if(a<-.01){for(l=t.length-1;l>=0;l--)t[l].dp-=i;n=!1}if(n){var c=0;for(o=0;o<t.length;o++)(s=t[o]).pos+s.dp+s.size>e.pmax&&c++;for(o=t.length-1;o>=0&&!(c<=0);o--)(s=t[o]).pos>e.pmax-1&&(s.del=!0,c--);for(o=0;o<t.length&&!(c<=0);o++)if((s=t[o]).pos<e.pmin+1)for(s.del=!0,c--,i=2*s.size,l=t.length-1;l>=0;l--)t[l].dp-=i;for(o=t.length-1;o>=0&&!(c<=0);o--)(s=t[o]).pos+s.dp+s.size>e.pmax&&(s.del=!0,c--)}}}for(;!n&&u<=t.length;){for(u++,n=!0,o=0;o<f.length-1;){var p=f[o],h=f[o+1],g=p[p.length-1],y=h[0];if((a=g.pos+g.dp+g.size-y.pos-y.dp+y.size)>.01&&g.pmin===y.pmin&&g.pmax===y.pmax){for(l=h.length-1;l>=0;l--)h[l].dp+=a;for(p.push.apply(p,h),f.splice(o+1,1),c=0,l=p.length-1;l>=0;l--)c+=p[l].dp;for(i=c/p.length,l=p.length-1;l>=0;l--)p[l].dp-=i;n=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var v=f[o];for(l=v.length-1;l>=0;l--){var m=v[l],b=t[m.i];b.offset=m.dp,b.del=m.del}}}(Q,Lt?"xa":"ya",u),T(Ot,Lt),e.target&&e.target.tagName){var Pt=h.getComponentMethod("annotations","hasClickToShow")(t,Tt);c(n.select(e.target),Pt?"pointer":"")}if(!e.target||i||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var a=r[n],i=t._hoverdata[n];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,Mt))return;Mt&&t.emit("plotly_unhover",{event:e,points:Mt});t.emit("plotly_hover",{event:e,points:t._hoverdata,xaxes:w,yaxes:k,xvals:I,yvals:N})}(t,e,r,i)})},r.loneHover=function(t,e){var r={color:t.color||f.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=n.select(e.container),i=e.outerContainer?n.select(e.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||f.background,container:a,outerContainer:i},l=M([r],o,e.gd);return T(l,o.rotateLabels),l.node()}},{"../../lib":163,"../../lib/events":156,"../../lib/override_cursor":174,"../../lib/svg_text_utils":184,"../../plots/cartesian/axes":207,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"./constants":82,"./helpers":84,d3:10,"fast-isnumeric":13,tinycolor2:28}],86:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,a){r("hoverlabel.bgcolor",(a=a||{}).bgcolor),r("hoverlabel.bordercolor",a.bordercolor),r("hoverlabel.namelength",a.namelength),n.coerceFont(r,"hoverlabel.font",a.font)}},{"../../lib":163}],87:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib"),i=t("../dragelement"),o=t("./helpers"),l=t("./layout_attributes");e.exports={moduleType:"component",name:"fx",constants:t("./constants"),schema:{layout:l},attributes:t("./attributes"),layoutAttributes:l,supplyLayoutGlobalDefaults:t("./layout_global_defaults"),supplyDefaults:t("./defaults"),supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc"),getDistanceFunction:o.getDistanceFunction,getClosest:o.getClosest,inbox:o.inbox,quadrature:o.quadrature,appendArrayPointValue:o.appendArrayPointValue,castHoverOption:function(t,e,r){return a.castOption(t,e,"hoverlabel."+r)},castHoverinfo:function(t,e,r){return a.castOption(t,r,"hoverinfo",function(r){return a.coerceHoverinfo({hoverinfo:r},{_module:t._module},e)})},hover:t("./hover").hover,unhover:i.unhover,loneHover:t("./hover").loneHover,loneUnhover:function(t){var e=a.isD3Selection(t)?t:n.select(t);e.selectAll("g.hovertext").remove(),e.selectAll(".spikeline").remove()},click:t("./click")}},{"../../lib":163,"../dragelement":67,"./attributes":79,"./calc":80,"./click":81,"./constants":82,"./defaults":83,"./helpers":84,"./hover":85,"./layout_attributes":88,"./layout_defaults":89,"./layout_global_defaults":90,d3:10}],88:[function(t,e,r){"use strict";var n=t("./constants"),a=t("../../plots/font_attributes")({editType:"none"});a.family.dflt=n.HOVERFONT,a.size.dflt=n.HOVERFONTSIZE,e.exports={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:a,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}}},{"../../plots/font_attributes":233,"./constants":82}],89:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e,r){function i(r,i){return n.coerce(t,e,a,r,i)}var o;"select"===i("dragmode")&&i("selectdirection"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r<t.length;r++){var n=t[r];if("h"!==n.orientation){e=!1;break}}return e}(r),o=e._isHoriz?"y":"x"):o="closest",i("hovermode",o)&&(i("hoverdistance"),i("spikedistance"));var l=e._has("mapbox"),s=e._has("geo"),c=e._basePlotModules.length;"zoom"===e.dragmode&&((l||s)&&1===c||l&&s&&2===c)&&(e.dragmode="pan")}},{"../../lib":163,"./layout_attributes":88}],90:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./hoverlabel_defaults"),i=t("./layout_attributes");e.exports=function(t,e){a(t,e,function(r,a){return n.coerce(t,e,i,r,a)})}},{"../../lib":163,"./hoverlabel_defaults":86,"./layout_attributes":88}],91:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../lib/regex").counter,i=t("../../plots/domain").attributes,o=t("../../plots/cartesian/constants").idRegex,l=t("../../plot_api/plot_template"),s={rows:{valType:"integer",min:1,editType:"plot"},roworder:{valType:"enumerated",values:["top to bottom","bottom to top"],dflt:"top to bottom",editType:"plot"},columns:{valType:"integer",min:1,editType:"plot"},subplots:{valType:"info_array",freeLength:!0,dimensions:2,items:{valType:"enumerated",values:[a("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[o.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[o.y.toString(),""],editType:"plot"},editType:"plot"},pattern:{valType:"enumerated",values:["independent","coupled"],dflt:"coupled",editType:"plot"},xgap:{valType:"number",min:0,max:1,editType:"plot"},ygap:{valType:"number",min:0,max:1,editType:"plot"},domain:i({name:"grid",editType:"plot",noGridCell:!0},{}),xside:{valType:"enumerated",values:["bottom","bottom plot","top plot","top"],dflt:"bottom plot",editType:"plot"},yside:{valType:"enumerated",values:["left","left plot","right plot","right"],dflt:"left plot",editType:"plot"},editType:"plot"};function c(t,e,r){var n=e[r+"axes"],a=Object.keys((t._splomAxes||{})[r]||{});return Array.isArray(n)?n:a.length?a:void 0}function u(t,e,r,n,a,i){var o=e(t+"gap",r),l=e("domain."+t);e(t+"side",n);for(var s=new Array(a),c=l[0],u=(l[1]-c)/(a-o),f=u*(1-o),d=0;d<a;d++){var p=c+u*d;s[i?a-1-d:d]=[p,p+f]}return s}function f(t,e,r,n,a){var i,o=new Array(r);function l(t,r){-1!==e.indexOf(r)&&void 0===n[r]?(o[t]=r,n[r]=t):o[t]=""}if(Array.isArray(t))for(i=0;i<r;i++)l(i,t[i]);else for(l(0,a),i=1;i<r;i++)l(i,a+(i+1));return o}e.exports={moduleType:"component",name:"grid",schema:{layout:{grid:s}},layoutAttributes:s,sizeDefaults:function(t,e){var r=t.grid||{},a=c(e,r,"x"),i=c(e,r,"y");if(t.grid||a||i){var o,f,d=Array.isArray(r.subplots)&&Array.isArray(r.subplots[0]),p=Array.isArray(a),h=Array.isArray(i),g=p&&a!==r.xaxes&&h&&i!==r.yaxes;d?(o=r.subplots.length,f=r.subplots[0].length):(h&&(o=i.length),p&&(f=a.length));var y=l.newContainer(e,"grid"),v=M("rows",o),m=M("columns",f);if(v*m>1){d||p||h||"independent"===M("pattern")&&(d=!0),y._hasSubplotGrid=d;var x,b,_="top to bottom"===M("roworder"),w=d?.2:.1,k=d?.3:.1;g&&e._splomGridDflt&&(x=e._splomGridDflt.xside,b=e._splomGridDflt.yside),y._domains={x:u("x",M,w,x,m),y:u("y",M,k,b,v,_)}}else delete e.grid}function M(t,e){return n.coerce(r,y,s,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,a,i,o,l,s,u,d=t.grid||{},p=e._subplots,h=r._hasSubplotGrid,g=r.rows,y=r.columns,v="independent"===r.pattern,m=r._axisMap={};if(h){var x=d.subplots||[];s=r.subplots=new Array(g);var b=1;for(n=0;n<g;n++){var _=s[n]=new Array(y),w=x[n]||[];for(a=0;a<y;a++)if(v?(l=1===b?"xy":"x"+b+"y"+b,b++):l=w[a],_[a]="",-1!==p.cartesian.indexOf(l)){if(u=l.indexOf("y"),i=l.slice(0,u),o=l.slice(u),void 0!==m[i]&&m[i]!==a||void 0!==m[o]&&m[o]!==n)continue;_[a]=l,m[i]=a,m[o]=n}}}else{var k=c(e,d,"x"),M=c(e,d,"y");r.xaxes=f(k,p.xaxis,y,m,"x"),r.yaxes=f(M,p.yaxis,g,m,"y")}var T=r._anchors={},A="top to bottom"===r.roworder;for(var L in m){var C,S,O,P=L.charAt(0),D=r[P+"side"];if(D.length<8)T[L]="free";else if("x"===P){if("t"===D.charAt(0)===A?(C=0,S=1,O=g):(C=g-1,S=-1,O=-1),h){var z=m[L];for(n=C;n!==O;n+=S)if((l=s[n][z])&&(u=l.indexOf("y"),l.slice(0,u)===L)){T[L]=l.slice(u);break}}else for(n=C;n!==O;n+=S)if(o=r.yaxes[n],-1!==p.cartesian.indexOf(L+o)){T[L]=o;break}}else if("l"===D.charAt(0)?(C=0,S=1,O=y):(C=y-1,S=-1,O=-1),h){var E=m[L];for(n=C;n!==O;n+=S)if((l=s[E][n])&&(u=l.indexOf("y"),l.slice(u)===L)){T[L]=l.slice(0,u);break}}else for(n=C;n!==O;n+=S)if(i=r.xaxes[n],-1!==p.cartesian.indexOf(i+L)){T[L]=i;break}}}}}},{"../../lib":163,"../../lib/regex":178,"../../plot_api/plot_template":197,"../../plots/cartesian/constants":212,"../../plots/domain":232}],92:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants"),a=t("../../plot_api/plot_template").templatedArray;e.exports=a("image",{visible:{valType:"boolean",dflt:!0,editType:"arraydraw"},source:{valType:"string",editType:"arraydraw"},layer:{valType:"enumerated",values:["below","above"],dflt:"above",editType:"arraydraw"},sizex:{valType:"number",dflt:0,editType:"arraydraw"},sizey:{valType:"number",dflt:0,editType:"arraydraw"},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain",editType:"arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},x:{valType:"any",dflt:0,editType:"arraydraw"},y:{valType:"any",dflt:0,editType:"arraydraw"},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left",editType:"arraydraw"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top",editType:"arraydraw"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper",editType:"arraydraw"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper",editType:"arraydraw"},editType:"arraydraw"})},{"../../plot_api/plot_template":197,"../../plots/cartesian/constants":212}],93:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib/to_log_range");e.exports=function(t,e,r,i){e=e||{};var o="log"===r&&"linear"===e.type,l="linear"===r&&"log"===e.type;if(o||l)for(var s,c,u=t._fullLayout.images,f=e._id.charAt(0),d=0;d<u.length;d++)if(c="images["+d+"].",(s=u[d])[f+"ref"]===e._id){var p=s[f],h=s["size"+f],g=null,y=null;if(o){g=a(p,e.range);var v=h/Math.pow(10,g)/2;y=2*Math.log(v+Math.sqrt(1+v*v))/Math.LN10}else y=(g=Math.pow(10,p))*(Math.pow(10,h/2)-Math.pow(10,-h/2));n(g)?n(y)||(y=null):(g=null,y=null),i(c+f,g),i(c+"size"+f,y)}}},{"../../lib/to_log_range":186,"fast-isnumeric":13}],94:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("./attributes");function l(t,e,r){function i(r,a){return n.coerce(t,e,o,r,a)}var l=i("source");if(!i("visible",!!l))return e;i("layer"),i("xanchor"),i("yanchor"),i("sizex"),i("sizey"),i("sizing"),i("opacity");for(var s={_fullLayout:r},c=["x","y"],u=0;u<2;u++){var f=c[u],d=a.coerceRef(t,e,s,f,"paper");a.coercePosition(e,s,i,d,f,0)}return e}e.exports=function(t,e){i(t,e,{name:"images",handleItemDefaults:l})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"./attributes":92}],95:[function(t,e,r){"use strict";var n=t("d3"),a=t("../drawing"),i=t("../../plots/cartesian/axes"),o=t("../../constants/xmlns_namespaces");e.exports=function(t){var e,r,l=t._fullLayout,s=[],c={},u=[];for(r=0;r<l.images.length;r++){var f=l.images[r];if(f.visible)if("below"===f.layer&&"paper"!==f.xref&&"paper"!==f.yref){e=f.xref+f.yref;var d=l._plots[e];if(!d){u.push(f);continue}d.mainplot&&(e=d.mainplot.id),c[e]||(c[e]=[]),c[e].push(f)}else"above"===f.layer?s.push(f):u.push(f)}var p={x:{left:{sizing:"xMin",offset:0},center:{sizing:"xMid",offset:-.5},right:{sizing:"xMax",offset:-1}},y:{top:{sizing:"YMin",offset:0},middle:{sizing:"YMid",offset:-.5},bottom:{sizing:"YMax",offset:-1}}};function h(e){var r=n.select(this);if(!this.img||this.img.src!==e.source){r.attr("xmlns",o.svg);var a=new Promise(function(t){var n=new Image;function a(){r.remove(),t()}this.img=n,n.setAttribute("crossOrigin","anonymous"),n.onerror=a,n.onload=function(){var e=document.createElement("canvas");e.width=this.width,e.height=this.height,e.getContext("2d").drawImage(this,0,0);var n=e.toDataURL("image/png");r.attr("xlink:href",n),t()},r.on("error",a),n.src=e.source}.bind(this));t._promises.push(a)}}function g(e){var r=n.select(this),o=i.getFromId(t,e.xref),s=i.getFromId(t,e.yref),c=l._size,u=o?Math.abs(o.l2p(e.sizex)-o.l2p(0)):e.sizex*c.w,f=s?Math.abs(s.l2p(e.sizey)-s.l2p(0)):e.sizey*c.h,d=u*p.x[e.xanchor].offset,h=f*p.y[e.yanchor].offset,g=p.x[e.xanchor].sizing+p.y[e.yanchor].sizing,y=(o?o.r2p(e.x)+o._offset:e.x*c.w+c.l)+d,v=(s?s.r2p(e.y)+s._offset:c.h-e.y*c.h+c.t)+h;switch(e.sizing){case"fill":g+=" slice";break;case"stretch":g="none"}r.attr({x:y,y:v,width:u,height:f,preserveAspectRatio:g,opacity:e.opacity});var m=(o?o._id:"")+(s?s._id:"");r.call(a.setClipUrl,m?"clip"+l._uid+m:null)}var y=l._imageLowerLayer.selectAll("image").data(u),v=l._imageUpperLayer.selectAll("image").data(s);y.enter().append("image"),v.enter().append("image"),y.exit().remove(),v.exit().remove(),y.each(function(t){h.bind(this)(t),g.bind(this)(t)}),v.each(function(t){h.bind(this)(t),g.bind(this)(t)});var m=Object.keys(l._plots);for(r=0;r<m.length;r++){e=m[r];var x=l._plots[e];if(x.imagelayer){var b=x.imagelayer.selectAll("image").data(c[e]||[]);b.enter().append("image"),b.exit().remove(),b.each(function(t){h.bind(this)(t),g.bind(this)(t)})}}}},{"../../constants/xmlns_namespaces":147,"../../plots/cartesian/axes":207,"../drawing":70,d3:10}],96:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"images",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("images"),draw:t("./draw"),convertCoords:t("./convert_coords")}},{"../../plots/cartesian/include_components":217,"./attributes":92,"./convert_coords":93,"./defaults":94,"./draw":95}],97:[function(t,e,r){"use strict";r.isRightAnchor=function(t){return"right"===t.xanchor||"auto"===t.xanchor&&t.x>=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],98:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../color/attributes");e.exports={bgcolor:{valType:"color",editType:"legend"},bordercolor:{valType:"color",dflt:a.defaultLine,editType:"legend"},borderwidth:{valType:"number",min:0,dflt:0,editType:"legend"},font:n({editType:"legend"}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v",editType:"legend"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"],editType:"legend"},tracegroupgap:{valType:"number",min:0,dflt:10,editType:"legend"},x:{valType:"number",min:-2,max:3,dflt:1.02,editType:"legend"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"legend"},y:{valType:"number",min:-2,max:3,dflt:1,editType:"legend"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"legend"},editType:"legend"}},{"../../plots/font_attributes":233,"../color/attributes":44}],99:[function(t,e,r){"use strict";e.exports={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],100:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../plot_api/plot_template"),o=t("./attributes"),l=t("../../plots/layout_attributes"),s=t("./helpers");e.exports=function(t,e,r){for(var c,u,f,d,p=t.legend||{},h=0,g="normal",y=0;y<r.length;y++){var v=r[y];s.legendGetsTrace(v)&&(h++,n.traceIs(v,"pie")&&h++),(n.traceIs(v,"bar")&&"stack"===e.barmode||-1!==["tonextx","tonexty"].indexOf(v.fill))&&(g=s.isGrouped({traceorder:g})?"grouped+reversed":"reversed"),void 0!==v.legendgroup&&""!==v.legendgroup&&(g=s.isReversed({traceorder:g})?"reversed+grouped":"grouped")}if(!1!==a.coerce(t,e,l,"showlegend",h>1)){var m=i.newContainer(e,"legend");if(b("bgcolor",e.paper_bgcolor),b("bordercolor"),b("borderwidth"),a.coerceFont(b,"font",e.font),b("orientation"),"h"===m.orientation){var x=t.xaxis;x&&x.rangeslider&&x.rangeslider.visible?(c=0,f="left",u=1.1,d="bottom"):(c=0,f="left",u=-.1,d="top")}b("traceorder",g),s.isGrouped(e.legend)&&b("tracegroupgap"),b("x",c),b("xanchor",f),b("y",u),b("yanchor",d),a.noneOrAll(p,m,["x","y"])}function b(t,e){return a.coerce(p,m,o,t,e)}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/layout_attributes":237,"../../registry":247,"./attributes":98,"./helpers":104}],101:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../lib/events"),s=t("../dragelement"),c=t("../drawing"),u=t("../color"),f=t("../../lib/svg_text_utils"),d=t("./handle_click"),p=t("./constants"),h=t("../../constants/interactions"),g=t("../../constants/alignment"),y=g.LINE_SPACING,v=g.FROM_TL,m=g.FROM_BR,x=t("./get_legend_data"),b=t("./style"),_=t("./helpers"),w=t("./anchor_utils"),k=h.DBLCLICKDELAY;function M(t,e,r,n,a){var i=r.data()[0][0].trace,o={event:a,node:r.node(),curveNumber:i.index,expandedIndex:i._expandedIndex,data:t.data,layout:t.layout,frames:t._transitionData._frames,config:t._context,fullData:t._fullData,fullLayout:t._fullLayout};if(i._group&&(o.group=i._group),"pie"===i.type&&(o.label=r.datum()[0].label),!1!==l.triggerHandler(t,"plotly_legendclick",o))if(1===n)e._clickTimeout=setTimeout(function(){d(r,t,n)},k);else if(2===n){e._clickTimeout&&clearTimeout(e._clickTimeout),t._legendMouseDownTime=0,!1!==l.triggerHandler(t,"plotly_legenddoubleclick",o)&&d(r,t,n)}}function T(t,e,r){var n=t.data()[0][0],i=e._fullLayout,l=n.trace,s=o.traceIs(l,"pie"),u=l.index,d=s?n.label:l.name,p=e._context.edits.legendText&&!s,h=a.ensureSingle(t,"text","legendtext");function g(r){f.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,a,i=t.select("g[class*=math-group]"),o=i.node(),l=e._fullLayout.legend.font.size*y;if(o){var s=c.bBox(o);n=s.height,a=s.width,c.setTranslate(i,0,n/4)}else{var u=t.select(".legendtext"),d=f.lineCount(u),p=u.node();n=l*d,a=p?c.bBox(p).width:0;var h=l*(.3+(1-d)/2);f.positionText(u,40,h)}n=Math.max(n,16)+3,r.height=n,r.width=a}(t,e)})}h.attr("text-anchor","start").classed("user-select-none",!0).call(c.font,i.legend.font).text(p?A(d,r):d),p?h.call(f.makeEditable,{gd:e,text:d}).call(g).on("edit",function(t){this.text(A(t,r)).call(g);var i=n.trace._fullInput||{},l={};if(o.hasTransform(i,"groupby")){var s=o.getTransformIndices(i,"groupby"),c=s[s.length-1],f=a.keyedContainer(i,"transforms["+c+"].styles","target","value.name");f.set(n.trace._group,t),l=f.constructUpdate()}else l.name=t;return o.call("restyle",e,l,u)}):g(h)}function A(t,e){var r=Math.max(4,e);if(t&&t.trim().length>=r/2)return t;for(var n=r-(t=t||"").length;n>0;n--)t+=" ";return t}function L(t,e){var r,i=1,o=a.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call(u.fill,"rgba(0,0,0,0)")});o.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTime<k?i+=1:(i=1,e._legendMouseDownTime=r)}),o.on("mouseup",function(){if(!e._dragged&&!e._editing){var r=e._fullLayout.legend;(new Date).getTime()-e._legendMouseDownTime>k&&(i=Math.max(i-1,1)),M(e,r,t,i,n.event)}})}function C(t,e,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=_.isGrouped(i),s=0;if(i._width=0,i._height=0,_.isVertical(i))l&&e.each(function(t,e){c.setTranslate(this,0,e*i.tracegroupgap)}),r.each(function(t){var e=t[0],r=e.height,n=e.width;c.setTranslate(this,o,5+o+i._height+r/2),i._height+=r,i._width=Math.max(i._width,n)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var u=[i._width],f=e.data(),d=0,p=f.length;d<p;d++){var h=f[d].map(function(t){return t[0].width}),g=40+Math.max.apply(null,h);i._width+=i.tracegroupgap+g,u.push(i._width)}e.each(function(t,e){c.setTranslate(this,u[e],0)}),e.each(function(){var t=n.select(this).selectAll("g.traces"),e=0;t.each(function(t){var r=t[0].height;c.setTranslate(this,0,5+o+e+r/2),e+=r}),i._height=Math.max(i._height,e)}),i._height+=10+2*o,i._width+=2*o}else{var y,v=0,m=0,x=0,b=0,w=0,k=i.tracegroupgap||5;r.each(function(t){x=Math.max(40+t[0].width,x),w+=40+t[0].width+k}),y=a.width-(a.margin.r+a.margin.l)>o+w-k,r.each(function(t){var e=t[0],r=y?40+t[0].width:x;o+b+k+r>a.width-(a.margin.r+a.margin.l)&&(b=0,v+=m,i._height=i._height+m,m=0),c.setTranslate(this,o+b,5+o+e.height/2+v),i._width+=k+r,i._height=Math.max(i._height,e.height),b+=k+r,m=Math.max(e.height,m)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(e){var r=e[0],a=n.select(this).select(".legendtoggle");c.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function S(t){var e=t._fullLayout.legend,r="left";w.isRightAnchor(e)?r="right":w.isCenterAnchor(e)&&(r="center");var n="top";w.isBottomAnchor(e)?n="bottom":w.isMiddleAnchor(e)&&(n="middle"),i.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*v[r],r:e._width*m[r],b:e._height*m[n],t:e._height*v[n]})}e.exports=function(t){var e=t._fullLayout,r="legend"+e._uid;if(e._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var l=e.legend,f=e.showlegend&&x(t.calcdata,l),d=e.hiddenlabels||[];if(!e.showlegend||!f.length)return e._infolayer.selectAll(".legend").remove(),e._topdefs.select("#"+r).remove(),void i.autoMargin(t,"legend");for(var h=0,g=0;g<f.length;g++)for(var y=0;y<f[g].length;y++){var _=f[g][y][0],k=_.trace,A=o.traceIs(k,"pie")?_.label:k.name;h=Math.max(h,A&&A.length||0)}var O=!1,P=a.ensureSingle(e._infolayer,"g","legend",function(t){t.attr("pointer-events","all"),O=!0}),D=a.ensureSingleById(e._topdefs,"clipPath",r,function(t){t.append("rect")}),z=a.ensureSingle(P,"rect","bg",function(t){t.attr("shape-rendering","crispEdges")});z.call(u.stroke,l.bordercolor).call(u.fill,l.bgcolor).style("stroke-width",l.borderwidth+"px");var E=a.ensureSingle(P,"g","scrollbox"),I=a.ensureSingle(P,"rect","scrollbar",function(t){t.attr({rx:20,ry:3,width:0,height:0}).call(u.fill,"#808BA4")}),N=E.selectAll("g.groups").data(f);N.enter().append("g").attr("class","groups"),N.exit().remove();var R=N.selectAll("g.traces").data(a.identity);R.enter().append("g").attr("class","traces"),R.exit().remove(),R.call(b,t).style("opacity",function(t){var e=t[0].trace;return o.traceIs(e,"pie")?-1!==d.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){n.select(this).call(T,t,h).call(L,t)}),O&&(C(t,N,R),S(t));var F=e.width,j=e.height;C(t,N,R),l._height>j?function(t){var e=t._fullLayout.legend,r="left";w.isRightAnchor(e)?r="right":w.isCenterAnchor(e)&&(r="center");i.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*v[r],r:e._width*m[r],b:0,t:0})}(t):S(t);var B=e._size,H=B.l+B.w*l.x,q=B.t+B.h*(1-l.y);w.isRightAnchor(l)?H-=l._width:w.isCenterAnchor(l)&&(H-=l._width/2),w.isBottomAnchor(l)?q-=l._height:w.isMiddleAnchor(l)&&(q-=l._height/2);var V=l._width,U=B.w;V>U?(H=B.l,V=U):(H+V>F&&(H=F-V),H<0&&(H=0),V=Math.min(F-H,l._width));var G,Y,X,Z,W=l._height,Q=B.h;if(W>Q?(q=B.t,W=Q):(q+W>j&&(q=j-W),q<0&&(q=0),W=Math.min(j-q,l._height)),c.setTranslate(P,H,q),I.on(".drag",null),P.on("wheel",null),l._height<=W||t._context.staticPlot)z.attr({width:V-l.borderwidth,height:W-l.borderwidth,x:l.borderwidth/2,y:l.borderwidth/2}),c.setTranslate(E,0,0),D.select("rect").attr({width:V-2*l.borderwidth,height:W-2*l.borderwidth,x:l.borderwidth,y:l.borderwidth}),c.setClipUrl(E,r),c.setRect(I,0,0,0,0),delete l._scrollY;else{var J,$,K=Math.max(p.scrollBarMinHeight,W*W/l._height),tt=W-K-2*p.scrollBarMargin,et=l._height-W,rt=tt/et,nt=Math.min(l._scrollY||0,et);z.attr({width:V-2*l.borderwidth+p.scrollBarWidth+p.scrollBarMargin,height:W-l.borderwidth,x:l.borderwidth/2,y:l.borderwidth/2}),D.select("rect").attr({width:V-2*l.borderwidth+p.scrollBarWidth+p.scrollBarMargin,height:W-2*l.borderwidth,x:l.borderwidth,y:l.borderwidth+nt}),c.setClipUrl(E,r),it(nt,K,rt),P.on("wheel",function(){it(nt=a.constrain(l._scrollY+n.event.deltaY/tt*et,0,et),K,rt),0!==nt&&nt!==et&&n.event.preventDefault()});var at=n.behavior.drag().on("dragstart",function(){J=n.event.sourceEvent.clientY,$=nt}).on("drag",function(){var t=n.event.sourceEvent;2===t.buttons||t.ctrlKey||it(nt=a.constrain((t.clientY-J)/rt+$,0,et),K,rt)});I.call(at)}if(t._context.edits.legendPosition)P.classed("cursor-move",!0),s.init({element:P.node(),gd:t,prepFn:function(){var t=c.getTranslate(P);X=t.x,Z=t.y},moveFn:function(t,e){var r=X+t,n=Z+e;c.setTranslate(P,r,n),G=s.align(r,0,B.l,B.l+B.w,l.xanchor),Y=s.align(n,0,B.t+B.h,B.t,l.yanchor)},doneFn:function(){void 0!==G&&void 0!==Y&&o.call("relayout",t,{"legend.x":G,"legend.y":Y})},clickFn:function(r,n){var a=e._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});a.size()>0&&M(t,P,a,r,n)}})}function it(e,r,n){l._scrollY=t._fullLayout.legend._scrollY=e,c.setTranslate(E,0,-e),c.setRect(I,V,p.scrollBarMargin+e*n,p.scrollBarWidth,r),D.select("rect").attr({y:l.borderwidth+e})}}},{"../../constants/alignment":143,"../../constants/interactions":144,"../../lib":163,"../../lib/events":156,"../../lib/svg_text_utils":184,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"./anchor_utils":97,"./constants":99,"./get_legend_data":102,"./handle_click":103,"./helpers":104,"./style":106,d3:10}],102:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./helpers");e.exports=function(t,e){var r,i,o={},l=[],s=!1,c={},u=0;function f(t,r){if(""!==t&&a.isGrouped(e))-1===l.indexOf(t)?(l.push(t),s=!0,o[t]=[[r]]):o[t].push([r]);else{var n="~~i"+u;l.push(n),o[n]=[[r]],u++}}for(r=0;r<t.length;r++){var d=t[r],p=d[0],h=p.trace,g=h.legendgroup;if(a.legendGetsTrace(h)&&h.showlegend)if(n.traceIs(h,"pie"))for(c[g]||(c[g]={}),i=0;i<d.length;i++){var y=d[i].label;c[g][y]||(f(g,{label:y,color:d[i].color,i:d[i].i,trace:h}),c[g][y]=!0)}else f(g,p)}if(!l.length)return[];var v,m,x=l.length;if(s&&a.isGrouped(e))for(m=new Array(x),r=0;r<x;r++)v=o[l[r]],m[r]=a.isReversed(e)?v.reverse():v;else{for(m=[new Array(x)],r=0;r<x;r++)v=o[l[r]][0],m[0][a.isReversed(e)?x-r-1:r]=v;x=1}return e._lgroupsLength=x,m}},{"../../registry":247,"./helpers":104}],103:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry"),i=!0;e.exports=function(t,e,r){if(!e._dragged&&!e._editing){var o,l,s,c,u,f=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],d=t.data()[0][0],p=e._fullData,h=d.trace,g=h.legendgroup,y={},v=[],m=[],x=[];if(1===r&&i&&e.data&&e._context.showTips?(n.notifier(n._(e,"Double-click on legend to isolate one trace"),"long"),i=!1):i=!1,a.traceIs(h,"pie")){var b=d.label,_=f.indexOf(b);1===r?-1===_?f.push(b):f.splice(_,1):2===r&&(f=[],e.calcdata[0].forEach(function(t){b!==t.label&&f.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===f.length&&-1===_&&(f=[])),a.call("relayout",e,"hiddenlabels",f)}else{var w,k=g&&g.length,M=[];if(k)for(o=0;o<p.length;o++)(w=p[o]).visible&&w.legendgroup===g&&M.push(o);if(1===r){var T;switch(h.visible){case!0:T="legendonly";break;case!1:T=!1;break;case"legendonly":T=!0}if(k)for(o=0;o<p.length;o++)!1!==p[o].visible&&p[o].legendgroup===g&&D(p[o],T);else D(h,T)}else if(2===r){var A,L,C=!0;for(o=0;o<p.length;o++)if(!(p[o]===h)&&!(A=k&&p[o].legendgroup===g)&&!0===p[o].visible&&!a.traceIs(p[o],"notLegendIsolatable")){C=!1;break}for(o=0;o<p.length;o++)if(!1!==p[o].visible&&!a.traceIs(p[o],"notLegendIsolatable"))switch(h.visible){case"legendonly":D(p[o],!0);break;case!0:L=!!C||"legendonly",A=p[o]===h||k&&p[o].legendgroup===g,D(p[o],!!A||L)}}for(o=0;o<m.length;o++)if(s=m[o]){var S=s.constructUpdate(),O=Object.keys(S);for(l=0;l<O.length;l++)c=O[l],(y[c]=y[c]||[])[x[o]]=S[c]}for(u=Object.keys(y),o=0;o<u.length;o++)for(c=u[o],l=0;l<v.length;l++)y[c].hasOwnProperty(l)||(y[c][l]=void 0);a.call("restyle",e,y,v)}}function P(t,e,r){var n=v.indexOf(t),a=y[e];return a||(a=y[e]=[]),-1===v.indexOf(t)&&(v.push(t),n=v.length-1),a[n]=r,n}function D(t,e){var r=t._fullInput;if(a.hasTransform(r,"groupby")){var i=m[r.index];if(!i){var o=a.getTransformIndices(r,"groupby"),l=o[o.length-1];i=n.keyedContainer(r,"transforms["+l+"].styles","target","value.visible"),m[r.index]=i}var s=i.get(t._group);void 0===s&&(s=!0),!1!==s&&i.set(t._group,e),x[r.index]=P(r.index,"visible",!1!==r.visible)}else{var c=!1!==r.visible&&e;P(r.index,"visible",c)}}}},{"../../lib":163,"../../registry":247}],104:[function(t,e,r){"use strict";r.legendGetsTrace=function(t){return t.visible&&void 0!==t.showlegend},r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{}],105:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"legend",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw"),style:t("./style")}},{"./attributes":98,"./defaults":100,"./draw":101,"./style":106}],106:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../lib"),o=t("../drawing"),l=t("../color"),s=t("../../traces/scatter/subtypes"),c=t("../../traces/pie/style_one");e.exports=function(t,e){t.each(function(t){var e=n.select(this),r=i.ensureSingle(e,"g","layers");r.style("opacity",t[0].trace.opacity),r.selectAll("g.legendfill").data([t]).enter().append("g").classed("legendfill",!0),r.selectAll("g.legendlines").data([t]).enter().append("g").classed("legendlines",!0);var a=r.selectAll("g.legendsymbols").data([t]);a.enter().append("g").classed("legendsymbols",!0),a.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(function(t){var e=t[0].trace,r=e.marker||{},i=r.line||{},o=n.select(this).select("g.legendpoints").selectAll("path.legendbar").data(a.traceIs(e,"bar")?[t]:[]);o.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),o.exit().remove(),o.each(function(t){var e=n.select(this),a=t[0],o=(a.mlw+1||i.width+1)-1;e.style("stroke-width",o+"px").call(l.fill,a.mc||r.color),o&&e.call(l.stroke,a.mlc||i.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendbox").data(a.traceIs(e,"box-violin")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(){var t=e.line.width,r=n.select(this);r.style("stroke-width",t+"px").call(l.fill,e.fillcolor),t&&l.stroke(r,e.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendpie").data(a.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(c,t[0],e)}).each(function(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,a=s.hasLines(e),i=e.contours;i&&"constraint"===i.type&&(a=i.showlines,r="="!==i._operation);var l=n.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);l.enter().append("path").classed("js-fill",!0),l.exit().remove(),l.attr("d","M5,0h30v6h-30z").call(o.fillGroupStyle);var c=n.select(this).select(".legendlines").selectAll("path").data(a?[t]:[]);c.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),c.exit().remove(),c.call(o.lineGroupStyle)}).each(function(t){var r,a,l=t[0],c=l.trace,u=s.hasMarkers(c),f=s.hasText(c),d=s.hasLines(c);function p(t,e,r){var n=i.nestedProperty(c,t).get(),a=Array.isArray(n)&&e?e(n):n;if(r){if(a<r[0])return r[0];if(a>r[1])return r[1]}return a}function h(t){return t[0]}if(u||f||d){var g={},y={};u&&(g.mc=p("marker.color",h),g.mx=p("marker.symbol",h),g.mo=p("marker.opacity",i.mean,[.2,1]),g.ms=p("marker.size",i.mean,[2,16]),g.mlc=p("marker.line.color",h),g.mlw=p("marker.line.width",i.mean,[0,5]),y.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),d&&(y.line={width:p("line.width",h,[0,10])}),f&&(g.tx="Aa",g.tp=p("textposition",h),g.ts=10,g.tc=p("textfont.color",h),g.tf=p("textfont.family",h)),r=[i.minExtend(l,g)],(a=i.minExtend(c,y)).selectedpoints=null}var v=n.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(u?r:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(o.pointStyle,a,e),u&&(r[0].mrc=3);var x=v.selectAll("g.pointtext").data(f?r:[]);x.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),x.exit().remove(),x.selectAll("text").call(o.textPointStyle,a,e)}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=e[r?"increasing":"decreasing"],i=a.line.width,o=n.select(this);o.style("stroke-width",i+"px").call(l.fill,a.fillcolor),i&&l.stroke(o,a.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=e[r?"increasing":"decreasing"],i=a.line.width,s=n.select(this);s.style("fill","none").call(o.dashLine,a.line.dash,i),i&&l.stroke(s,a.line.color)})})}},{"../../lib":163,"../../registry":247,"../../traces/pie/style_one":312,"../../traces/scatter/subtypes":336,"../color":45,"../drawing":70,d3:10}],107:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../plots/plots"),i=t("../../plots/cartesian/axis_ids"),o=t("../../lib"),l=t("../../../build/ploticon"),s=o._,c=e.exports={};function u(t,e){var r,a,o=e.currentTarget,l=o.getAttribute("data-attr"),s=o.getAttribute("data-val")||!0,c=t._fullLayout,u={},f=i.list(t,null,!0),d="on";if("zoom"===l){var p,h="in"===s?.5:2,g=(1+h)/2,y=(1-h)/2;for(a=0;a<f.length;a++)if(!(r=f[a]).fixedrange)if(p=r._name,"auto"===s)u[p+".autorange"]=!0;else if("reset"===s){if(void 0===r._rangeInitial)u[p+".autorange"]=!0;else{var v=r._rangeInitial.slice();u[p+".range[0]"]=v[0],u[p+".range[1]"]=v[1]}void 0!==r._showSpikeInitial&&(u[p+".showspikes"]=r._showSpikeInitial,"on"!==d||r._showSpikeInitial||(d="off"))}else{var m=[r.r2l(r.range[0]),r.r2l(r.range[1])],x=[g*m[0]+y*m[1],g*m[1]+y*m[0]];u[p+".range[0]"]=r.l2r(x[0]),u[p+".range[1]"]=r.l2r(x[1])}c._cartesianSpikesEnabled=d}else{if("hovermode"!==l||"x"!==s&&"y"!==s){if("hovermode"===l&&"closest"===s){for(a=0;a<f.length;a++)r=f[a],"on"!==d||r.showspikes||(d="off");c._cartesianSpikesEnabled=d}}else s=c._isHoriz?"y":"x",o.setAttribute("data-val",s);u[l]=s}n.call("relayout",t,u)}function f(t,e){for(var r=e.currentTarget,a=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,o=t._fullLayout._subplots.gl3d,l={},s=a.split("."),c=0;c<o.length;c++)l[o[c]+"."+s[1]]=i;var u="pan"===i?i:"zoom";l.dragmode=u,n.call("relayout",t,l)}function d(t,e){for(var r=e.currentTarget.getAttribute("data-attr"),a=t._fullLayout,i=a._subplots.gl3d,l={},s=0;s<i.length;s++){var c=i[s],u=c+".camera",f=a[c]._scene;"resetDefault"===r?l[u]=null:"resetLastSave"===r&&(l[u]=o.extendDeep({},f.cameraInitial))}n.call("relayout",t,l)}function p(t,e){var r=e.currentTarget,a=r._previousVal||!1,i=t.layout,l=t._fullLayout,s=l._subplots.gl3d,c=["xaxis","yaxis","zaxis"],u=["showspikes","spikesides","spikethickness","spikecolor"],f={},d={},p={};if(a)p=o.extendDeep(i,a),r._previousVal=null;else{p={"allaxes.showspikes":!1};for(var h=0;h<s.length;h++){var g=s[h],y=l[g],v=f[g]={};v.hovermode=y.hovermode,p[g+".hovermode"]=!1;for(var m=0;m<3;m++){var x=c[m];d=v[x]={};for(var b=0;b<u.length;b++){var _=u[b];d[_]=y[x][_]}}}r._previousVal=o.extendDeep({},f)}n.call("relayout",t,p)}function h(t,e){for(var r=e.currentTarget,a=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,o=t._fullLayout,l=o._subplots.geo,s=0;s<l.length;s++){var c=l[s],u=o[c];if("zoom"===a){var f=u.projection.scale,d="in"===i?2*f:.5*f;n.call("relayout",t,c+".projection.scale",d)}else"reset"===a&&y(t,"geo")}}function g(t){var e,r=t._fullLayout;e=r._has("cartesian")?r._isHoriz?"y":"x":"closest";var a=!t._fullLayout.hovermode&&e;n.call("relayout",t,"hovermode",a)}function y(t,e){for(var r=t._fullLayout,a=r._subplots[e],i={},o=0;o<a.length;o++)for(var l=a[o],s=r[l]._subplot.viewInitial,c=Object.keys(s),u=0;u<c.length;u++){var f=c[u];i[l+"."+f]=s[f]}n.call("relayout",t,i)}c.toImage={name:"toImage",title:function(t){var e=(t._context.toImageButtonOptions||{}).format||"png";return s(t,"png"===e?"Download plot as a png":"Download plot")},icon:l.camera,click:function(t){var e=t._context.toImageButtonOptions,r={format:e.format||"png"};o.notifier(s(t,"Taking snapshot - this may take a few seconds"),"long"),"svg"!==r.format&&o.isIE()&&(o.notifier(s(t,"IE only supports svg. Changing format to svg."),"long"),r.format="svg"),["filename","width","height","scale"].forEach(function(t){e[t]&&(r[t]=e[t])}),n.call("downloadImage",t,r).then(function(e){o.notifier(s(t,"Snapshot succeeded")+" - "+e,"long")}).catch(function(){o.notifier(s(t,"Sorry, there was a problem downloading your snapshot!"),"long")})}},c.sendDataToCloud={name:"sendDataToCloud",title:function(t){return s(t,"Edit in Chart Studio")},icon:l.disk,click:function(t){a.sendDataToCloud(t)}},c.zoom2d={name:"zoom2d",title:function(t){return s(t,"Zoom")},attr:"dragmode",val:"zoom",icon:l.zoombox,click:u},c.pan2d={name:"pan2d",title:function(t){return s(t,"Pan")},attr:"dragmode",val:"pan",icon:l.pan,click:u},c.select2d={name:"select2d",title:function(t){return s(t,"Box Select")},attr:"dragmode",val:"select",icon:l.selectbox,click:u},c.lasso2d={name:"lasso2d",title:function(t){return s(t,"Lasso Select")},attr:"dragmode",val:"lasso",icon:l.lasso,click:u},c.zoomIn2d={name:"zoomIn2d",title:function(t){return s(t,"Zoom in")},attr:"zoom",val:"in",icon:l.zoom_plus,click:u},c.zoomOut2d={name:"zoomOut2d",title:function(t){return s(t,"Zoom out")},attr:"zoom",val:"out",icon:l.zoom_minus,click:u},c.autoScale2d={name:"autoScale2d",title:function(t){return s(t,"Autoscale")},attr:"zoom",val:"auto",icon:l.autoscale,click:u},c.resetScale2d={name:"resetScale2d",title:function(t){return s(t,"Reset axes")},attr:"zoom",val:"reset",icon:l.home,click:u},c.hoverClosestCartesian={name:"hoverClosestCartesian",title:function(t){return s(t,"Show closest data on hover")},attr:"hovermode",val:"closest",icon:l.tooltip_basic,gravity:"ne",click:u},c.hoverCompareCartesian={name:"hoverCompareCartesian",title:function(t){return s(t,"Compare data on hover")},attr:"hovermode",val:function(t){return t._fullLayout._isHoriz?"y":"x"},icon:l.tooltip_compare,gravity:"ne",click:u},c.zoom3d={name:"zoom3d",title:function(t){return s(t,"Zoom")},attr:"scene.dragmode",val:"zoom",icon:l.zoombox,click:f},c.pan3d={name:"pan3d",title:function(t){return s(t,"Pan")},attr:"scene.dragmode",val:"pan",icon:l.pan,click:f},c.orbitRotation={name:"orbitRotation",title:function(t){return s(t,"Orbital rotation")},attr:"scene.dragmode",val:"orbit",icon:l["3d_rotate"],click:f},c.tableRotation={name:"tableRotation",title:function(t){return s(t,"Turntable rotation")},attr:"scene.dragmode",val:"turntable",icon:l["z-axis"],click:f},c.resetCameraDefault3d={name:"resetCameraDefault3d",title:function(t){return s(t,"Reset camera to default")},attr:"resetDefault",icon:l.home,click:d},c.resetCameraLastSave3d={name:"resetCameraLastSave3d",title:function(t){return s(t,"Reset camera to last save")},attr:"resetLastSave",icon:l.movie,click:d},c.hoverClosest3d={name:"hoverClosest3d",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:p},c.zoomInGeo={name:"zoomInGeo",title:function(t){return s(t,"Zoom in")},attr:"zoom",val:"in",icon:l.zoom_plus,click:h},c.zoomOutGeo={name:"zoomOutGeo",title:function(t){return s(t,"Zoom out")},attr:"zoom",val:"out",icon:l.zoom_minus,click:h},c.resetGeo={name:"resetGeo",title:function(t){return s(t,"Reset")},attr:"reset",val:null,icon:l.autoscale,click:h},c.hoverClosestGeo={name:"hoverClosestGeo",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:g},c.hoverClosestGl2d={name:"hoverClosestGl2d",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:g},c.hoverClosestPie={name:"hoverClosestPie",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:"closest",icon:l.tooltip_basic,gravity:"ne",click:g},c.toggleHover={name:"toggleHover",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:function(t,e){g(t),p(t,e)}},c.resetViews={name:"resetViews",title:function(t){return s(t,"Reset views")},icon:l.home,click:function(t,e){var r=e.currentTarget;r.setAttribute("data-attr","zoom"),r.setAttribute("data-val","reset"),u(t,e),r.setAttribute("data-attr","resetLastSave"),d(t,e),y(t,"geo"),y(t,"mapbox")}},c.toggleSpikelines={name:"toggleSpikelines",title:function(t){return s(t,"Toggle Spike Lines")},icon:l.spikeline,attr:"_cartesianSpikesEnabled",val:"on",click:function(t){var e=t._fullLayout;e._cartesianSpikesEnabled="on"===e._cartesianSpikesEnabled?"off":"on";var r=function(t){for(var e,r,n=t._fullLayout,a=i.list(t,null,!0),o={},l=0;l<a.length;l++)e=a[l],r=e._name,o[r+".showspikes"]="on"===n._cartesianSpikesEnabled||e._showSpikeInitial;return o}(t);n.call("relayout",t,r)}},c.resetViewMapbox={name:"resetViewMapbox",title:function(t){return s(t,"Reset view")},attr:"reset",icon:l.home,click:function(t){y(t,"mapbox")}}},{"../../../build/ploticon":2,"../../lib":163,"../../plots/cartesian/axis_ids":210,"../../plots/plots":239,"../../registry":247}],108:[function(t,e,r){"use strict";r.manage=t("./manage")},{"./manage":109}],109:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids"),a=t("../../traces/scatter/subtypes"),i=t("../../registry"),o=t("./modebar"),l=t("./buttons");e.exports=function(t){var e=t._fullLayout,r=t._context,s=e._modeBar;if(r.displayModeBar){if(!Array.isArray(r.modeBarButtonsToRemove))throw new Error(["*modeBarButtonsToRemove* configuration options","must be an array."].join(" "));if(!Array.isArray(r.modeBarButtonsToAdd))throw new Error(["*modeBarButtonsToAdd* configuration options","must be an array."].join(" "));var c,u=r.modeBarButtons;c=Array.isArray(u)&&u.length?function(t){for(var e=0;e<t.length;e++)for(var r=t[e],n=0;n<r.length;n++){var a=r[n];if("string"==typeof a){if(void 0===l[a])throw new Error(["*modeBarButtons* configuration options","invalid button name"].join(" "));t[e][n]=l[a]}}return t}(u):function(t,e,r){var o=t._fullLayout,s=t._fullData,c=o._has("cartesian"),u=o._has("gl3d"),f=o._has("geo"),d=o._has("pie"),p=o._has("gl2d"),h=o._has("ternary"),g=o._has("mapbox"),y=o._has("polar"),v=function(t){for(var e=n.list({_fullLayout:t},null,!0),r=0;r<e.length;r++)if(!e[r].fixedrange)return!1;return!0}(o),m=[];function x(t){if(t.length){for(var r=[],n=0;n<t.length;n++){var a=t[n];-1===e.indexOf(a)&&r.push(l[a])}m.push(r)}}x(["toImage","sendDataToCloud"]);var b=[],_=[],w=[],k=[];(c||p||d||h)+f+u+g+y>1?(_=["toggleHover"],w=["resetViews"]):f?(b=["zoomInGeo","zoomOutGeo"],_=["hoverClosestGeo"],w=["resetGeo"]):u?(_=["hoverClosest3d"],w=["resetCameraDefault3d","resetCameraLastSave3d"]):g?(_=["toggleHover"],w=["resetViewMapbox"]):_=p?["hoverClosestGl2d"]:d?["hoverClosestPie"]:["toggleHover"];c&&(_=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]);!c&&!p||v||(b=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==w[0]&&(w=["resetScale2d"]));u?k=["zoom3d","pan3d","orbitRotation","tableRotation"]:(c||p)&&!v||h?k=["zoom2d","pan2d"]:g||f?k=["pan2d"]:y&&(k=["zoom2d"]);(function(t){for(var e=!1,r=0;r<t.length&&!e;r++){var n=t[r];n._module&&n._module.selectPoints&&(i.traceIs(n,"scatter-like")?(a.hasMarkers(n)||a.hasText(n))&&(e=!0):i.traceIs(n,"box-violin")&&"all"!==n.boxpoints&&"all"!==n.points||(e=!0))}return e})(s)&&k.push("select2d","lasso2d");return x(k),x(b.concat(w)),x(_),function(t,e){if(e.length)if(Array.isArray(e[0]))for(var r=0;r<e.length;r++)t.push(e[r]);else t.push(e);return t}(m,r)}(t,r.modeBarButtonsToRemove,r.modeBarButtonsToAdd),s?s.update(t,c):e._modeBar=o(t,c)}else s&&(s.destroy(),delete e._modeBar)}},{"../../plots/cartesian/axis_ids":210,"../../registry":247,"../../traces/scatter/subtypes":336,"./buttons":107,"./modebar":110}],110:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../lib"),o=t("../../../build/ploticon");function l(t){this.container=t.container,this.element=document.createElement("div"),this.update(t.graphInfo,t.buttons),this.container.appendChild(this.element)}var s=l.prototype;s.update=function(t,e){this.graphInfo=t;var r=this.graphInfo._context;"hover"===r.displayModeBar?this.element.className="modebar modebar--hover":this.element.className="modebar";var n=!this.hasButtons(e),a=this.hasLogo!==r.displaylogo,i=this.locale!==r.locale;this.locale=r.locale,(n||a||i)&&(this.removeAllButtons(),this.updateButtons(e),r.displaylogo&&(this.element.appendChild(this.getLogo()),this.hasLogo=!0)),this.updateActiveButton()},s.updateButtons=function(t){var e=this;this.buttons=t,this.buttonElements=[],this.buttonsNames=[],this.buttons.forEach(function(t){var r=e.createGroup();t.forEach(function(t){var n=t.name;if(!n)throw new Error("must provide button 'name' in button config");if(-1!==e.buttonsNames.indexOf(n))throw new Error("button name '"+n+"' is taken");e.buttonsNames.push(n);var a=e.createButton(t);e.buttonElements.push(a),r.appendChild(a)}),e.element.appendChild(r)})},s.createGroup=function(){var t=document.createElement("div");return t.className="modebar-group",t},s.createButton=function(t){var e=this,r=document.createElement("a");r.setAttribute("rel","tooltip"),r.className="modebar-btn";var a=t.title;void 0===a?a=t.name:"function"==typeof a&&(a=a(this.graphInfo)),(a||0===a)&&r.setAttribute("data-title",a),void 0!==t.attr&&r.setAttribute("data-attr",t.attr);var i=t.val;if(void 0!==i&&("function"==typeof i&&(i=i(this.graphInfo)),r.setAttribute("data-val",i)),"function"!=typeof t.click)throw new Error("must provide button 'click' function in button config");r.addEventListener("click",function(r){t.click(e.graphInfo,r),e.updateActiveButton(r.currentTarget)}),r.setAttribute("data-toggle",t.toggle||!1),t.toggle&&n.select(r).classed("active",!0);var l=t.icon;return"function"==typeof l?r.appendChild(l()):r.appendChild(this.createIcon(l||o.question)),r.setAttribute("data-gravity",t.gravity||"n"),r},s.createIcon=function(t){var e=a(t.height)?Number(t.height):t.ascent-t.descent,r="http://www.w3.org/2000/svg",n=document.createElementNS(r,"svg"),i=document.createElementNS(r,"path");return n.setAttribute("height","1em"),n.setAttribute("width",t.width/e+"em"),n.setAttribute("viewBox",[0,0,t.width,e].join(" ")),i.setAttribute("d",t.path),t.transform?i.setAttribute("transform",t.transform):void 0!==t.ascent&&i.setAttribute("transform","matrix(1 0 0 -1 0 "+t.ascent+")"),n.appendChild(i),n},s.updateActiveButton=function(t){var e=this.graphInfo._fullLayout,r=void 0!==t?t.getAttribute("data-attr"):null;this.buttonElements.forEach(function(t){var a=t.getAttribute("data-val")||!0,o=t.getAttribute("data-attr"),l="true"===t.getAttribute("data-toggle"),s=n.select(t);if(l)o===r&&s.classed("active",!s.classed("active"));else{var c=null===o?o:i.nestedProperty(e,o).get();s.classed("active",c===a)}})},s.hasButtons=function(t){var e=this.buttons;if(!e)return!1;if(t.length!==e.length)return!1;for(var r=0;r<t.length;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n<t[r].length;n++)if(t[r][n].name!==e[r][n].name)return!1}return!0},s.getLogo=function(){var t=this.createGroup(),e=document.createElement("a");return e.href="https://plot.ly/",e.target="_blank",e.setAttribute("data-title",i._(this.graphInfo,"Produced with Plotly")),e.className="modebar-btn plotlyjsicon modebar-btn--logo",e.appendChild(this.createIcon(o.plotlylogo)),t.appendChild(e),t},s.removeAllButtons=function(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);this.hasLogo=!1},s.destroy=function(){i.removeElement(this.container.querySelector(".modebar"))},e.exports=function(t,e){var r=t._fullLayout,a=new l({graphInfo:t,container:r._paperdiv.node(),buttons:e});return r._privateplot&&n.select(a.element).append("span").classed("badge-private float--left",!0).text("PRIVATE"),a}},{"../../../build/ploticon":2,"../../lib":163,d3:10,"fast-isnumeric":13}],111:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../color/attributes"),i=(0,t("../../plot_api/plot_template").templatedArray)("button",{visible:{valType:"boolean",dflt:!0,editType:"plot"},step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"});e.exports={visible:{valType:"boolean",editType:"plot"},buttons:i,x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:n({editType:"plot"}),bgcolor:{valType:"color",dflt:a.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:a.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"}},{"../../plot_api/plot_template":197,"../../plots/font_attributes":233,"../color/attributes":44}],112:[function(t,e,r){"use strict";e.exports={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10}},{}],113:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../color"),i=t("../../plot_api/plot_template"),o=t("../../plots/array_container_defaults"),l=t("./attributes"),s=t("./constants");function c(t,e,r,a){var i=a.calendar;function o(r,a){return n.coerce(t,e,l.buttons,r,a)}if(o("visible")){var s=o("step");"all"!==s&&(!i||"gregorian"===i||"month"!==s&&"year"!==s?o("stepmode"):e.stepmode="backward",o("count")),o("label")}}e.exports=function(t,e,r,u,f){var d=t.rangeselector||{},p=i.newContainer(e,"rangeselector");function h(t,e){return n.coerce(d,p,l,t,e)}if(h("visible",o(d,p,{name:"buttons",handleItemDefaults:c,calendar:f}).length>0)){var g=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),a=0,i=0;i<n.length;i++){var o=e[n[i]].domain;o&&(a=Math.max(o[1],a))}return[t.domain[0],a+s.yPad]}(e,r,u);h("x",g[0]),h("y",g[1]),n.noneOrAll(t,e,["x","y"]),h("xanchor"),h("yanchor"),n.coerceFont(h,"font",r.font);var y=h("bgcolor");h("activecolor",a.contrast(y,s.lightAmount,s.darkAmount)),h("bordercolor"),h("borderwidth")}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/array_container_defaults":203,"../color":45,"./attributes":111,"./constants":112}],114:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../plots/plots"),o=t("../color"),l=t("../drawing"),s=t("../../lib"),c=t("../../lib/svg_text_utils"),u=t("../../plots/cartesian/axis_ids"),f=t("../legend/anchor_utils"),d=t("../../constants/alignment"),p=d.LINE_SPACING,h=d.FROM_TL,g=d.FROM_BR,y=t("./constants"),v=t("./get_update_object");function m(t){return t._id}function x(t,e,r){var n=s.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:y.rx,ry:y.ry}),n.call(o.stroke,e.bordercolor).call(o.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function b(t,e,r,n){var a;s.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(l.font,e.font).text((a=r,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(t){c.convertToTspans(t,n)})}e.exports=function(t){var e=t._fullLayout._infolayer.selectAll(".rangeselector").data(function(t){for(var e=u.list(t,"x",!0),r=[],n=0;n<e.length;n++){var a=e[n];a.rangeselector&&a.rangeselector.visible&&r.push(a)}return r}(t),m);e.enter().append("g").classed("rangeselector",!0),e.exit().remove(),e.style({cursor:"pointer","pointer-events":"all"}),e.each(function(e){var r=n.select(this),o=e,u=o.rangeselector,d=r.selectAll("g.button").data(s.filterVisible(u.buttons));d.enter().append("g").classed("button",!0),d.exit().remove(),d.each(function(e){var r=n.select(this),i=v(o,e);e._isActive=function(t,e,r){if("all"===e.step)return!0===t.autorange;var n=Object.keys(r);return t.range[0]===r[n[0]]&&t.range[1]===r[n[1]]}(o,e,i),r.call(x,u,e),r.call(b,u,e,t),r.on("click",function(){t._dragged||a.call("relayout",t,i)}),r.on("mouseover",function(){e._isHovered=!0,r.call(x,u,e)}),r.on("mouseout",function(){e._isHovered=!1,r.call(x,u,e)})}),function(t,e,r,a,o){var s=0,u=0,d=r.borderwidth;e.each(function(){var t=n.select(this),e=t.select(".selector-text"),a=r.font.size*p,i=Math.max(a*c.lineCount(e),16)+3;u=Math.max(u,i)}),e.each(function(){var t=n.select(this),e=t.select(".selector-rect"),a=t.select(".selector-text"),i=a.node()&&l.bBox(a.node()).width,o=r.font.size*p,f=c.lineCount(a),h=Math.max(i+10,y.minButtonWidth);t.attr("transform","translate("+(d+s)+","+d+")"),e.attr({x:0,y:0,width:h,height:u}),c.positionText(a,h/2,u/2-(f-1)*o/2+3),s+=h+5});var v=t._fullLayout._size,m=v.l+v.w*r.x,x=v.t+v.h*(1-r.y),b="left";f.isRightAnchor(r)&&(m-=s,b="right");f.isCenterAnchor(r)&&(m-=s/2,b="center");var _="top";f.isBottomAnchor(r)&&(x-=u,_="bottom");f.isMiddleAnchor(r)&&(x-=u/2,_="middle");s=Math.ceil(s),u=Math.ceil(u),m=Math.round(m),x=Math.round(x),i.autoMargin(t,a+"-range-selector",{x:r.x,y:r.y,l:s*h[b],r:s*g[b],b:u*g[_],t:u*h[_]}),o.attr("transform","translate("+m+","+x+")")}(t,d,u,o._name,r)})}},{"../../constants/alignment":143,"../../lib":163,"../../lib/svg_text_utils":184,"../../plots/cartesian/axis_ids":210,"../../plots/plots":239,"../../registry":247,"../color":45,"../drawing":70,"../legend/anchor_utils":97,"./constants":112,"./get_update_object":115,d3:10}],115:[function(t,e,r){"use strict";var n=t("d3");e.exports=function(t,e){var r=t._name,a={};if("all"===e.step)a[r+".autorange"]=!0;else{var i=function(t,e){var r,a=t.range,i=new Date(t.r2l(a[1])),o=e.step,l=e.count;switch(e.stepmode){case"backward":r=t.l2r(+n.time[o].utc.offset(i,-l));break;case"todate":var s=n.time[o].utc.offset(i,-l);r=t.l2r(+n.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,e);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a}},{d3:10}],116:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":111,"./defaults":113,"./draw":114}],117:[function(t,e,r){"use strict";var n=t("../color/attributes");e.exports={bgcolor:{valType:"color",dflt:n.background,editType:"plot"},bordercolor:{valType:"color",dflt:n.defaultLine,editType:"plot"},borderwidth:{valType:"integer",dflt:0,min:0,editType:"plot"},autorange:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},range:{valType:"info_array",items:[{valType:"any",editType:"calc",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"calc",impliedEdits:{"^autorange":!1}}],editType:"calc",impliedEdits:{autorange:!1}},thickness:{valType:"number",dflt:.15,min:0,max:1,editType:"plot"},visible:{valType:"boolean",dflt:!0,editType:"calc"},editType:"calc"}},{"../color/attributes":44}],118:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids").list,a=t("../../plots/cartesian/autorange").getAutoRange,i=t("./constants");e.exports=function(t){for(var e=n(t,"x",!0),r=0;r<e.length;r++){var o=e[r],l=o[i.name];l&&l.visible&&l.autorange&&o._min.length&&o._max.length&&(l._input.autorange=!0,l._input.range=l.range=a(o))}}},{"../../plots/cartesian/autorange":206,"../../plots/cartesian/axis_ids":210,"./constants":119}],119:[function(t,e,r){"use strict";e.exports={name:"rangeslider",containerClassName:"rangeslider-container",bgClassName:"rangeslider-bg",rangePlotClassName:"rangeslider-rangeplot",maskMinClassName:"rangeslider-mask-min",maskMaxClassName:"rangeslider-mask-max",slideBoxClassName:"rangeslider-slidebox",grabberMinClassName:"rangeslider-grabber-min",grabAreaMinClassName:"rangeslider-grabarea-min",handleMinClassName:"rangeslider-handle-min",grabberMaxClassName:"rangeslider-grabber-max",grabAreaMaxClassName:"rangeslider-grabarea-max",handleMaxClassName:"rangeslider-handle-max",maskMinOppAxisClassName:"rangeslider-mask-min-opp-axis",maskMaxOppAxisClassName:"rangeslider-mask-max-opp-axis",maskColor:"rgba(0,0,0,0.4)",maskOppAxisColor:"rgba(0,0,0,0.2)",slideBoxFill:"transparent",slideBoxCursor:"ew-resize",grabAreaFill:"transparent",grabAreaCursor:"col-resize",grabAreaWidth:10,handleWidth:4,handleRadius:1,handleStrokeWidth:1,extraPad:15}},{}],120:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plot_api/plot_template"),i=t("../../plots/cartesian/axis_ids"),o=t("./attributes"),l=t("./oppaxis_attributes");e.exports=function(t,e,r){var s=t[r],c=e[r];if(s.rangeslider||e._requestRangeslider[c._id]){n.isPlainObject(s.rangeslider)||(s.rangeslider={});var u,f,d=s.rangeslider,p=a.newContainer(c,"rangeslider");if(w("visible")){w("bgcolor",e.plot_bgcolor),w("bordercolor"),w("borderwidth"),w("thickness"),c._rangesliderAutorange=w("autorange",!c.isValidRange(d.range)),w("range");var h=e._subplots;if(h)for(var g=h.cartesian.filter(function(t){return t.substr(0,t.indexOf("y"))===i.name2id(r)}).map(function(t){return t.substr(t.indexOf("y"),t.length)}),y=n.simpleMap(g,i.id2name),v=0;v<y.length;v++){var m=y[v];u=d[m]||{},f=a.newContainer(p,m,"yaxis");var x,b=e[m];u.range&&b.isValidRange(u.range)&&(x="fixed");var _=k("rangemode",x);"match"!==_&&k("range",b.range.slice()),b._rangesliderAutorange="auto"===_}p._input=d}}function w(t,e){return n.coerce(d,p,o,t,e)}function k(t,e){return n.coerce(u,f,l,t,e)}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/cartesian/axis_ids":210,"./attributes":117,"./oppaxis_attributes":123}],121:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../plots/plots"),o=t("../../lib"),l=t("../drawing"),s=t("../color"),c=t("../titles"),u=t("../../plots/cartesian"),f=t("../../plots/cartesian/axes"),d=t("../dragelement"),p=t("../../lib/setcursor"),h=t("./constants");function g(t,e,r,n){var a=o.ensureSingle(t,"rect",h.bgClassName,function(t){t.attr({x:0,y:0,"shape-rendering":"crispEdges"})}),i=n.borderwidth%2==0?n.borderwidth:n.borderwidth-1,s=-n._offsetShift,c=l.crispRound(e,n.borderwidth);a.attr({width:n._width+i,height:n._height+i,transform:"translate("+s+","+s+")",fill:n.bgcolor,stroke:n.bordercolor,"stroke-width":c})}function y(t,e,r,n){var a=e._fullLayout;o.ensureSingleById(a._topdefs,"clipPath",n._clipId,function(t){t.append("rect").attr({x:0,y:0})}).select("rect").attr({width:n._width,height:n._height})}function v(t,e,r,a){var s,c=f.getSubplots(e,r),d=e.calcdata,p=t.selectAll("g."+h.rangePlotClassName).data(c,o.identity);p.enter().append("g").attr("class",function(t){return h.rangePlotClassName+" "+t}).call(l.setClipUrl,a._clipId),p.order(),p.exit().remove(),p.each(function(t,o){var l=n.select(this),c=0===o,p=f.getFromId(e,t,"y"),h=p._name,g=a[h],y={data:[],layout:{xaxis:{type:r.type,domain:[0,1],range:a.range.slice(),calendar:r.calendar},width:a._width,height:a._height,margin:{t:0,b:0,l:0,r:0}},_context:e._context};y.layout[h]={type:p.type,domain:[0,1],range:"match"!==g.rangemode?g.range.slice():p.range.slice(),calendar:p.calendar},i.supplyDefaults(y);var v={id:t,plotgroup:l,xaxis:y._fullLayout.xaxis,yaxis:y._fullLayout[h],isRangePlot:!0};c?s=v:(v.mainplot="xy",v.mainplotinfo=s),u.rangePlot(e,v,function(t,e){for(var r=[],n=0;n<t.length;n++){var a=t[n],i=a[0].trace;i.xaxis+i.yaxis===e&&r.push(a)}return r}(d,t))})}function m(t,e,r,n,a){(o.ensureSingle(t,"rect",h.maskMinClassName,function(t){t.attr({x:0,y:0,"shape-rendering":"crispEdges"})}).attr("height",n._height).call(s.fill,h.maskColor),o.ensureSingle(t,"rect",h.maskMaxClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("height",n._height).call(s.fill,h.maskColor),"match"!==a.rangemode)&&(o.ensureSingle(t,"rect",h.maskMinOppAxisClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("width",n._width).call(s.fill,h.maskOppAxisColor),o.ensureSingle(t,"rect",h.maskMaxOppAxisClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("width",n._width).style("border-top",h.maskOppBorder).call(s.fill,h.maskOppAxisColor))}function x(t,e,r,n){e._context.staticPlot||o.ensureSingle(t,"rect",h.slideBoxClassName,function(t){t.attr({y:0,cursor:h.slideBoxCursor,"shape-rendering":"crispEdges"})}).attr({height:n._height,fill:h.slideBoxFill})}function b(t,e,r,n){var a=o.ensureSingle(t,"g",h.grabberMinClassName),i=o.ensureSingle(t,"g",h.grabberMaxClassName),l={x:0,width:h.handleWidth,rx:h.handleRadius,fill:s.background,stroke:s.defaultLine,"stroke-width":h.handleStrokeWidth,"shape-rendering":"crispEdges"},c={y:Math.round(n._height/4),height:Math.round(n._height/2)};if(o.ensureSingle(a,"rect",h.handleMinClassName,function(t){t.attr(l)}).attr(c),o.ensureSingle(i,"rect",h.handleMaxClassName,function(t){t.attr(l)}).attr(c),!e._context.staticPlot){var u={width:h.grabAreaWidth,x:0,y:0,fill:h.grabAreaFill,cursor:h.grabAreaCursor};o.ensureSingle(a,"rect",h.grabAreaMinClassName,function(t){t.attr(u)}).attr("height",n._height),o.ensureSingle(i,"rect",h.grabAreaMaxClassName,function(t){t.attr(u)}).attr("height",n._height)}}e.exports=function(t){var e=t._fullLayout,r=function(t){var e=f.list({_fullLayout:t},"x",!0),r=h.name,n=[];if(t._has("gl2d"))return n;for(var a=0;a<e.length;a++){var i=e[a];i[r]&&i[r].visible&&n.push(i)}return n}(e);var l=e._infolayer.selectAll("g."+h.containerClassName).data(r,function(t){return t._name});l.enter().append("g").classed(h.containerClassName,!0).attr("pointer-events","all"),l.exit().each(function(t){var r=t[h.name];e._topdefs.select("#"+r._clipId).remove()}).remove(),0!==r.length&&l.each(function(r){var l=n.select(this),s=r[h.name],u=e[f.id2name(r.anchor)],_=s[f.id2name(r.anchor)];if(s.range){var w=s.range,k=r.range;w[0]=r.l2r(Math.min(r.r2l(w[0]),r.r2l(k[0]))),w[1]=r.l2r(Math.max(r.r2l(w[1]),r.r2l(k[1]))),s._input.range=w.slice()}r.cleanRange("rangeslider.range");for(var M=e.margin,T=e._size,A=r.domain,L=(r._boundingBox||{}).height||0,C=1/0,S=f.getSubplots(t,r),O=0;O<S.length;O++){var P=f.getFromId(t,S[O].substr(S[O].indexOf("y")));C=Math.min(C,P.domain[0])}s._id=h.name+r._id,s._clipId=s._id+"-"+e._uid,s._width=T.w*(A[1]-A[0]),s._height=(e.height-M.b-M.t)*s.thickness,s._offsetShift=Math.floor(s.borderwidth/2);var D=Math.round(M.l+T.w*A[0]),z=Math.round(T.t+T.h*(1-C)+L+s._offsetShift+h.extraPad);l.attr("transform","translate("+D+","+z+")");var E=r.r2l(s.range[0]),I=r.r2l(s.range[1]),N=I-E;if(s.p2d=function(t){return t/s._width*N+E},s.d2p=function(t){return(t-E)/N*s._width},s._rl=[E,I],"match"!==_.rangemode){var R=u.r2l(_.range[0]),F=u.r2l(_.range[1])-R;s.d2pOppAxis=function(t){return(t-R)/F*s._height}}l.call(g,t,r,s).call(y,t,r,s).call(v,t,r,s).call(m,t,r,s,_).call(x,t,r,s).call(b,t,r,s),function(t,e,r,i){var l=t.select("rect."+h.slideBoxClassName).node(),s=t.select("rect."+h.grabAreaMinClassName).node(),c=t.select("rect."+h.grabAreaMaxClassName).node();t.on("mousedown",function(){var u=n.event,f=u.target,h=u.clientX,g=h-t.node().getBoundingClientRect().left,y=i.d2p(r._rl[0]),v=i.d2p(r._rl[1]),m=d.coverSlip();function x(t){var u,d,x,b=+t.clientX-h;switch(f){case l:x="ew-resize",u=y+b,d=v+b;break;case s:x="col-resize",u=y+b,d=v;break;case c:x="col-resize",u=y,d=v+b;break;default:x="ew-resize",u=g,d=g+b}if(d<u){var _=d;d=u,u=_}i._pixelMin=u,i._pixelMax=d,p(n.select(m),x),function(t,e,r,n){function i(t){return r.l2r(o.constrain(t,n._rl[0],n._rl[1]))}var l=i(n.p2d(n._pixelMin)),s=i(n.p2d(n._pixelMax));window.requestAnimationFrame(function(){a.call("relayout",e,r._name+".range",[l,s])})}(0,e,r,i)}m.addEventListener("mousemove",x),m.addEventListener("mouseup",function t(){m.removeEventListener("mousemove",x);m.removeEventListener("mouseup",t);o.removeElement(m)})})}(l,t,r,s),function(t,e,r,n,a,i){var l=h.handleWidth/2;function s(t){return o.constrain(t,0,n._width)}function c(t){return o.constrain(t,0,n._height)}function u(t){return o.constrain(t,-l,n._width+l)}var f=s(n.d2p(r._rl[0])),d=s(n.d2p(r._rl[1]));if(t.select("rect."+h.slideBoxClassName).attr("x",f).attr("width",d-f),t.select("rect."+h.maskMinClassName).attr("width",f),t.select("rect."+h.maskMaxClassName).attr("x",d).attr("width",n._width-d),"match"!==i.rangemode){var p=n._height-c(n.d2pOppAxis(a._rl[1])),g=n._height-c(n.d2pOppAxis(a._rl[0]));t.select("rect."+h.maskMinOppAxisClassName).attr("x",f).attr("height",p).attr("width",d-f),t.select("rect."+h.maskMaxOppAxisClassName).attr("x",f).attr("y",g).attr("height",n._height-g).attr("width",d-f),t.select("rect."+h.slideBoxClassName).attr("y",p).attr("height",g-p)}var y=Math.round(u(f-l))-.5,v=Math.round(u(d-l))+.5;t.select("g."+h.grabberMinClassName).attr("transform","translate("+y+",0.5)"),t.select("g."+h.grabberMaxClassName).attr("transform","translate("+v+",0.5)")}(l,0,r,s,u,_),"bottom"===r.side&&c.draw(t,r._id+"title",{propContainer:r,propName:r._name+".title",placeholder:e._dfltTitle.x,attributes:{x:r._offset+r._length/2,y:z+s._height+s._offsetShift+10+1.5*r.titlefont.size,"text-anchor":"middle"}}),i.autoMargin(t,s._id,{x:A[0],y:C,l:0,r:0,t:0,b:s._height+M.b+L,pad:h.extraPad+2*s._offsetShift})})}},{"../../lib":163,"../../lib/setcursor":182,"../../plots/cartesian":218,"../../plots/cartesian/axes":207,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"../titles":136,"./constants":119,d3:10}],122:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./attributes"),i=t("./oppaxis_attributes");e.exports={moduleType:"component",name:"rangeslider",schema:{subplots:{xaxis:{rangeslider:n.extendFlat({},a,{yaxis:i})}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),calcAutorange:t("./calc_autorange"),draw:t("./draw")}},{"../../lib":163,"./attributes":117,"./calc_autorange":118,"./defaults":120,"./draw":121,"./oppaxis_attributes":123}],123:[function(t,e,r){"use strict";e.exports={_isSubplotObj:!0,rangemode:{valType:"enumerated",values:["auto","fixed","match"],dflt:"match",editType:"calc"},range:{valType:"info_array",items:[{valType:"any",editType:"plot"},{valType:"any",editType:"plot"}],editType:"plot"},editType:"calc"}},{}],124:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),a=t("../../traces/scatter/attributes").line,i=t("../drawing/attributes").dash,o=t("../../lib/extend").extendFlat,l=t("../../plot_api/plot_template").templatedArray;e.exports=l("shape",{visible:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},type:{valType:"enumerated",values:["circle","rect","path","line"],editType:"calcIfAutorange+arraydraw"},layer:{valType:"enumerated",values:["below","above"],dflt:"above",editType:"arraydraw"},xref:o({},n.xref,{}),xsizemode:{valType:"enumerated",values:["scaled","pixel"],dflt:"scaled",editType:"calcIfAutorange+arraydraw"},xanchor:{valType:"any",editType:"calcIfAutorange+arraydraw"},x0:{valType:"any",editType:"calcIfAutorange+arraydraw"},x1:{valType:"any",editType:"calcIfAutorange+arraydraw"},yref:o({},n.yref,{}),ysizemode:{valType:"enumerated",values:["scaled","pixel"],dflt:"scaled",editType:"calcIfAutorange+arraydraw"},yanchor:{valType:"any",editType:"calcIfAutorange+arraydraw"},y0:{valType:"any",editType:"calcIfAutorange+arraydraw"},y1:{valType:"any",editType:"calcIfAutorange+arraydraw"},path:{valType:"string",editType:"calcIfAutorange+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},line:{color:o({},a.color,{editType:"arraydraw"}),width:o({},a.width,{editType:"calcIfAutorange+arraydraw"}),dash:o({},i,{editType:"arraydraw"}),editType:"calcIfAutorange+arraydraw"},fillcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},editType:"arraydraw"})},{"../../lib/extend":157,"../../plot_api/plot_template":197,"../../traces/scatter/attributes":314,"../annotations/attributes":30,"../drawing/attributes":69}],125:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("./constants"),o=t("./helpers");function l(t){return c(t.line.width,t.xsizemode,t.x0,t.x1,t.path,!1)}function s(t){return c(t.line.width,t.ysizemode,t.y0,t.y1,t.path,!0)}function c(t,e,r,a,l,s){var c=t/2,u=s;if("pixel"===e){var f=l?o.extractPathCoords(l,s?i.paramIsY:i.paramIsX):[r,a],d=n.aggNums(Math.max,null,f),p=n.aggNums(Math.min,null,f),h=p<0?Math.abs(p)+c:c,g=d>0?d+c:c;return{ppad:c,ppadplus:u?h:g,ppadminus:u?g:h}}return{ppad:c}}function u(t,e,r,n,a){var l="category"===t.type?t.r2c:t.d2c;if(void 0!==e)return[l(e),l(r)];if(n){var s,c,u,f,d=1/0,p=-1/0,h=n.match(i.segmentRE);for("date"===t.type&&(l=o.decodeDate(l)),s=0;s<h.length;s++)void 0!==(c=a[h[s].charAt(0)].drawn)&&(!(u=h[s].substr(1).match(i.paramRE))||u.length<c||((f=l(u[c]))<d&&(d=f),f>p&&(p=f)));return p>=d?[d,p]:void 0}}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var o=0;o<r.length;o++){var c,f,d=r[o];if("paper"!==d.xref){var p="pixel"===d.xsizemode?d.xanchor:d.x0,h="pixel"===d.xsizemode?d.xanchor:d.x1;(f=u(c=a.getFromId(t,d.xref),p,h,d.path,i.paramIsX))&&a.expand(c,f,l(d))}if("paper"!==d.yref){var g="pixel"===d.ysizemode?d.yanchor:d.y0,y="pixel"===d.ysizemode?d.yanchor:d.y1;(f=u(c=a.getFromId(t,d.yref),g,y,d.path,i.paramIsY))&&a.expand(c,f,s(d))}}}},{"../../lib":163,"../../plots/cartesian/axes":207,"./constants":126,"./helpers":129}],126:[function(t,e,r){"use strict";e.exports={segmentRE:/[MLHVQCTSZ][^MLHVQCTSZ]*/g,paramRE:/[^\s,]+/g,paramIsX:{M:{0:!0,drawn:0},L:{0:!0,drawn:0},H:{0:!0,drawn:0},V:{},Q:{0:!0,2:!0,drawn:2},C:{0:!0,2:!0,4:!0,drawn:4},T:{0:!0,drawn:0},S:{0:!0,2:!0,drawn:2},Z:{}},paramIsY:{M:{1:!0,drawn:1},L:{1:!0,drawn:1},H:{},V:{0:!0,drawn:0},Q:{1:!0,3:!0,drawn:3},C:{1:!0,3:!0,5:!0,drawn:5},T:{1:!0,drawn:1},S:{1:!0,3:!0,drawn:5},Z:{}},numParams:{M:2,L:2,H:1,V:1,Q:4,C:6,T:2,S:4,Z:0}}},{}],127:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("./attributes"),l=t("./helpers");function s(t,e,r){function i(r,a){return n.coerce(t,e,o,r,a)}if(i("visible")){i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var s=i("type",t.path?"path":"rect"),c=i("xsizemode"),u=i("ysizemode"),f=["x","y"],d=0;d<2;d++){var p,h,g,y=f[d],v=y+"anchor",m="x"===y?c:u,x={_fullLayout:r},b=a.coerceRef(t,e,x,y,"","paper");if("paper"!==b?(p=a.getFromId(x,b),g=l.rangeToShapePosition(p),h=l.shapePositionToRange(p)):h=g=n.identity,"path"!==s){var _=y+"0",w=y+"1",k=t[_],M=t[w];t[_]=h(t[_],!0),t[w]=h(t[w],!0),"pixel"===m?(i(_,0),i(w,10)):(a.coercePosition(e,x,i,b,_,.25),a.coercePosition(e,x,i,b,w,.75)),e[_]=g(e[_]),e[w]=g(e[w]),t[_]=k,t[w]=M}if("pixel"===m){var T=t[v];t[v]=h(t[v],!0),a.coercePosition(e,x,i,b,v,.25),e[v]=g(e[v]),t[v]=T}}"path"===s?i("path"):n.noneOrAll(t,e,["x0","x1","y0","y1"])}}e.exports=function(t,e){i(t,e,{name:"shapes",handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"./attributes":124,"./helpers":129}],128:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../plots/cartesian/axes"),o=t("../color"),l=t("../drawing"),s=t("../../plot_api/plot_template").arrayEditor,c=t("../dragelement"),u=t("../../lib/setcursor"),f=t("./constants"),d=t("./helpers");function p(t,e){t._fullLayout._paperdiv.selectAll('.shapelayer [data-index="'+e+'"]').remove();var r=t._fullLayout.shapes[e]||{};if(r._input&&!1!==r.visible)if("below"!==r.layer)v(t._fullLayout._shapeUpperLayer);else if("paper"===r.xref||"paper"===r.yref)v(t._fullLayout._shapeLowerLayer);else{var p=t._fullLayout._plots[r.xref+r.yref];if(p)v((p.mainplotinfo||p).shapelayer);else v(t._fullLayout._shapeLowerLayer)}function v(p){var v={"data-index":e,"fill-rule":"evenodd",d:g(t,r)},m=r.line.width?r.line.color:"rgba(0,0,0,0)",x=p.append("path").attr(v).style("opacity",r.opacity).call(o.stroke,m).call(o.fill,r.fillcolor).call(l.dashLine,r.line.dash,r.line.width);h(x,t,r),t._context.edits.shapePosition&&function(t,e,r,o,p){var v,m,x,b,_,w,k,M,T,A,L,C,S,O,P,D,z=10,E=10,I="pixel"===r.xsizemode,N="pixel"===r.ysizemode,R="line"===r.type,F="path"===r.type,j=s(t.layout,"shapes",r),B=j.modifyItem,H=i.getFromId(t,r.xref),q=i.getFromId(t,r.yref),V=d.getDataToPixel(t,H),U=d.getDataToPixel(t,q,!0),G=d.getPixelToData(t,H),Y=d.getPixelToData(t,q,!0),X=R?function(){var t=Math.max(r.line.width,10),n=p.append("g").attr("data-index",o);n.append("path").attr("d",e.attr("d")).style({cursor:"move","stroke-width":t,"stroke-opacity":"0"});var a={"fill-opacity":"0"},i=t/2>10?t/2:10;return n.append("circle").attr({"data-line-point":"start-point",cx:I?V(r.xanchor)+r.x0:V(r.x0),cy:N?U(r.yanchor)-r.y0:U(r.y0),r:i}).style(a).classed("cursor-grab",!0),n.append("circle").attr({"data-line-point":"end-point",cx:I?V(r.xanchor)+r.x1:V(r.x1),cy:N?U(r.yanchor)-r.y1:U(r.y1),r:i}).style(a).classed("cursor-grab",!0),n}():e,Z={element:X.node(),gd:t,prepFn:function(n){I&&(_=V(r.xanchor));N&&(w=U(r.yanchor));"path"===r.type?P=r.path:(v=I?r.x0:V(r.x0),m=N?r.y0:U(r.y0),x=I?r.x1:V(r.x1),b=N?r.y1:U(r.y1));v<x?(T=v,S="x0",A=x,O="x1"):(T=x,S="x1",A=v,O="x0");!N&&m<b||N&&m>b?(k=m,L="y0",M=b,C="y1"):(k=b,L="y1",M=m,C="y0");W(n),$(p,r),function(t,e,r){var n=e.xref,a=e.yref,o=i.getFromId(r,n),s=i.getFromId(r,a),c="";"paper"===n||o.autorange||(c+=n);"paper"===a||s.autorange||(c+=a);t.call(l.setClipUrl,c?"clip"+r._fullLayout._uid+c:null)}(e,r,t),Z.moveFn="move"===D?Q:J},doneFn:function(){u(e),K(p),h(e,t,r),n.call("relayout",t,j.getUpdateObj())},clickFn:function(){K(p)}};function W(t){if(R)D="path"===t.target.tagName?"move":"start-point"===t.target.attributes["data-line-point"].value?"resize-over-start-point":"resize-over-end-point";else{var r=Z.element.getBoundingClientRect(),n=r.right-r.left,a=r.bottom-r.top,i=t.clientX-r.left,o=t.clientY-r.top,l=!F&&n>z&&a>E&&!t.shiftKey?c.getCursor(i/n,1-o/a):"move";u(e,l),D=l.split("-")[0]}}function Q(n,a){if("path"===r.type){var i=function(t){return t},o=i,l=i;I?B("xanchor",r.xanchor=G(_+n)):(o=function(t){return G(V(t)+n)},H&&"date"===H.type&&(o=d.encodeDate(o))),N?B("yanchor",r.yanchor=Y(w+a)):(l=function(t){return Y(U(t)+a)},q&&"date"===q.type&&(l=d.encodeDate(l))),B("path",r.path=y(P,o,l))}else I?B("xanchor",r.xanchor=G(_+n)):(B("x0",r.x0=G(v+n)),B("x1",r.x1=G(x+n))),N?B("yanchor",r.yanchor=Y(w+a)):(B("y0",r.y0=Y(m+a)),B("y1",r.y1=Y(b+a)));e.attr("d",g(t,r)),$(p,r)}function J(n,a){if(F){var i=function(t){return t},o=i,l=i;I?B("xanchor",r.xanchor=G(_+n)):(o=function(t){return G(V(t)+n)},H&&"date"===H.type&&(o=d.encodeDate(o))),N?B("yanchor",r.yanchor=Y(w+a)):(l=function(t){return Y(U(t)+a)},q&&"date"===q.type&&(l=d.encodeDate(l))),B("path",r.path=y(P,o,l))}else if(R){if("resize-over-start-point"===D){var s=v+n,c=N?m-a:m+a;B("x0",r.x0=I?s:G(s)),B("y0",r.y0=N?c:Y(c))}else if("resize-over-end-point"===D){var u=x+n,f=N?b-a:b+a;B("x1",r.x1=I?u:G(u)),B("y1",r.y1=N?f:Y(f))}}else{var h=~D.indexOf("n")?k+a:k,j=~D.indexOf("s")?M+a:M,X=~D.indexOf("w")?T+n:T,Z=~D.indexOf("e")?A+n:A;~D.indexOf("n")&&N&&(h=k-a),~D.indexOf("s")&&N&&(j=M-a),(!N&&j-h>E||N&&h-j>E)&&(B(L,r[L]=N?h:Y(h)),B(C,r[C]=N?j:Y(j))),Z-X>z&&(B(S,r[S]=I?X:G(X)),B(O,r[O]=I?Z:G(Z)))}e.attr("d",g(t,r)),$(p,r)}function $(t,e){(I||N)&&function(){var r="path"!==e.type,n=t.selectAll(".visual-cue").data([0]);n.enter().append("path").attr({fill:"#fff","fill-rule":"evenodd",stroke:"#000","stroke-width":1}).classed("visual-cue",!0);var i=V(I?e.xanchor:a.midRange(r?[e.x0,e.x1]:d.extractPathCoords(e.path,f.paramIsX))),o=U(N?e.yanchor:a.midRange(r?[e.y0,e.y1]:d.extractPathCoords(e.path,f.paramIsY)));if(i=d.roundPositionForSharpStrokeRendering(i,1),o=d.roundPositionForSharpStrokeRendering(o,1),I&&N){var l="M"+(i-1-1)+","+(o-1-1)+"h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z";n.attr("d",l)}else if(I){var s="M"+(i-1-1)+","+(o-9-1)+"v18 h2 v-18 Z";n.attr("d",s)}else{var c="M"+(i-9-1)+","+(o-1-1)+"h18 v2 h-18 Z";n.attr("d",c)}}()}function K(t){t.selectAll(".visual-cue").remove()}c.init(Z),X.node().onmousemove=W}(t,x,r,e,p)}}function h(t,e,r){var n=(r.xref+r.yref).replace(/paper/g,"");t.call(l.setClipUrl,n?"clip"+e._fullLayout._uid+n:null)}function g(t,e){var r,n,o,l,s,c,u,p,h=e.type,g=i.getFromId(t,e.xref),y=i.getFromId(t,e.yref),v=t._fullLayout._size;if(g?(r=d.shapePositionToRange(g),n=function(t){return g._offset+g.r2p(r(t,!0))}):n=function(t){return v.l+v.w*t},y?(o=d.shapePositionToRange(y),l=function(t){return y._offset+y.r2p(o(t,!0))}):l=function(t){return v.t+v.h*(1-t)},"path"===h)return g&&"date"===g.type&&(n=d.decodeDate(n)),y&&"date"===y.type&&(l=d.decodeDate(l)),function(t,e,r){var n=t.path,i=t.xsizemode,o=t.ysizemode,l=t.xanchor,s=t.yanchor;return n.replace(f.segmentRE,function(t){var n=0,c=t.charAt(0),u=f.paramIsX[c],d=f.paramIsY[c],p=f.numParams[c],h=t.substr(1).replace(f.paramRE,function(t){return u[n]?t="pixel"===i?e(l)+Number(t):e(t):d[n]&&(t="pixel"===o?r(s)-Number(t):r(t)),++n>p&&(t="X"),t});return n>p&&(h=h.replace(/[\s,]*X.*/,""),a.log("Ignoring extra params in segment "+t)),c+h})}(e,n,l);if("pixel"===e.xsizemode){var m=n(e.xanchor);s=m+e.x0,c=m+e.x1}else s=n(e.x0),c=n(e.x1);if("pixel"===e.ysizemode){var x=l(e.yanchor);u=x-e.y0,p=x-e.y1}else u=l(e.y0),p=l(e.y1);if("line"===h)return"M"+s+","+u+"L"+c+","+p;if("rect"===h)return"M"+s+","+u+"H"+c+"V"+p+"H"+s+"Z";var b=(s+c)/2,_=(u+p)/2,w=Math.abs(b-s),k=Math.abs(_-u),M="A"+w+","+k,T=b+w+","+_;return"M"+T+M+" 0 1,1 "+(b+","+(_-k))+M+" 0 0,1 "+T+"Z"}function y(t,e,r){return t.replace(f.segmentRE,function(t){var n=0,a=t.charAt(0),i=f.paramIsX[a],o=f.paramIsY[a],l=f.numParams[a];return a+t.substr(1).replace(f.paramRE,function(t){return n>=l?t:(i[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}e.exports={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var a=0;a<e.shapes.length;a++)e.shapes[a].visible&&p(t,a)},drawOne:p}},{"../../lib":163,"../../lib/setcursor":182,"../../plot_api/plot_template":197,"../../plots/cartesian/axes":207,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"./constants":126,"./helpers":129}],129:[function(t,e,r){"use strict";var n=t("./constants"),a=t("../../lib");r.rangeToShapePosition=function(t){return"log"===t.type?t.r2d:function(t){return t}},r.shapePositionToRange=function(t){return"log"===t.type?t.d2r:function(t){return t}},r.decodeDate=function(t){return function(e){return e.replace&&(e=e.replace("_"," ")),t(e)}},r.encodeDate=function(t){return function(e){return t(e).replace(" ","_")}},r.extractPathCoords=function(t,e){var r=[];return t.match(n.segmentRE).forEach(function(t){var i=e[t.charAt(0)].drawn;if(void 0!==i){var o=t.substr(1).match(n.paramRE);!o||o.length<i||r.push(a.cleanNumber(o[i]))}}),r},r.getDataToPixel=function(t,e,n){var a,i=t._fullLayout._size;if(e){var o=r.shapePositionToRange(e);a=function(t){return e._offset+e.r2p(o(t,!0))},"date"===e.type&&(a=r.decodeDate(a))}else a=n?function(t){return i.t+i.h*(1-t)}:function(t){return i.l+i.w*t};return a},r.getPixelToData=function(t,e,n){var a,i=t._fullLayout._size;if(e){var o=r.rangeToShapePosition(e);a=function(t){return o(e.p2r(t-e._offset))}}else a=n?function(t){return 1-(t-i.t)/i.h}:function(t){return(t-i.l)/i.w};return a},r.roundPositionForSharpStrokeRendering=function(t,e){var r=1===Math.round(e%2),n=Math.round(t);return r?n+.5:n}},{"../../lib":163,"./constants":126}],130:[function(t,e,r){"use strict";var n=t("./draw");e.exports={moduleType:"component",name:"shapes",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("shapes"),calcAutorange:t("./calc_autorange"),draw:n.draw,drawOne:n.drawOne}},{"../../plots/cartesian/include_components":217,"./attributes":124,"./calc_autorange":125,"./defaults":127,"./draw":128}],131:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../../plots/pad_attributes"),i=t("../../lib/extend").extendDeepAll,o=t("../../plot_api/edit_types").overrideAll,l=t("../../plots/animation_attributes"),s=t("../../plot_api/plot_template").templatedArray,c=t("./constants"),u=s("step",{visible:{valType:"boolean",dflt:!0},method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string"},value:{valType:"string"},execute:{valType:"boolean",dflt:!0}});e.exports=o(s("slider",{visible:{valType:"boolean",dflt:!0},active:{valType:"number",min:0,dflt:0},steps:u,lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",min:-2,max:3,dflt:0},pad:i({},a,{},{t:{dflt:20}}),xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:0},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},transition:{duration:{valType:"number",min:0,dflt:150},easing:{valType:"enumerated",values:l.transition.easing.values,dflt:"cubic-in-out"}},currentvalue:{visible:{valType:"boolean",dflt:!0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},offset:{valType:"number",dflt:10},prefix:{valType:"string"},suffix:{valType:"string"},font:n({})},font:n({}),activebgcolor:{valType:"color",dflt:c.gripBgActiveColor},bgcolor:{valType:"color",dflt:c.railBgColor},bordercolor:{valType:"color",dflt:c.railBorderColor},borderwidth:{valType:"number",min:0,dflt:c.railBorderWidth},ticklen:{valType:"number",min:0,dflt:c.tickLength},tickcolor:{valType:"color",dflt:c.tickColor},tickwidth:{valType:"number",min:0,dflt:1},minorticklen:{valType:"number",min:0,dflt:c.minorTickLength}}),"arraydraw","from-root")},{"../../lib/extend":157,"../../plot_api/edit_types":190,"../../plot_api/plot_template":197,"../../plots/animation_attributes":202,"../../plots/font_attributes":233,"../../plots/pad_attributes":238,"./constants":132}],132:[function(t,e,r){"use strict";e.exports={name:"sliders",containerClassName:"slider-container",groupClassName:"slider-group",inputAreaClass:"slider-input-area",railRectClass:"slider-rail-rect",railTouchRectClass:"slider-rail-touch-rect",gripRectClass:"slider-grip-rect",tickRectClass:"slider-tick-rect",inputProxyClass:"slider-input-proxy",labelsClass:"slider-labels",labelGroupClass:"slider-label-group",labelClass:"slider-label",currentValueClass:"slider-current-value",railHeight:5,menuIndexAttrName:"slider-active-index",autoMarginIdRoot:"slider-",minWidth:30,minHeight:30,textPadX:40,arrowOffsetX:4,railRadius:2,railWidth:5,railBorder:4,railBorderWidth:1,railBorderColor:"#bec8d9",railBgColor:"#f8fafc",railInset:8,stepInset:10,gripRadius:10,gripWidth:20,gripHeight:20,gripBorder:20,gripBorderWidth:1,gripBorderColor:"#bec8d9",gripBgColor:"#f6f8fa",gripBgActiveColor:"#dbdde0",labelPadding:8,labelOffset:0,tickWidth:1,tickColor:"#333",tickOffset:25,tickLength:7,minorTickOffset:25,minorTickColor:"#333",minorTickLength:4,currentValuePadding:8,currentValueInset:0}},{}],133:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/array_container_defaults"),i=t("./attributes"),o=t("./constants").name,l=i.steps;function s(t,e,r){function o(r,a){return n.coerce(t,e,i,r,a)}for(var l=a(t,e,{name:"steps",handleItemDefaults:c}),s=0,u=0;u<l.length;u++)l[u].visible&&s++;if(s<2?e.visible=!1:o("visible")){e._stepCount=s;var f=e._visibleSteps=n.filterVisible(l);(l[o("active")]||{}).visible||(e.active=f[0]._index),o("x"),o("y"),n.noneOrAll(t,e,["x","y"]),o("xanchor"),o("yanchor"),o("len"),o("lenmode"),o("pad.t"),o("pad.r"),o("pad.b"),o("pad.l"),n.coerceFont(o,"font",r.font),o("currentvalue.visible")&&(o("currentvalue.xanchor"),o("currentvalue.prefix"),o("currentvalue.suffix"),o("currentvalue.offset"),n.coerceFont(o,"currentvalue.font",e.font)),o("transition.duration"),o("transition.easing"),o("bgcolor"),o("activebgcolor"),o("bordercolor"),o("borderwidth"),o("ticklen"),o("tickwidth"),o("tickcolor"),o("minorticklen")}}function c(t,e){function r(r,a){return n.coerce(t,e,l,r,a)}if("skip"===t.method||Array.isArray(t.args)?r("visible"):e.visible=!1){r("method"),r("args");var a=r("label","step-"+e._index);r("value",a),r("execute")}}e.exports=function(t,e){a(t,e,{name:o,handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"./attributes":131,"./constants":132}],134:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../plots/plots"),i=t("../color"),o=t("../drawing"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../legend/anchor_utils"),u=t("../../plot_api/plot_template").arrayEditor,f=t("./constants"),d=t("../../constants/alignment"),p=d.LINE_SPACING,h=d.FROM_TL,g=d.FROM_BR;function y(t){return f.autoMarginIdRoot+t._index}function v(t){return t._index}function m(t,e){var r=o.tester.selectAll("g."+f.labelGroupClass).data(e._visibleSteps);r.enter().append("g").classed(f.labelGroupClass,!0);var i=0,l=0;r.each(function(t){var r=_(n.select(this),{step:t},e).node();if(r){var a=o.bBox(r);l=Math.max(l,a.height),i=Math.max(i,a.width)}}),r.remove();var u=e._dims={};u.inputAreaWidth=Math.max(f.railWidth,f.gripHeight);var d=t._fullLayout._size;u.lx=d.l+d.w*e.x,u.ly=d.t+d.h*(1-e.y),"fraction"===e.lenmode?u.outerLength=Math.round(d.w*e.len):u.outerLength=e.len,u.inputAreaStart=0,u.inputAreaLength=Math.round(u.outerLength-e.pad.l-e.pad.r);var p=(u.inputAreaLength-2*f.stepInset)/(e._stepCount-1),v=i+f.labelPadding;if(u.labelStride=Math.max(1,Math.ceil(v/p)),u.labelHeight=l,u.currentValueMaxWidth=0,u.currentValueHeight=0,u.currentValueTotalHeight=0,u.currentValueMaxLines=1,e.currentvalue.visible){var m=o.tester.append("g");r.each(function(t){var r=x(m,e,t.label),n=r.node()&&o.bBox(r.node())||{width:0,height:0},a=s.lineCount(r);u.currentValueMaxWidth=Math.max(u.currentValueMaxWidth,Math.ceil(n.width)),u.currentValueHeight=Math.max(u.currentValueHeight,Math.ceil(n.height)),u.currentValueMaxLines=Math.max(u.currentValueMaxLines,a)}),u.currentValueTotalHeight=u.currentValueHeight+e.currentvalue.offset,m.remove()}u.height=u.currentValueTotalHeight+f.tickOffset+e.ticklen+f.labelOffset+u.labelHeight+e.pad.t+e.pad.b;var b="left";c.isRightAnchor(e)&&(u.lx-=u.outerLength,b="right"),c.isCenterAnchor(e)&&(u.lx-=u.outerLength/2,b="center");var w="top";c.isBottomAnchor(e)&&(u.ly-=u.height,w="bottom"),c.isMiddleAnchor(e)&&(u.ly-=u.height/2,w="middle"),u.outerLength=Math.ceil(u.outerLength),u.height=Math.ceil(u.height),u.lx=Math.round(u.lx),u.ly=Math.round(u.ly);var k={y:e.y,b:u.height*g[w],t:u.height*h[w]};"fraction"===e.lenmode?(k.l=0,k.xl=e.x-e.len*h[b],k.r=0,k.xr=e.x+e.len*g[b]):(k.x=e.x,k.l=u.outerLength*h[b],k.r=u.outerLength*g[b]),a.autoMargin(t,y(e),k)}function x(t,e,r){if(e.currentvalue.visible){var n,a,i=e._dims;switch(e.currentvalue.xanchor){case"right":n=i.inputAreaLength-f.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":n=.5*i.inputAreaLength,a="middle";break;default:n=f.currentValueInset,a="left"}var c=l.ensureSingle(t,"text",f.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),u=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)u+=r;else u+=e.steps[e.active].label;e.currentvalue.suffix&&(u+=e.currentvalue.suffix),c.call(o.font,e.currentvalue.font).text(u).call(s.convertToTspans,e._gd);var d=s.lineCount(c),h=(i.currentValueMaxLines+1-d)*e.currentvalue.font.size*p;return s.positionText(c,n,h),c}}function b(t,e,r){l.ensureSingle(t,"rect",f.gripRectClass,function(n){n.call(T,e,t,r).style("pointer-events","all")}).attr({width:f.gripWidth,height:f.gripHeight,rx:f.gripRadius,ry:f.gripRadius}).call(i.stroke,r.bordercolor).call(i.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function _(t,e,r){var n=l.ensureSingle(t,"text",f.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return n.call(o.font,r.font).text(e.step.label).call(s.convertToTspans,r._gd),n}function w(t,e){var r=l.ensureSingle(t,"g",f.labelsClass),a=e._dims,i=r.selectAll("g."+f.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(f.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=n.select(this);r.call(_,t,e),o.setTranslate(r,C(e,t.fraction),f.tickOffset+e.ticklen+e.font.size*p+f.labelOffset+a.currentValueTotalHeight)})}function k(t,e,r,n,a){var i=Math.round(n*(r._stepCount-1)),o=r._visibleSteps[i]._index;o!==r.active&&M(t,e,r,o,!0,a)}function M(t,e,r,n,i,o){var l=r.active;r.active=n,u(t.layout,f.name,r).applyUpdate("active",n);var s=r.steps[r.active];e.call(L,r,o),e.call(x,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:l}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=o):(e._nextMethod={step:s,doCallback:i,doTransition:o},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&a.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function T(t,e,r){var a=r.node(),o=n.select(e);function l(){return r.data()[0]}t.on("mousedown",function(){var t=l();e.emit("plotly_sliderstart",{slider:t});var s=r.select("."+f.gripRectClass);n.event.stopPropagation(),n.event.preventDefault(),s.call(i.fill,t.activebgcolor);var c=S(t,n.mouse(a)[0]);k(e,r,t,c,!0),t._dragging=!0,o.on("mousemove",function(){var t=l(),i=S(t,n.mouse(a)[0]);k(e,r,t,i,!1)}),o.on("mouseup",function(){var t=l();t._dragging=!1,s.call(i.fill,t.bgcolor),o.on("mouseup",null),o.on("mousemove",null),e.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function A(t,e){var r=t.selectAll("rect."+f.tickRectClass).data(e._visibleSteps),a=e._dims;r.enter().append("rect").classed(f.tickRectClass,!0),r.exit().remove(),r.attr({width:e.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var l=r%a.labelStride==0,s=n.select(this);s.attr({height:l?e.ticklen:e.minorticklen}).call(i.fill,e.tickcolor),o.setTranslate(s,C(e,r/(e._stepCount-1))-.5*e.tickwidth,(l?f.tickOffset:f.minorTickOffset)+a.currentValueTotalHeight)})}function L(t,e,r){for(var n=t.select("rect."+f.gripRectClass),a=0,i=0;i<e._stepCount;i++)if(e._visibleSteps[i]._index===e.active){a=i;break}var o=C(e,a/(e._stepCount-1));if(!e._invokingCommand){var l=n;r&&e.transition.duration>0&&(l=l.transition().duration(e.transition.duration).ease(e.transition.easing)),l.attr("transform","translate("+(o-.5*f.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function C(t,e){var r=t._dims;return r.inputAreaStart+f.stepInset+(r.inputAreaLength-2*f.stepInset)*Math.min(1,Math.max(0,e))}function S(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-f.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*f.stepInset-2*r.inputAreaStart)))}function O(t,e,r){var n=r._dims,a=l.ensureSingle(t,"rect",f.railTouchRectClass,function(n){n.call(T,e,t,r).style("pointer-events","all")});a.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,f.tickOffset+r.ticklen+n.labelHeight)}).call(i.fill,r.bgcolor).attr("opacity",0),o.setTranslate(a,0,n.currentValueTotalHeight)}function P(t,e){var r=e._dims,n=r.inputAreaLength-2*f.railInset,a=l.ensureSingle(t,"rect",f.railRectClass);a.attr({width:n,height:f.railWidth,rx:f.railRadius,ry:f.railRadius,"shape-rendering":"crispEdges"}).call(i.stroke,e.bordercolor).call(i.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),o.setTranslate(a,f.railInset,.5*(r.inputAreaWidth-f.railWidth)+r.currentValueTotalHeight)}e.exports=function(t){var e=t._fullLayout,r=function(t,e){for(var r=t[f.name],n=[],a=0;a<r.length;a++){var i=r[a];i.visible&&(i._gd=e,n.push(i))}return n}(e,t),i=e._infolayer.selectAll("g."+f.containerClassName).data(r.length>0?[0]:[]);function l(e){e._commandObserver&&(e._commandObserver.remove(),delete e._commandObserver),a.autoMargin(t,y(e))}if(i.enter().append("g").classed(f.containerClassName,!0).style("cursor","ew-resize"),i.exit().each(function(){n.select(this).selectAll("g."+f.groupClassName).each(l)}).remove(),0!==r.length){var s=i.selectAll("g."+f.groupClassName).data(r,v);s.enter().append("g").classed(f.groupClassName,!0),s.exit().each(l).remove();for(var c=0;c<r.length;c++){var u=r[c];m(t,u)}s.each(function(e){var r=n.select(this);!function(t){var e=t._dims;e.labelSteps=[];for(var r=t._stepCount,n=0;n<r;n+=e.labelStride)e.labelSteps.push({fraction:n/(r-1),step:t._visibleSteps[n]})}(e),a.manageCommandObserver(t,e,e._visibleSteps,function(e){var n=r.data()[0];n.active!==e.index&&(n._dragging||M(t,r,n,e.index,!1,!0))}),function(t,e,r){(r.steps[r.active]||{}).visible||(r.active=r._visibleSteps[0]._index);e.call(x,r).call(P,r).call(w,r).call(A,r).call(O,t,r).call(b,t,r);var n=r._dims;o.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(L,r,!1),e.call(x,r)}(t,n.select(this),e)})}}},{"../../constants/alignment":143,"../../lib":163,"../../lib/svg_text_utils":184,"../../plot_api/plot_template":197,"../../plots/plots":239,"../color":45,"../drawing":70,"../legend/anchor_utils":97,"./constants":132,d3:10}],135:[function(t,e,r){"use strict";var n=t("./constants");e.exports={moduleType:"component",name:n.name,layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":131,"./constants":132,"./defaults":133,"./draw":134}],136:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../lib"),s=t("../drawing"),c=t("../color"),u=t("../../lib/svg_text_utils"),f=t("../../constants/interactions");e.exports={draw:function(t,e,r){var p,h=r.propContainer,g=r.propName,y=r.placeholder,v=r.traceIndex,m=r.avoid||{},x=r.attributes,b=r.transform,_=r.containerGroup,w=t._fullLayout,k=h.titlefont||{},M=k.family,T=k.size,A=k.color,L=1,C=!1,S=(h.title||"").trim();"title"===g?p="titleText":-1!==g.indexOf("axis")?p="axisTitleText":g.indexOf(!0)&&(p="colorbarTitleText");var O=t._context.edits[p];""===S?L=0:S.replace(d," % ")===y.replace(d," % ")&&(L=.2,C=!0,O||(S=""));var P=S||O;_||(_=l.ensureSingle(w._infolayer,"g","g-"+e));var D=_.selectAll("text").data(P?[0]:[]);if(D.enter().append("text"),D.text(S).attr("class",e),D.exit().remove(),!P)return _;function z(t){l.syncOrAsync([E,I],t)}function E(e){var r;return b?(r="",b.rotate&&(r+="rotate("+[b.rotate,x.x,x.y]+")"),b.offset&&(r+="translate(0, "+b.offset+")")):r=null,e.attr("transform",r),e.style({"font-family":M,"font-size":n.round(T,2)+"px",fill:c.rgb(A),opacity:L*c.opacity(A),"font-weight":i.fontWeight}).attr(x).call(u.convertToTspans,t),i.previousPromises(t)}function I(t){var e=n.select(t.node().parentNode);if(m&&m.selection&&m.side&&S){e.attr("transform",null);var r=0,i={left:"right",right:"left",top:"bottom",bottom:"top"}[m.side],o=-1!==["left","top"].indexOf(m.side)?-1:1,c=a(m.pad)?m.pad:2,u=s.bBox(e.node()),f={left:0,top:0,right:w.width,bottom:w.height},d=m.maxShift||(f[m.side]-u[m.side])*("left"===m.side||"top"===m.side?-1:1);if(d<0)r=d;else{var p=m.offsetLeft||0,h=m.offsetTop||0;u.left-=p,u.right-=p,u.top-=h,u.bottom-=h,m.selection.each(function(){var t=s.bBox(this);l.bBoxIntersect(u,t,c)&&(r=Math.max(r,o*(t[m.side]-u[i])+c))}),r=Math.min(d,r)}if(r>0||d<0){var g={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[m.side];e.attr("transform","translate("+g+")")}}}D.call(z),O&&(S?D.on(".opacity",null):(L=0,C=!0,D.text(y).on("mouseover.opacity",function(){n.select(this).transition().duration(f.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(f.HIDE_PLACEHOLDER).style("opacity",0)})),D.call(u.makeEditable,{gd:t}).on("edit",function(e){void 0!==v?o.call("restyle",t,g,e,v):o.call("relayout",t,g,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(z)}).on("input",function(t){this.text(t||" ").call(u.positionText,x.x,x.y)}));return D.classed("js-placeholder",C),_}};var d=/ [XY][0-9]* /},{"../../constants/interactions":144,"../../lib":163,"../../lib/svg_text_utils":184,"../../plots/plots":239,"../../registry":247,"../color":45,"../drawing":70,d3:10,"fast-isnumeric":13}],137:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../color/attributes"),i=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll,l=t("../../plots/pad_attributes"),s=t("../../plot_api/plot_template").templatedArray,c=s("button",{visible:{valType:"boolean"},method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}});e.exports=o(s("updatemenu",{_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:c,x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:i({},l,{}),font:n({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:a.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}}),"arraydraw","from-root")},{"../../lib/extend":157,"../../plot_api/edit_types":190,"../../plot_api/plot_template":197,"../../plots/font_attributes":233,"../../plots/pad_attributes":238,"../color/attributes":44}],138:[function(t,e,r){"use strict";e.exports={name:"updatemenus",containerClassName:"updatemenu-container",headerGroupClassName:"updatemenu-header-group",headerClassName:"updatemenu-header",headerArrowClassName:"updatemenu-header-arrow",dropdownButtonGroupClassName:"updatemenu-dropdown-button-group",dropdownButtonClassName:"updatemenu-dropdown-button",buttonClassName:"updatemenu-button",itemRectClassName:"updatemenu-item-rect",itemTextClassName:"updatemenu-item-text",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}}},{}],139:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/array_container_defaults"),i=t("./attributes"),o=t("./constants").name,l=i.buttons;function s(t,e,r){function o(r,a){return n.coerce(t,e,i,r,a)}o("visible",a(t,e,{name:"buttons",handleItemDefaults:c}).length>0)&&(o("active"),o("direction"),o("type"),o("showactive"),o("x"),o("y"),n.noneOrAll(t,e,["x","y"]),o("xanchor"),o("yanchor"),o("pad.t"),o("pad.r"),o("pad.b"),o("pad.l"),n.coerceFont(o,"font",r.font),o("bgcolor",r.paper_bgcolor),o("bordercolor"),o("borderwidth"))}function c(t,e){function r(r,a){return n.coerce(t,e,l,r,a)}r("visible","skip"===t.method||Array.isArray(t.args))&&(r("method"),r("args"),r("label"),r("execute"))}e.exports=function(t,e){a(t,e,{name:o,handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"./attributes":137,"./constants":138}],140:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../plots/plots"),i=t("../color"),o=t("../drawing"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../legend/anchor_utils"),u=t("../../plot_api/plot_template").arrayEditor,f=t("../../constants/alignment").LINE_SPACING,d=t("./constants"),p=t("./scrollbox");function h(t){return t._index}function g(t,e){return+t.attr(d.menuIndexAttrName)===e._index}function y(t,e,r,n,a,i,o,l){e.active=o,u(t.layout,d.name,e).applyUpdate("active",o),"buttons"===e.type?m(t,n,null,null,e):"dropdown"===e.type&&(a.attr(d.menuIndexAttrName,"-1"),v(t,n,a,i,e),l||m(t,n,a,i,e))}function v(t,e,r,n,a){var i=l.ensureSingle(e,"g",d.headerClassName,function(t){t.style("pointer-events","all")}),s=a._dims,c=a.active,u=a.buttons[c]||d.blankHeaderOpts,f={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},p={width:s.headerWidth,height:s.headerHeight};i.call(x,a,u,t).call(L,a,f,p),l.ensureSingle(e,"text",d.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(o.font,a.font).text(d.arrowSymbol[a.direction])}).attr({x:s.headerWidth-d.arrowOffsetX+a.pad.l,y:s.headerHeight/2+d.textOffsetY+a.pad.t}),i.on("click",function(){r.call(C,String(g(r,a)?-1:a._index)),m(t,e,r,n,a)}),i.on("mouseover",function(){i.call(k)}),i.on("mouseout",function(){i.call(M,a)}),o.setTranslate(e,s.lx,s.ly)}function m(t,e,r,i,o){r||(r=e).attr("pointer-events","all");var s=function(t){return-1==+t.attr(d.menuIndexAttrName)}(r)&&"buttons"!==o.type?[]:o.buttons,c="dropdown"===o.type?d.dropdownButtonClassName:d.buttonClassName,u=r.selectAll("g."+c).data(l.filterVisible(s)),f=u.enter().append("g").classed(c,!0),p=u.exit();"dropdown"===o.type?(f.attr("opacity","0").transition().attr("opacity","1"),p.transition().attr("opacity","0").remove()):p.remove();var h=0,g=0,v=o._dims,m=-1!==["up","down"].indexOf(o.direction);"dropdown"===o.type&&(m?g=v.headerHeight+d.gapButtonHeader:h=v.headerWidth+d.gapButtonHeader),"dropdown"===o.type&&"up"===o.direction&&(g=-d.gapButtonHeader+d.gapButton-v.openHeight),"dropdown"===o.type&&"left"===o.direction&&(h=-d.gapButtonHeader+d.gapButton-v.openWidth);var b={x:v.lx+h+o.pad.l,y:v.ly+g+o.pad.t,yPad:d.gapButton,xPad:d.gapButton,index:0},_={l:b.x+o.borderwidth,t:b.y+o.borderwidth};u.each(function(l,s){var c=n.select(this);c.call(x,o,l,t).call(L,o,b),c.on("click",function(){n.event.defaultPrevented||(y(t,o,0,e,r,i,s),l.execute&&a.executeAPICommand(t,l.method,l.args),t.emit("plotly_buttonclicked",{menu:o,button:l,active:o.active}))}),c.on("mouseover",function(){c.call(k)}),c.on("mouseout",function(){c.call(M,o),u.call(w,o)})}),u.call(w,o),m?(_.w=Math.max(v.openWidth,v.headerWidth),_.h=b.y-_.t):(_.w=b.x-_.l,_.h=Math.max(v.openHeight,v.headerHeight)),_.direction=o.direction,i&&(u.size()?function(t,e,r,n,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,p=a.active;if(u)for(l=0,s=0;s<p;s++)l+=f.heights[s]+d.gapButton;else for(o=0,s=0;s<p;s++)o+=f.widths[s]+d.gapButton;n.enable(i,o,l),n.hbar&&n.hbar.attr("opacity","0").transition().attr("opacity","1");n.vbar&&n.vbar.attr("opacity","0").transition().attr("opacity","1")}(0,0,0,i,o,_):function(t){var e=!!t.hbar,r=!!t.vbar;e&&t.hbar.transition().attr("opacity","0").each("end",function(){e=!1,r||t.disable()});r&&t.vbar.transition().attr("opacity","0").each("end",function(){r=!1,e||t.disable()})}(i))}function x(t,e,r,n){t.call(b,e).call(_,e,r,n)}function b(t,e){l.ensureSingle(t,"rect",d.itemRectClassName,function(t){t.attr({rx:d.rx,ry:d.ry,"shape-rendering":"crispEdges"})}).call(i.stroke,e.bordercolor).call(i.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px")}function _(t,e,r,n){l.ensureSingle(t,"text",d.itemTextClassName,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"start","data-notex":1})}).call(o.font,e.font).text(r.label).call(s.convertToTspans,n)}function w(t,e){var r=e.active;t.each(function(t,a){var o=n.select(this);a===r&&e.showactive&&o.select("rect."+d.itemRectClassName).call(i.fill,d.activeColor)})}function k(t){t.select("rect."+d.itemRectClassName).call(i.fill,d.hoverColor)}function M(t,e){t.select("rect."+d.itemRectClassName).call(i.fill,e.bgcolor)}function T(t,e){var r=e._dims={width1:0,height1:0,heights:[],widths:[],totalWidth:0,totalHeight:0,openWidth:0,openHeight:0,lx:0,ly:0},i=o.tester.selectAll("g."+d.dropdownButtonClassName).data(l.filterVisible(e.buttons));i.enter().append("g").classed(d.dropdownButtonClassName,!0);var u=-1!==["up","down"].indexOf(e.direction);i.each(function(a,i){var l=n.select(this);l.call(x,e,a,t);var c=l.select("."+d.itemTextClassName),p=c.node()&&o.bBox(c.node()).width,h=Math.max(p+d.textPadX,d.minWidth),g=e.font.size*f,y=s.lineCount(c),v=Math.max(g*y,d.minHeight)+d.textOffsetY;v=Math.ceil(v),h=Math.ceil(h),r.widths[i]=h,r.heights[i]=v,r.height1=Math.max(r.height1,v),r.width1=Math.max(r.width1,h),u?(r.totalWidth=Math.max(r.totalWidth,h),r.openWidth=r.totalWidth,r.totalHeight+=v+d.gapButton,r.openHeight+=v+d.gapButton):(r.totalWidth+=h+d.gapButton,r.openWidth+=h+d.gapButton,r.totalHeight=Math.max(r.totalHeight,v),r.openHeight=r.totalHeight)}),u?r.totalHeight-=d.gapButton:r.totalWidth-=d.gapButton,r.headerWidth=r.width1+d.arrowPadX,r.headerHeight=r.height1,"dropdown"===e.type&&(u?(r.width1+=d.arrowPadX,r.totalHeight=r.height1):r.totalWidth=r.width1,r.totalWidth+=d.arrowPadX),i.remove();var p=r.totalWidth+e.pad.l+e.pad.r,h=r.totalHeight+e.pad.t+e.pad.b,g=t._fullLayout._size;r.lx=g.l+g.w*e.x,r.ly=g.t+g.h*(1-e.y);var y="left";c.isRightAnchor(e)&&(r.lx-=p,y="right"),c.isCenterAnchor(e)&&(r.lx-=p/2,y="center");var v="top";c.isBottomAnchor(e)&&(r.ly-=h,v="bottom"),c.isMiddleAnchor(e)&&(r.ly-=h/2,v="middle"),r.totalWidth=Math.ceil(r.totalWidth),r.totalHeight=Math.ceil(r.totalHeight),r.lx=Math.round(r.lx),r.ly=Math.round(r.ly),a.autoMargin(t,A(e),{x:e.x,y:e.y,l:p*({right:1,center:.5}[y]||0),r:p*({left:1,center:.5}[y]||0),b:h*({top:1,middle:.5}[v]||0),t:h*({bottom:1,middle:.5}[v]||0)})}function A(t){return d.autoMarginIdRoot+t._index}function L(t,e,r,n){n=n||{};var a=t.select("."+d.itemRectClassName),i=t.select("."+d.itemTextClassName),l=e.borderwidth,c=r.index,u=e._dims;o.setTranslate(t,l+r.x,l+r.y);var p=-1!==["up","down"].indexOf(e.direction),h=n.height||(p?u.heights[c]:u.height1);a.attr({x:0,y:0,width:n.width||(p?u.width1:u.widths[c]),height:h});var g=e.font.size*f,y=(s.lineCount(i)-1)*g/2;s.positionText(i,d.textOffsetX,h/2-y+d.textOffsetY),p?r.y+=u.heights[c]+r.yPad:r.x+=u.widths[c]+r.xPad,r.index++}function C(t,e){t.attr(d.menuIndexAttrName,e||"-1").selectAll("g."+d.dropdownButtonClassName).remove()}e.exports=function(t){var e=t._fullLayout,r=l.filterVisible(e[d.name]);function i(e){a.autoMargin(t,A(e))}var o=e._menulayer.selectAll("g."+d.containerClassName).data(r.length>0?[0]:[]);if(o.enter().append("g").classed(d.containerClassName,!0).style("cursor","pointer"),o.exit().each(function(){n.select(this).selectAll("g."+d.headerGroupClassName).each(i)}).remove(),0!==r.length){var s=o.selectAll("g."+d.headerGroupClassName).data(r,h);s.enter().append("g").classed(d.headerGroupClassName,!0);for(var c=l.ensureSingle(o,"g",d.dropdownButtonGroupClassName,function(t){t.style("pointer-events","all")}),u=0;u<r.length;u++){var f=r[u];T(t,f)}var x="updatemenus"+e._uid,b=new p(t,c,x);s.enter().size()&&(c.node().parentNode.appendChild(c.node()),c.call(C)),s.exit().each(function(t){c.call(C),i(t)}).remove(),s.each(function(e){var r=n.select(this),i="dropdown"===e.type?c:null;a.manageCommandObserver(t,e,e.buttons,function(n){y(t,e,e.buttons[n.index],r,i,b,n.index,!0)}),"dropdown"===e.type?(v(t,r,c,b,e),g(c,e)&&m(t,r,c,b,e)):m(t,r,null,null,e)})}}},{"../../constants/alignment":143,"../../lib":163,"../../lib/svg_text_utils":184,"../../plot_api/plot_template":197,"../../plots/plots":239,"../color":45,"../drawing":70,"../legend/anchor_utils":97,"./constants":138,"./scrollbox":142,d3:10}],141:[function(t,e,r){arguments[4][135][0].apply(r,arguments)},{"./attributes":137,"./constants":138,"./defaults":139,"./draw":140,dup:135}],142:[function(t,e,r){"use strict";e.exports=l;var n=t("d3"),a=t("../color"),i=t("../drawing"),o=t("../../lib");function l(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}l.barWidth=2,l.barLength=20,l.barRadius=2,l.barPad=1,l.barColor="#808BA4",l.prototype.enable=function(t,e,r){var o=this.gd._fullLayout,s=o.width,c=o.height;this.position=t;var u,f,d,p,h=this.position.l,g=this.position.w,y=this.position.t,v=this.position.h,m=this.position.direction,x="down"===m,b="left"===m,_="up"===m,w=g,k=v;x||b||"right"===m||_||(this.position.direction="down",x=!0),x||_?(f=(u=h)+w,x?(d=y,k=(p=Math.min(d+k,c))-d):k=(p=y+k)-(d=Math.max(p-k,0))):(p=(d=y)+k,b?w=(f=h+w)-(u=Math.max(f-w,0)):(u=h,w=(f=Math.min(u+w,s))-u)),this._box={l:u,t:d,w:w,h:k};var M=g>w,T=l.barLength+2*l.barPad,A=l.barWidth+2*l.barPad,L=h,C=y+v;C+A>c&&(C=c-A);var S=this.container.selectAll("rect.scrollbar-horizontal").data(M?[0]:[]);S.exit().on(".drag",null).remove(),S.enter().append("rect").classed("scrollbar-horizontal",!0).call(a.fill,l.barColor),M?(this.hbar=S.attr({rx:l.barRadius,ry:l.barRadius,x:L,y:C,width:T,height:A}),this._hbarXMin=L+T/2,this._hbarTranslateMax=w-T):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var O=v>k,P=l.barWidth+2*l.barPad,D=l.barLength+2*l.barPad,z=h+g,E=y;z+P>s&&(z=s-P);var I=this.container.selectAll("rect.scrollbar-vertical").data(O?[0]:[]);I.exit().on(".drag",null).remove(),I.enter().append("rect").classed("scrollbar-vertical",!0).call(a.fill,l.barColor),O?(this.vbar=I.attr({rx:l.barRadius,ry:l.barRadius,x:z,y:E,width:P,height:D}),this._vbarYMin=E+D/2,this._vbarTranslateMax=k-D):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var N=this.id,R=u-.5,F=O?f+P+.5:f+.5,j=d-.5,B=M?p+A+.5:p+.5,H=o._topdefs.selectAll("#"+N).data(M||O?[0]:[]);if(H.exit().remove(),H.enter().append("clipPath").attr("id",N).append("rect"),M||O?(this._clipRect=H.select("rect").attr({x:Math.floor(R),y:Math.floor(j),width:Math.ceil(F)-Math.floor(R),height:Math.ceil(B)-Math.floor(j)}),this.container.call(i.setClipUrl,N),this.bg.attr({x:h,y:y,width:g,height:v})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(i.setClipUrl,null),delete this._clipRect),M||O){var q=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(q);var V=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault(),n.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));M&&this.hbar.on(".drag",null).call(V),O&&this.vbar.on(".drag",null).call(V)}this.setTranslate(e,r)},l.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(i.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},l.prototype._onBoxDrag=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t-=n.event.dx),this.vbar&&(e-=n.event.dy),this.setTranslate(t,e)},l.prototype._onBoxWheel=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t+=n.event.deltaY),this.vbar&&(e+=n.event.deltaY),this.setTranslate(t,e)},l.prototype._onBarDrag=function(){var t=this.translateX,e=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(o.constrain(n.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=e+this._vbarYMin,l=i+this._vbarTranslateMax;e=(o.constrain(n.event.y,i,l)-i)/(l-i)*(this.position.h-this._box.h)}this.setTranslate(t,e)},l.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=o.constrain(t||0,0,r),e=o.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(i.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var a=t/r;this.hbar.call(i.setTranslate,t+a*this._hbarTranslateMax,e)}if(this.vbar){var l=e/n;this.vbar.call(i.setTranslate,t,e+l*this._vbarTranslateMax)}}},{"../../lib":163,"../color":45,"../drawing":70,d3:10}],143:[function(t,e,r){"use strict";e.exports={FROM_BL:{left:0,center:.5,right:1,bottom:0,middle:.5,top:1},FROM_TL:{left:0,center:.5,right:1,bottom:1,middle:.5,top:0},FROM_BR:{left:1,center:.5,right:0,bottom:0,middle:.5,top:1},LINE_SPACING:1.3,MID_SHIFT:.35,OPPOSITE_SIDE:{left:"right",right:"left",top:"bottom",bottom:"top"}}},{}],144:[function(t,e,r){"use strict";e.exports={SHOW_PLACEHOLDER:100,HIDE_PLACEHOLDER:1e3,DBLCLICKDELAY:300,DESELECTDIM:.2}},{}],145:[function(t,e,r){"use strict";e.exports={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"}},{}],146:[function(t,e,r){"use strict";e.exports={entityToUnicode:{mu:"\u03bc","#956":"\u03bc",amp:"&","#28":"&",lt:"<","#60":"<",gt:">","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}}},{}],147:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],148:[function(t,e,r){"use strict";r.version="1.39.2",t("es6-promise").polyfill(),t("../build/plotcss"),t("./fonts/mathjax_config");for(var n=t("./registry"),a=r.register=n.register,i=t("./plot_api"),o=Object.keys(i),l=0;l<o.length;l++){var s=o[l];r[s]=i[s],a({moduleType:"apiMethod",name:s,fn:i[s]})}a(t("./traces/scatter")),a([t("./components/fx"),t("./components/legend"),t("./components/annotations"),t("./components/annotations3d"),t("./components/shapes"),t("./components/images"),t("./components/updatemenus"),t("./components/sliders"),t("./components/rangeslider"),t("./components/rangeselector"),t("./components/grid"),t("./components/errorbars")]),a([t("./locale-en"),t("./locale-en-us")]),r.Icons=t("../build/ploticon"),r.Plots=t("./plots/plots"),r.Fx=t("./components/fx"),r.Snapshot=t("./snapshot"),r.PlotSchema=t("./plot_api/plot_schema"),r.Queue=t("./lib/queue"),r.d3=t("d3")},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":38,"./components/annotations3d":43,"./components/errorbars":76,"./components/fx":87,"./components/grid":91,"./components/images":96,"./components/legend":105,"./components/rangeselector":116,"./components/rangeslider":122,"./components/shapes":130,"./components/sliders":135,"./components/updatemenus":141,"./fonts/mathjax_config":149,"./lib/queue":177,"./locale-en":188,"./locale-en-us":187,"./plot_api":192,"./plot_api/plot_schema":196,"./plots/plots":239,"./registry":247,"./snapshot":252,"./traces/scatter":325,d3:10,"es6-promise":11}],149:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],150:[function(t,e,r){"use strict";var n=Math.PI;r.deg2rad=function(t){return t/180*n},r.rad2deg=function(t){return t/n*180},r.wrap360=function(t){var e=t%360;return e<0?e+360:e},r.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t}},{}],151:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../constants/numerical").BADNUM,i=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;e.exports=function(t){return"string"==typeof t&&(t=t.replace(i,"")),n(t)?Number(t):a}},{"../constants/numerical":145,"fast-isnumeric":13}],152:[function(t,e,r){"use strict";e.exports=function(t){var e=t._fullLayout;e._glcanvas&&e._glcanvas.size()&&e._glcanvas.each(function(t){t.regl&&t.regl.clear({color:!0,depth:!0})})}},{}],153:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("tinycolor2"),i=t("../plots/attributes"),o=t("../components/colorscale/get_scale"),l=(Object.keys(t("../components/colorscale/scales")),t("./nested_property")),s=t("./regex").counter,c=t("../constants/interactions").DESELECTDIM,u=t("./angles").wrap180,f=t("./is_array").isArrayOrTypedArray;function d(t,e){var n=r.valObjectMeta[e.valType];if(e.arrayOk&&f(t))return!0;if(n.validateFunction)return n.validateFunction(t,e);var a={},i=a,o={set:function(t){i=t}};return n.coerceFunction(t,o,a,e),i!==a}r.valObjectMeta={data_array:{coerceFunction:function(t,e,r){f(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)},validateFunction:function(t,e){e.coerceNumber&&(t=+t);for(var r=e.values,n=0;n<r.length;n++){var a=String(r[n]);if("/"===a.charAt(0)&&"/"===a.charAt(a.length-1)){if(new RegExp(a.substr(1,a.length-2)).test(t))return!0}else if(t===r[n])return!0}return!1}},boolean:{coerceFunction:function(t,e,r){!0===t||!1===t?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,a){!n(t)||void 0!==a.min&&t<a.min||void 0!==a.max&&t>a.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,a){t%1||!n(t)||void 0!==a.min&&t<a.min||void 0!==a.max&&t>a.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var a="number"==typeof t;!0!==n.strict&&a?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){a(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return a(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?e.set(u(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r,n){var a=n.regex||s(r);"string"==typeof t&&a.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!s(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var a=t.split("+"),i=0;i<a.length;){var o=a[i];-1===n.flags.indexOf(o)||a.indexOf(o)<i?a.splice(i,1):i++}a.length?e.set(a.join("+")):e.set(r)}else e.set(t);else e.set(r)}},any:{coerceFunction:function(t,e,r){void 0===t?e.set(r):e.set(t)}},info_array:{coerceFunction:function(t,e,n,a){function i(t,e,n){var a,i={set:function(t){a=t}};return void 0===n&&(n=e.dflt),r.valObjectMeta[e.valType].coerceFunction(t,i,n,e),a}var o=2===a.dimensions||"1-2"===a.dimensions&&Array.isArray(t)&&Array.isArray(t[0]);if(Array.isArray(t)){var l,s,c,u,f,d,p=a.items,h=[],g=Array.isArray(p),y=g&&o&&Array.isArray(p[0]),v=o&&g&&!y,m=g&&!v?p.length:t.length;if(n=Array.isArray(n)?n:[],o)for(l=0;l<m;l++)for(h[l]=[],c=Array.isArray(t[l])?t[l]:[],f=v?p.length:g?p[l].length:c.length,s=0;s<f;s++)u=v?p[s]:g?p[l][s]:p,void 0!==(d=i(c[s],u,(n[l]||[])[s]))&&(h[l][s]=d);else for(l=0;l<m;l++)void 0!==(d=i(t[l],g?p[l]:p,n[l]))&&(h[l]=d);e.set(h)}else e.set(n)},validateFunction:function(t,e){if(!Array.isArray(t))return!1;var r=e.items,n=Array.isArray(r),a=2===e.dimensions;if(!e.freeLength&&t.length!==r.length)return!1;for(var i=0;i<t.length;i++)if(a){if(!Array.isArray(t[i])||!e.freeLength&&t[i].length!==r[i].length)return!1;for(var o=0;o<t[i].length;o++)if(!d(t[i][o],n?r[i][o]:r))return!1}else if(!d(t[i],n?r[i]:r))return!1;return!0}}},r.coerce=function(t,e,n,a,i){var o=l(n,a).get(),s=l(t,a),c=l(e,a),u=s.get(),p=e._template;if(void 0===u&&p&&(u=l(p,a).get(),p=0),void 0===i&&(i=o.dflt),o.arrayOk&&f(u))return c.set(u),u;var h=r.valObjectMeta[o.valType].coerceFunction;h(u,c,i,o);var g=c.get();return p&&g===i&&!d(u,o)&&(h(u=l(p,a).get(),c,i,o),g=c.get()),g},r.coerce2=function(t,e,n,a,i){var o=l(t,a),s=r.coerce(t,e,n,a,i),c=o.get();return null!=c&&s},r.coerceFont=function(t,e,r){var n={};return r=r||{},n.family=t(e+".family",r.family),n.size=t(e+".size",r.size),n.color=t(e+".color",r.color),n},r.coerceHoverinfo=function(t,e,n){var a,o=e._module.attributes,l=o.hoverinfo?o:i,s=l.hoverinfo;if(1===n._dataLength){var c="all"===s.dflt?s.flags.slice():s.dflt.split("+");c.splice(c.indexOf("name"),1),a=c.join("+")}return r.coerce(t,e,l,"hoverinfo",a)},r.coerceSelectionMarkerOpacity=function(t,e){if(t.marker){var r,n,a=t.marker.opacity;if(void 0!==a)f(a)||t.selected||t.unselected||(r=a,n=c*a),e("selected.marker.opacity",r),e("unselected.marker.opacity",n)}},r.validate=d},{"../components/colorscale/get_scale":58,"../components/colorscale/scales":64,"../constants/interactions":144,"../plots/attributes":204,"./angles":150,"./is_array":164,"./nested_property":171,"./regex":178,"fast-isnumeric":13,tinycolor2:28}],154:[function(t,e,r){"use strict";var n,a,i=t("d3"),o=t("fast-isnumeric"),l=t("./loggers"),s=t("./mod"),c=t("../constants/numerical"),u=c.BADNUM,f=c.ONEDAY,d=c.ONEHOUR,p=c.ONEMIN,h=c.ONESEC,g=c.EPOCHJD,y=t("../registry"),v=i.time.format.utc,m=/^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m,x=/^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m,b=(new Date).getFullYear()-70;function _(t){return t&&y.componentsRegistry.calendars&&"string"==typeof t&&"gregorian"!==t}function w(t,e){return String(t+Math.pow(10,e)).substr(1)}r.dateTick0=function(t,e){return _(t)?e?y.getComponentMethod("calendars","CANONICAL_SUNDAY")[t]:y.getComponentMethod("calendars","CANONICAL_TICK")[t]:e?"2000-01-02":"2000-01-01"},r.dfltRange=function(t){return _(t)?y.getComponentMethod("calendars","DFLTRANGE")[t]:["2000-01-01","2001-01-01"]},r.isJSDate=function(t){return"object"==typeof t&&null!==t&&"function"==typeof t.getTime},r.dateTime2ms=function(t,e){if(r.isJSDate(t)){var i=t.getTimezoneOffset()*p,o=(t.getUTCMinutes()-t.getMinutes())*p+(t.getUTCSeconds()-t.getSeconds())*h+(t.getUTCMilliseconds()-t.getMilliseconds());if(o){var l=3*p;i=i-l/2+s(o-i+l/2,l)}return(t=Number(t)-i)>=n&&t<=a?t:u}if("string"!=typeof t&&"number"!=typeof t)return u;t=String(t);var c=_(e),v=t.charAt(0);!c||"G"!==v&&"g"!==v||(t=t.substr(1),e="");var w=c&&"chinese"===e.substr(0,7),k=t.match(w?x:m);if(!k)return u;var M=k[1],T=k[3]||"1",A=Number(k[5]||1),L=Number(k[7]||0),C=Number(k[9]||0),S=Number(k[11]||0);if(c){if(2===M.length)return u;var O;M=Number(M);try{var P=y.getComponentMethod("calendars","getCal")(e);if(w){var D="i"===T.charAt(T.length-1);T=parseInt(T,10),O=P.newDate(M,P.toMonthIndex(M,T,D),A)}else O=P.newDate(M,Number(T),A)}catch(t){return u}return O?(O.toJD()-g)*f+L*d+C*p+S*h:u}M=2===M.length?(Number(M)+2e3-b)%100+b:Number(M),T-=1;var z=new Date(Date.UTC(2e3,T,A,L,C));return z.setUTCFullYear(M),z.getUTCMonth()!==T?u:z.getUTCDate()!==A?u:z.getTime()+S*h},n=r.MIN_MS=r.dateTime2ms("-9999"),a=r.MAX_MS=r.dateTime2ms("9999-12-31 23:59:59.9999"),r.isDateTime=function(t,e){return r.dateTime2ms(t,e)!==u};var k=90*f,M=3*d,T=5*p;function A(t,e,r,n,a){if((e||r||n||a)&&(t+=" "+w(e,2)+":"+w(r,2),(n||a)&&(t+=":"+w(n,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;t+="."+w(a,i)}return t}r.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=n&&t<=a))return u;e||(e=0);var i,o,l,c,m,x,b=Math.floor(10*s(t+.05,1)),w=Math.round(t-b/10);if(_(r)){var L=Math.floor(w/f)+g,C=Math.floor(s(t,f));try{i=y.getComponentMethod("calendars","getCal")(r).fromJD(L).formatDate("yyyy-mm-dd")}catch(t){i=v("G%Y-%m-%d")(new Date(w))}if("-"===i.charAt(0))for(;i.length<11;)i="-0"+i.substr(1);else for(;i.length<10;)i="0"+i;o=e<k?Math.floor(C/d):0,l=e<k?Math.floor(C%d/p):0,c=e<M?Math.floor(C%p/h):0,m=e<T?C%h*10+b:0}else x=new Date(w),i=v("%Y-%m-%d")(x),o=e<k?x.getUTCHours():0,l=e<k?x.getUTCMinutes():0,c=e<M?x.getUTCSeconds():0,m=e<T?10*x.getUTCMilliseconds()+b:0;return A(i,o,l,c,m)},r.ms2DateTimeLocal=function(t){if(!(t>=n+f&&t<=a-f))return u;var e=Math.floor(10*s(t+.05,1)),r=new Date(Math.round(t-e/10));return A(i.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+e)},r.cleanDate=function(t,e,n){if(r.isJSDate(t)||"number"==typeof t){if(_(n))return l.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=r.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!r.isDateTime(t,n))return l.error("unrecognized date",t),e;return t};var L=/%\d?f/g;function C(t,e,r,n){t=t.replace(L,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(e+.05));if(_(n))try{t=y.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(a)}var S=[59,59.9,59.99,59.999,59.9999];r.formatDate=function(t,e,r,n,a,i){if(a=_(a)&&a,!e)if("y"===r)e=i.year;else if("m"===r)e=i.month;else{if("d"!==r)return function(t,e){var r=s(t+.05,f),n=w(Math.floor(r/d),2)+":"+w(s(Math.floor(r/p),60),2);if("M"!==e){o(e)||(e=0);var a=(100+Math.min(s(t/h,60),S[e])).toFixed(e).substr(1);e>0&&(a=a.replace(/0+$/,"").replace(/[\.]$/,"")),n+=":"+a}return n}(t,r)+"\n"+C(i.dayMonthYear,t,n,a);e=i.dayMonth+"\n"+i.year}return C(e,t,n,a)};var O=3*f;r.incrementMonth=function(t,e,r){r=_(r)&&r;var n=s(t,f);if(t=Math.round(t-n),r)try{var a=Math.round(t/f)+g,i=y.getComponentMethod("calendars","getCal")(r),o=i.fromJD(a);return e%12?i.add(o,e,"m"):i.add(o,e/12,"y"),(o.toJD()-g)*f+n}catch(e){l.error("invalid ms "+t+" in calendar "+r)}var c=new Date(t+O);return c.setUTCMonth(c.getUTCMonth()+e)+n-O},r.findExactDates=function(t,e){for(var r,n,a=0,i=0,l=0,s=0,c=_(e)&&y.getComponentMethod("calendars","getCal")(e),u=0;u<t.length;u++)if(n=t[u],o(n)){if(!(n%f))if(c)try{1===(r=c.fromJD(n/f+g)).day()?1===r.month()?a++:i++:l++}catch(t){}else 1===(r=new Date(n)).getUTCDate()?0===r.getUTCMonth()?a++:i++:l++}else s++;l+=i+=a;var d=t.length-s;return{exactYears:a/d,exactMonths:i/d,exactDays:l/d}}},{"../constants/numerical":145,"../registry":247,"./loggers":168,"./mod":170,d3:10,"fast-isnumeric":13}],155:[function(t,e,r){"use strict";e.exports=function(t,e){return Array.isArray(t)||(t=[]),t.length=e,t}},{}],156:[function(t,e,r){"use strict";var n=t("events").EventEmitter,a={init:function(t){if(t._ev instanceof n)return t;var e=new n,r=new n;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,a){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,a),e.emit(n,a),r.emit(n,a)},t},triggerHandler:function(t,e,r){var n,a;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var i=t._ev;if(!i)return n;var o,l=i._events[e];if(!l)return n;function s(t){return t.listener?(i.removeListener(e,t.listener),t.fired?void 0:(t.fired=!0,t.listener.apply(i,[r]))):t.apply(i,[r])}for(l=Array.isArray(l)?l:[l],o=0;o<l.length-1;o++)s(l[o]);return a=s(l[o]),void 0!==n?n:a},purge:function(t){return delete t._ev,delete t.on,delete t.once,delete t.removeListener,delete t.removeAllListeners,delete t.emit,delete t._ev,delete t._internalEv,delete t._internalOn,delete t._internalOnce,delete t._removeInternalListener,delete t._removeAllInternalListeners,t}};e.exports=a},{events:12}],157:[function(t,e,r){"use strict";var n=t("./is_plain_object.js"),a=Array.isArray;function i(t,e,r,o){var l,s,c,u,f,d,p=t[0],h=t.length;if(2===h&&a(p)&&a(t[1])&&0===p.length){if(function(t,e){var r,n;for(r=0;r<t.length;r++){if(null!==(n=t[r])&&"object"==typeof n)return!1;void 0!==n&&(e[r]=n)}return!0}(t[1],p))return p;p.splice(0,p.length)}for(var g=1;g<h;g++)for(s in l=t[g])c=p[s],u=l[s],o&&a(u)?p[s]=u:e&&u&&(n(u)||(f=a(u)))?(f?(f=!1,d=c&&a(c)?c:[]):d=c&&n(c)?c:{},p[s]=i([d,u],e,r,o)):("undefined"!=typeof u||r)&&(p[s]=u);return p}r.extendFlat=function(){return i(arguments,!1,!1,!1)},r.extendDeep=function(){return i(arguments,!0,!1,!1)},r.extendDeepAll=function(){return i(arguments,!0,!0,!1)},r.extendDeepNoArrays=function(){return i(arguments,!0,!1,!0)}},{"./is_plain_object.js":165}],158:[function(t,e,r){"use strict";e.exports=function(t){for(var e={},r=[],n=0,a=0;a<t.length;a++){var i=t[a];1!==e[i]&&(e[i]=1,r[n++]=i)}return r}},{}],159:[function(t,e,r){"use strict";function n(t){return!0===t.visible}function a(t){return!0===t[0].trace.visible}e.exports=function(t){for(var e,r=(e=t,Array.isArray(e)&&Array.isArray(e[0])&&e[0][0]&&e[0][0].trace?a:n),i=[],o=0;o<t.length;o++){var l=t[o];r(l)&&i.push(l)}return i}},{}],160:[function(t,e,r){"use strict";var n,a,i,o=t("./mod");function l(t,e,r,n,a,i,o,l){var s=r-t,c=a-t,u=o-a,f=n-e,d=i-e,p=l-i,h=s*p-u*f;if(0===h)return null;var g=(c*p-u*d)/h,y=(c*f-s*d)/h;return y<0||y>1||g<0||g>1?null:{x:t+s*g,y:e+f*g}}function s(t,e,r,n,a){var i=n*t+a*e;if(i<0)return n*n+a*a;if(i>r){var o=n-t,l=a-e;return o*o+l*l}var s=n*e-a*t;return s*s/r}r.segmentsIntersect=l,r.segmentDistance=function(t,e,r,n,a,i,o,c){if(l(t,e,r,n,a,i,o,c))return 0;var u=r-t,f=n-e,d=o-a,p=c-i,h=u*u+f*f,g=d*d+p*p,y=Math.min(s(u,f,h,a-t,i-e),s(u,f,h,o-t,c-e),s(d,p,g,t-a,e-i),s(d,p,g,r-a,n-i));return Math.sqrt(y)},r.getTextLocation=function(t,e,r,l){if(t===a&&l===i||(n={},a=t,i=l),n[r])return n[r];var s=t.getPointAtLength(o(r-l/2,e)),c=t.getPointAtLength(o(r+l/2,e)),u=Math.atan((c.y-s.y)/(c.x-s.x)),f=t.getPointAtLength(o(r,e)),d={x:(4*f.x+s.x+c.x)/6,y:(4*f.y+s.y+c.y)/6,theta:u};return n[r]=d,d},r.clearLocationCache=function(){a=null},r.getVisibleSegment=function(t,e,r){var n,a,i=e.left,o=e.right,l=e.top,s=e.bottom,c=0,u=t.getTotalLength(),f=u;function d(e){var r=t.getPointAtLength(e);0===e?n=r:e===u&&(a=r);var c=r.x<i?i-r.x:r.x>o?r.x-o:0,f=r.y<l?l-r.y:r.y>s?r.y-s:0;return Math.sqrt(c*c+f*f)}for(var p=d(c);p;){if((c+=p+r)>f)return;p=d(c)}for(p=d(f);p;){if(c>(f-=p+r))return;p=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(n.x-a.x)<.1&&Math.abs(n.y-a.y)<.1}},r.findPointOnPath=function(t,e,r,n){for(var a,i,o,l=(n=n||{}).pathLength||t.getTotalLength(),s=n.tolerance||.001,c=n.iterationLimit||30,u=t.getPointAtLength(0)[r]>t.getPointAtLength(l)[r]?-1:1,f=0,d=0,p=l;f<c;){if(a=(d+p)/2,o=(i=t.getPointAtLength(a))[r]-e,Math.abs(o)<s)return i;u*o>0?p=a:d=a,f++}return i}},{"./mod":170}],161:[function(t,e,r){"use strict";e.exports=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null==t)throw new Error("DOM element provided is null or undefined");return t}},{}],162:[function(t,e,r){"use strict";e.exports=function(t){return t}},{}],163:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../constants/numerical"),o=i.FP_SAFE,l=i.BADNUM,s=e.exports={};s.nestedProperty=t("./nested_property"),s.keyedContainer=t("./keyed_container"),s.relativeAttr=t("./relative_attr"),s.isPlainObject=t("./is_plain_object"),s.mod=t("./mod"),s.toLogRange=t("./to_log_range"),s.relinkPrivateKeys=t("./relink_private"),s.ensureArray=t("./ensure_array");var c=t("./is_array");s.isTypedArray=c.isTypedArray,s.isArrayOrTypedArray=c.isArrayOrTypedArray,s.isArray1D=c.isArray1D;var u=t("./coerce");s.valObjectMeta=u.valObjectMeta,s.coerce=u.coerce,s.coerce2=u.coerce2,s.coerceFont=u.coerceFont,s.coerceHoverinfo=u.coerceHoverinfo,s.coerceSelectionMarkerOpacity=u.coerceSelectionMarkerOpacity,s.validate=u.validate;var f=t("./dates");s.dateTime2ms=f.dateTime2ms,s.isDateTime=f.isDateTime,s.ms2DateTime=f.ms2DateTime,s.ms2DateTimeLocal=f.ms2DateTimeLocal,s.cleanDate=f.cleanDate,s.isJSDate=f.isJSDate,s.formatDate=f.formatDate,s.incrementMonth=f.incrementMonth,s.dateTick0=f.dateTick0,s.dfltRange=f.dfltRange,s.findExactDates=f.findExactDates,s.MIN_MS=f.MIN_MS,s.MAX_MS=f.MAX_MS;var d=t("./search");s.findBin=d.findBin,s.sorterAsc=d.sorterAsc,s.sorterDes=d.sorterDes,s.distinctVals=d.distinctVals,s.roundUp=d.roundUp;var p=t("./stats");s.aggNums=p.aggNums,s.len=p.len,s.mean=p.mean,s.midRange=p.midRange,s.variance=p.variance,s.stdev=p.stdev,s.interp=p.interp;var h=t("./matrix");s.init2dArray=h.init2dArray,s.transposeRagged=h.transposeRagged,s.dot=h.dot,s.translationMatrix=h.translationMatrix,s.rotationMatrix=h.rotationMatrix,s.rotationXYMatrix=h.rotationXYMatrix,s.apply2DTransform=h.apply2DTransform,s.apply2DTransform2=h.apply2DTransform2;var g=t("./angles");s.deg2rad=g.deg2rad,s.rad2deg=g.rad2deg,s.wrap360=g.wrap360,s.wrap180=g.wrap180;var y=t("./geometry2d");s.segmentsIntersect=y.segmentsIntersect,s.segmentDistance=y.segmentDistance,s.getTextLocation=y.getTextLocation,s.clearLocationCache=y.clearLocationCache,s.getVisibleSegment=y.getVisibleSegment,s.findPointOnPath=y.findPointOnPath;var v=t("./extend");s.extendFlat=v.extendFlat,s.extendDeep=v.extendDeep,s.extendDeepAll=v.extendDeepAll,s.extendDeepNoArrays=v.extendDeepNoArrays;var m=t("./loggers");s.log=m.log,s.warn=m.warn,s.error=m.error;var x=t("./regex");s.counterRegex=x.counter;var b=t("./throttle");function _(t){var e={};for(var r in t)for(var n=t[r],a=0;a<n.length;a++)e[n[a]]=+r;return e}s.throttle=b.throttle,s.throttleDone=b.done,s.clearThrottle=b.clear,s.getGraphDiv=t("./get_graph_div"),s._=t("./localize"),s.notifier=t("./notifier"),s.filterUnique=t("./filter_unique"),s.filterVisible=t("./filter_visible"),s.pushUnique=t("./push_unique"),s.cleanNumber=t("./clean_number"),s.ensureNumber=function(t){return a(t)?(t=Number(t))<-o||t>o?l:a(t)?Number(t):l:l},s.isIndex=function(t,e){return!(void 0!==e&&t>=e)&&(a(t)&&t>=0&&t%1==0)},s.noop=t("./noop"),s.identity=t("./identity"),s.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;a<e.length;a++){var i=e[a],o=s.nestedProperty(t,i.replace("?",r)),l=s.nestedProperty(t,i.replace("?",n)),c=o.get();o.set(l.get()),l.set(c)}},s.raiseToTop=function(t){t.parentNode.appendChild(t)},s.cancelTransition=function(t){return t.transition().duration(0)},s.constrain=function(t,e,r){return e>r?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},s.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},s.simpleMap=function(t,e,r,n){for(var a=t.length,i=new Array(a),o=0;o<a;o++)i[o]=e(t[o],r,n);return i},s.randstr=function t(e,r,n,a){if(n||(n=16),void 0===r&&(r=24),r<=0)return"0";var i,o,l=Math.log(Math.pow(2,r))/Math.log(n),c="";for(i=2;l===1/0;i*=2)l=Math.log(Math.pow(2,r/i))/Math.log(n)*i;var u=l-Math.floor(l);for(i=0;i<Math.floor(l);i++)c=Math.floor(Math.random()*n).toString(n)+c;u&&(o=Math.pow(n,u),c=Math.floor(Math.random()*o).toString(n)+c);var f=parseInt(c,n);return e&&e[c]||f!==1/0&&f>=Math.pow(2,r)?a>10?(s.warn("randstr failed uniqueness"),c):t(e,r,n,(a||0)+1):c},s.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},s.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,a,i,o=t.length,l=2*o,s=2*e-1,c=new Array(s),u=new Array(o);for(r=0;r<s;r++)c[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;r<o;r++){for(i=0,n=0;n<s;n++)(a=r+n+1-e)<-o?a-=l*Math.round(a/l):a>=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=t[a]*c[n];u[r]=i}return u},s.syncOrAsync=function(t,e,r){var n;function a(){return s.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(a).then(void 0,s.promiseError);return r&&r(e)},s.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},s.noneOrAll=function(t,e,r){if(t){var n,a=!1,i=!0;for(n=0;n<r.length;n++)null!=t[r[n]]?a=!0:i=!1;if(a&&!i)for(n=0;n<r.length;n++)t[r[n]]=e[r[n]]}},s.mergeArray=function(t,e,r){if(s.isArrayOrTypedArray(t))for(var n=Math.min(t.length,e.length),a=0;a<n;a++)e[a][r]=t[a]},s.fillArray=function(t,e,r,n){if(n=n||s.identity,s.isArrayOrTypedArray(t))for(var a=0;a<e.length;a++)e[a][r]=n(t[a])},s.castOption=function(t,e,r,n){n=n||s.identity;var a=s.nestedProperty(t,r).get();return s.isArrayOrTypedArray(a)?Array.isArray(e)&&s.isArrayOrTypedArray(a[e[0]])?n(a[e[0]][e[1]]):n(a[e]):a},s.extractOption=function(t,e,r,n){if(r in t)return t[r];var a=s.nestedProperty(e,n).get();return Array.isArray(a)?void 0:a},s.tagSelected=function(t,e,r){var n,a,i=e.selectedpoints,o=e._indexToPoints;o&&(n=_(o));for(var l=0;l<i.length;l++){var c=i[l];if(s.isIndex(c)){var u=n?n[c]:c,f=r?r[u]:u;void 0!==(a=f)&&a<t.length&&(t[f].selected=1)}}},s.selIndices2selPoints=function(t){var e=t.selectedpoints,r=t._indexToPoints;if(r){for(var n=_(r),a=[],i=0;i<e.length;i++){var o=e[i];if(s.isIndex(o)){var l=n[o];s.isIndex(l)&&a.push(l)}}return a}return e},s.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=s.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},s.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,i,o=Object.keys(t);for(n=0;n<o.length;n++)i=t[a=o[n]],"_"!==a.charAt(0)&&"function"!=typeof i&&("module"===a?r[a]=i:Array.isArray(i)?r[a]=i.slice(0,3):r[a]=i&&"object"==typeof i?s.minExtend(t[a],e[a]):i);for(o=Object.keys(e),n=0;n<o.length;n++)"object"==typeof(i=e[a=o[n]])&&a in r&&"object"==typeof r[a]||(r[a]=i);return r},s.titleCase=function(t){return t.charAt(0).toUpperCase()+t.substr(1)},s.containsAny=function(t,e){for(var r=0;r<e.length;r++)if(-1!==t.indexOf(e[r]))return!0;return!1},s.isPlotDiv=function(t){var e=n.select(t);return e.node()instanceof HTMLElement&&e.size()&&e.classed("js-plotly-plot")},s.removeElement=function(t){var e=t&&t.parentNode;e&&e.removeChild(t)},s.addStyleRule=function(t,e){if(!s.styleSheet){var r=document.createElement("style");r.appendChild(document.createTextNode("")),document.head.appendChild(r),s.styleSheet=r.sheet}var n=s.styleSheet;n.insertRule?n.insertRule(t+"{"+e+"}",0):n.addRule?n.addRule(t,e,0):s.warn("addStyleRule failed")},s.isIE=function(){return"undefined"!=typeof window.navigator.msSaveBlob},s.isD3Selection=function(t){return t&&"function"==typeof t.classed},s.ensureSingle=function(t,e,r,n){var a=t.select(e+(r?"."+r:""));if(a.size())return a;var i=t.append(e).classed(r,!0);return n&&i.call(n),i},s.ensureSingleById=function(t,e,r,n){var a=t.select(e+"#"+r);if(a.size())return a;var i=t.append(e).attr("id",r);return n&&i.call(n),i},s.objectFromPath=function(t,e){for(var r,n=t.split("."),a=r={},i=0;i<n.length;i++){var o=n[i],l=null,s=n[i].match(/(.*)\[([0-9]+)\]/);s?(o=s[1],l=s[2],r=r[o]=[],i===n.length-1?r[l]=e:r[l]={},r=r[l]):(i===n.length-1?r[o]=e:r[o]={},r=r[o])}return a};var w=/^([^\[\.]+)\.(.+)?/,k=/^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;s.expandObjectPaths=function(t){var e,r,n,a,i,o,l;if("object"==typeof t&&!Array.isArray(t))for(r in t)t.hasOwnProperty(r)&&((e=r.match(w))?(a=t[r],n=e[1],delete t[r],t[n]=s.extendDeepNoArrays(t[n]||{},s.objectFromPath(r,s.expandObjectPaths(a))[n])):(e=r.match(k))?(a=t[r],n=e[1],i=parseInt(e[2]),delete t[r],t[n]=t[n]||[],"."===e[3]?(l=e[4],o=t[n][i]=t[n][i]||{},s.extendDeepNoArrays(o,s.objectFromPath(l,s.expandObjectPaths(a)))):t[n][i]=s.expandObjectPaths(a)):t[r]=s.expandObjectPaths(t[r]));return t},s.numSeparate=function(t,e,r){if(r||(r=!1),"string"!=typeof e||0===e.length)throw new Error("Separator string required for formatting!");"number"==typeof t&&(t=String(t));var n=/(\d+)(\d{3})/,a=e.charAt(0),i=e.charAt(1),o=t.split("."),l=o[0],s=o.length>1?a+o[1]:"";if(i&&(o.length>1||l.length>4||r))for(;n.test(l);)l=l.replace(n,"$1"+i+"$2");return l+s};var M=/%{([^\s%{}]*)}/g,T=/^\w*$/;s.templateString=function(t,e){var r={};return t.replace(M,function(t,n){return T.test(n)?e[n]||"":(r[n]=r[n]||s.nestedProperty(e,n).get,r[n]()||"")})};s.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,a=0,i=0;i<r;i++){var o=t.charCodeAt(i)||0,l=e.charCodeAt(i)||0,s=o>=48&&o<=57,c=l>=48&&l<=57;if(s&&(n=10*n+o-48),c&&(a=10*a+l-48),!s||!c){if(n!==a)return n-a;if(o!==l)return o-l}}return a-n};var A=2e9;s.seedPseudoRandom=function(){A=2e9},s.pseudoRandom=function(){var t=A;return A=(69069*A+1)%4294967296,Math.abs(A-t)<429496729?s.pseudoRandom():A/4294967296}},{"../constants/numerical":145,"./angles":150,"./clean_number":151,"./coerce":153,"./dates":154,"./ensure_array":155,"./extend":157,"./filter_unique":158,"./filter_visible":159,"./geometry2d":160,"./get_graph_div":161,"./identity":162,"./is_array":164,"./is_plain_object":165,"./keyed_container":166,"./localize":167,"./loggers":168,"./matrix":169,"./mod":170,"./nested_property":171,"./noop":172,"./notifier":173,"./push_unique":176,"./regex":178,"./relative_attr":179,"./relink_private":180,"./search":181,"./stats":183,"./throttle":185,"./to_log_range":186,d3:10,"fast-isnumeric":13}],164:[function(t,e,r){"use strict";var n="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer:{isView:function(){return!1}},a="undefined"==typeof DataView?function(){}:DataView;function i(t){return n.isView(t)&&!(t instanceof a)}function o(t){return Array.isArray(t)||i(t)}e.exports={isTypedArray:i,isArrayOrTypedArray:o,isArray1D:function(t){return!o(t[0])}}},{}],165:[function(t,e,r){"use strict";e.exports=function(t){return window&&window.process&&window.process.versions?"[object Object]"===Object.prototype.toString.call(t):"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],166:[function(t,e,r){"use strict";var n=t("./nested_property"),a=/^\w*$/;e.exports=function(t,e,r,i){var o,l,s;r=r||"name",i=i||"value";var c={};e&&e.length?(s=n(t,e),l=s.get()):l=t,e=e||"";var u={};if(l)for(o=0;o<l.length;o++)u[l[o][r]]=o;var f=a.test(i),d={set:function(t,e){var a=null===e?4:0;if(!l){if(!s||4===a)return;l=[],s.set(l)}var o=u[t];if(void 0===o){if(4===a)return;a|=3,o=l.length,u[t]=o}else e!==(f?l[o][i]:n(l[o],i).get())&&(a|=2);var p=l[o]=l[o]||{};return p[r]=t,f?p[i]=e:n(p,i).set(e),null!==e&&(a&=-5),c[o]=c[o]|a,d},get:function(t){if(l){var e=u[t];return void 0===e?void 0:f?l[e][i]:n(l[e],i).get()}},rename:function(t,e){var n=u[t];return void 0===n?d:(c[n]=1|c[n],u[e]=n,delete u[t],l[n][r]=e,d)},remove:function(t){var e=u[t];if(void 0===e)return d;var a=l[e];if(Object.keys(a).length>2)return c[e]=2|c[e],d.set(t,null);if(f){for(o=e;o<l.length;o++)c[o]=3|c[o];for(o=e;o<l.length;o++)u[l[o][r]]--;l.splice(e,1),delete u[t]}else n(a,i).set(null),c[e]=6|c[e];return d},constructUpdate:function(){for(var t,a,o={},s=Object.keys(c),u=0;u<s.length;u++)a=s[u],t=e+"["+a+"]",l[a]?(1&c[a]&&(o[t+"."+r]=l[a][r]),2&c[a]&&(o[t+"."+i]=f?4&c[a]?null:l[a][i]:4&c[a]?null:n(l[a],i).get())):o[t]=null;return o}};return d}},{"./nested_property":171}],167:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t,e){for(var r=t._context.locale,a=0;a<2;a++){for(var i=t._context.locales,o=0;o<2;o++){var l=(i[r]||{}).dictionary;if(l){var s=l[e];if(s)return s}i=n.localeRegistry}var c=r.split("-")[0];if(c===r)break;r=c}return e}},{"../registry":247}],168:[function(t,e,r){"use strict";var n=t("../plot_api/plot_config"),a=e.exports={};function i(t,e){if(t.apply)t.apply(t,e);else for(var r=0;r<e.length;r++)t(e[r])}a.log=function(){if(n.logging>1){for(var t=["LOG:"],e=0;e<arguments.length;e++)t.push(arguments[e]);i(console.trace||console.log,t)}},a.warn=function(){if(n.logging>0){for(var t=["WARN:"],e=0;e<arguments.length;e++)t.push(arguments[e]);i(console.trace||console.log,t)}},a.error=function(){if(n.logging>0){for(var t=["ERROR:"],e=0;e<arguments.length;e++)t.push(arguments[e]);i(console.error,t)}}},{"../plot_api/plot_config":195}],169:[function(t,e,r){"use strict";r.init2dArray=function(t,e){for(var r=new Array(t),n=0;n<t;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,a=t.length;for(e=0;e<a;e++)n=Math.max(n,t[e].length);var i=new Array(n);for(e=0;e<n;e++)for(i[e]=new Array(a),r=0;r<a;r++)i[e][r]=t[r][e];return i},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,a,i=t.length;if(t[0].length)for(n=new Array(i),a=0;a<i;a++)n[a]=r.dot(t[a],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),a=0;a<o.length;a++)n[a]=r.dot(t,o[a])}else for(n=0,a=0;a<i;a++)n+=t[a]*e[a];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],170:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t%e;return r<0?r+e:r}},{}],171:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("./is_array").isArrayOrTypedArray;e.exports=function(t,e){if(n(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,c=e.split(".");s<c.length;){if(r=String(c[s]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/)){if(r[1])c[s]=r[1];else{if(0!==s)throw"bad property string";c.splice(0,1)}for(i=r[2].substr(1,r[2].length-2).split("]["),o=0;o<i.length;o++)s++,c.splice(s,0,Number(i[o]))}s++}return"object"!=typeof t?function(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}(t,e,c):{set:l(t,c,e),get:function t(e,r){return function(){var n,i,o,l,s,c=e;for(l=0;l<r.length-1;l++){if(-1===(n=r[l])){for(i=!0,o=[],s=0;s<c.length;s++)o[s]=t(c[s],r.slice(l+1))(),o[s]!==o[0]&&(i=!1);return i?o[0]:o}if("number"==typeof n&&!a(c))return;if("object"!=typeof(c=c[n])||null===c)return}if("object"==typeof c&&null!==c&&null!==(o=c[r[l]]))return o}}(t,c),astr:e,parts:c,obj:t}};var i=/(^|\.)args\[/;function o(t,e){return void 0===t||null===t&&!e.match(i)}function l(t,e,r){return function(n){var i,l,f=t,d="",p=[[t,d]],h=o(n,r);for(l=0;l<e.length-1;l++){if("number"==typeof(i=e[l])&&!a(f))throw"array index but container is not an array";if(-1===i){if(h=!c(f,e.slice(l+1),n,r))break;return}if(!u(f,i,e[l+1],h))break;if("object"!=typeof(f=f[i])||null===f)throw"container is not an object";d=s(d,i),p.push([f,d])}if(h){if(l===e.length-1&&(delete f[e[l]],Array.isArray(f)&&+e[l]==f.length-1))for(;f.length&&void 0===f[f.length-1];)f.pop()}else f[e[l]]=n}}function s(t,e){var r=e;return n(e)?r="["+e+"]":t&&(r="."+e),t+r}function c(t,e,r,n){var i,s=a(r),c=!0,f=r,d=n.replace("-1",0),p=!s&&o(r,d),h=e[0];for(i=0;i<t.length;i++)d=n.replace("-1",i),s&&(p=o(f=r[i%r.length],d)),p&&(c=!1),u(t,i,h,p)&&l(t[i],e,n.replace("-1",i))(f);return c}function u(t,e,r,n){if(void 0===t[e]){if(n)return!1;t[e]="number"==typeof r?[]:{}}return!0}},{"./is_array":164,"fast-isnumeric":13}],172:[function(t,e,r){"use strict";e.exports=function(){}},{}],173:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=[];e.exports=function(t,e){if(-1===i.indexOf(t)){i.push(t);var r=1e3;a(e)?r=e:"long"===e&&(r=3e3);var o=n.select("body").selectAll(".plotly-notifier").data([0]);o.enter().append("div").classed("plotly-notifier",!0),o.selectAll(".notifier-note").data(i).enter().append("div").classed("notifier-note",!0).style("opacity",0).each(function(t){var e=n.select(this);e.append("button").classed("notifier-close",!0).html("×").on("click",function(){e.transition().call(l)});for(var a=e.append("p"),i=t.split(/<br\s*\/?>/g),o=0;o<i.length;o++)o&&a.append("br"),a.append("span").text(i[o]);e.transition().duration(700).style("opacity",1).transition().delay(r).call(l)})}function l(t){t.duration(700).style("opacity",0).each("end",function(t){var e=i.indexOf(t);-1!==e&&i.splice(e,1),n.select(this).remove()})}}},{d3:10,"fast-isnumeric":13}],174:[function(t,e,r){"use strict";var n=t("./setcursor"),a="data-savedcursor";e.exports=function(t,e){var r=t.attr(a);if(e){if(!r){for(var i=(t.attr("class")||"").split(" "),o=0;o<i.length;o++){var l=i[o];0===l.indexOf("cursor-")&&t.attr(a,l.substr(7)).classed(l,!1)}t.attr(a)||t.attr(a,"!!")}n(t,e)}else r&&(t.attr(a,null),"!!"===r?n(t):n(t,r))}},{"./setcursor":182}],175:[function(t,e,r){"use strict";var n=t("./matrix").dot,a=t("../constants/numerical").BADNUM,i=e.exports={};i.tester=function(t){if(Array.isArray(t[0][0]))return i.multitester(t);var e,r=t.slice(),n=r[0][0],o=n,l=r[0][1],s=l;for(r.push(r[0]),e=1;e<r.length;e++)n=Math.min(n,r[e][0]),o=Math.max(o,r[e][0]),l=Math.min(l,r[e][1]),s=Math.max(s,r[e][1]);var c,u=!1;5===r.length&&(r[0][0]===r[1][0]?r[2][0]===r[3][0]&&r[0][1]===r[3][1]&&r[1][1]===r[2][1]&&(u=!0,c=function(t){return t[0]===r[0][0]}):r[0][1]===r[1][1]&&r[2][1]===r[3][1]&&r[0][0]===r[3][0]&&r[1][0]===r[2][0]&&(u=!0,c=function(t){return t[1]===r[0][1]}));var f=!0,d=r[0];for(e=1;e<r.length;e++)if(d[0]!==r[e][0]||d[1]!==r[e][1]){f=!1;break}return{xmin:n,xmax:o,ymin:l,ymax:s,pts:r,contains:u?function(t,e){var r=t[0],i=t[1];return!(r===a||r<n||r>o||i===a||i<l||i>s||e&&c(t))}:function(t,e){var i=t[0],c=t[1];if(i===a||i<n||i>o||c===a||c<l||c>s)return!1;var u,f,d,p,h,g=r.length,y=r[0][0],v=r[0][1],m=0;for(u=1;u<g;u++)if(f=y,d=v,y=r[u][0],v=r[u][1],!(i<(p=Math.min(f,y))||i>Math.max(f,y)||c>Math.max(d,v)))if(c<Math.min(d,v))i!==p&&m++;else{if(c===(h=y===f?c:d+(i-f)*(v-d)/(y-f)))return 1!==u||!e;c<=h&&i!==p&&m++}return m%2==1},isRect:u,degenerate:f}},i.multitester=function(t){for(var e=[],r=t[0][0][0],n=r,a=t[0][0][1],o=a,l=0;l<t.length;l++){var s=i.tester(t[l]);s.subtract=t[l].subtract,e.push(s),r=Math.min(r,s.xmin),n=Math.max(n,s.xmax),a=Math.min(a,s.ymin),o=Math.max(o,s.ymax)}return{xmin:r,xmax:n,ymin:a,ymax:o,pts:[],contains:function(t,r){for(var n=!1,a=0;a<e.length;a++)e[a].contains(t,r)&&(n=!1===e[a].subtract);return n},isRect:!1,degenerate:!1}};var o=i.isSegmentBent=function(t,e,r,a){var i,o,l,s=t[e],c=[t[r][0]-s[0],t[r][1]-s[1]],u=n(c,c),f=Math.sqrt(u),d=[-c[1]/f,c[0]/f];for(i=e+1;i<r;i++)if(o=[t[i][0]-s[0],t[i][1]-s[1]],(l=n(o,c))<0||l>u||Math.abs(n(o,d))>a)return!0;return!1};i.filter=function(t,e){var r=[t[0]],n=0,a=0;function i(i){t.push(i);var l=r.length,s=n;r.splice(a+1);for(var c=s+1;c<t.length;c++)(c===t.length-1||o(t,s,c+1,e))&&(r.push(t[c]),r.length<l-2&&(n=c,a=r.length-1),s=c)}t.length>1&&i(t.pop());return{addPt:i,raw:t,filtered:r}}},{"../constants/numerical":145,"./matrix":169}],176:[function(t,e,r){"use strict";e.exports=function(t,e){if(e instanceof RegExp){var r,n=e.toString();for(r=0;r<t.length;r++)if(t[r]instanceof RegExp&&t[r].toString()===n)return t;t.push(e)}else!e&&0!==e||-1!==t.indexOf(e)||t.push(e);return t}},{}],177:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plot_api/plot_config");var i={add:function(t,e,r,n,i){var o,l;t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},l=t.undoQueue.index,t.autoplay?t.undoQueue.inSequence||(t.autoplay=!1):(!t.undoQueue.sequence||t.undoQueue.beginSequence?(o={undo:{calls:[],args:[]},redo:{calls:[],args:[]}},t.undoQueue.queue.splice(l,t.undoQueue.queue.length-l,o),t.undoQueue.index+=1):o=t.undoQueue.queue[l-1],t.undoQueue.beginSequence=!1,o&&(o.undo.calls.unshift(e),o.undo.args.unshift(r),o.redo.calls.push(n),o.redo.args.push(i)),t.undoQueue.queue.length>a.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.undo.calls.length;r++)i.plotDo(t,e.undo.calls[r],e.undo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1}},redo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.redo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index>=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.redo.calls.length;r++)i.plotDo(t,e.redo.calls[r],e.redo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1,t.undoQueue.index++}}};i.plotDo=function(t,e,r){t.autoplay=!0,r=function(t,e){for(var r,a=[],i=0;i<e.length;i++)r=e[i],a[i]=r===t?r:"object"==typeof r?Array.isArray(r)?n.extendDeep([],r):n.extendDeepAll({},r):r;return a}(t,r),e.apply(null,r)},e.exports=i},{"../lib":163,"../plot_api/plot_config":195}],178:[function(t,e,r){"use strict";r.counter=function(t,e,r){var n=(e||"")+(r?"":"$");return"xy"===t?new RegExp("^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?"+n):new RegExp("^"+t+"([2-9]|[1-9][0-9]+)?"+n)}},{}],179:[function(t,e,r){"use strict";var n=/^(.*)(\.[^\.\[\]]+|\[\d\])$/,a=/^[^\.\[\]]+$/;e.exports=function(t,e){for(;e;){var r=t.match(n);if(r)t=r[1];else{if(!t.match(a))throw new Error("bad relativeAttr call:"+[t,e]);t=""}if("^"!==e.charAt(0))break;e=e.slice(1)}return t&&"["!==e.charAt(0)?t+"."+e:t+e}},{}],180:[function(t,e,r){"use strict";var n=t("./is_array").isArrayOrTypedArray,a=t("./is_plain_object");e.exports=function t(e,r){for(var i in r){var o=r[i],l=e[i];if(l!==o)if("_"===i.charAt(0)||"function"==typeof o){if(i in e)continue;e[i]=o}else if(n(o)&&n(l)&&a(o[0])){if("customdata"===i||"ids"===i)continue;for(var s=Math.min(o.length,l.length),c=0;c<s;c++)l[c]!==o[c]&&a(o[c])&&a(l[c])&&t(l[c],o[c])}else a(o)&&a(l)&&(t(l,o),Object.keys(l).length||delete e[i])}}},{"./is_array":164,"./is_plain_object":165}],181:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("./loggers");function i(t,e){return t<e}function o(t,e){return t<=e}function l(t,e){return t>e}function s(t,e){return t>=e}r.findBin=function(t,e,r){if(n(e.start))return r?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var c,u,f=0,d=e.length,p=0,h=d>1?(e[d-1]-e[0])/(d-1):1;for(u=h>=0?r?i:o:r?s:l,t+=1e-9*h*(r?-1:1)*(h>=0?1:-1);f<d&&p++<100;)u(e[c=Math.floor((f+d)/2)],t)?f=c+1:d=c;return p>90&&a.log("Long binary search..."),f-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,a=e[n]-e[0]||1,i=a/(n||1)/1e4,o=[e[0]],l=0;l<n;l++)e[l+1]>e[l]+i&&(a=Math.min(a,e[l+1]-e[l]),o.push(e[l+1]));return{vals:o,minDiff:a}},r.roundUp=function(t,e,r){for(var n,a=0,i=e.length-1,o=0,l=r?0:1,s=r?1:0,c=r?Math.ceil:Math.floor;a<i&&o++<100;)e[n=c((a+i)/2)]<=t?a=n+l:i=n-s;return e[a]}},{"./loggers":168,"fast-isnumeric":13}],182:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],183:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("./is_array").isArrayOrTypedArray;r.aggNums=function(t,e,i,o){var l,s;if((!o||o>i.length)&&(o=i.length),n(e)||(e=!1),a(i[0])){for(s=new Array(o),l=0;l<o;l++)s[l]=r.aggNums(t,e,i[l]);i=s}for(l=0;l<o;l++)n(e)?n(i[l])&&(e=t(+e,+i[l])):e=i[l];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.midRange=function(t){if(void 0!==t&&0!==t.length)return(r.aggNums(Math.max,null,t)+r.aggNums(Math.min,null,t))/2},r.variance=function(t,e,a){return e||(e=r.len(t)),n(a)||(a=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-a,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if((e=e*t.length-.5)<0)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"./is_array":164,"fast-isnumeric":13}],184:[function(t,e,r){"use strict";var n=t("d3"),a=t("../lib"),i=t("../constants/xmlns_namespaces"),o=t("../constants/string_mappings"),l=t("../constants/alignment").LINE_SPACING;function s(t,e){return t.node().getBoundingClientRect()[e]}var c=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;r.convertToTspans=function(t,e,o){var v=t.text(),S=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&v.match(c),O=n.select(t.node().parentNode);if(!O.empty()){var P=t.attr("class")?t.attr("class").split(" ")[0]:"text";return P+="-math",O.selectAll("svg."+P).remove(),O.selectAll("g."+P+"-group").remove(),t.style("display",null).attr({"data-unformatted":v,"data-math":"N"}),S?(e&&e._promises||[]).push(new Promise(function(e){t.style("display","none");var r=parseInt(t.node().style.fontSize,10),i={fontSize:r};!function(t,e,r){var i="math-output-"+a.randstr({},64),o=n.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text((l=t,l.replace(u,"\\lt ").replace(f,"\\gt ")));var l;MathJax.Hub.Queue(["Typeset",MathJax.Hub,o.node()],function(){var e=n.select("body").select("#MathJax_SVG_glyphs");if(o.select(".MathJax_SVG").empty()||!o.select("svg").node())a.log("There was an error in the tex syntax.",t),r();else{var i=o.select("svg").node().getBoundingClientRect();r(o.select(".MathJax_SVG"),e,i)}o.remove()})}(S[2],i,function(n,a,i){O.selectAll("svg."+P).remove(),O.selectAll("g."+P+"-group").remove();var l=n&&n.select("svg");if(!l||!l.node())return D(),void e();var c=O.append("g").classed(P+"-group",!0).attr({"pointer-events":"none","data-unformatted":v,"data-math":"Y"});c.node().appendChild(l.node()),a&&a.node()&&l.node().insertBefore(a.node().cloneNode(!0),l.node().firstChild),l.attr({class:P,height:i.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var u=t.node().style.fill||"black";l.select("g").attr({fill:u,stroke:u});var f=s(l,"width"),d=s(l,"height"),p=+t.attr("x")-f*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],h=-(r||s(t,"height"))/4;"y"===P[0]?(c.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-f/2,h-d/2]+")"}),l.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===P[0]?l.attr({x:t.attr("x"),y:h-d/2}):"a"===P[0]?l.attr({x:0,y:h}):l.attr({x:p,y:+t.attr("y")+h-d/2}),o&&o.call(t,c),e(c)})})):D(),t}function D(){O.empty()||(P=t.attr("class")+"-math",O.select("svg."+P).remove()),t.text("").style("white-space","pre"),function(t,e){e=(r=e,function(t,e){if(!t)return"";for(var r=0;r<e.length;r++){var n=e[r];t=t.replace(n.regExp,n.sub)}return t}(r,m)).replace(x," ");var r;var o,s=!1,c=[],u=-1;function f(){u++;var e=document.createElementNS(i.svg,"tspan");n.select(e).attr({class:"line",dy:u*l+"em"}),t.appendChild(e),o=e;var r=c;if(c=[{node:e}],r.length>1)for(var a=1;a<r.length;a++)v(r[a])}function v(t){var e,r=t.type,a={};if("a"===r){e="a";var l=t.target,s=t.href,u=t.popup;s&&(a={"xlink:xlink:show":"_blank"===l||"_"!==l.charAt(0)?"new":"replace",target:l,"xlink:xlink:href":s},u&&(a.onclick='window.open(this.href.baseVal,this.target.baseVal,"'+u+'");return false;'))}else e="tspan";t.style&&(a.style=t.style);var f=document.createElementNS(i.svg,e);if("sup"===r||"sub"===r){S(o,g),o.appendChild(f);var d=document.createElementNS(i.svg,"tspan");S(d,g),n.select(d).attr("dy",h[r]),a.dy=p[r],o.appendChild(f),o.appendChild(d)}else o.appendChild(f);n.select(f).attr(a),o=t.node=f,c.push(t)}function S(t,e){t.appendChild(document.createTextNode(e))}function O(t){if(1!==c.length){var r=c.pop();t!==r.type&&a.log("Start tag <"+r.type+"> doesnt match end tag <"+t+">. Pretending it did match.",e),o=c[c.length-1].node}else a.log("Ignoring unexpected end tag </"+t+">.",e)}w.test(e)?f():(o=t,c=[{node:t}]);for(var P=e.split(b),D=0;D<P.length;D++){var z=P[D],E=z.match(_),I=E&&E[2].toLowerCase(),N=d[I];if("br"===I)f();else if(void 0===N)S(o,z);else if(E[1])O(I);else{var R=E[4],F={type:I},j=L(R,k);if(j?(j=j.replace(C,"$1 fill:"),N&&(j+=";"+N)):N&&(j=N),j&&(F.style=j),"a"===I){s=!0;var B=L(R,M);if(B){var H=document.createElement("a");H.href=B,-1!==y.indexOf(H.protocol)&&(F.href=encodeURI(decodeURI(B)),F.target=L(R,T)||"_blank",F.popup=L(R,A))}}v(F)}}return s}(t.node(),v)&&t.style("pointer-events","all"),r.positionText(t),o&&o.call(t)}};var u=/(<|<|<)/g,f=/(>|>|>)/g;var d={sup:"font-size:70%",sub:"font-size:70%",b:"font-weight:bold",i:"font-style:italic",a:"cursor:pointer",span:"",em:"font-style:italic;font-weight:bold"},p={sub:"0.3em",sup:"-0.6em"},h={sub:"-0.21em",sup:"0.42em"},g="\u200b",y=["http:","https:","mailto:","",void 0,":"],v=new RegExp("</?("+Object.keys(d).join("|")+")( [^>]*)?/?>","g"),m=Object.keys(o.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:o.entityToUnicode[t]}}),x=/(\r\n?|\n)/g,b=/(<[^<>]*>)/,_=/<(\/?)([^ >]*)(\s+(.*))?>/i,w=/<br(\s+.*)?>/i,k=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,M=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,T=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,A=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function L(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var C=/(^|;)\s*color:/;function S(t,e,r){var n,a,i,o=r.horizontalAlign,l=r.verticalAlign||"top",s=t.node().getBoundingClientRect(),c=e.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-n.height}:"middle"===l?function(){return s.top+(s.height-n.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-n.width}:"center"===o?function(){return s.left+(s.width-n.width)/2}:function(){return s.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}r.plainText=function(t){return(t||"").replace(v," ")},r.lineCount=function(t){return t.selectAll("tspan.line").size()||1},r.positionText=function(t,e,r){return t.each(function(){var t=n.select(this);function a(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var i=a("x",e),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},r.makeEditable=function(t,e){var r=e.gd,a=e.delegate,i=n.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){!function(){var a=n.select(r).select(".svg-container"),o=a.append("div"),l=t.node().style,c=parseFloat(l.fontSize||12),u=e.text;void 0===u&&(u=t.attr("data-unformatted"));o.classed("plugin-editable editable",!0).style({position:"absolute","font-family":l.fontFamily||"Arial","font-size":c,color:e.fill||l.fill||"black",opacity:1,"background-color":e.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(u).call(S(t,a,e)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var e,a=n.select(this).attr("class");(e=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(e).style({opacity:0});var o=this.textContent;n.select(this).transition().duration(0).remove(),n.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,n.select(document).on("mouseup",function(){if(n.event.target===t)return!1;document.activeElement===o.node()&&o.node().blur()})}).on("keyup",function(){27===n.event.which?(r._editing=!1,t.style({opacity:1}),n.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),n.select(this).call(S(t,a,e)))}).on("keydown",function(){13===n.event.which&&this.blur()}).call(s)}(),t.style({opacity:0});var a,l=o.attr("class");(a=l?"."+l.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(a).style({opacity:0})}function s(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return e.immediate?l():o.on("click",l),n.rebind(t,i,"on")}},{"../constants/alignment":143,"../constants/string_mappings":146,"../constants/xmlns_namespaces":147,"../lib":163,d3:10}],185:[function(t,e,r){"use strict";var n={};function a(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}r.throttle=function(t,e,r){var i=n[t],o=Date.now();if(!i){for(var l in n)n[l].ts<o-6e4&&delete n[l];i=n[t]={ts:0,timer:null}}function s(){r(),i.ts=Date.now(),i.onDone&&(i.onDone(),i.onDone=null)}a(i),o>i.ts+e?s():i.timer=setTimeout(function(){s(),i.timer=null},e)},r.done=function(t){var e=n[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},r.clear=function(t){if(t)a(n[t]),delete n[t];else for(var e in n)r.clear(e)}},{}],186:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var r=Math.log(Math.min(e[0],e[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),r}},{"fast-isnumeric":13}],187:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en-US",dictionary:{"Click to enter Colorscale title":"Click to enter Colorscale title"},format:{date:"%m/%d/%Y"}}},{}],188:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en",dictionary:{"Click to enter Colorscale title":"Click to enter Colourscale title"},format:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],periods:["AM","PM"],dateTime:"%a %b %e %X %Y",date:"%d/%m/%Y",time:"%H:%M:%S",decimal:".",thousands:",",grouping:[3],currency:["$",""],year:"%Y",month:"%b %Y",dayMonth:"%b %-d",dayMonthYear:"%b %-d, %Y"}}},{}],189:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t){for(var e,r,a=n.layoutArrayContainers,i=n.layoutArrayRegexes,o=t.split("[")[0],l=0;l<i.length;l++)if((r=t.match(i[l]))&&0===r.index){e=r[0];break}if(e||(e=a[a.indexOf(o)]),!e)return!1;var s=t.substr(e.length);return s?!!(r=s.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/))&&{array:e,index:Number(r[1]),property:r[3]||""}:{array:e,index:"",property:""}}},{"../registry":247}],190:[function(t,e,r){"use strict";var n=t("../lib"),a=n.extendFlat,i=n.isPlainObject,o={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},l={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","layoutstyle","modebar","camera","arraydraw"]},s=o.flags.slice().concat(["clearCalc","fullReplot"]),c=l.flags.slice().concat("layoutReplot");function u(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!1;return e}function f(t,e,r){var n=a({},t);for(var o in n){var l=n[o];i(l)&&(n[o]=d(l,e,r,o))}return"from-root"===r&&(n.editType=e),n}function d(t,e,r,n){if(t.valType){var i=a({},t);if(i.editType=e,Array.isArray(t.items)){i.items=new Array(t.items.length);for(var o=0;o<t.items.length;o++)i.items[o]=d(t.items[o],e,"from-root")}return i}return f(t,e,"_"===n.charAt(0)?"nested":"from-root")}e.exports={traces:o,layout:l,traceFlags:function(){return u(s)},layoutFlags:function(){return u(c)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),a=0;a<n.length;a++)t[n[a]]=!0},overrideAll:f}},{"../lib":163}],191:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("gl-mat4/fromQuat"),i=t("../registry"),o=t("../lib"),l=t("../plots/plots"),s=t("../plots/cartesian/axis_ids"),c=s.cleanId,u=s.getFromTrace,f=t("../components/color");function d(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=c(r,n))}function p(t){if(!o.isPlainObject(t))return!1;var e=t.name;return delete t.name,delete t.showlegend,("string"==typeof e||"number"==typeof e)&&String(e)}function h(t,e,r,n){if(r&&!n)return t;if(n&&!r)return e;if(!t.trim())return e;if(!e.trim())return t;var a,i=Math.min(t.length,e.length);for(a=0;a<i&&t.charAt(a)===e.charAt(a);a++);return t.substr(0,a).trim()}function g(t){var e="middle",r="center";return-1!==t.indexOf("top")?e="top":-1!==t.indexOf("bottom")&&(e="bottom"),-1!==t.indexOf("left")?r="left":-1!==t.indexOf("right")&&(r="right"),e+" "+r}function y(t,e){return e in t&&"object"==typeof t[e]&&0===Object.keys(t[e]).length}r.clearPromiseQueue=function(t){Array.isArray(t._promises)&&t._promises.length>0&&o.log("Clearing previous rejected promises from queue."),t._promises=[]},r.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(l.subplotsRegistry.cartesian||{}).attrRegex,i=(l.subplotsRegistry.gl3d||{}).attrRegex,s=Object.keys(t);for(e=0;e<s.length;e++){var u=s[e];if(n&&n.test(u)){var p=t[u];p.anchor&&"free"!==p.anchor&&(p.anchor=c(p.anchor)),p.overlaying&&(p.overlaying=c(p.overlaying)),p.type||(p.isdate?p.type="date":p.islog?p.type="log":!1===p.isdate&&!1===p.islog&&(p.type="linear")),"withzero"!==p.autorange&&"tozero"!==p.autorange||(p.autorange=!0,p.rangemode="tozero"),delete p.islog,delete p.isdate,delete p.categories,y(p,"domain")&&delete p.domain,void 0!==p.autotick&&(void 0===p.tickmode&&(p.tickmode=p.autotick?"auto":"linear"),delete p.autotick)}else if(i&&i.test(u)){var h=t[u],g=h.cameraposition;if(Array.isArray(g)&&4===g[0].length){var v=g[0],m=g[1],x=g[2],b=a([],v),_=[];for(r=0;r<3;++r)_[r]=m[r]+x*b[2+4*r];h.camera={eye:{x:_[0],y:_[1],z:_[2]},center:{x:m[0],y:m[1],z:m[2]},up:{x:b[1],y:b[5],z:b[9]}},delete h.cameraposition}}}var w=Array.isArray(t.annotations)?t.annotations.length:0;for(e=0;e<w;e++){var k=t.annotations[e];o.isPlainObject(k)&&(k.ref&&("paper"===k.ref?(k.xref="paper",k.yref="paper"):"data"===k.ref&&(k.xref="x",k.yref="y"),delete k.ref),d(k,"xref"),d(k,"yref"))}var M=Array.isArray(t.shapes)?t.shapes.length:0;for(e=0;e<M;e++){var T=t.shapes[e];o.isPlainObject(T)&&(d(T,"xref"),d(T,"yref"))}var A=t.legend;return A&&(A.x>3?(A.x=1.02,A.xanchor="left"):A.x<-2&&(A.x=-.02,A.xanchor="right"),A.y>3?(A.y=1.02,A.yanchor="bottom"):A.y<-2&&(A.y=-.02,A.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),f.clean(t),t},r.cleanData=function(t){for(var e=0;e<t.length;e++){var n,a=t[e];if("histogramy"===a.type&&"xbins"in a&&!("ybins"in a)&&(a.ybins=a.xbins,delete a.xbins),a.error_y&&"opacity"in a.error_y){var s=f.defaults,u=a.error_y.color||(i.traceIs(a,"bar")?f.defaultLine:s[e%s.length]);a.error_y.color=f.addOpacity(f.rgb(u),f.opacity(u)*a.error_y.opacity),delete a.error_y.opacity}if("bardir"in a&&("h"!==a.bardir||!i.traceIs(a,"bar")&&"histogram"!==a.type.substr(0,9)||(a.orientation="h",r.swapXYData(a)),delete a.bardir),"histogramy"===a.type&&r.swapXYData(a),"histogramx"!==a.type&&"histogramy"!==a.type||(a.type="histogram"),"scl"in a&&(a.colorscale=a.scl,delete a.scl),"reversescl"in a&&(a.reversescale=a.reversescl,delete a.reversescl),a.xaxis&&(a.xaxis=c(a.xaxis,"x")),a.yaxis&&(a.yaxis=c(a.yaxis,"y")),i.traceIs(a,"gl3d")&&a.scene&&(a.scene=l.subplotsRegistry.gl3d.cleanId(a.scene)),!i.traceIs(a,"pie")&&!i.traceIs(a,"bar"))if(Array.isArray(a.textposition))for(n=0;n<a.textposition.length;n++)a.textposition[n]=g(a.textposition[n]);else a.textposition&&(a.textposition=g(a.textposition));var d=i.getModule(a);if(d&&d.colorbar){var v=d.colorbar.container,m=v?a[v]:a;m&&m.colorscale&&("YIGnBu"===m.colorscale&&(m.colorscale="YlGnBu"),"YIOrRd"===m.colorscale&&(m.colorscale="YlOrRd"))}if("surface"===a.type&&o.isPlainObject(a.contours)){var x=["x","y","z"];for(n=0;n<x.length;n++){var b=a.contours[x[n]];o.isPlainObject(b)&&(b.highlightColor&&(b.highlightcolor=b.highlightColor,delete b.highlightColor),b.highlightWidth&&(b.highlightwidth=b.highlightWidth,delete b.highlightWidth))}}if("candlestick"===a.type||"ohlc"===a.type){var _=!1!==(a.increasing||{}).showlegend,w=!1!==(a.decreasing||{}).showlegend,k=p(a.increasing),M=p(a.decreasing);if(!1!==k&&!1!==M){var T=h(k,M,_,w);T&&(a.name=T)}else!k&&!M||a.name||(a.name=k||M)}if(Array.isArray(a.transforms)){var A=a.transforms;for(n=0;n<A.length;n++){var L=A[n];if(o.isPlainObject(L))switch(L.type){case"filter":L.filtersrc&&(L.target=L.filtersrc,delete L.filtersrc),L.calendar&&(L.valuecalendar||(L.valuecalendar=L.calendar),delete L.calendar);break;case"groupby":if(L.styles=L.styles||L.style,L.styles&&!Array.isArray(L.styles)){var C=L.styles,S=Object.keys(C);L.styles=[];for(var O=0;O<S.length;O++)L.styles.push({target:S[O],value:C[S[O]]})}}}}y(a,"line")&&delete a.line,"marker"in a&&(y(a.marker,"line")&&delete a.marker.line,y(a,"marker")&&delete a.marker),f.clean(a)}},r.swapXYData=function(t){var e;if(o.swapAttrs(t,["?","?0","d?","?bins","nbins?","autobin?","?src","error_?"]),Array.isArray(t.z)&&Array.isArray(t.z[0])&&(t.transpose?delete t.transpose:t.transpose=!0),t.error_x&&t.error_y){var r=t.error_y,n="copy_ystyle"in r?r.copy_ystyle:!(r.color||r.thickness||r.width);o.swapAttrs(t,["error_?.copy_ystyle"]),n&&o.swapAttrs(t,["error_?.color","error_?.thickness","error_?.width"])}if("string"==typeof t.hoverinfo){var a=t.hoverinfo.split("+");for(e=0;e<a.length;e++)"x"===a[e]?a[e]="y":"y"===a[e]&&(a[e]="x");t.hoverinfo=a.join("+")}},r.coerceTraceIndices=function(t,e){return n(e)?[e]:Array.isArray(e)&&e.length?e:t.data.map(function(t,e){return e})},r.manageArrayContainers=function(t,e,r){var a=t.obj,i=t.parts,l=i.length,s=i[l-1],c=n(s);if(c&&null===e){var u=i.slice(0,l-1).join(".");o.nestedProperty(a,u).get().splice(s,1)}else c&&void 0===t.get()?(void 0===t.get()&&(r[t.astr]=null),t.set(e)):t.set(e)};var v=/(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;function m(t){var e=t.search(v);if(e>0)return t.substr(0,e)}r.hasParent=function(t,e){for(var r=m(e);r;){if(r in t)return!0;r=m(r)}return!1};var x=["x","y","z"];r.clearAxisTypes=function(t,e,r){for(var n=0;n<e.length;n++)for(var a=t._fullData[n],i=0;i<3;i++){var l=u(t,a,x[i]);if(l&&"log"!==l.type){var s=l._name,c=l._id.substr(1);if("scene"===c.substr(0,5)){if(void 0!==r[c])continue;s=c+"."+s}var f=s+".type";void 0===r[s]&&void 0===r[f]&&o.nestedProperty(t.layout,f).set(null)}}}},{"../components/color":45,"../lib":163,"../plots/cartesian/axis_ids":210,"../plots/plots":239,"../registry":247,"fast-isnumeric":13,"gl-mat4/fromQuat":14}],192:[function(t,e,r){"use strict";var n=t("./plot_api");r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.update=n.update,r.react=n.react,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.addFrames=n.addFrames,r.deleteFrames=n.deleteFrames,r.animate=n.animate,r.setPlotConfig=n.setPlotConfig,r.toImage=t("./to_image"),r.validate=t("./validate"),r.downloadImage=t("../snapshot/download");var a=t("./template_api");r.makeTemplate=a.makeTemplate,r.validateTemplate=a.validateTemplate},{"../snapshot/download":249,"./plot_api":194,"./template_api":199,"./to_image":200,"./validate":201}],193:[function(t,e,r){"use strict";var n=t("../lib/nested_property"),a=t("../lib/is_plain_object"),i=t("../lib/noop"),o=t("../lib/loggers"),l=t("../lib/search").sorterAsc,s=t("../registry");r.containerArrayMatch=t("./container_array_match");var c=r.isAddVal=function(t){return"add"===t||a(t)},u=r.isRemoveVal=function(t){return null===t||"remove"===t};r.applyContainerArrayChanges=function(t,e,r,a){var f=e.astr,d=s.getComponentMethod(f,"supplyLayoutDefaults"),p=s.getComponentMethod(f,"draw"),h=s.getComponentMethod(f,"drawOne"),g=a.replot||a.recalc||d===i||p===i,y=t.layout,v=t._fullLayout;if(r[""]){Object.keys(r).length>1&&o.warn("Full array edits are incompatible with other edits",f);var m=r[""][""];if(u(m))e.set(null);else{if(!Array.isArray(m))return o.warn("Unrecognized full array edit value",f,m),!0;e.set(m)}return!g&&(d(y,v),p(t),!0)}var x,b,_,w,k,M,T,A=Object.keys(r).map(Number).sort(l),L=e.get(),C=L||[],S=n(v,f).get(),O=[],P=-1,D=C.length;for(x=0;x<A.length;x++)if(w=r[_=A[x]],k=Object.keys(w),M=w[""],T=c(M),_<0||_>C.length-(T?0:1))o.warn("index out of range",f,_);else if(void 0!==M)k.length>1&&o.warn("Insertion & removal are incompatible with edits to the same index.",f,_),u(M)?O.push(_):T?("add"===M&&(M={}),C.splice(_,0,M),S&&S.splice(_,0,{})):o.warn("Unrecognized full object edit value",f,_,M),-1===P&&(P=_);else for(b=0;b<k.length;b++)n(C[_],k[b]).set(w[k[b]]);for(x=O.length-1;x>=0;x--)C.splice(O[x],1),S&&S.splice(O[x],1);if(C.length?L||e.set(C):e.set(null),g)return!1;if(d(y,v),h!==i){var z;if(-1===P)z=A;else{for(D=Math.max(C.length,D),z=[],x=0;x<A.length&&!((_=A[x])>=P);x++)z.push(_);for(x=P;x<D;x++)z.push(x)}for(x=0;x<z.length;x++)h(t,z[x])}else p(t);return!0}},{"../lib/is_plain_object":165,"../lib/loggers":168,"../lib/nested_property":171,"../lib/noop":172,"../lib/search":181,"../registry":247,"./container_array_match":189}],194:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("has-hover"),o=t("../lib"),l=t("../lib/events"),s=t("../lib/queue"),c=t("../registry"),u=t("./plot_schema"),f=t("../plots/plots"),d=t("../plots/polar/legacy"),p=t("../plots/cartesian/axes"),h=t("../components/drawing"),g=t("../components/color"),y=t("../components/colorbar/connect"),v=t("../plots/cartesian/graph_interact").initInteractions,m=t("../constants/xmlns_namespaces"),x=t("../lib/svg_text_utils"),b=t("./plot_config"),_=t("./manage_arrays"),w=t("./helpers"),k=t("./subroutines"),M=t("./edit_types"),T=t("../plots/cartesian/constants").AX_NAME_PATTERN,A=0;function L(t){var e=t._fullLayout;e._redrawFromAutoMarginCount?e._redrawFromAutoMarginCount--:t.emit("plotly_afterplot")}function C(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){o.error(t)}}function S(t,e){C(t,g.combine(e,"white"))}function O(t,e){t._context||(t._context=o.extendDeep({},b));var r,n,a,l=t._context;if(e){for(n=Object.keys(e),r=0;r<n.length;r++)"editable"!==(a=n[r])&&"edits"!==a&&a in l&&("setBackground"===a&&"opaque"===e[a]?l[a]=S:l[a]=e[a]);e.plot3dPixelRatio&&!l.plotGlPixelRatio&&(l.plotGlPixelRatio=l.plot3dPixelRatio);var s=e.editable;if(void 0!==s)for(l.editable=s,n=Object.keys(l.edits),r=0;r<n.length;r++)l.edits[n[r]]=s;if(e.edits)for(n=Object.keys(e.edits),r=0;r<n.length;r++)(a=n[r])in l.edits&&(l.edits[a]=e.edits[a])}l.staticPlot&&(l.editable=!1,l.edits={},l.autosizable=!1,l.scrollZoom=!1,l.doubleClick=!1,l.showTips=!1,l.showLink=!1,l.displayModeBar=!1),"hover"!==l.displayModeBar||i||(l.displayModeBar=!0),"transparent"!==l.setBackground&&"function"==typeof l.setBackground||(l.setBackground=C)}function P(t,e){var r,n,a=e+1,i=[];for(r=0;r<t.length;r++)(n=t[r])<0?i.push(a+n):i.push(n);return i}function D(t,e,r){var n,a;for(n=0;n<e.length;n++){if((a=e[n])!==parseInt(a,10))throw new Error("all values in "+r+" must be integers");if(a>=t.data.length||a<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(a,n+1)>-1||a>=0&&e.indexOf(-t.data.length+a)>-1||a<0&&e.indexOf(t.data.length+a)>-1)throw new Error("each index in "+r+" must be unique.")}}function z(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),D(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&D(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function E(t,e,r,n,i){!function(t,e,r,n){var a=o.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!o.isPlainObject(e))throw new Error("update must be a key:value object");if("undefined"==typeof r)throw new Error("indices must be an integer or array of integers");for(var i in D(t,r,"indices"),e){if(!Array.isArray(e[i])||e[i].length!==r.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in n)||!Array.isArray(n[i])||n[i].length!==e[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,r,n);for(var l=function(t,e,r,n){var i,l,s,c,u,f=o.isPlainObject(n),d=[];for(var p in Array.isArray(r)||(r=[r]),r=P(r,t.data.length-1),e)for(var h=0;h<r.length;h++){if(i=t.data[r[h]],l=(s=o.nestedProperty(i,p)).get(),c=e[p][h],!o.isArrayOrTypedArray(c))throw new Error("attribute: "+p+" index: "+h+" must be an array");if(!o.isArrayOrTypedArray(l))throw new Error("cannot extend missing or non-array attribute: "+p);if(l.constructor!==c.constructor)throw new Error("cannot extend array with an array of a different type: "+p);u=f?n[p][h]:n,a(u)||(u=-1),d.push({prop:s,target:l,insert:c,maxp:Math.floor(u)})}return d}(t,e,r,n),s={},c={},u=0;u<l.length;u++){var f=l[u].prop,d=l[u].maxp,p=i(l[u].target,l[u].insert,d);f.set(p[0]),Array.isArray(s[f.astr])||(s[f.astr]=[]),s[f.astr].push(p[1]),Array.isArray(c[f.astr])||(c[f.astr]=[]),c[f.astr].push(l[u].target.length)}return{update:s,maxPoints:c}}function I(t,e){var r=new t.constructor(t.length+e.length);return r.set(t),r.set(e,t.length),r}function N(t){return void 0===t?null:t}function R(t,e,r){var n,a,i=t._fullLayout,l=t._fullData,s=t.data,d=M.traceFlags(),h={},g={};function y(){return r.map(function(){})}function v(t){var e=p.id2name(t);-1===a.indexOf(e)&&a.push(e)}function m(t){return"LAYOUT"+t+".autorange"}function x(t){return"LAYOUT"+t+".range"}function b(n,a,i){var l;Array.isArray(n)?n.forEach(function(t){b(t,a,i)}):n in e||w.hasParent(e,n)||(l="LAYOUT"===n.substr(0,6)?o.nestedProperty(t.layout,n.replace("LAYOUT","")):o.nestedProperty(s[r[i]],n),n in g||(g[n]=y()),void 0===g[n][i]&&(g[n][i]=N(l.get())),void 0!==a&&l.set(a))}for(var _ in e){if(w.hasParent(e,_))throw new Error("cannot set "+_+"and a parent attribute simultaneously");var k,T,A,L,C,S,O=e[_];if(h[_]=O,"LAYOUT"!==_.substr(0,6)){for(g[_]=y(),n=0;n<r.length;n++)if(k=s[r[n]],T=l[r[n]],L=(A=o.nestedProperty(k,_)).get(),void 0!==(C=Array.isArray(O)?O[n%O.length]:O)){var P=A.parts[A.parts.length-1],D=_.substr(0,_.length-P.length-1),z=D?D+".":"",E=D?o.nestedProperty(T,D).get():T;if((S=u.getTraceValObject(T,A.parts))&&S.impliedEdits&&null!==C)for(var I in S.impliedEdits)b(o.relativeAttr(_,I),S.impliedEdits[I],n);else if("thicknessmode"!==P&&"lenmode"!==P||L===C||"fraction"!==C&&"pixels"!==C||!E){if("type"===_&&"pie"===C!=("pie"===L)){var R="x",F="y";"bar"!==C&&"bar"!==L||"h"!==k.orientation||(R="y",F="x"),o.swapAttrs(k,["?","?src"],"labels",R),o.swapAttrs(k,["d?","?0"],"label",R),o.swapAttrs(k,["?","?src"],"values",F),"pie"===L?(o.nestedProperty(k,"marker.color").set(o.nestedProperty(k,"marker.colors").get()),i._pielayer.selectAll("g.trace").remove()):c.traceIs(k,"cartesian")&&o.nestedProperty(k,"marker.colors").set(o.nestedProperty(k,"marker.color").get())}}else{var j=i._size,B=E.orient,H="top"===B||"bottom"===B;if("thicknessmode"===P){var q=H?j.h:j.w;b(z+"thickness",E.thickness*("fraction"===C?1/q:q),n)}else{var V=H?j.w:j.h;b(z+"len",E.len*("fraction"===C?1/V:V),n)}}g[_][n]=N(L);if(-1!==["swapxy","swapxyaxes","orientation","orientationaxes"].indexOf(_)){if("orientation"===_){A.set(C);var U=k.x&&!k.y?"h":"v";if((A.get()||U)===T.orientation)continue}else"orientationaxes"===_&&(k.orientation={v:"h",h:"v"}[T.orientation]);w.swapXYData(k),d.calc=d.clearAxisTypes=!0}else-1!==f.dataArrayContainers.indexOf(A.parts[0])?(w.manageArrayContainers(A,C,g),d.calc=!0):(S?S.arrayOk&&(o.isArrayOrTypedArray(C)||o.isArrayOrTypedArray(L))?d.calc=!0:M.update(d,S):d.calc=!0,A.set(C))}if(-1!==["swapxyaxes","orientationaxes"].indexOf(_)&&p.swap(t,r),"orientationaxes"===_){var G=o.nestedProperty(t.layout,"hovermode");"x"===G.get()?G.set("y"):"y"===G.get()&&G.set("x")}if(-1!==["orientation","type"].indexOf(_)){for(a=[],n=0;n<r.length;n++){var Y=s[r[n]];c.traceIs(Y,"cartesian")&&(v(Y.xaxis||"x"),v(Y.yaxis||"y"),"type"===_&&b(["autobinx","autobiny"],!0,n))}b(a.map(m),!0,0),b(a.map(x),[0,1],0)}}else A=o.nestedProperty(t.layout,_.replace("LAYOUT","")),g[_]=[N(A.get())],A.set(Array.isArray(O)?O[0]:O),d.calc=!0}var X=!1,Z=p.list(t);for(n=0;n<Z.length;n++)if(Z[n].autorange){X=!0;break}return(d.calc||d.calcIfAutorange&&X)&&(d.clearCalc=!0),(d.calc||d.plot||d.calcIfAutorange)&&(d.fullReplot=!0),{flags:d,undoit:g,redoit:h,traces:r,eventData:o.extendDeepNoArrays([],[h,r])}}function F(t,e){var r=e?function(t){return k.doTicksRelayout(t,e)}:k.doTicksRelayout;t.push(r,k.drawData,k.finalDraw)}r.plot=function(t,e,a,i){var s;if(t=o.getGraphDiv(t),l.init(t),o.isPlainObject(e)){var u=e;e=u.data,a=u.layout,i=u.config,s=u.frames}if(!1===l.triggerHandler(t,"plotly_beforeplot",[e,a,i]))return Promise.reject();e||a||o.isPlotDiv(t)||o.warn("Calling Plotly.plot as if redrawing but this container doesn't yet have a plot.",t),O(t,i),a||(a={}),n.select(t).classed("js-plotly-plot",!0),h.makeTester(),delete h.baseUrl,Array.isArray(t._promises)||(t._promises=[]);var g=0===(t.data||[]).length&&Array.isArray(e);if(Array.isArray(e)&&(w.cleanData(e),g?t.data=e:t.data.push.apply(t.data,e),t.empty=!1),t.layout&&!g||(t.layout=w.cleanLayout(a)),t._dragging&&!t._transitioning)return t._replotPending=!0,Promise.reject();t._replotPending=!1,f.supplyDefaults(t);var m=t._fullLayout,b=m._has("cartesian");if(!m._has("polar")&&e&&e[0]&&e[0].r)return o.log("Legacy polar charts are deprecated!"),function(t,e,r){var a=n.select(t).selectAll(".plot-container").data([0]);a.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=a.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e);r&&(t.layout=r);d.manager.fillLayout(t),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=d.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var l=t.framework.svg(),s=1,c=t._fullLayout.title;""!==c&&c||(s=0);var u=function(){this.call(x.convertToTspans,t)},p=l.select(".title-group text").call(u);if(t._context.edits.titleText){var h=o._(t,"Click to enter Plot title");c&&c!==h||(s=.2,p.attr({"data-unformatted":h}).text(h).style({opacity:s}).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)}));var g=function(){this.call(x.makeEditable,{gd:t}).on("edit",function(e){t.framework({layout:{title:e}}),this.text(e).call(u),this.call(g)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(u)})};p.call(g)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),f.addLinks(t),Promise.resolve()}(t,e,a);m._replotting=!0,g&&Y(t),t.framework!==Y&&(t.framework=Y,Y(t)),h.initGradients(t),g&&p.saveShowSpikeInitial(t);var _=!t.calcdata||t.calcdata.length!==(t._fullData||[]).length;_&&f.doCalcdata(t);for(var M=0;M<t.calcdata.length;M++)t.calcdata[M][0].trace=t._fullData[M];var T=JSON.stringify(m._size);function A(){var e,r,n,a=t.calcdata;for(f.clearAutoMarginIds(t),k.drawMarginPushers(t),p.allowAutoMargin(t),e=0;e<a.length;e++){var i=(n=(r=a[e])[0].trace)._module.colorbar;!0===n.visible&&i?y(t,r,i):f.autoMargin(t,"cb"+n.uid)}return f.doAutoMargin(t),f.previousPromises(t)}function C(){t._transitioning||(k.doAutoRangeAndConstraints(t),g&&p.saveRangeInitial(t))}var S=[f.previousPromises,function(){if(s)return r.addFrames(t,s)},function(){for(var e=m._basePlotModules,r=0;r<e.length;r++)e[r].drawFramework&&e[r].drawFramework(t);return!m._glcanvas&&m._has("gl")&&(m._glcanvas=m._glcontainer.selectAll(".gl-canvas").data([{key:"contextLayer",context:!0,pick:!1},{key:"focusLayer",context:!1,pick:!1},{key:"pickLayer",context:!1,pick:!0}],function(t){return t.key}),m._glcanvas.enter().append("canvas").attr("class",function(t){return"gl-canvas gl-canvas-"+t.key.replace("Layer","")}).style({position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible","pointer-events":"none"})),m._glcanvas&&m._glcanvas.attr("width",m.width).attr("height",m.height),f.previousPromises(t)},A,function(){if(JSON.stringify(m._size)!==T)return o.syncOrAsync([A,k.layoutStyles],t)}];b&&S.push(function(){if(_)return f.doSetPositions(t),c.getComponentMethod("errorbars","calc")(t),o.syncOrAsync([c.getComponentMethod("shapes","calcAutorange"),c.getComponentMethod("annotations","calcAutorange"),C,c.getComponentMethod("rangeslider","calcAutorange")],t);C()}),S.push(k.layoutStyles),b&&S.push(function(){return p.doTicks(t,g?"":"redraw")}),S.push(k.drawData,k.finalDraw,v,f.addLinks,f.rehover,f.doAutoMargin,f.previousPromises);var P=o.syncOrAsync(S,t);return P&&P.then||(P=Promise.resolve()),P.then(function(){return L(t),t})},r.setPlotConfig=function(t){return o.extendFlat(b,t)},r.redraw=function(t){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t);return w.cleanData(t.data),w.cleanLayout(t.layout),t.calcdata=void 0,r.plot(t).then(function(){return t.emit("plotly_redraw"),t})},r.newPlot=function(t,e,n,a){return t=o.getGraphDiv(t),f.cleanPlot([],{},t._fullData||[],t._fullLayout||{},t.calcdata||[]),f.purge(t),r.plot(t,e,n,a)},r.extendTraces=function t(e,n,a,i){var l=E(e=o.getGraphDiv(e),n,a,i,function(t,e,r){var n,a;if(o.isTypedArray(t))if(r<0){var i=new t.constructor(0),l=I(t,e);r<0?(n=l,a=i):(n=i,a=l)}else if(n=new t.constructor(r),a=new t.constructor(t.length+e.length-r),r===e.length)n.set(e),a.set(t);else if(r<e.length){var s=e.length-r;n.set(e.subarray(s)),a.set(t),a.set(e.subarray(0,s),t.length)}else{var c=r-e.length,u=t.length-c;n.set(t.subarray(u)),n.set(e,c),a.set(t.subarray(0,u))}else n=t.concat(e),a=r>=0&&r<n.length?n.splice(0,n.length-r):[];return[n,a]}),c=r.redraw(e),u=[e,l.update,a,l.maxPoints];return s.add(e,r.prependTraces,u,t,arguments),c},r.prependTraces=function t(e,n,a,i){var l=E(e=o.getGraphDiv(e),n,a,i,function(t,e,r){var n,a;if(o.isTypedArray(t))if(r<=0){var i=new t.constructor(0),l=I(e,t);r<0?(n=l,a=i):(n=i,a=l)}else if(n=new t.constructor(r),a=new t.constructor(t.length+e.length-r),r===e.length)n.set(e),a.set(t);else if(r<e.length){var s=e.length-r;n.set(e.subarray(0,s)),a.set(e.subarray(s)),a.set(t,s)}else{var c=r-e.length;n.set(e),n.set(t.subarray(0,c),e.length),a.set(t.subarray(c))}else n=e.concat(t),a=r>=0&&r<n.length?n.splice(r,n.length):[];return[n,a]}),c=r.redraw(e),u=[e,l.update,a,l.maxPoints];return s.add(e,r.extendTraces,u,t,arguments),c},r.addTraces=function t(e,n,a){e=o.getGraphDiv(e);var i,l,c=[],u=r.deleteTraces,f=t,d=[e,c],p=[e,n];for(function(t,e,r){var n,a;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n<e.length;n++)if("object"!=typeof(a=e[n])||Array.isArray(a)||null===a)throw new Error("all values in traces array must be non-array objects");if("undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&r.length!==e.length)throw new Error("if indices is specified, traces.length must equal indices.length")}(e,n,a),Array.isArray(n)||(n=[n]),n=n.map(function(t){return o.extendFlat({},t)}),w.cleanData(n),i=0;i<n.length;i++)e.data.push(n[i]);for(i=0;i<n.length;i++)c.push(-n.length+i);if("undefined"==typeof a)return l=r.redraw(e),s.add(e,u,d,f,p),l;Array.isArray(a)||(a=[a]);try{z(e,c,a)}catch(t){throw e.data.splice(e.data.length-n.length,n.length),t}return s.startSequence(e),s.add(e,u,d,f,p),l=r.moveTraces(e,c,a),s.stopSequence(e),l},r.deleteTraces=function t(e,n){e=o.getGraphDiv(e);var a,i,l=[],c=r.addTraces,u=t,f=[e,l,n],d=[e,n];if("undefined"==typeof n)throw new Error("indices must be an integer or array of integers.");for(Array.isArray(n)||(n=[n]),D(e,n,"indices"),(n=P(n,e.data.length-1)).sort(o.sorterDes),a=0;a<n.length;a+=1)i=e.data.splice(n[a],1)[0],l.push(i);var p=r.redraw(e);return s.add(e,c,f,u,d),p},r.moveTraces=function t(e,n,a){var i,l=[],c=[],u=t,f=t,d=[e=o.getGraphDiv(e),a,n],p=[e,n,a];if(z(e,n,a),n=Array.isArray(n)?n:[n],"undefined"==typeof a)for(a=[],i=0;i<n.length;i++)a.push(-n.length+i);for(a=Array.isArray(a)?a:[a],n=P(n,e.data.length-1),a=P(a,e.data.length-1),i=0;i<e.data.length;i++)-1===n.indexOf(i)&&l.push(e.data[i]);for(i=0;i<n.length;i++)c.push({newIndex:a[i],trace:e.data[n[i]]});for(c.sort(function(t,e){return t.newIndex-e.newIndex}),i=0;i<c.length;i+=1)l.splice(c[i].newIndex,0,c[i].trace);e.data=l;var h=r.redraw(e);return s.add(e,u,d,f,p),h},r.restyle=function t(e,n,a,i){e=o.getGraphDiv(e),w.clearPromiseQueue(e);var l={};if("string"==typeof n)l[n]=a;else{if(!o.isPlainObject(n))return o.warn("Restyle fail.",n,a,i),Promise.reject();l=o.extendFlat({},n),void 0===i&&(i=a)}Object.keys(l).length&&(e.changed=!0);var c=w.coerceTraceIndices(e,i),u=R(e,l,c),d=u.flags;d.clearCalc&&(e.calcdata=void 0),d.clearAxisTypes&&w.clearAxisTypes(e,c,{});var p=[];d.fullReplot?p.push(r.plot):(p.push(f.previousPromises),f.supplyDefaults(e),d.style&&p.push(k.doTraceStyle),d.colorbars&&p.push(k.doColorBars),p.push(L)),p.push(f.rehover),s.add(e,t,[e,u.undoit,u.traces],t,[e,u.redoit,u.traces]);var h=o.syncOrAsync(p,e);return h&&h.then||(h=Promise.resolve()),h.then(function(){return e.emit("plotly_restyle",u.eventData),e})},r.relayout=function t(e,r,n){if(e=o.getGraphDiv(e),w.clearPromiseQueue(e),e.framework&&e.framework.isPolar)return Promise.resolve(e);var a={};if("string"==typeof r)a[r]=n;else{if(!o.isPlainObject(r))return o.warn("Relayout fail.",r,n),Promise.reject();a=o.extendFlat({},r)}Object.keys(a).length&&(e.changed=!0);var i=q(e,a),l=i.flags;l.calc&&(e.calcdata=void 0);var c=[f.previousPromises];l.layoutReplot?c.push(k.layoutReplot):Object.keys(a).length&&(f.supplyDefaults(e),l.legend&&c.push(k.doLegend),l.layoutstyle&&c.push(k.layoutStyles),l.axrange&&F(c,i.rangesAltered),l.ticks&&c.push(k.doTicksRelayout),l.modebar&&c.push(k.doModeBar),l.camera&&c.push(k.doCamera),c.push(L)),c.push(f.rehover),s.add(e,t,[e,i.undoit],t,[e,i.redoit]);var u=o.syncOrAsync(c,e);return u&&u.then||(u=Promise.resolve(e)),u.then(function(){return e.emit("plotly_relayout",i.eventData),e})};var j=/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/,B=/^[xyz]axis[0-9]*\.autorange$/,H=/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;function q(t,e){var r,n,a,i=t.layout,l=t._fullLayout,s=Object.keys(e),f=p.list(t),d={};for(n=0;n<s.length;n++)if(0===s[n].indexOf("allaxes")){for(a=0;a<f.length;a++){var h=f[a]._id.substr(1),g=-1!==h.indexOf("scene")?h+".":"",y=s[n].replace("allaxes",g+f[a]._name);e[y]||(e[y]=e[s[n]])}delete e[s[n]]}var v=M.layoutFlags(),m={},x={};function b(t,r){if(Array.isArray(t))t.forEach(function(t){b(t,r)});else if(!(t in e||w.hasParent(e,t))){var n=o.nestedProperty(i,t);t in x||(x[t]=N(n.get())),void 0!==r&&n.set(r)}}var k,A={};function L(t){var e=p.name2id(t.split(".")[0]);return A[e]=1,e}for(var C in e){if(w.hasParent(e,C))throw new Error("cannot set "+C+"and a parent attribute simultaneously");for(var S=o.nestedProperty(i,C),O=e[C],P=S.parts.length-1;P>0&&"string"!=typeof S.parts[P];)P--;var D=S.parts[P],z=S.parts[P-1]+"."+D,E=S.parts.slice(0,P).join("."),I=o.nestedProperty(t.layout,E).get(),R=o.nestedProperty(l,E).get(),F=S.get();if(void 0!==O){m[C]=O,x[C]="reverse"===D?O:N(F);var q=u.getLayoutValObject(l,S.parts);if(q&&q.impliedEdits&&null!==O)for(var G in q.impliedEdits)b(o.relativeAttr(C,G),q.impliedEdits[G]);if(-1!==["width","height"].indexOf(C)&&null===O)l[C]=t._initialAutoSize[C];else if(z.match(j))L(z),o.nestedProperty(l,E+"._inputRange").set(null);else if(z.match(B)){L(z),o.nestedProperty(l,E+"._inputRange").set(null);var Y=o.nestedProperty(l,E).get();Y._inputDomain&&(Y._input.domain=Y._inputDomain.slice())}else z.match(H)&&o.nestedProperty(l,E+"._inputDomain").set(null);if("type"===D){var X=I,Z="linear"===R.type&&"log"===O,W="log"===R.type&&"linear"===O;if(Z||W){if(X&&X.range)if(R.autorange)Z&&(X.range=X.range[1]>X.range[0]?[1,2]:[2,1]);else{var Q=X.range[0],J=X.range[1];Z?(Q<=0&&J<=0&&b(E+".autorange",!0),Q<=0?Q=J/1e6:J<=0&&(J=Q/1e6),b(E+".range[0]",Math.log(Q)/Math.LN10),b(E+".range[1]",Math.log(J)/Math.LN10)):(b(E+".range[0]",Math.pow(10,Q)),b(E+".range[1]",Math.pow(10,J)))}else b(E+".autorange",!0);Array.isArray(l._subplots.polar)&&l._subplots.polar.length&&l[S.parts[0]]&&"radialaxis"===S.parts[1]&&delete l[S.parts[0]]._subplot.viewInitial["radialaxis.range"],c.getComponentMethod("annotations","convertCoords")(t,R,O,b),c.getComponentMethod("images","convertCoords")(t,R,O,b)}else b(E+".autorange",!0),b(E+".range",null);o.nestedProperty(l,E+"._inputRange").set(null)}else if(D.match(T)){var $=o.nestedProperty(l,C).get(),K=(O||{}).type;K&&"-"!==K||(K="linear"),c.getComponentMethod("annotations","convertCoords")(t,$,K,b),c.getComponentMethod("images","convertCoords")(t,$,K,b)}var tt=_.containerArrayMatch(C);if(tt){r=tt.array,n=tt.index;var et=tt.property,rt=(o.nestedProperty(i,r)||[])[n]||{},nt=rt,at=q||{editType:"calc"},it=-1!==at.editType.indexOf("calcIfAutorange");""===n?(it?v.calc=!0:M.update(v,at),it=!1):""===et&&(nt=O,_.isAddVal(O)?x[C]=null:_.isRemoveVal(O)?(x[C]=rt,nt=rt):o.warn("unrecognized full object value",e)),it&&(U(t,nt,"x")||U(t,nt,"y"))?v.calc=!0:M.update(v,at),d[r]||(d[r]={});var ot=d[r][n];ot||(ot=d[r][n]={}),ot[et]=O,delete e[C]}else"reverse"===D?(I.range?I.range.reverse():(b(E+".autorange",!0),I.range=[1,0]),R.autorange?v.calc=!0:v.plot=!0):(l._has("scatter-like")&&l._has("regl")&&"dragmode"===C&&("lasso"===O||"select"===O)&&"lasso"!==F&&"select"!==F?v.plot=!0:q?M.update(v,q):v.calc=!0,S.set(O))}}for(r in d){_.applyContainerArrayChanges(t,o.nestedProperty(i,r),d[r],v)||(v.plot=!0)}var lt=l._axisConstraintGroups||[];for(k in A)for(n=0;n<lt.length;n++){var st=lt[n];if(st[k])for(var ct in v.calc=!0,st)A[ct]||(p.getFromId(t,ct)._constraintShrinkable=!0)}return(V(t)||e.height||e.width)&&(v.plot=!0),(v.plot||v.calc)&&(v.layoutReplot=!0),{flags:v,rangesAltered:A,undoit:x,redoit:m,eventData:o.extendDeep({},m)}}function V(t){var e=t._fullLayout,r=e.width,n=e.height;return t.layout.autosize&&f.plotAutoSize(t,t.layout,e),e.width!==r||e.height!==n}function U(t,e,r){if(!o.isPlainObject(e))return!1;var n=e[r+"ref"]||r,a=p.getFromId(t,n);return a||n.charAt(0)!==r||(a=p.getFromId(t,r)),(a||{}).autorange}function G(t,e,r,n){var a,i,l=n.getValObject,s=n.flags,c=n.immutable,u=n.inArray,f=n.arrayIndex,d=n.gd,p=n.autoranged;function h(){var t=a.editType;-1!==t.indexOf("calcIfAutorange")&&(p||void 0===p&&(U(d,e,"x")||U(d,e,"y")))?s.calc=!0:u&&-1!==t.indexOf("arraydraw")?o.pushUnique(s.arrays[u],f):M.update(s,a)}function g(t){return"data_array"===t.valType||t.arrayOk}for(i in t){if(s.calc)return;var y=t[i],v=e[i];if("_"!==i.charAt(0)&&"function"!=typeof y&&y!==v){if("tick0"===i||"dtick"===i){var m=e.tickmode;if("auto"===m||"array"===m||!m)continue}if(("range"!==i||!e.autorange)&&("zmin"!==i&&"zmax"!==i||"contourcarpet"!==e.type)){var x=r.concat(i);if((a=l(x))&&(!a._compareAsJSON||JSON.stringify(y)!==JSON.stringify(v))){var b,_=a.valType,w=g(a),k=Array.isArray(y),T=Array.isArray(v);if(k&&T){var A="_input_"+i,L=t[A],C=e[A];if(Array.isArray(L)&&L===C)continue}if(void 0===v)w&&k?s.calc=!0:h();else if(a._isLinkedToArray){var S=[],O=!1;u||(s.arrays[i]=S);var P=Math.min(y.length,v.length),D=Math.max(y.length,v.length);if(P!==D){if("arraydraw"!==a.editType){h();continue}O=!0}for(b=0;b<P;b++)G(y[b],v[b],x.concat(b),o.extendFlat({inArray:i,arrayIndex:b},n));if(O)for(b=P;b<D;b++)S.push(b)}else!_&&o.isPlainObject(y)?G(y,v,x,n):w?k&&T?c&&(s.calc=!0):k!==T?s.calc=!0:h():k&&T&&y.length===v.length&&String(y)===String(v)||h()}}}}for(i in e)if(!(i in t||"_"===i.charAt(0)||"function"==typeof e[i])){if(g(a=l(r.concat(i)))&&Array.isArray(e[i]))return void(s.calc=!0);h()}}function Y(t){var e=n.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([{}]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var a={};n.selectAll("defs").each(function(){this.id&&(a[this.id.split("-")[1]]=1)}),r._uid=o.randstr(a)}r._paperdiv.selectAll(".main-svg").attr(m.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._clips=r._defs.append("g").classed("clips",!0),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._topclips=r._topdefs.append("g").classed("clips",!0),r._bgLayer=r._paper.append("g").classed("bglayer",!0),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=i.append("g").classed("imagelayer",!0),r._shapeLowerLayer=i.append("g").classed("shapelayer",!0),r._cartesianlayer=r._paper.append("g").classed("cartesianlayer",!0),r._polarlayer=r._paper.append("g").classed("polarlayer",!0),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0),r._geolayer=r._paper.append("g").classed("geolayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0);var l=r._toppaper.append("g").classed("layer-above",!0);r._imageUpperLayer=l.append("g").classed("imagelayer",!0),r._shapeUpperLayer=l.append("g").classed("shapelayer",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._menulayer=r._toppaper.append("g").classed("menulayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework")}r.update=function t(e,n,a,i){if(e=o.getGraphDiv(e),w.clearPromiseQueue(e),e.framework&&e.framework.isPolar)return Promise.resolve(e);o.isPlainObject(n)||(n={}),o.isPlainObject(a)||(a={}),Object.keys(n).length&&(e.changed=!0),Object.keys(a).length&&(e.changed=!0);var l=w.coerceTraceIndices(e,i),c=R(e,o.extendFlat({},n),l),u=c.flags,d=q(e,o.extendFlat({},a)),p=d.flags;(u.clearCalc||p.calc)&&(e.calcdata=void 0),u.clearAxisTypes&&w.clearAxisTypes(e,l,a);var h=[];if(u.fullReplot&&p.layoutReplot){var g=e.data,y=e.layout;e.data=void 0,e.layout=void 0,h.push(function(){return r.plot(e,g,y)})}else u.fullReplot?h.push(r.plot):p.layoutReplot?h.push(k.layoutReplot):(h.push(f.previousPromises),f.supplyDefaults(e),u.style&&h.push(k.doTraceStyle),u.colorbars&&h.push(k.doColorBars),p.legend&&h.push(k.doLegend),p.layoutstyle&&h.push(k.layoutStyles),p.axrange&&F(h,d.rangesAltered),p.ticks&&h.push(k.doTicksRelayout),p.modebar&&h.push(k.doModeBar),p.camera&&h.push(k.doCamera),h.push(L));h.push(f.rehover),s.add(e,t,[e,c.undoit,d.undoit,c.traces],t,[e,c.redoit,d.redoit,c.traces]);var v=o.syncOrAsync(h,e);return v&&v.then||(v=Promise.resolve(e)),v.then(function(){return e.emit("plotly_update",{data:c.eventData,layout:d.eventData}),e})},r.react=function(t,e,n,a){var i,l;var s=(t=o.getGraphDiv(t))._fullData,d=t._fullLayout;if(o.isPlotDiv(t)&&s&&d){if(o.isPlainObject(e)){var h=e;e=h.data,n=h.layout,a=h.config,i=h.frames}var g=!1;if(a){var y=o.extendDeep({},t._context);t._context=void 0,O(t,a),g=function t(e,r){var n;for(n in e){var a=e[n],i=r[n];if(a!==i)if(o.isPlainObject(a)&&o.isPlainObject(i)){if(t(a,i))return!0}else{if(!Array.isArray(a)||!Array.isArray(i))return!0;if(a.length!==i.length)return!0;for(var l=0;l<a.length;l++)if(a[l]!==i[l]){if(!o.isPlainObject(a[l])||!o.isPlainObject(i[l]))return!0;if(t(a[l],i[l]))return!0}}}}(y,t._context)}t.data=e||[],w.cleanData(t.data),t.layout=n||{},w.cleanLayout(t.layout),f.supplyDefaults(t,{skipUpdateCalc:!0});var v=t._fullData,m=t._fullLayout,x=void 0===m.datarevision,b=function(t,e,r,n){if(e.length!==r.length)return{fullReplot:!0,calc:!0};var a,i,o=M.traceFlags();o.arrays={};var l={getValObject:function(t){return u.getTraceValObject(i,t)},flags:o,immutable:n,gd:t},s={};for(a=0;a<e.length;a++)i=r[a]._fullInput,s[i.uid]||(s[i.uid]=1,l.autoranged=!!i.xaxis&&(p.getFromId(t,i.xaxis).autorange||p.getFromId(t,i.yaxis).autorange),G(e[a]._fullInput,i,[],l));(o.calc||o.plot||o.calcIfAutorange)&&(o.fullReplot=!0);return o}(t,s,v,x),_=function(t,e,r,n){var a=M.layoutFlags();a.arrays={},G(e,r,[],{getValObject:function(t){return u.getLayoutValObject(r,t)},flags:a,immutable:n,gd:t}),(a.plot||a.calc)&&(a.layoutReplot=!0);return a}(t,d,m,x);V(t)&&(_.layoutReplot=!0),b.calc||_.calc?t.calcdata=void 0:f.supplyDefaultsUpdateCalc(t.calcdata,v);var T=[];if(i&&(t._transitionData={},f.createTransitionData(t),T.push(function(){return r.addFrames(t,i)})),b.fullReplot||_.layoutReplot||g)t._fullLayout._skipDefaults=!0,T.push(r.plot);else{for(var A in _.arrays){var C=_.arrays[A];if(C.length){var S=c.getComponentMethod(A,"drawOne");if(S!==o.noop)for(var P=0;P<C.length;P++)S(t,C[P]);else{var D=c.getComponentMethod(A,"draw");if(D===o.noop)throw new Error("cannot draw components: "+A);D(t)}}}T.push(f.previousPromises),b.style&&T.push(k.doTraceStyle),b.colorbars&&T.push(k.doColorBars),_.legend&&T.push(k.doLegend),_.layoutstyle&&T.push(k.layoutStyles),_.axrange&&F(T),_.ticks&&T.push(k.doTicksRelayout),_.modebar&&T.push(k.doModeBar),_.camera&&T.push(k.doCamera),T.push(L)}T.push(f.rehover),(l=o.syncOrAsync(T,t))&&l.then||(l=Promise.resolve(t))}else l=r.newPlot(t,e,n,a);return l.then(function(){return t.emit("plotly_react",{data:e,layout:n}),t})},r.animate=function(t,e,r){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t+". It's likely that you've failed to create a plot before animating it. For more details, see https://plot.ly/javascript/animations/");var n=t._transitionData;n._frameQueue||(n._frameQueue=[]);var a=(r=f.supplyAnimationDefaults(r)).transition,i=r.frame;function l(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function s(t){return Array.isArray(i)?t>=i.length?i[0]:i[t]:i}function c(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(i,u){function d(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,f.transition(t,e.frame.data,e.frame.layout,w.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function p(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&d()};e()}var h,g,y=0;function v(t){return Array.isArray(a)?y>=a.length?t.transitionOpts=a[y]:t.transitionOpts=a[0]:t.transitionOpts=a,y++,t}var m=[],x=null==e,b=Array.isArray(e);if(!x&&!b&&o.isPlainObject(e))m.push({type:"object",data:v(o.extendFlat({},e))});else if(x||-1!==["string","number"].indexOf(typeof e))for(h=0;h<n._frames.length;h++)(g=n._frames[h])&&(x||String(g.group)===String(e))&&m.push({type:"byname",name:String(g.name),data:v({name:g.name})});else if(b)for(h=0;h<e.length;h++){var _=e[h];-1!==["number","string"].indexOf(typeof _)?(_=String(_),m.push({type:"byname",name:_,data:v({name:_})})):o.isPlainObject(_)&&m.push({type:"object",data:v(o.extendFlat({},_))})}for(h=0;h<m.length;h++)if("byname"===(g=m[h]).type&&!n._frameHash[g.data.name])return o.warn('animate failure: frame not found: "'+g.data.name+'"'),void u();-1!==["next","immediate"].indexOf(r.mode)&&function(){if(0!==n._frameQueue.length){for(;n._frameQueue.length;){var e=n._frameQueue.pop();e.onInterrupt&&e.onInterrupt()}t.emit("plotly_animationinterrupted",[])}}(),"reverse"===r.direction&&m.reverse();var k=t._fullLayout._currentFrame;if(k&&r.fromcurrent){var M=-1;for(h=0;h<m.length;h++)if("byname"===(g=m[h]).type&&g.name===k){M=h;break}if(M>0&&M<m.length-1){var T=[];for(h=0;h<m.length;h++)g=m[h],("byname"!==m[h].type||h>M)&&T.push(g);m=T}}m.length>0?function(e){if(0!==e.length){for(var a=0;a<e.length;a++){var o;o="byname"===e[a].type?f.computeFrame(t,e[a].name):e[a].data;var d=s(a),h=l(a);h.duration=Math.min(h.duration,d.duration);var g={frame:o,name:e[a].name,frameOpts:d,transitionOpts:h};a===e.length-1&&(g.onComplete=c(i,2),g.onInterrupt=u),n._frameQueue.push(g)}"immediate"===r.mode&&(n._lastFrameAt=-1/0),n._animationRaf||p()}}(m):(t.emit("plotly_animated"),i())})},r.addFrames=function(t,e,r){if(t=o.getGraphDiv(t),null==e)return Promise.resolve();if(!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t+". It's likely that you've failed to create a plot before adding frames. For more details, see https://plot.ly/javascript/animations/");var n,a,i,l,c=t._transitionData._frames,u=t._transitionData._frameHash;if(!Array.isArray(e))throw new Error("addFrames failure: frameList must be an Array of frame definitions"+e);var d=c.length+2*e.length,p=[],h={};for(n=e.length-1;n>=0;n--)if(o.isPlainObject(e[n])){var g=e[n].name,y=(u[g]||h[g]||{}).name,v=e[n].name,m=u[y]||h[y];y&&v&&"number"==typeof v&&m&&A<5&&(A++,o.warn('addFrames: overwriting frame "'+(u[y]||h[y]).name+'" with a frame whose name of type "number" also equates to "'+y+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===A&&o.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),h[g]={name:g},p.push({frame:f.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:d+n})}p.sort(function(t,e){return t.index>e.index?-1:t.index<e.index?1:0});var x=[],b=[],_=c.length;for(n=p.length-1;n>=0;n--){if("number"==typeof(a=p[n].frame).name&&o.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;u[a.name="frame "+t._transitionData._counter++];);if(u[a.name]){for(i=0;i<c.length&&(c[i]||{}).name!==a.name;i++);x.push({type:"replace",index:i,value:a}),b.unshift({type:"replace",index:i,value:c[i]})}else l=Math.max(0,Math.min(p[n].index,_)),x.push({type:"insert",index:l,value:a}),b.unshift({type:"delete",index:l}),_++}var w=f.modifyFrames,k=f.modifyFrames,M=[t,b],T=[t,x];return s&&s.add(t,w,M,k,T),f.modifyFrames(t,x)},r.deleteFrames=function(t,e){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t);var r,n,a=t._transitionData._frames,i=[],l=[];if(!e)for(e=[],r=0;r<a.length;r++)e.push(r);for((e=e.slice(0)).sort(),r=e.length-1;r>=0;r--)n=e[r],i.push({type:"delete",index:n}),l.unshift({type:"insert",index:n,value:a[n]});var c=f.modifyFrames,u=f.modifyFrames,d=[t,l],p=[t,i];return s&&s.add(t,c,d,u,p),f.modifyFrames(t,i)},r.purge=function(t){var e=(t=o.getGraphDiv(t))._fullLayout||{},r=t._fullData||[],n=t.calcdata||[];return f.cleanPlot([],{},r,e,n),f.purge(t),l.purge(t),e._container&&e._container.remove(),delete t._context,t}},{"../components/color":45,"../components/colorbar/connect":47,"../components/drawing":70,"../constants/xmlns_namespaces":147,"../lib":163,"../lib/events":156,"../lib/queue":177,"../lib/svg_text_utils":184,"../plots/cartesian/axes":207,"../plots/cartesian/constants":212,"../plots/cartesian/graph_interact":216,"../plots/plots":239,"../plots/polar/legacy":242,"../registry":247,"./edit_types":190,"./helpers":191,"./manage_arrays":193,"./plot_config":195,"./plot_schema":196,"./subroutines":198,d3:10,"fast-isnumeric":13,"has-hover":15}],195:[function(t,e,r){"use strict";e.exports={staticPlot:!1,plotlyServerURL:"https://plot.ly",editable:!1,edits:{annotationPosition:!1,annotationTail:!1,annotationText:!1,axisTitleText:!1,colorbarPosition:!1,colorbarTitleText:!1,legendPosition:!1,legendText:!1,shapePosition:!1,titleText:!1},autosizable:!1,queueLength:0,fillFrame:!1,frameMargins:0,scrollZoom:!1,doubleClick:"reset+autosize",showTips:!0,showAxisDragHandles:!0,showAxisRangeEntryBoxes:!0,showLink:!1,sendData:!0,linkText:"Edit chart",showSources:!1,displayModeBar:"hover",modeBarButtonsToRemove:[],modeBarButtonsToAdd:[],modeBarButtons:!1,toImageButtonOptions:{},displaylogo:!0,plotGlPixelRatio:2,setBackground:"transparent",topojsonURL:"https://cdn.plot.ly/",mapboxAccessToken:null,logging:1,globalTransforms:[],locale:"en-US",locales:{}}},{}],196:[function(t,e,r){"use strict";var n=t("../registry"),a=t("../lib"),i=t("../plots/attributes"),o=t("../plots/layout_attributes"),l=t("../plots/frame_attributes"),s=t("../plots/animation_attributes"),c=t("../plots/polar/legacy/area_attributes"),u=t("../plots/polar/legacy/axis_attributes"),f=t("./edit_types"),d=a.extendFlat,p=a.extendDeepAll,h=a.isPlainObject,g="_isSubplotObj",y="_isLinkedToArray",v=[g,y,"_arrayAttrRegexps","_deprecated"];function m(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(x(e[r]))r++;else if(r<e.length)return!1;for(;r<e.length;r++){var n=t[e[r]];if(!h(n))break;if(t=n,r===e.length-1)break;if(t._isLinkedToArray){if(!x(e[++r]))return!1}else if("info_array"===t.valType){var a=e[++r];if(!x(a))return!1;var i=t.items;if(Array.isArray(i)){if(a>=i.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!x(o))return!1;t=i[a][o]}else t=i[a]}else t=i}}return t}function x(t){return t===Math.round(t)&&t>=0}function b(t){return function(t){r.crawl(t,function(t,e,n){r.isValObject(t)?"data_array"===t.valType?(t.role="data",n[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(n[e+"src"]={valType:"string",editType:"none"}):h(t)&&(t.role="object")})}(t),function(t){r.crawl(t,function(t,e,r){if(!t)return;var n=t[y];if(!n)return;delete t[y],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(h(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n<e[r].length;n++)t(e[r][n]);else e[r]instanceof RegExp&&(e[r]=e[r].toString())}(t)}(t),t}function _(t,e,r){var n=a.nestedProperty(t,r),i=p({},e.layoutAttributes);i[g]=!0,n.set(i)}function w(t,e,r){var n=a.nestedProperty(t,r);n.set(p(n.get()||{},e))}r.IS_SUBPLOT_OBJ=g,r.IS_LINKED_TO_ARRAY=y,r.DEPRECATED="_deprecated",r.UNDERSCORE_ATTRS=v,r.get=function(){var t={};n.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:c},r={}):(e=n.modules[t]._module,r=e.basePlotModule);var a={type:null};p(a,i),p(a,e.attributes),r.attributes&&p(a,r.attributes);a.type=t;var o={meta:e.meta||{},attributes:b(a)};if(e.layoutAttributes){var l={};p(l,e.layoutAttributes),o.layoutAttributes=b(l)}return o}(e)});var e,r={};return Object.keys(n.transformsRegistry).forEach(function(t){r[t]=function(t){var e=n.transformsRegistry[t],r=p({},e.attributes);return Object.keys(n.componentsRegistry).forEach(function(e){var a=n.componentsRegistry[e];a.schema&&a.schema.transforms&&a.schema.transforms[t]&&Object.keys(a.schema.transforms[t]).forEach(function(e){w(r,a.schema.transforms[t][e],e)})}),{attributes:b(r)}}(t)}),{defs:{valObjects:a.valObjectMeta,metaKeys:v.concat(["description","role","editType","impliedEdits"]),editType:{traces:f.traces,layout:f.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in p(r,o),n.subplotsRegistry)if((e=n.subplotsRegistry[t]).layoutAttributes)if(Array.isArray(e.attr))for(var a=0;a<e.attr.length;a++)_(r,e,e.attr[a]);else{var i="subplot"===e.attr?e.name:e.attr;_(r,e,i)}for(t in r=function(t){return d(t,{radialaxis:u.radialaxis,angularaxis:u.angularaxis}),d(t,u.layout),t}(r),n.componentsRegistry){var l=(e=n.componentsRegistry[t]).schema;if(l&&(l.subplots||l.layout)){var s=l.subplots;if(s&&s.xaxis&&!s.yaxis)for(var c in s.xaxis)delete r.yaxis[c]}else e.layoutAttributes&&w(r,e.layoutAttributes,e.name)}return{layoutAttributes:b(r)}}(),transforms:r,frames:(e={frames:a.extendDeepAll({},l)},b(e),e.frames),animation:b(s)}},r.crawl=function(t,e,n,a){var i=n||0;a=a||"",Object.keys(t).forEach(function(n){var o=t[n];if(-1===v.indexOf(n)){var l=(a?a+".":"")+n;e(o,n,t,i,l),r.isValObject(o)||h(o)&&"impliedEdits"!==n&&r.crawl(o,e,i+1,l)}})},r.isValObject=function(t){return t&&void 0!==t.valType},r.findArrayAttributes=function(t){var e,n,o=[],l=[],s=[];function c(t,r,i,c){l=l.slice(0,c).concat([r]),s=s.slice(0,c).concat([t&&t._isLinkedToArray]),t&&("data_array"===t.valType||!0===t.arrayOk)&&!("colorbar"===l[c-1]&&("ticktext"===r||"tickvals"===r))&&function t(e,r,i){var c=e[l[r]];var u=i+l[r];if(r===l.length-1)a.isArrayOrTypedArray(c)&&o.push(n+u);else if(s[r]){if(Array.isArray(c))for(var f=0;f<c.length;f++)a.isPlainObject(c[f])&&t(c[f],r+1,u+"["+f+"].")}else a.isPlainObject(c)&&t(c,r+1,u+".")}(e,0,"")}e=t,n="",r.crawl(i,c),t._module&&t._module.attributes&&r.crawl(t._module.attributes,c);var u=t.transforms;if(u)for(var f=0;f<u.length;f++){var d=u[f],p=d._module;p&&(n="transforms["+f+"].",e=d,r.crawl(p.attributes,c))}return o},r.getTraceValObject=function(t,e){var r,a,o=e[0],l=1;if("transforms"===o){if(1===e.length)return i.transforms;var s=t.transforms;if(!Array.isArray(s)||!s.length)return!1;var u=e[1];if(!x(u)||u>=s.length)return!1;a=(r=(n.transformsRegistry[s[u].type]||{}).attributes)&&r[e[2]],l=3}else if("area"===t.type)a=c[o];else{var f=t._module;if(f||(f=(n.modules[t.type||i.type.dflt]||{})._module),!f)return!1;if(!(a=(r=f.attributes)&&r[o])){var d=f.basePlotModule;d&&d.attributes&&(a=d.attributes[o])}a||(a=i[o])}return m(a,e,l)},r.getLayoutValObject=function(t,e){return m(function(t,e){var r,a,i,l,s=t._basePlotModules;if(s){var c;for(r=0;r<s.length;r++){if((i=s[r]).attrRegex&&i.attrRegex.test(e)){if(i.layoutAttrOverrides)return i.layoutAttrOverrides;!c&&i.layoutAttributes&&(c=i.layoutAttributes)}var f=i.baseLayoutAttrOverrides;if(f&&e in f)return f[e]}if(c)return c}var d=t._modules;if(d)for(r=0;r<d.length;r++)if((l=d[r].layoutAttributes)&&e in l)return l[e];for(a in n.componentsRegistry)if(!(i=n.componentsRegistry[a]).schema&&e===i.name)return i.layoutAttributes;if(e in o)return o[e];if("radialaxis"===e||"angularaxis"===e)return u[e];return u.layout[e]||!1}(t,e[0]),e,1)}},{"../lib":163,"../plots/animation_attributes":202,"../plots/attributes":204,"../plots/frame_attributes":234,"../plots/layout_attributes":237,"../plots/polar/legacy/area_attributes":240,"../plots/polar/legacy/axis_attributes":241,"../registry":247,"./edit_types":190}],197:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plots/attributes"),i="templateitemname",o={name:{valType:"string",editType:"none"}};function l(t){return t&&"string"==typeof t}function s(t){var e=t.length-1;return"s"!==t.charAt(e)&&n.warn("bad argument to arrayDefaultKey: "+t),t.substr(0,t.length-1)+"defaults"}o[i]={valType:"string",editType:"calc"},r.templatedArray=function(t,e){return e._isLinkedToArray=t,e.name=o.name,e[i]=o[i],e},r.traceTemplater=function(t){var e,r,i={};for(e in t)r=t[e],Array.isArray(r)&&r.length&&(i[e]=0);return{newTrace:function(o){var l={type:e=n.coerce(o,{},a,"type"),_template:null};if(e in i){r=t[e];var s=i[e]%r.length;i[e]++,l._template=r[s]}return l}}},r.newContainer=function(t,e,r){var a=t._template,i=a&&(a[e]||r&&a[r]);return n.isPlainObject(i)||(i=null),t[e]={_template:i}},r.arrayTemplater=function(t,e,r){var n=t._template,a=n&&n[s(e)],o=n&&n[e];Array.isArray(o)&&o.length||(o=[]);var c={};return{newItem:function(t){var e={name:t.name,_input:t},n=e[i]=t[i];if(!l(n))return e._template=a,e;for(var s=0;s<o.length;s++){var u=o[s];if(u.name===n)return c[n]=1,e._template=u,e}return e[r]=t[r]||!1,e._template=!1,e},defaultItems:function(){for(var t=[],e=0;e<o.length;e++){var r=o[e],n=r.name;if(l(n)&&!c[n]){var a={_template:r,name:n,_input:{_templateitemname:n}};a[i]=r[i],t.push(a),c[n]=1}}return t}}},r.arrayDefaultKey=s,r.arrayEditor=function(t,e,r){var a=(n.nestedProperty(t,e).get()||[]).length,o=r._index,l=o>=a&&(r._input||{})._templateitemname;l&&(o=a);var s,c=e+"["+o+"]";function u(){s={},l&&(s[c]={},s[c][i]=l)}function f(t,e){l?n.nestedProperty(s[c],t).set(e):s[c+"."+t]=e}function d(){var t=s;return u(),t}return u(),{modifyBase:function(t,e){s[t]=e},modifyItem:f,getUpdateObj:d,applyUpdate:function(e,r){e&&f(e,r);var a=d();for(var i in a)n.nestedProperty(t,i).set(a[i])}}}},{"../lib":163,"../plots/attributes":204}],198:[function(t,e,r){"use strict";var n=t("d3"),a=t("../registry"),i=t("../plots/plots"),o=t("../lib"),l=t("../lib/clear_gl_canvases"),s=t("../components/color"),c=t("../components/drawing"),u=t("../components/titles"),f=t("../components/modebar"),d=t("../plots/cartesian/axes"),p=t("../constants/alignment"),h=t("../plots/cartesian/constraints"),g=h.enforce,y=h.clean,v=t("../plots/cartesian/autorange").doAutoRange;function m(t){var e,a=t._fullLayout,i=a._size,l=i.p,u=d.list(t,"",!0),h=a._has("cartesian");function g(t,e,r){var n=t._lw/2;return"x"===t._id.charAt(0)?e?"top"===r?e._offset-l-n:e._offset+e._length+l+n:i.t+i.h*(1-(t.position||0))+n%1:e?"right"===r?e._offset+e._length+l+n:e._offset-l-n:i.l+i.w*(t.position||0)+n%1}for(e=0;e<u.length;e++){var y=u[e];y.setScale();var v=y._anchorAxis;y._linepositions={},y._lw=c.crispRound(t,y.linewidth,1),y._mainLinePosition=g(y,v,y.side),y._mainMirrorPosition=y.mirror&&v?g(y,v,p.OPPOSITE_SIDE[y.side]):null,y._mainSubplot=x(y,a)}a._paperdiv.style({width:a.width+"px",height:a.height+"px"}).selectAll(".main-svg").call(c.setSize,a.width,a.height),t._context.setBackground(t,a.paper_bgcolor);var m=a._paper.selectAll("g.subplot"),_=[],k=[];m.each(function(t){var e=a._plots[t];if(e.mainplot)return e.bg&&e.bg.remove(),void(e.bg=void 0);var r=e.xaxis.domain,n=e.yaxis.domain,i=e.plotgroup;if(function(t,e,r){for(var n=0;n<r.length;n++){var a=r[n][0],i=r[n][1];if(!(a[0]>=t[1]||a[1]<=t[0])&&i[0]<e[1]&&i[1]>e[0])return!0}return!1}(r,n,k)){var l=i.node(),s=e.bg=o.ensureSingle(i,"rect","bg");l.insertBefore(s.node(),l.childNodes[0])}else i.select("rect.bg").remove(),_.push(t),k.push([r,n])});var M=a._bgLayer.selectAll(".bg").data(_);return M.enter().append("rect").classed("bg",!0),M.exit().remove(),M.each(function(t){a._plots[t].bg=n.select(this)}),m.each(function(t){var e=a._plots[t],r=e.xaxis,n=e.yaxis;e.bg&&h&&e.bg.call(c.setRect,r._offset-l,n._offset-l,r._length+2*l,n._length+2*l).call(s.fill,a.plot_bgcolor).style("stroke-width",0);var i,f,d=e.clipId="clip"+a._uid+t+"plot",p=o.ensureSingleById(a._clips,"clipPath",d,function(t){t.classed("plotclip",!0).append("rect")});if(e.clipRect=p.select("rect").attr({width:r._length,height:n._length}),c.setTranslate(e.plot,r._offset,n._offset),e._hasClipOnAxisFalse?(i=null,f=d):(i=d,f=null),c.setClipUrl(e.plot,i),e.layerClipId=f,h){var y,v,m,x,_,k,M,T,A,L,C,S,O,P="M0,0";b(r,t)&&(_=w(r,"left",n,u),y=r._offset-(_?l+_:0),k=w(r,"right",n,u),v=r._offset+r._length+(k?l+k:0),m=g(r,n,"bottom"),x=g(r,n,"top"),(O=!r._anchorAxis||t!==r._mainSubplot)&&r.ticks&&"allticks"===r.mirror&&(r._linepositions[t]=[m,x]),P=I(r,z,function(t){return"M"+r._offset+","+t+"h"+r._length}),O&&r.showline&&("all"===r.mirror||"allticks"===r.mirror)&&(P+=z(m)+z(x)),e.xlines.style("stroke-width",r._lw+"px").call(s.stroke,r.showline?r.linecolor:"rgba(0,0,0,0)")),e.xlines.attr("d",P);var D="M0,0";b(n,t)&&(C=w(n,"bottom",r,u),M=n._offset+n._length+(C?l:0),S=w(n,"top",r,u),T=n._offset-(S?l:0),A=g(n,r,"left"),L=g(n,r,"right"),(O=!n._anchorAxis||t!==r._mainSubplot)&&n.ticks&&"allticks"===n.mirror&&(n._linepositions[t]=[A,L]),D=I(n,E,function(t){return"M"+t+","+n._offset+"v"+n._length}),O&&n.showline&&("all"===n.mirror||"allticks"===n.mirror)&&(D+=E(A)+E(L)),e.ylines.style("stroke-width",n._lw+"px").call(s.stroke,n.showline?n.linecolor:"rgba(0,0,0,0)")),e.ylines.attr("d",D)}function z(t){return"M"+y+","+t+"H"+v}function E(t){return"M"+t+","+T+"V"+M}function I(e,r,n){if(!e.showline||t!==e._mainSubplot)return"";if(!e._anchorAxis)return n(e._mainLinePosition);var a=r(e._mainLinePosition);return e.mirror&&(a+=r(e._mainMirrorPosition)),a}}),d.makeClipPaths(t),r.drawMainTitle(t),f.manage(t),t._promises.length&&Promise.all(t._promises)}function x(t,e){var r=e._subplots,n=r.cartesian.concat(r.gl2d||[]),a={_fullLayout:e},i="x"===t._id.charAt(0),o=t._mainAxis._anchorAxis,l="",s="",c="";if(o&&(c=o._mainAxis._id,l=i?t._id+c:c+t._id),!l||!e._plots[l]){l="";for(var u=0;u<n.length;u++){var f=n[u],p=f.indexOf("y"),h=i?f.substr(0,p):f.substr(p),g=i?f.substr(p):f.substr(0,p);if(h===t._id){s||(s=f);var y=d.getFromId(a,g);if(c&&y.overlaying===c){l=f;break}}}}return l||s}function b(t,e){return(t.ticks||t.showline)&&(e===t._mainSubplot||"all"===t.mirror||"allticks"===t.mirror)}function _(t,e,r){if(!r.showline||!r._lw)return!1;if("all"===r.mirror||"allticks"===r.mirror)return!0;var n=r._anchorAxis;if(!n)return!1;var a=p.FROM_BL[e];return r.side===e?n.domain[a]===t.domain[a]:r.mirror&&n.domain[1-a]===t.domain[1-a]}function w(t,e,r,n){if(_(t,e,r))return r._lw;for(var a=0;a<n.length;a++){var i=n[a];if(i._mainAxis===r._mainAxis&&_(t,e,i))return i._lw}return 0}r.layoutStyles=function(t){return o.syncOrAsync([i.doAutoMargin,m],t)},r.drawMainTitle=function(t){var e=t._fullLayout;u.draw(t,"gtitle",{propContainer:e,propName:"title",placeholder:e._dfltTitle.plot,attributes:{x:e.width/2,y:e._size.t/2,"text-anchor":"middle"}})},r.doTraceStyle=function(t){for(var e=0;e<t.calcdata.length;e++){var r=t.calcdata[e],n=(((r[0]||{}).trace||{})._module||{}).arraysToCalcdata;n&&n(r,r[0].trace)}return i.style(t),a.getComponentMethod("legend","draw")(t),i.previousPromises(t)},r.doColorBars=function(t){for(var e=0;e<t.calcdata.length;e++){var r=t.calcdata[e][0];if((r.t||{}).cb){var n=r.trace,o=r.t.cb;a.traceIs(n,"contour")&&o.line({width:!1!==n.contours.showlines?n.line.width:0,dash:n.line.dash,color:"line"===n.contours.coloring?o._opts.line.color:n.line.color});var l=n._module.colorbar.container,s=(l?n[l]:n).colorbar;o.options(s)()}}return i.previousPromises(t)},r.layoutReplot=function(t){var e=t.layout;return t.layout=void 0,a.call("plot",t,"",e)},r.doLegend=function(t){return a.getComponentMethod("legend","draw")(t),i.previousPromises(t)},r.doTicksRelayout=function(t,e){return e?d.doTicks(t,Object.keys(e),!0):d.doTicks(t,"redraw"),t._fullLayout._hasOnlyLargeSploms&&(l(t),a.subplotsRegistry.splom.plot(t)),r.drawMainTitle(t),i.previousPromises(t)},r.doModeBar=function(t){var e=t._fullLayout;f.manage(t);for(var r=0;r<e._basePlotModules.length;r++){var n=e._basePlotModules[r].updateFx;n&&n(e)}return i.previousPromises(t)},r.doCamera=function(t){for(var e=t._fullLayout,r=e._subplots.gl3d,n=0;n<r.length;n++){var a=e[r[n]];a._scene.setCamera(a.camera)}},r.drawData=function(t){var e,r=t._fullLayout,n=t.calcdata;for(e=0;e<n.length;e++){var o=n[e][0].trace;!0===o.visible&&o._module.colorbar||r._infolayer.select(".cb"+o.uid).remove()}l(t);var s=r._basePlotModules;for(e=0;e<s.length;e++)s[e].plot(t);return i.style(t),a.getComponentMethod("shapes","draw")(t),a.getComponentMethod("annotations","draw")(t),r._replotting=!1,i.previousPromises(t)},r.doAutoRangeAndConstraints=function(t){for(var e=d.list(t,"",!0),r=0;r<e.length;r++){var n=e[r];y(t,n),v(n)}g(t)},r.finalDraw=function(t){a.getComponentMethod("shapes","draw")(t),a.getComponentMethod("images","draw")(t),a.getComponentMethod("annotations","draw")(t),a.getComponentMethod("rangeslider","draw")(t),a.getComponentMethod("rangeselector","draw")(t)},r.drawMarginPushers=function(t){a.getComponentMethod("legend","draw")(t),a.getComponentMethod("rangeselector","draw")(t),a.getComponentMethod("sliders","draw")(t),a.getComponentMethod("updatemenus","draw")(t)}},{"../components/color":45,"../components/drawing":70,"../components/modebar":108,"../components/titles":136,"../constants/alignment":143,"../lib":163,"../lib/clear_gl_canvases":152,"../plots/cartesian/autorange":206,"../plots/cartesian/axes":207,"../plots/cartesian/constraints":214,"../plots/plots":239,"../registry":247,d3:10}],199:[function(t,e,r){"use strict";var n=t("../lib"),a=n.isPlainObject,i=t("./plot_schema"),o=t("../plots/plots"),l=t("../plots/attributes"),s=t("./plot_template"),c=t("./plot_config");function u(t,e){t=n.extendDeep({},t);var r,i,o=Object.keys(t).sort();function l(e,r,n){if(a(r)&&a(e))u(e,r);else if(Array.isArray(r)&&Array.isArray(e)){var o=s.arrayTemplater({_template:t},n);for(i=0;i<r.length;i++){var l=r[i],c=o.newItem(l)._template;c&&u(c,l)}var f=o.defaultItems();for(i=0;i<f.length;i++)r.push(f[i]._template);for(i=0;i<r.length;i++)delete r[i].templateitemname}}for(r=0;r<o.length;r++){var c=o[r],d=t[c];if(c in e?l(d,e[c],c):e[c]=d,f(c)===c)for(var p in e){var h=f(p);p===h||h!==c||p in t||l(d,e[p],c)}}}function f(t){return t.replace(/[0-9]+$/,"")}function d(t,e,r,i,o){var l=o&&r(o);for(var c in t){var u=t[c],h=p(t,c,i),g=p(t,c,o),y=r(g);if(!y){var v=f(c);v!==c&&(y=r(g=p(t,v,o)))}if((!l||l!==y)&&!(!y||y._noTemplating||"data_array"===y.valType||y.arrayOk&&Array.isArray(u)))if(!y.valType&&a(u))d(u,e,r,h,g);else if(y._isLinkedToArray&&Array.isArray(u))for(var m=!1,x=0,b={},_=0;_<u.length;_++){var w=u[_];if(a(w)){var k=w.name;if(k)b[k]||(d(w,e,r,p(u,x,h),p(u,x,g)),x++,b[k]=1);else if(!m){var M=p(t,s.arrayDefaultKey(c),i),T=p(u,x,h);d(w,e,r,T,p(u,x,g));var A=n.nestedProperty(e,T);n.nestedProperty(e,M).set(A.get()),A.set(null),m=!0}}}else{n.nestedProperty(e,h).set(u)}}}function p(t,e,r){return r?Array.isArray(t)?r+"["+e+"]":r+"."+e:e}function h(t){for(var e=0;e<t.length;e++)if(a(t[e]))return!0}function g(t){var e;switch(t.code){case"data":e="The template has no key data.";break;case"layout":e="The template has no key layout.";break;case"missing":e=t.path?"There are no templates for item "+t.path+" with name "+t.templateitemname:"There are no templates for trace "+t.index+", of type "+t.traceType+".";break;case"unused":e=t.path?"The template item at "+t.path+" was not used in constructing the plot.":t.dataCount?"Some of the templates of type "+t.traceType+" were not used. The template has "+t.templateCount+" traces, the data only has "+t.dataCount+" of this type.":"The template has "+t.templateCount+" traces of type "+t.traceType+" but there are none in the data.";break;case"reused":e="Some of the templates of type "+t.traceType+" were used more than once. The template has "+t.templateCount+" traces, the data has "+t.dataCount+" of this type."}return t.msg=e,t}r.makeTemplate=function(t){t=n.extendDeep({_context:c},t),o.supplyDefaults(t);var e=t.data||[],r=t.layout||{};r._basePlotModules=t._fullLayout._basePlotModules,r._modules=t._fullLayout._modules;var s={data:{},layout:{}};e.forEach(function(t){var e={};d(t,e,function(t,e){return i.getTraceValObject(t,n.nestedProperty({},e).parts)}.bind(null,t));var r=n.coerce(t,{},l,"type"),a=s.data[r];a||(a=s.data[r]=[]),a.push(e)}),d(r,s.layout,function(t,e){return i.getLayoutValObject(t,n.nestedProperty({},e).parts)}.bind(null,r)),delete s.layout.template;var f=r.template;if(a(f)){var p,h,g,y,v,m,x=f.layout;a(x)&&u(x,s.layout);var b=f.data;if(a(b)){for(h in s.data)if(g=b[h],Array.isArray(g)){for(m=(v=s.data[h]).length,y=g.length,p=0;p<m;p++)u(g[p%y],v[p]);for(p=m;p<y;p++)v.push(n.extendDeep({},g[p]))}for(h in b)h in s.data||(s.data[h]=n.extendDeep([],b[h]))}}return s},r.validateTemplate=function(t,e){var r=n.extendDeep({},{_context:c,data:t.data,layout:t.layout}),i=r.layout||{};a(e)||(e=i.template||{});var l=e.layout,s=e.data,u=[];r.layout=i,r.layout.template=e,o.supplyDefaults(r);var d=r._fullLayout,y=r._fullData,v={};if(a(l)?(!function t(e,r){for(var n in e)if("_"!==n.charAt(0)&&a(e[n])){var i,o=f(n),l=[];for(i=0;i<r.length;i++)l.push(p(e,n,r[i])),o!==n&&l.push(p(e,o,r[i]));for(i=0;i<l.length;i++)v[l[i]]=1;t(e[n],l)}}(d,["layout"]),function t(e,r){for(var n in e)if(-1===n.indexOf("defaults")&&a(e[n])){var i=p(e,n,r);v[i]?t(e[n],i):u.push({code:"unused",path:i})}}(l,"layout")):u.push({code:"layout"}),a(s)){for(var m,x={},b=0;b<y.length;b++){var _=y[b];x[m=_.type]=(x[m]||0)+1,_._fullInput._template||u.push({code:"missing",index:_._fullInput.index,traceType:m})}for(m in s){var w=s[m].length,k=x[m]||0;w>k?u.push({code:"unused",traceType:m,templateCount:w,dataCount:k}):k>w&&u.push({code:"reused",traceType:m,templateCount:w,dataCount:k})}}else u.push({code:"data"});if(function t(e,r){for(var n in e)if("_"!==n.charAt(0)){var i=e[n],o=p(e,n,r);a(i)?(Array.isArray(e)&&!1===i._template&&i.templateitemname&&u.push({code:"missing",path:o,templateitemname:i.templateitemname}),t(i,o)):Array.isArray(i)&&h(i)&&t(i,o)}}({data:y,layout:d},""),u.length)return u.map(g)}},{"../lib":163,"../plots/attributes":204,"../plots/plots":239,"./plot_config":195,"./plot_schema":196,"./plot_template":197}],200:[function(t,e,r){"use strict";var n=t("./plot_api"),a=t("../lib"),i=t("../snapshot/helpers"),o=t("../snapshot/tosvg"),l=t("../snapshot/svgtoimg"),s={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},c=/^data:image\/\w+;base64,/;e.exports=function(t,e){var r,u,f;function d(t){return!(t in e)||a.validate(e[t],s[t])}if(e=e||{},a.isPlainObject(t)?(r=t.data||[],u=t.layout||{},f=t.config||{}):(t=a.getGraphDiv(t),r=a.extendDeep([],t.data),u=a.extendDeep({},t.layout),f=t._context),!d("width")||!d("height"))throw new Error("Height and width should be pixel values.");if(!d("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var p={};function h(t,r){return a.coerce(e,p,s,t,r)}var g=h("format"),y=h("width"),v=h("height"),m=h("scale"),x=h("setBackground"),b=h("imageDataOnly"),_=document.createElement("div");_.style.position="absolute",_.style.left="-5000px",document.body.appendChild(_);var w=a.extendFlat({},u);y&&(w.width=y),v&&(w.height=v);var k=a.extendFlat({},f,{staticPlot:!0,setBackground:x}),M=i.getRedrawFunc(_);function T(){return new Promise(function(t){setTimeout(t,i.getDelay(_._fullLayout))})}function A(){return new Promise(function(t,e){var r=o(_,g,m),i=_._fullLayout.width,s=_._fullLayout.height;if(n.purge(_),document.body.removeChild(_),"svg"===g)return t(b?r:"data:image/svg+xml,"+encodeURIComponent(r));var c=document.createElement("canvas");c.id=a.randstr(),l({format:g,width:i,height:s,scale:m,canvas:c,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){n.plot(_,r,w,k).then(M).then(T).then(A).then(function(e){t(function(t){return b?t.replace(c,""):t}(e))}).catch(function(t){e(t)})})}},{"../lib":163,"../snapshot/helpers":251,"../snapshot/svgtoimg":253,"../snapshot/tosvg":255,"./plot_api":194}],201:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plots/plots"),i=t("./plot_schema"),o=t("./plot_config"),l=n.isPlainObject,s=Array.isArray,c=n.isArrayOrTypedArray;function u(t,e,r,a,i,o){o=o||[];for(var f=Object.keys(t),d=0;d<f.length;d++){var y=f[d];if("transforms"!==y){var v=o.slice();v.push(y);var m=t[y],x=e[y],b=g(r,y),_="info_array"===(b||{}).valType,w="colorscale"===(b||{}).valType,k=(b||{}).items;if(h(r,y))if(l(m)&&l(x))u(m,x,b,a,i,v);else if(_&&s(m)){m.length>x.length&&a.push(p("unused",i,v.concat(x.length)));var M,T,A,L,C,S=x.length,O=Array.isArray(k);if(O&&(S=Math.min(S,k.length)),2===b.dimensions)for(T=0;T<S;T++)if(s(m[T])){m[T].length>x[T].length&&a.push(p("unused",i,v.concat(T,x[T].length)));var P=x[T].length;for(M=0;M<(O?Math.min(P,k[T].length):P);M++)A=O?k[T][M]:k,L=m[T][M],C=x[T][M],n.validate(L,A)?C!==L&&C!==+L&&a.push(p("dynamic",i,v.concat(T,M),L,C)):a.push(p("value",i,v.concat(T,M),L))}else a.push(p("array",i,v.concat(T),m[T]));else for(T=0;T<S;T++)A=O?k[T]:k,L=m[T],C=x[T],n.validate(L,A)?C!==L&&C!==+L&&a.push(p("dynamic",i,v.concat(T),L,C)):a.push(p("value",i,v.concat(T),L))}else if(b.items&&!_&&s(m)){var D,z,E=k[Object.keys(k)[0]],I=[];for(D=0;D<x.length;D++){var N=x[D]._index||D;if((z=v.slice()).push(N),l(m[N])&&l(x[D])){I.push(N);var R=m[N],F=x[D];l(R)&&!1!==R.visible&&!1===F.visible?a.push(p("invisible",i,z)):u(R,F,E,a,i,z)}}for(D=0;D<m.length;D++)(z=v.slice()).push(D),l(m[D])?-1===I.indexOf(D)&&a.push(p("unused",i,z)):a.push(p("object",i,z,m[D]))}else!l(m)&&l(x)?a.push(p("object",i,v,m)):c(m)||!c(x)||_||w?y in e?n.validate(m,b)?"enumerated"===b.valType&&(b.coerceNumber&&m!==+x||m!==x)&&a.push(p("dynamic",i,v,m,x)):a.push(p("value",i,v,m)):a.push(p("unused",i,v,m)):a.push(p("array",i,v,m));else a.push(p("schema",i,v))}}return a}e.exports=function(t,e){var r,c,f=i.get(),d=[],h={_context:n.extendFlat({},o)};s(t)?(h.data=n.extendDeep([],t),r=t):(h.data=[],r=[],d.push(p("array","data"))),l(e)?(h.layout=n.extendDeep({},e),c=e):(h.layout={},c={},arguments.length>1&&d.push(p("object","layout"))),a.supplyDefaults(h);for(var g=h._fullData,y=r.length,v=0;v<y;v++){var m=r[v],x=["data",v];if(l(m)){var b=g[v],_=b.type,w=f.traces[_].attributes;w.type={valType:"enumerated",values:[_]},!1===b.visible&&!1!==m.visible&&d.push(p("invisible",x)),u(m,b,w,d,x);var k=m.transforms,M=b.transforms;if(k){s(k)||d.push(p("array",x,["transforms"])),x.push("transforms");for(var T=0;T<k.length;T++){var A=["transforms",T],L=k[T].type;if(l(k[T])){var C=f.transforms[L]?f.transforms[L].attributes:{};C.type={valType:"enumerated",values:Object.keys(f.transforms)},u(k[T],M[T],C,d,x,A)}else d.push(p("object",x,A))}}}else d.push(p("object",x))}return u(c,h._fullLayout,function(t,e){for(var r=0;r<e.length;r++){var a=e[r].type,i=t.traces[a].layoutAttributes;i&&n.extendFlat(t.layout.layoutAttributes,i)}return t.layout.layoutAttributes}(f,g),d,"layout"),0===d.length?void 0:d};var f={object:function(t,e){return("layout"===t&&""===e?"The layout argument":"data"===t[0]&&""===e?"Trace "+t[1]+" in the data argument":d(t)+"key "+e)+" must be linked to an object container"},array:function(t,e){return("data"===t?"The data argument":d(t)+"key "+e)+" must be linked to an array container"},schema:function(t,e){return d(t)+"key "+e+" is not part of the schema"},unused:function(t,e,r){var n=l(r)?"container":"key";return d(t)+n+" "+e+" did not get coerced"},dynamic:function(t,e,r,n){return[d(t)+"key",e,"(set to '"+r+"')","got reset to","'"+n+"'","during defaults."].join(" ")},invisible:function(t,e){return(e?d(t)+"item "+e:"Trace "+t[1])+" got defaulted to be not visible"},value:function(t,e,r){return[d(t)+"key "+e,"is set to an invalid value ("+r+")"].join(" ")}};function d(t){return s(t)?"In data trace "+t[1]+", ":"In "+t+", "}function p(t,e,r,a,i){var o,l;r=r||"",s(e)?(o=e[0],l=e[1]):(o=e,l=null);var c=function(t){if(!s(t))return String(t);for(var e="",r=0;r<t.length;r++){var n=t[r];"number"==typeof n?e=e.substr(0,e.length-1)+"["+n+"]":e+=n,r<t.length-1&&(e+=".")}return e}(r),u=f[t](e,c,a,i);return n.log(u),{code:t,container:o,trace:l,path:r,astr:c,msg:u}}function h(t,e){var r=v(e),n=r.keyMinusId,a=r.id;return!!(n in t&&t[n]._isSubplotObj&&a)||e in t}function g(t,e){return e in t?t[e]:t[v(e).keyMinusId]}var y=n.counterRegex("([a-z]+)");function v(t){var e=t.match(y);return{keyMinusId:e&&e[1],id:e&&e[2]}}},{"../lib":163,"../plots/plots":239,"./plot_config":195,"./plot_schema":196}],202:[function(t,e,r){"use strict";e.exports={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500},easing:{valType:"enumerated",dflt:"cubic-in-out",values:["linear","quad","cubic","sin","exp","circle","elastic","back","bounce","linear-in","quad-in","cubic-in","sin-in","exp-in","circle-in","elastic-in","back-in","bounce-in","linear-out","quad-out","cubic-out","sin-out","exp-out","circle-out","elastic-out","back-out","bounce-out","linear-in-out","quad-in-out","cubic-in-out","sin-in-out","exp-in-out","circle-in-out","elastic-in-out","back-in-out","bounce-in-out"]}}}},{}],203:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plot_api/plot_template");e.exports=function(t,e,r){var i,o,l=r.name,s=r.inclusionAttr||"visible",c=e[l],u=n.isArrayOrTypedArray(t[l])?t[l]:[],f=e[l]=[],d=a.arrayTemplater(e,l,s);for(i=0;i<u.length;i++){var p=u[i];n.isPlainObject(p)?o=d.newItem(p):(o=d.newItem({}))[s]=!1,o._index=i,!1!==o[s]&&r.handleItemDefaults(p,o,e,r),f.push(o)}var h=d.defaultItems();for(i=0;i<h.length;i++)(o=h[i])._index=f.length,r.handleItemDefaults({},o,e,r,{}),f.push(o);if(n.isArrayOrTypedArray(c)){var g=Math.min(c.length,f.length);for(i=0;i<g;i++)n.relinkPrivateKeys(f[i],c[i])}return f}},{"../lib":163,"../plot_api/plot_template":197}],204:[function(t,e,r){"use strict";var n=t("../components/fx/attributes");e.exports={type:{valType:"enumerated",values:[],dflt:"scatter",editType:"calc+clearAxisTypes",_noTemplating:!0},visible:{valType:"enumerated",values:[!0,!1,"legendonly"],dflt:!0,editType:"calc"},showlegend:{valType:"boolean",dflt:!0,editType:"style"},legendgroup:{valType:"string",dflt:"",editType:"style"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"style"},name:{valType:"string",editType:"style"},uid:{valType:"string",editType:"plot"},ids:{valType:"data_array",editType:"calc"},customdata:{valType:"data_array",editType:"calc"},selectedpoints:{valType:"any",editType:"calc"},hoverinfo:{valType:"flaglist",flags:["x","y","z","text","name"],extras:["all","none","skip"],arrayOk:!0,dflt:"all",editType:"none"},hoverlabel:n.hoverlabel,stream:{token:{valType:"string",noBlank:!0,strict:!0,editType:"calc"},maxpoints:{valType:"number",min:0,max:1e4,dflt:500,editType:"calc"},editType:"calc"},transforms:{_isLinkedToArray:"transform",editType:"calc"}}},{"../components/fx/attributes":79}],205:[function(t,e,r){"use strict";e.exports={xaxis:{valType:"subplotid",dflt:"x",editType:"calc+clearAxisTypes"},yaxis:{valType:"subplotid",dflt:"y",editType:"calc+clearAxisTypes"}}},{}],206:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../constants/numerical").FP_SAFE;function o(t){var e,r,n,i,o,s,c,u,f=[],d=t._min[0].val,p=t._max[0].val,h=0,g=!1,y=l(t);for(e=1;e<t._min.length&&d===p;e++)d=Math.min(d,t._min[e].val);for(e=1;e<t._max.length&&d===p;e++)p=Math.max(p,t._max[e].val);if(t.range){var v=a.simpleMap(t.range,t.r2l);g=v[1]<v[0]}for("reversed"===t.autorange&&(g=!0,t.autorange=!0),e=0;e<t._min.length;e++)for(n=t._min[e],r=0;r<t._max.length;r++)u=(i=t._max[r]).val-n.val,c=t._length-y(n)-y(i),u>0&&c>0&&u/c>h&&(o=n,s=i,h=u/c);if(d===p){var m=d-1,x=d+1;f="tozero"===t.rangemode?d<0?[m,0]:[0,x]:"nonnegative"===t.rangemode?[Math.max(0,m),Math.max(0,x)]:[m,x]}else h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(o.val>=0&&(o={val:0,pad:0}),s.val<=0&&(s={val:0,pad:0})):"nonnegative"===t.rangemode&&(o.val-h*y(o)<0&&(o={val:0,pad:0}),s.val<0&&(s={val:1,pad:0})),h=(s.val-o.val)/(t._length-y(o)-y(s))),f=[o.val-h*y(o),s.val+h*y(s)]);return f[0]===f[1]&&("tozero"===t.rangemode?f=f[0]<0?[f[0],0]:f[0]>0?[0,f[0]]:[0,1]:(f=[f[0]-1,f[0]+1],"nonnegative"===t.rangemode&&(f[0]=Math.max(0,f[0])))),g&&f.reverse(),a.simpleMap(f,t.l2r||Number)}function l(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function s(t){return n(t)&&Math.abs(t)<i}function c(t,e){return t<=e}function u(t,e){return t>=e}e.exports={getAutoRange:o,makePadFn:l,doAutoRange:function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=o(t),t._r=t.range.slice(),t._rl=a.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?o(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=a.extendFlat({},n)}},expand:function(t,e,r){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!e)return;t._min||(t._min=[]);t._max||(t._max=[]);r||(r={});t._m||t.setScale();var a,o,l,f,d,p,h,g,y,v,m,x,b=e.length,_=r.padded||!1,w=r.tozero&&("linear"===t.type||"-"===t.type),k="log"===t.type,M=!1;function T(t){if(Array.isArray(t))return M=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var A=T((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),L=T((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),C=T(r.vpadplus||r.vpad),S=T(r.vpadminus||r.vpad);if(!M){if(m=1/0,x=-1/0,k)for(a=0;a<b;a++)(f=e[a])<m&&f>0&&(m=f),f>x&&f<i&&(x=f);else for(a=0;a<b;a++)(f=e[a])<m&&f>-i&&(m=f),f>x&&f<i&&(x=f);e=[m,x],b=2}function O(r){if(d=e[r],n(d))for(g=A(r),y=L(r),m=d-S(r),x=d+C(r),k&&m<x/10&&(m=x/10),p=t.c2l(m),h=t.c2l(x),w&&(p=Math.min(0,p),h=Math.max(0,h)),l=0;l<2;l++){var a=l?h:p;if(s(a)){var i=l?t._max:t._min,b=l?g:y,M=l?u:c;for(v=!0,o=0;o<i.length&&v;o++){if(f=i[o],M(f.val,a)&&f.pad>=b&&(f.extrapad||!_)){v=!1;break}M(a,f.val)&&f.pad<=b&&(_||!f.extrapad)&&(i.splice(o,1),o--)}if(v){var T=w&&0===a;i.push({val:a,pad:T?0:b,extrapad:!T&&_})}}}}var P=Math.min(6,b);for(a=0;a<P;a++)O(a);for(a=b-1;a>=P;a--)O(a)}}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],207:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../../components/titles"),u=t("../../components/color"),f=t("../../components/drawing"),d=t("../../constants/numerical"),p=d.ONEAVGYEAR,h=d.ONEAVGMONTH,g=d.ONEDAY,y=d.ONEHOUR,v=d.ONEMIN,m=d.ONESEC,x=d.MINUS_SIGN,b=d.BADNUM,_=t("../../constants/alignment").MID_SHIFT,w=t("../../constants/alignment").LINE_SPACING,k=e.exports={};k.setConvert=t("./set_convert");var M=t("./axis_autotype"),T=t("./axis_ids");k.id2name=T.id2name,k.name2id=T.name2id,k.cleanId=T.cleanId,k.list=T.list,k.listIds=T.listIds,k.getFromId=T.getFromId,k.getFromTrace=T.getFromTrace;var A=t("./autorange");k.expand=A.expand,k.getAutoRange=A.getAutoRange,k.coerceRef=function(t,e,r,n,a,i){var o=n.charAt(n.length-1),s=r._fullLayout._subplots[o+"axis"],c=n+"ref",u={};return a||(a=s[0]||i),i||(i=a),u[c]={valType:"enumerated",values:s.concat(i?[i]:[]),dflt:a},l.coerce(t,e,u,c)},k.coercePosition=function(t,e,r,n,a,i){var o,s;if("paper"===n||"pixel"===n)o=l.ensureNumber,s=r(a,i);else{var c=k.getFromId(e,n);s=r(a,i=c.fraction2r(i)),o=c.cleanPos}t[a]=o(s)},k.cleanPosition=function(t,e,r){return("paper"===r||"pixel"===r?l.ensureNumber:k.getFromId(e,r).cleanPos)(t)};var L=k.getDataConversions=function(t,e,r,n){var a,i="x"===r||"y"===r||"z"===r?r:n;if(Array.isArray(i)){if(a={type:M(n),_categories:[]},k.setConvert(a),"category"===a.type)for(var o=0;o<n.length;o++)a.d2c(n[o])}else a=k.getFromTrace(t,e,i);return a?{d2c:a.d2c,c2d:a.c2d}:"ids"===i?{d2c:S,c2d:S}:{d2c:C,c2d:C}};function C(t){return+t}function S(t){return String(t)}k.getDataToCoordFunc=function(t,e,r,n){return L(t,e,r,n).d2c},k.counterLetter=function(t){var e=t.charAt(0);return"x"===e?"y":"y"===e?"x":void 0},k.minDtick=function(t,e,r,n){-1===["log","category"].indexOf(t.type)&&n?void 0===t._minDtick?(t._minDtick=e,t._forceTick0=r):t._minDtick&&((t._minDtick/e+1e-6)%1<2e-6&&((r-t._forceTick0)/e%1+1.000001)%1<2e-6?(t._minDtick=e,t._forceTick0=r):((e/t._minDtick+1e-6)%1>2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},k.saveRangeInitial=function(t,e){for(var r=k.list(t,"",!0),n=!1,a=0;a<r.length;a++){var i=r[a],o=void 0===i._rangeInitial,l=o||!(i.range[0]===i._rangeInitial[0]&&i.range[1]===i._rangeInitial[1]);(o&&!1===i.autorange||e&&l)&&(i._rangeInitial=i.range.slice(),n=!0)}return n},k.saveShowSpikeInitial=function(t,e){for(var r=k.list(t,"",!0),n=!1,a="on",i=0;i<r.length;i++){var o=r[i],l=void 0===o._showSpikeInitial,s=l||!(o.showspikes===o._showspikes);(l||e&&s)&&(o._showSpikeInitial=o.showspikes,n=!0),"on"!==a||o.showspikes||(a="off")}return t._fullLayout._cartesianSpikesEnabled=a,n},k.autoBin=function(t,e,r,n,i){var o,s,c=l.aggNums(Math.min,null,t),u=l.aggNums(Math.max,null,t);if(i||(i=e.calendar),"category"===e.type)return{start:c-.5,end:u+.5,size:1,_dataSpan:u-c};if(r)o=(u-c)/r;else{var f=l.distinctVals(t),d=Math.pow(10,Math.floor(Math.log(f.minDiff)/Math.LN10)),p=d*l.roundUp(f.minDiff/d,[.9,1.9,4.9,9.9],!0);o=Math.max(p,2*l.stdev(t)/Math.pow(t.length,n?.25:.4)),a(o)||(o=1)}s="log"===e.type?{type:"linear",range:[c,u]}:{type:e.type,range:l.simpleMap([c,u],e.c2r,0,i),calendar:i},k.setConvert(s),k.autoTicks(s,o);var h,y=k.tickIncrement(k.tickFirst(s),s.dtick,"reverse",i);if("number"==typeof s.dtick)h=(y=function(t,e,r,n,i){var o=0,l=0,s=0,c=0;function u(e){return(1+100*(e-t)/r.dtick)%100<2}for(var f=0;f<e.length;f++)e[f]%1==0?s++:a(e[f])||c++,u(e[f])&&o++,u(e[f]+r.dtick/2)&&l++;var d=e.length-c;if(s===d&&"date"!==r.type)r.dtick<1?t=n-.5*r.dtick:(t-=.5)+r.dtick<n&&(t+=r.dtick);else if(l<.1*d&&(o>.3*d||u(n)||u(i))){var p=r.dtick/2;t+=t+p<n?p:-p}return t}(y,t,s,c,u))+(1+Math.floor((u-y)/s.dtick))*s.dtick;else for("M"===s.dtick.charAt(0)&&(y=function(t,e,r,n,a){var i=l.findExactDates(e,a);if(i.exactDays>.8){var o=Number(r.substr(1));i.exactYears>.8&&o%12==0?t=k.tickIncrement(t,"M6","reverse")+1.5*g:i.exactMonths>.8?t=k.tickIncrement(t,"M1","reverse")+15.5*g:t-=g/2;var s=k.tickIncrement(t,r);if(s<=n)return s}return t}(y,t,s.dtick,c,i)),h=y,0;h<=u;)h=k.tickIncrement(h,s.dtick,!1,i),0;return{start:e.c2r(y,0,i),end:e.c2r(h,0,i),size:s.dtick,_dataSpan:u-c}},k.prepTicks=function(t){var e=l.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=l.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),k.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),F(t)},k.calcTicks=function(t){k.prepTicks(t);var e=l.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,a=t.ticktext,i=new Array(n.length),o=l.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],c=1.0001*o[1]-1e-4*o[0],u=Math.min(s,c),f=Math.max(s,c),d=0;Array.isArray(a)||(a=[]);var p="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;r<n.length;r++)(e=p(n[r]))>u&&e<f&&(void 0===a[r]?i[d]=k.tickText(t,e):i[d]=j(t,e,String(a[r])),d++);d<n.length&&i.splice(d,n.length-d);return i}(t);t._tmin=k.tickFirst(t);var r=1.0001*e[0]-1e-4*e[1],n=1.0001*e[1]-1e-4*e[0],a=e[1]<e[0];if(t._tmin<r!==a)return[];var i=[];"category"===t.type&&(n=a?Math.max(-.5,n):Math.min(t._categories.length-.5,n));for(var o=null,s=Math.max(1e3,t._length||0),c=t._tmin;(a?c>=n:c<=n)&&!(i.length>s||c===o);c=k.tickIncrement(c,t.dtick,a,t.calendar))o=c,i.push(c);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&i.pop(),t._tmax=i[i.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(i.length),f=0;f<i.length;f++)u[f]=k.tickText(t,i[f]);return t._inCalcTicks=!1,u};var O=[2,5,10],P=[1,2,3,6,12],D=[1,2,5,10,15,30],z=[1,2,3,7,14],E=[-.046,0,.301,.477,.602,.699,.778,.845,.903,.954,1],I=[-.301,0,.301,.699,1],N=[15,30,45,90,180];function R(t,e,r){return e*l.roundUp(t/e,r)}function F(t){var e=t.dtick;if(t._tickexponent=0,a(e)||"string"==typeof e||(e=1),"category"===t.type&&(t._tickround=null),"date"===t.type){var r=t.r2l(t.tick0),n=t.l2r(r).replace(/(^-|i)/g,""),i=n.length;if("M"===String(e).charAt(0))i>10||"01-01"!==n.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=g&&i<=10||e>=15*g)t._tickround="d";else if(e>=v&&i<=16||e>=y)t._tickround="M";else if(e>=m&&i<=19||e>=v)t._tickround="S";else{var o=t.l2r(r+e).replace(/^-/,"").length;t._tickround=Math.max(i,o)-20}}else if(a(e)||"L"===e.charAt(0)){var l=t.range.map(t.r2d||Number);a(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(H(t.exponentformat)&&!q(c)?t._tickexponent=3*Math.round((c-1)/3):t._tickexponent=c)}else t._tickround=null}function j(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}k.autoTicks=function(t,e){var r;function n(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=l.dateTick0(t.calendar);var i=2*e;i>p?(e/=p,r=n(10),t.dtick="M"+12*R(e,r,O)):i>h?(e/=h,t.dtick="M"+R(e,1,P)):i>g?(t.dtick=R(e,g,z),t.tick0=l.dateTick0(t.calendar,!0)):i>y?t.dtick=R(e,y,P):i>v?t.dtick=R(e,v,D):i>m?t.dtick=R(e,m,D):(r=n(10),t.dtick=R(e,r,O))}else if("log"===t.type){t.tick0=0;var o=l.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/e);e=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,r=n(10),t.dtick="L"+R(e,r,O)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):"angular"===t._id?(t.tick0=0,r=1,t.dtick=R(e,r,N)):(t.tick0=0,r=n(10),t.dtick=R(e,r,O));if(0===t.dtick&&(t.dtick=1),!a(t.dtick)&&"string"!=typeof t.dtick){var c=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(c)}},k.tickIncrement=function(t,e,r,i){var o=r?-1:1;if(a(e))return t+o*e;var s=e.charAt(0),c=o*Number(e.substr(1));if("M"===s)return l.incrementMonth(t,c,i);if("L"===s)return Math.log(Math.pow(10,t)+c)/Math.LN10;if("D"===s){var u="D2"===e?I:E,f=t+.01*o,d=l.roundUp(l.mod(f,1),u,r);return Math.floor(f)+Math.log(n.round(Math.pow(10,d),1))/Math.LN10}throw"unrecognized dtick "+String(e)},k.tickFirst=function(t){var e=t.r2l||Number,r=l.simpleMap(t.range,e),i=r[1]<r[0],o=i?Math.floor:Math.ceil,s=1.0001*r[0]-1e-4*r[1],c=t.dtick,u=e(t.tick0);if(a(c)){var f=o((s-u)/c)*c+u;return"category"===t.type&&(f=l.constrain(f,0,t._categories.length-1)),f}var d=c.charAt(0),p=Number(c.substr(1));if("M"===d){for(var h,g,y,v=0,m=u;v<10;){if(((h=k.tickIncrement(m,c,i,t.calendar))-s)*(m-s)<=0)return i?Math.min(m,h):Math.max(m,h);g=(s-(m+h)/2)/(h-m),y=d+(Math.abs(Math.round(g))||1)*p,m=k.tickIncrement(m,y,g<0?!i:i,t.calendar),v++}return l.error("tickFirst did not converge",t),m}if("L"===d)return Math.log(o((Math.pow(10,s)-u)/p)*p+u)/Math.LN10;if("D"===d){var x="D2"===c?I:E,b=l.roundUp(l.mod(s,1),x,i);return Math.floor(s)+Math.log(n.round(Math.pow(10,b),1))/Math.LN10}throw"unrecognized dtick "+String(c)},k.tickText=function(t,e,r){var n,i,o=j(t,e),s="array"===t.tickmode,c=r||s,u="category"===t.type?t.d2l_noadd:t.d2l;if(s&&Array.isArray(t.ticktext)){var f=l.simpleMap(t.range,t.r2l),d=Math.abs(f[1]-f[0])/1e4;for(i=0;i<t.ticktext.length&&!(Math.abs(e-u(t.tickvals[i]))<d);i++);if(i<t.ticktext.length)return o.text=String(t.ticktext[i]),o}function p(n){var a;return void 0===n||(r?"none"===n:(a={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==a))}return n=r?"never":"none"!==t.exponentformat&&p(t.showexponent)?"hide":"","date"===t.type?function(t,e,r,n){var i=t._tickround,o=r&&t.hoverformat||k.getTickFormat(t);n&&(i=a(i)?4:{y:"m",m:"d",d:"M",M:"S",S:4}[i]);var s,c=l.formatDate(e.x,o,i,t._dateFormat,t.calendar,t._extraFormat),u=c.indexOf("\n");-1!==u&&(s=c.substr(u+1),c=c.substr(0,u));n&&("00:00:00"===c||"00:00"===c?(c=s,s=""):8===c.length&&(c=c.replace(/:00$/,"")));s&&(r?"d"===i?c+=", "+s:c=s+(c?", "+c:""):t._inCalcTicks&&s===t._prevDateHead||(c+="<br>"+s,t._prevDateHead=s));e.text=c}(t,o,r,c):"log"===t.type?function(t,e,r,n,i){var o=t.dtick,s=e.x,c=t.tickformat;"never"===i&&(i="");!n||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(c||"string"==typeof o&&"L"===o.charAt(0))e.text=V(Math.pow(10,s),t,i,n);else if(a(o)||"D"===o.charAt(0)&&l.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||H(t.exponentformat)&&q(u)?(e.text=0===u?1:1===u?"10":u>1?"10<sup>"+u+"</sup>":"10<sup>"+x+-u+"</sup>",e.fontSize*=1.25):(e.text=V(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);e.text=String(Math.round(Math.pow(10,l.mod(s,1)))),e.fontSize*=.75}if("D1"===t.dtick){var f=String(e.text).charAt(0);"0"!==f&&"1"!==f||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(s<0?.5:.25)))}}(t,o,0,c,n):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,a){if("radians"!==t.thetaunit||r)e.text=V(e.x,t,a,n);else{var i=e.x/180;if(0===i)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,a=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/a),Math.round(r/a)]}(i);if(o[1]>=100)e.text=V(l.deg2rad(e.x),t,a,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["<sup>",o[0],"</sup>","\u2044","<sub>",o[1],"</sub>","\u03c0"].join(""),s&&(e.text=x+e.text)}}}}(t,o,r,c,n):function(t,e,r,n,a){"never"===a?a="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(a="hide");e.text=V(e.x,t,a,n)}(t,o,0,c,n),t.tickprefix&&!p(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!p(t.showticksuffix)&&(o.text+=t.ticksuffix),o},k.hoverLabelText=function(t,e,r){if(r!==b&&r!==e)return k.hoverLabelText(t,e)+" - "+k.hoverLabelText(t,r);var n="log"===t.type&&e<=0,a=k.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":x+a:a};var B=["f","p","n","\u03bc","m","","k","M","G","T"];function H(t){return"SI"===t||"B"===t}function q(t){return t>14||t<-15}function V(t,e,r,n){var i=t<0,o=e._tickround,s=r||e.exponentformat||"B",c=e._tickexponent,u=k.getTickFormat(e),f=e.separatethousands;if(n){var d={exponentformat:s,dtick:"none"===e.showexponent?e.dtick:a(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};F(d),o=(Number(d._tickround)||0)+4,c=d._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,x);var p,h=Math.pow(10,-o)/2;if("none"===s&&(c=0),(t=Math.abs(t))<h)t="0",i=!1;else{if(t+=h,c&&(t*=Math.pow(10,-c),o+=c),0===o)t=String(Math.floor(t));else if(o<0){t=(t=String(Math.round(t))).substr(0,t.length+o);for(var g=o;g<0;g++)t+="0"}else{var y=(t=String(t)).indexOf(".")+1;y&&(t=t.substr(0,y+o).replace(/\.?0+$/,""))}t=l.numSeparate(t,e._separators,f)}c&&"hide"!==s&&(H(s)&&q(c)&&(s="power"),p=c<0?x+-c:"power"!==s?"+"+c:String(c),"e"===s?t+="e"+p:"E"===s?t+="E"+p:"power"===s?t+="\xd710<sup>"+p+"</sup>":"B"===s&&9===c?t+="B":H(s)&&(t+=B[c/3+5]));return i?x+t:t}function U(t,e){for(var r=0;r<e.length;r++)-1===t.indexOf(e[r])&&t.push(e[r])}function G(t,e,r){var n,a,i=[],o=[],s=t.layout;for(n=0;n<e.length;n++)i.push(k.getFromId(t,e[n]));for(n=0;n<r.length;n++)o.push(k.getFromId(t,r[n]));var c=Object.keys(i[0]),u=["anchor","domain","overlaying","position","side","tickangle"],f=["linear","log"];for(n=0;n<c.length;n++){var d=c[n],p=i[0][d],h=o[0][d],g=!0,y=!1,v=!1;if("_"!==d.charAt(0)&&"function"!=typeof p&&-1===u.indexOf(d)){for(a=1;a<i.length&&g;a++){var m=i[a][d];"type"===d&&-1!==f.indexOf(p)&&-1!==f.indexOf(m)&&p!==m?y=!0:m!==p&&(g=!1)}for(a=1;a<o.length&&g;a++){var x=o[a][d];"type"===d&&-1!==f.indexOf(h)&&-1!==f.indexOf(x)&&h!==x?v=!0:o[a][d]!==h&&(g=!1)}g&&(y&&(s[i[0]._name].type="linear"),v&&(s[o[0]._name].type="linear"),Y(s,d,i,o,t._fullLayout._dfltTitle))}}for(n=0;n<t._fullLayout.annotations.length;n++){var b=t._fullLayout.annotations[n];-1!==e.indexOf(b.xref)&&-1!==r.indexOf(b.yref)&&l.swapAttrs(s.annotations[n],["?"])}}function Y(t,e,r,n,a){var i,o=l.nestedProperty,s=o(t[r[0]._name],e).get(),c=o(t[n[0]._name],e).get();for("title"===e&&(s===a.x&&(s=a.y),c===a.y&&(c=a.x)),i=0;i<r.length;i++)o(t,r[i]._name+"."+e).set(c);for(i=0;i<n.length;i++)o(t,n[i]._name+"."+e).set(s)}k.getTickFormat=function(t){var e,r,n,a,i,o,l,s;function c(t){return"string"!=typeof t?t:Number(t.replace("M",""))*h}function u(t,e){var r=["L","D"];if(typeof t==typeof e){if("number"==typeof t)return t-e;var n=r.indexOf(t.charAt(0)),a=r.indexOf(e.charAt(0));return n===a?Number(t.replace(/(L|D)/g,""))-Number(e.replace(/(L|D)/g,"")):n-a}return"number"==typeof t?1:-1}function f(t,e){var r=null===e[0],n=null===e[1],a=u(t,e[0])>=0,i=u(t,e[1])<=0;return(r||a)&&(n||i)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e<t.tickformatstops.length;e++)if((n=t.tickformatstops[e]).enabled&&(a=t.dtick,i=n.dtickrange,o=void 0,void 0,void 0,o=c||function(t){return t},l=i[0],s=i[1],(!l&&"number"!=typeof l||o(l)<=o(a))&&(!s&&"number"!=typeof s||o(s)>=o(a)))){r=n;break}break;case"log":for(e=0;e<t.tickformatstops.length;e++)if((n=t.tickformatstops[e]).enabled&&f(t.dtick,n.dtickrange)){r=n;break}}return r?r.value:t.tickformat},k.getSubplots=function(t,e){var r=t._fullLayout._subplots,n=r.cartesian.concat(r.gl2d||[]),a=e?k.findSubplotsWithAxis(n,e):n;return a.sort(function(t,e){var r=t.substr(1).split("y"),n=e.substr(1).split("y");return r[0]===n[0]?+r[1]-+n[1]:+r[0]-+n[0]}),a},k.findSubplotsWithAxis=function(t,e){for(var r=new RegExp("x"===e._id.charAt(0)?"^"+e._id+"y":e._id+"$"),n=[],a=0;a<t.length;a++){var i=t[a];r.test(i)&&n.push(i)}return n},k.makeClipPaths=function(t){var e=t._fullLayout;if(!e._hasOnlyLargeSploms){var r,a,i={_offset:0,_length:e.width,_id:""},o={_offset:0,_length:e.height,_id:""},l=k.list(t,"x",!0),s=k.list(t,"y",!0),c=[];for(r=0;r<l.length;r++)for(c.push({x:l[r],y:o}),a=0;a<s.length;a++)0===r&&c.push({x:i,y:s[a]}),c.push({x:l[r],y:s[a]});var u=e._clips.selectAll(".axesclip").data(c,function(t){return t.x._id+t.y._id});u.enter().append("clipPath").classed("axesclip",!0).attr("id",function(t){return"clip"+e._uid+t.x._id+t.y._id}).append("rect"),u.exit().remove(),u.each(function(t){n.select(this).select("rect").attr({x:t.x._offset||0,y:t.y._offset||0,width:t.x._length||1,height:t.y._length||1})})}},k.doTicks=function(t,e,r){var n=t._fullLayout;"redraw"===e&&n._paper.selectAll("g.subplot").each(function(t){var e=n._plots[t],r=e.xaxis,a=e.yaxis;e.xaxislayer.selectAll("."+r._id+"tick").remove(),e.yaxislayer.selectAll("."+a._id+"tick").remove(),e.gridlayer&&e.gridlayer.selectAll("path").remove(),e.zerolinelayer&&e.zerolinelayer.selectAll("path").remove(),n._infolayer.select(".g-"+r._id+"title").remove(),n._infolayer.select(".g-"+a._id+"title").remove()});var a=e&&"redraw"!==e?e:k.listIds(t);l.syncOrAsync(a.map(function(e){return function(){if(e){var n=k.doTicksSingle(t,e,r),a=k.getFromId(t,e);return a._r=a.range.slice(),a._rl=l.simpleMap(a._r,a.r2l),n}}}))},k.doTicksSingle=function(t,e,r){var d,p=t._fullLayout,h=!1;l.isPlainObject(e)?(d=e,h=!0):d=k.getFromId(t,e),d.setScale();var g,y,v,m,x,b,M=d._id,A=M.charAt(0),L=k.counterLetter(M),C=d._vals=k.calcTicks(d),S=function(t){return[t.text,t.x,d.mirror,t.font,t.fontSize,t.fontColor].join("_")},O=M+"tick",P=M+"grid",D=M+"zl",z=(d.linewidth||1)/2,E="outside"===d.ticks?d.ticklen:0,I=0,N=f.crispRound(t,d.gridwidth,1),R=f.crispRound(t,d.zerolinewidth,N),F=f.crispRound(t,d.tickwidth,1);if(d._counterangle&&"outside"===d.ticks){var j=d._counterangle*Math.PI/180;E=d.ticklen*Math.cos(j)+1,I=d.ticklen*Math.sin(j)}if(d.showticklabels&&("outside"===d.ticks||d.showline)&&(E+=.2*d.tickfont.size),"x"===A)g=["bottom","top"],y=d._transfn||function(t){return"translate("+(d._offset+d.l2p(t.x))+",0)"},v=function(t,e){if(d._counterangle){var r=d._counterangle*Math.PI/180;return"M0,"+t+"l"+Math.sin(r)*e+","+Math.cos(r)*e}return"M0,"+t+"v"+e};else if("y"===A)g=["left","right"],y=d._transfn||function(t){return"translate(0,"+(d._offset+d.l2p(t.x))+")"},v=function(t,e){if(d._counterangle){var r=d._counterangle*Math.PI/180;return"M"+t+",0l"+Math.cos(r)*e+","+-Math.sin(r)*e}return"M"+t+",0h"+e};else{if("angular"!==M)return void l.warn("Unrecognized doTicks axis:",M);g=["left","right"],y=d._transfn,v=function(t,e){return"M"+t+",0h"+e}}var B=d.side||g[0],H=[-1,1,B===g[1]?1:-1];if("inside"!==d.ticks==("x"===A)&&(H=H.map(function(t){return-t})),d.visible){d._tickFilter&&(C=C.filter(d._tickFilter));var q=C.filter(W);if("angular"===d._id&&(q=C),h){if(Q(d._axislayer,v(d._pos+z*H[2],H[2]*d.ticklen)),d._counteraxis)tt({gridlayer:d._gridlayer,zerolinelayer:d._zerolinelayer},d._counteraxis);return J(d._axislayer,d._pos)}if(p._has("cartesian")){m=k.getSubplots(t,d);var V={};m.map(function(t){var e=p._plots[t],r=e[L+"axis"],n=r._mainAxis._id;V[n]||(V[n]=1,tt(e,r,t))});var U=d._mainSubplot,G=p._plots[U],Y=[];if(d.ticks){var X=H[2],Z=v(d._mainLinePosition+z*X,X*d.ticklen);d._anchorAxis&&d.mirror&&!0!==d.mirror&&(Z+=v(d._mainMirrorPosition-z*X,-X*d.ticklen)),Q(G[A+"axislayer"],Z),Y=Object.keys(d._linepositions||{})}return Y.map(function(t){var e=p._plots[t][A+"axislayer"],r=d._linepositions[t]||[];function n(t){var e=H[t];return v(r[t]+z*e,e*d.ticklen)}Q(e,n(0)+n(1))}),J(G[A+"axislayer"],d._mainLinePosition)}}function W(t){var e=d.l2p(t.x);return e>1&&e<d._length-1}function Q(t,e){var r=t.selectAll("path."+O).data("inside"===d.ticks?q:C,S);e&&d.ticks?(r.enter().append("path").classed(O,1).classed("ticks",1).classed("crisp",1).call(u.stroke,d.tickcolor).style("stroke-width",F+"px").attr("d",e),r.attr("transform",y),r.exit().remove()):r.remove()}function J(e,r){if(x=e.selectAll("g."+O).data(C,S),!a(r))return x.remove(),void $();if(!d.showticklabels)return x.remove(),$(),void P();var o,c,u,h,g;"x"===A?(o=function(t){return t.dx+I*g},h=r+(E+z)*(g="bottom"===B?1:-1),c=function(t){return t.dy+h+t.fontSize*("bottom"===B?1:-.2)},u=function(t){return a(t)&&0!==t&&180!==t?t*g<0?"end":"start":"middle"}):"y"===A?(g="right"===B?1:-1,c=function(t){return t.dy+t.fontSize*_-I*g},o=function(t){return t.dx+r+(E+z+(90===Math.abs(d.tickangle)?t.fontSize/2:0))*g},u=function(t){return a(t)&&90===Math.abs(t)?"middle":"right"===B?"start":"end"}):"angular"===M&&(d._labelShift=I,d._labelStandoff=E,d._pad=z,o=d._labelx,c=d._labely,u=d._labelanchor);var v=0,k=0,T=[];function L(t,e){t.each(function(t){var r=u(e,t),i=n.select(this),l=i.select(".text-math-group"),d=y.call(i.node(),t)+(a(e)&&0!=+e?" rotate("+e+","+o(t)+","+(c(t)-t.fontSize/2)+")":""),p=function(t,e,r){var n=(t-1)*e;if("x"===A){if(r<-60||60<r)return-.5*n;if("top"===B)return-n}else{if((r*="left"===B?1:-1)<-30)return-n;if(r<30)return-.5*n}return 0}(s.lineCount(i),w*t.fontSize,a(e)?+e:0);if(p&&(d+=" translate(0, "+p+")"),l.empty())i.select("text").attr({transform:d,"text-anchor":r});else{var h=f.bBox(l.node()).width*{end:-.5,start:.5}[r];l.attr("transform",d+(h?"translate("+h+",0)":""))}})}function P(){if(d.showticklabels){var r=t.getBoundingClientRect(),n=e.node().getBoundingClientRect();d._boundingBox={width:n.width,height:n.height,left:n.left-r.left,right:n.right-r.left,top:n.top-r.top,bottom:n.bottom-r.top}}else{var a,i=p._size;"x"===A?(a="free"===d.anchor?i.t+i.h*(1-d.position):i.t+i.h*(1-d._anchorAxis.domain[{bottom:0,top:1}[d.side]]),d._boundingBox={top:a,bottom:a,left:d._offset,right:d._offset+d._length,width:d._length,height:0}):(a="free"===d.anchor?i.l+i.w*d.position:i.l+i.w*d._anchorAxis.domain[{left:0,right:1}[d.side]],d._boundingBox={left:a,right:a,bottom:d._offset+d._length,top:d._offset,height:d._length,width:0})}if(m){var o=d._counterSpan=[1/0,-1/0];for(b=0;b<m.length;b++){var l=p._plots[m[b]]["x"===A?"yaxis":"xaxis"];s(o,[l._offset,l._offset+l._length])}"free"===d.anchor&&s(o,"x"===A?[d._boundingBox.bottom,d._boundingBox.top]:[d._boundingBox.right,d._boundingBox.left])}function s(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.max(t[1],e[1])}}x.enter().append("g").classed(O,1).append("text").attr("text-anchor","middle").each(function(e){var r=n.select(this),a=t._promises.length;r.call(s.positionText,o(e),c(e)).call(f.font,e.font,e.fontSize,e.fontColor).text(e.text).call(s.convertToTspans,t),(a=t._promises[a])?T.push(t._promises.pop().then(function(){L(r,d.tickangle)})):L(r,d.tickangle)}),x.exit().remove(),x.each(function(t){v=Math.max(v,t.fontSize)}),"angular"===M&&x.each(function(t){n.select(this).select("text").call(s.positionText,o(t),c(t))}),L(x,d._lastangle||d.tickangle);var D=l.syncOrAsync([function(){return T.length&&Promise.all(T)},function(){if(L(x,d.tickangle),"x"===A&&!a(d.tickangle)&&("log"!==d.type||"D"!==String(d.dtick).charAt(0))){var t=[];for(x.each(function(e){var r=n.select(this),a=r.select(".text-math-group"),i=d.l2p(e.x);a.empty()&&(a=r.select("text"));var o=f.bBox(a.node());t.push({top:0,bottom:10,height:10,left:i-o.width/2,right:i+o.width/2+2,width:o.width+2})}),b=0;b<t.length-1;b++)if(l.bBoxIntersect(t[b],t[b+1])){k=30;break}k&&(Math.abs((C[C.length-1].x-C[0].x)*d._m)/(C.length-1)<2.5*v&&(k=90),L(x,k)),d._lastangle=k}return $(),M+" done"},P,function(){var e=d._name+".automargin";if("x"===A||"y"===A)if(d.automargin){var r=d.side[0],n={x:0,y:0,r:0,l:0,t:0,b:0};"x"===A?(n.y="free"===d.anchor?d.position:d._anchorAxis.domain["t"===r?1:0],n[r]+=d._boundingBox.height):(n.x="free"===d.anchor?d.position:d._anchorAxis.domain["r"===r?1:0],n[r]+=d._boundingBox.width),d.title!==p._dfltTitle[A]&&(n[r]+=d.titlefont.size),i.autoMargin(t,e,n)}else i.autoMargin(t,e)}]);return D&&D.then&&t._promises.push(D),D}function $(){if(!(r||d.rangeslider&&d.rangeslider.visible&&d._boundingBox&&"bottom"===d.side)){var e,n,a,i,o={selection:x,side:d.side},l=M.charAt(0),s=t._fullLayout._size,u=d.titlefont.size;if(x.size()){var h=f.getTranslate(x.node().parentNode);o.offsetLeft=h.x,o.offsetTop=h.y}var g=10+1.5*u+(d.linewidth?d.linewidth-1:0);"x"===l?(n="free"===d.anchor?{_offset:s.t+(1-(d.position||0))*s.h,_length:0}:T.getFromId(t,d.anchor),a=d._offset+d._length/2,i="top"===d.side?-g-u*(d.showticklabels?1:0):n._length+g+u*(d.showticklabels?1.5:.5),i+=n._offset,o.side||(o.side="bottom")):(n="free"===d.anchor?{_offset:s.l+(d.position||0)*s.w,_length:0}:T.getFromId(t,d.anchor),i=d._offset+d._length/2,a="right"===d.side?n._length+g+u*(d.showticklabels?1:.5):-g-u*(d.showticklabels?.5:0),a+=n._offset,e={rotate:"-90",offset:0},o.side||(o.side="left")),c.draw(t,M+"title",{propContainer:d,propName:d._name+".title",placeholder:p._dfltTitle[l],avoid:o,transform:e,attributes:{x:a,y:i,"text-anchor":"middle"}})}}function K(t,e){return!0===t.visible&&t.xaxis+t.yaxis===e&&(!(!o.traceIs(t,"bar")||t.orientation!=={x:"h",y:"v"}[A])||t.fill&&t.fill.charAt(t.fill.length-1)===A)}function tt(e,r,a){if(!p._hasOnlyLargeSploms){var i=e.gridlayer.selectAll("."+M),o=e.zerolinelayer,s=e["hidegrid"+A]?[]:q,c=d._gridpath||("x"===A?"M0,"+r._offset+"v":"M"+r._offset+",0h")+r._length,f=i.selectAll("path."+P).data(!1===d.showgrid?[]:s,S);if(f.enter().append("path").classed(P,1).classed("crisp",1).attr("d",c).each(function(t){d.zeroline&&("linear"===d.type||"-"===d.type)&&Math.abs(t.x)<d.dtick/100&&n.select(this).remove()}),f.attr("transform",y).call(u.stroke,d.gridcolor||"#ddd").style("stroke-width",N+"px"),"function"==typeof c&&f.attr("d",c),f.exit().remove(),o){for(var h=!1,g=0;g<t._fullData.length;g++)if(K(t._fullData[g],a)){h=!0;break}var v=l.simpleMap(d.range,d.r2l),m=v[0]*v[1]<=0&&d.zeroline&&("linear"===d.type||"-"===d.type)&&s.length&&(h||W({x:0})||!d.showline),x=o.selectAll("path."+D).data(m?[{x:0,id:M}]:[]);x.enter().append("path").classed(D,1).classed("zl",1).classed("crisp",1).attr("d",c).each(function(){o.selectAll("path").sort(function(t,e){return T.idSort(t.id,e.id)})}),x.attr("transform",y).call(u.stroke,d.zerolinecolor||u.defaultLine).style("stroke-width",R+"px"),x.exit().remove()}}}},k.allowAutoMargin=function(t){for(var e=k.list(t,"",!0),r=0;r<e.length;r++){var n=e[r];n.automargin&&i.allowAutoMargin(t,n._name+".automargin"),n.rangeslider&&n.rangeslider.visible&&i.allowAutoMargin(t,"rangeslider"+n._id)}},k.swap=function(t,e){for(var r=function(t,e){var r,n,a=[];for(r=0;r<e.length;r++){var i=[],o=t._fullData[e[r]].xaxis,l=t._fullData[e[r]].yaxis;if(o&&l){for(n=0;n<a.length;n++)-1===a[n].x.indexOf(o)&&-1===a[n].y.indexOf(l)||i.push(n);if(i.length){var s,c=a[i[0]];if(i.length>1)for(n=1;n<i.length;n++)s=a[i[n]],U(c.x,s.x),U(c.y,s.y);U(c.x,[o]),U(c.y,[l])}else a.push({x:[o],y:[l]})}}return a}(t,e),n=0;n<r.length;n++)G(t,r[n].x,r[n].y)}},{"../../components/color":45,"../../components/drawing":70,"../../components/titles":136,"../../constants/alignment":143,"../../constants/numerical":145,"../../lib":163,"../../lib/svg_text_utils":184,"../../plots/plots":239,"../../registry":247,"./autorange":206,"./axis_autotype":208,"./axis_ids":210,"./set_convert":225,d3:10,"fast-isnumeric":13}],208:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../constants/numerical").BADNUM;e.exports=function(t,e){return function(t,e){for(var r,i=0,o=0,l=Math.max(1,(t.length-1)/1e3),s=0;s<t.length;s+=l)r=t[Math.round(s)],a.isDateTime(r,e)&&(i+=1),n(r)&&(o+=1);return i>2*o}(t,e)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,o=0,l=0;l<t.length;l+=r)e=t[Math.round(l)],a.cleanNumber(e)!==i?n++:"string"==typeof e&&""!==e&&"None"!==e&&o++;return o>2*n}(t)?"category":function(t){if(!t)return!1;for(var e=0;e<t.length;e++)if(n(t[e]))return!0;return!1}(t)?"linear":"-"}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],209:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("./layout_attributes"),o=t("./tick_value_defaults"),l=t("./tick_mark_defaults"),s=t("./tick_label_defaults"),c=t("./category_order_defaults"),u=t("./line_grid_defaults"),f=t("./set_convert");e.exports=function(t,e,r,d,p){var h=d.letter,g=e._id,y=d.font||{},v=r("visible",!d.cheateronly),m=e.type;"date"===m&&n.getComponentMethod("calendars","handleDefaults")(t,e,"calendar",d.calendar);f(e,p);var x=r("autorange",!e.isValidRange(t.range));if(e._rangesliderAutorange=!1,x&&r("rangemode"),r("range"),e.cleanRange(),c(t,e,r,d),"category"===m||d.noHover||r("hoverformat"),!v)return e;var b=r("color"),_=b!==i.color.dflt?b:y.color;return r("title",((p._splomAxes||{})[h]||{})[g]||p._dfltTitle[h]),a.coerceFont(r,"titlefont",{family:y.family,size:Math.round(1.2*y.size),color:_}),o(t,e,r,m),s(t,e,r,m,d),l(t,e,r,d),u(t,e,r,{dfltColor:b,bgColor:d.bgColor,showGrid:d.showGrid,attributes:i}),(e.showline||e.ticks)&&r("mirror"),d.automargin&&r("automargin"),e}},{"../../lib":163,"../../registry":247,"./category_order_defaults":211,"./layout_attributes":219,"./line_grid_defaults":221,"./set_convert":225,"./tick_label_defaults":226,"./tick_mark_defaults":227,"./tick_value_defaults":228}],210:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./constants");r.id2name=function(t){if("string"==typeof t&&t.match(a.AX_ID_PATTERN)){var e=t.substr(1);return"1"===e&&(e=""),t.charAt(0)+"axis"+e}},r.name2id=function(t){if(t.match(a.AX_NAME_PATTERN)){var e=t.substr(5);return"1"===e&&(e=""),t.charAt(0)+e}},r.cleanId=function(t,e){if(t.match(a.AX_ID_PATTERN)&&(!e||t.charAt(0)===e)){var r=t.substr(1).replace(/^0+/,"");return"1"===r&&(r=""),t.charAt(0)+r}},r.list=function(t,e,n){var a=t._fullLayout;if(!a)return[];var i,o=r.listIds(t,e),l=new Array(o.length);for(i=0;i<o.length;i++){var s=o[i];l[i]=a[s.charAt(0)+"axis"+s.substr(1)]}if(!n){var c=a._subplots.gl3d||[];for(i=0;i<c.length;i++){var u=a[c[i]];e?l.push(u[e+"axis"]):l.push(u.xaxis,u.yaxis,u.zaxis)}}return l},r.listIds=function(t,e){var r=t._fullLayout;if(!r)return[];var n=r._subplots;return e?n[e+"axis"]:n.xaxis.concat(n.yaxis)},r.getFromId=function(t,e,n){var a=t._fullLayout;return"x"===n?e=e.replace(/y[0-9]*/,""):"y"===n&&(e=e.replace(/x[0-9]*/,"")),a[r.id2name(e)]},r.getFromTrace=function(t,e,a){var i=t._fullLayout,o=null;if(n.traceIs(e,"gl3d")){var l=e.scene;"scene"===l.substr(0,5)&&(o=i[l][a+"axis"])}else o=r.getFromId(t,e[a+"axis"]||a);return o},r.idSort=function(t,e){var r=t.charAt(0),n=e.charAt(0);return r!==n?r>n?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},{"../../registry":247,"./constants":212}],211:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){if("category"===e.type){var a,i=t.categoryarray,o=Array.isArray(i)&&i.length>0;o&&(a="array");var l,s=r("categoryorder",a);"array"===s&&(l=r("categoryarray")),o||"array"!==s||(s=e.categoryorder="trace"),"trace"===s?e._initialCategories=[]:"array"===s?e._initialCategories=l.slice():(l=function(t,e){var r,n,a,i=e.dataAttr||t._id.charAt(0),o={};if(e.axData)r=e.axData;else for(r=[],n=0;n<e.data.length;n++){var l=e.data[n];l[i+"axis"]===t._id&&r.push(l)}for(n=0;n<r.length;n++){var s=r[n][i];for(a=0;a<s.length;a++){var c=s[a];null!=c&&(o[c]=1)}}return Object.keys(o)}(e,n).sort(),"category ascending"===s?e._initialCategories=l:"category descending"===s&&(e._initialCategories=l.reverse()))}}},{}],212:[function(t,e,r){"use strict";var n=t("../../lib/regex").counter;e.exports={idRegex:{x:n("x"),y:n("y")},attrRegex:n("[xy]axis"),xAxisMatch:n("xaxis"),yAxisMatch:n("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["heatmaplayer","contourcarpetlayer","contourlayer","barlayer","carpetlayer","violinlayer","boxlayer","ohlclayer","scattercarpetlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}}},{"../../lib/regex":178}],213:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./axis_ids").id2name;e.exports=function(t,e,r,i,o){var l=o._axisConstraintGroups,s=e._id,c=s.charAt(0);if(!e.fixedrange&&(r("constrain"),n.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===c?["left","center","right"]:["bottom","middle","top"],dflt:"x"===c?"center":"middle"}},"constraintoward"),t.scaleanchor)){var u=function(t,e,r,n){var i,o,l,s,c=n[a(e)].type,u=[];for(o=0;o<r.length;o++)(l=r[o])!==e&&((s=n[a(l)]).type!==c||s.fixedrange||u.push(l));for(i=0;i<t.length;i++)if(t[i][e]){var f=t[i],d=[];for(o=0;o<u.length;o++)l=u[o],f[l]||d.push(l);return{linkableAxes:d,thisGroup:f}}return{linkableAxes:u,thisGroup:null}}(l,s,i,o),f=n.coerce(t,e,{scaleanchor:{valType:"enumerated",values:u.linkableAxes}},"scaleanchor");if(f){var d=r("scaleratio");d||(d=e.scaleratio=1),function(t,e,r,n,a){var i,o,l,s,c;null===e?((e={})[r]=1,c=t.length,t.push(e)):c=t.indexOf(e);var u=Object.keys(e);for(i=0;i<t.length;i++)if(l=t[i],i!==c&&l[n]){var f=l[n];for(o=0;o<u.length;o++)s=u[o],l[s]=f*a*e[s];return void t.splice(c,1)}if(1!==a)for(o=0;o<u.length;o++)e[u[o]]*=a;e[n]=1}(l,u.thisGroup,s,f,d)}else-1!==i.indexOf(t.scaleanchor)&&n.warn("ignored "+e._name+'.scaleanchor: "'+t.scaleanchor+'" to avoid either an infinite loop and possibly inconsistent scaleratios, or because the targetaxis has fixed range.')}}},{"../../lib":163,"./axis_ids":210}],214:[function(t,e,r){"use strict";var n=t("./axis_ids").id2name,a=t("./scale_zoom"),i=t("./autorange").makePadFn,o=t("../../constants/numerical").ALMOST_EQUAL,l=t("../../constants/alignment").FROM_BL;function s(t,e){var r=t._inputDomain,n=l[t.constraintoward],a=r[0]+(r[1]-r[0])*n;t.domain=t._input.domain=[a+(r[0]-a)/e,a+(r[1]-a)/e]}r.enforce=function(t){var e,r,l,c,u,f,d,p=t._fullLayout,h=p._axisConstraintGroups||[];for(e=0;e<h.length;e++){var g=h[e],y=Object.keys(g),v=1/0,m=0,x=1/0,b={},_={},w=!1;for(r=0;r<y.length;r++)_[l=y[r]]=c=p[n(l)],c._inputDomain?c.domain=c._inputDomain.slice():c._inputDomain=c.domain.slice(),c._inputRange||(c._inputRange=c.range.slice()),c.setScale(),b[l]=u=Math.abs(c._m)/g[l],v=Math.min(v,u),"domain"!==c.constrain&&c._constraintShrinkable||(x=Math.min(x,u)),delete c._constraintShrinkable,m=Math.max(m,u),"domain"===c.constrain&&(w=!0);if(!(v>o*m)||w)for(r=0;r<y.length;r++)if(u=b[l=y[r]],f=(c=_[l]).constrain,u!==x||"domain"===f)if(d=u/x,"range"===f)a(c,d);else{var k=c._inputDomain,M=(c.domain[1]-c.domain[0])/(k[1]-k[0]),T=(c.r2l(c.range[1])-c.r2l(c.range[0]))/(c.r2l(c._inputRange[1])-c.r2l(c._inputRange[0]));if((d/=M)*T<1){c.domain=c._input.domain=k.slice(),a(c,d);continue}if(T<1&&(c.range=c._input.range=c._inputRange.slice(),d*=T),c.autorange&&c._min.length&&c._max.length){var A=c.r2l(c.range[0]),L=c.r2l(c.range[1]),C=(A+L)/2,S=C,O=C,P=Math.abs(L-C),D=C-P*d*1.0001,z=C+P*d*1.0001,E=i(c);s(c,d),c.setScale();var I,N,R=Math.abs(c._m);for(N=0;N<c._min.length;N++)(I=c._min[N].val-E(c._min[N])/R)>D&&I<S&&(S=I);for(N=0;N<c._max.length;N++)(I=c._max[N].val+E(c._max[N])/R)<z&&I>O&&(O=I);d/=(O-S)/(2*P),S=c.l2r(S),O=c.l2r(O),c.range=c._input.range=A<L?[S,O]:[O,S]}s(c,d)}}},r.clean=function(t,e){if(e._inputDomain){for(var r=!1,n=e._id,a=t._fullLayout._axisConstraintGroups,i=0;i<a.length;i++)if(a[i][n]){r=!0;break}r&&"domain"===e.constrain||(e._input.domain=e.domain=e._inputDomain,delete e._inputDomain)}}},{"../../constants/alignment":143,"../../constants/numerical":145,"./autorange":206,"./axis_ids":210,"./scale_zoom":223}],215:[function(t,e,r){"use strict";var n=t("d3"),a=t("tinycolor2"),i=t("has-passive-events"),o=t("../../registry"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../../lib/clear_gl_canvases"),u=t("../../components/color"),f=t("../../components/drawing"),d=t("../../components/fx"),p=t("../../lib/setcursor"),h=t("../../components/dragelement"),g=t("../../constants/alignment").FROM_TL,y=t("../plots"),v=t("./axes").doTicksSingle,m=t("./axis_ids").getFromId,x=t("./select").prepSelect,b=t("./select").clearSelect,_=t("./scale_zoom"),w=t("./constants"),k=w.MINDRAG,M=w.MINZOOM,T=!0;function A(t,e,r,n){var a=l.ensureSingle(t.draglayer,e,r,function(e){e.classed("drag",!0).style({fill:"transparent","stroke-width":0}).attr("data-subplot",t.id)});return a.call(p,n),a.node()}function L(t,e,r,a,i,o,l){var s=A(t,"rect",e,r);return n.select(s).call(f.setRect,a,i,o,l),s}function C(t,e){for(var r=0;r<t.length;r++)if(!t[r].fixedrange)return e;return""}function S(t,e,r,n,a){var i,o,l,s;for(i=0;i<t.length;i++)(o=t[i]).fixedrange||(l=o._rl[0],s=o._rl[1]-l,o.range=[o.l2r(l+s*e),o.l2r(l+s*r)],n[o._name+".range[0]"]=o.range[0],n[o._name+".range[1]"]=o.range[1]);if(a&&a.length){var c=(e+(1-r))/2;S(a,c,1-c,n)}}function O(t,e){for(var r=0;r<t.length;r++){var n=t[r];n.fixedrange||(n.range=[n.l2r(n._rl[0]-e/n._m),n.l2r(n._rl[1]-e/n._m)])}}function P(t){return 1-(t>=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function D(t,e,r,n,a){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",a+"Z")}function z(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:u.background,stroke:u.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function E(t,e,r,n,a,i){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),I(t,e,a,i)}function I(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function N(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function R(t){T&&t.data&&t._context.showTips&&(l.notifier(l._(t,"Double-click to zoom back out"),"long"),T=!1)}function F(t){return"lasso"===t||"select"===t}function j(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,M)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function B(t,e){if(i){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function H(t){var e=[];for(var r in t)e.push(t[r]);return e}e.exports={makeDragBox:function(t,e,r,i,u,p,T,A){var I,q,V,U,G,Y,X,Z,W,Q,J,$,K,tt,et,rt,nt,at,it,ot,lt,st=t._fullLayout._zoomlayer,ct=T+A==="nsew",ut=1===(T+A).length;function ft(){if(I=e.xaxis,q=e.yaxis,W=I._length,Q=q._length,X=I._offset,Z=q._offset,(V={})[I._id]=I,(U={})[q._id]=q,T&&A)for(var r=e.overlays,n=0;n<r.length;n++){var a=r[n].xaxis;V[a._id]=a;var i=r[n].yaxis;U[i._id]=i}G=H(V),Y=H(U),$=C(G,A),K=C(Y,T),tt=!K&&!$,J=function(t,e,r){for(var n,a,i,o,s=t._fullLayout._axisConstraintGroups,c=!1,u={},f={},d=0;d<s.length;d++){var p=s[d];for(n in e)if(p[n]){for(i in p)("x"===i.charAt(0)?e:r)[i]||(u[i]=1);for(a in r)p[a]&&(c=!0)}for(a in r)if(p[a])for(o in p)("x"===o.charAt(0)?e:r)[o]||(f[o]=1)}c&&(l.extendFlat(u,f),f={});var h={},g=[];for(i in u){var y=m(t,i);g.push(y),h[y._id]=y}var v={},x=[];for(o in f){var b=m(t,o);x.push(b),v[b._id]=b}return{xaHash:h,yaHash:v,xaxes:g,yaxes:x,isSubplotConstrained:c}}(t,V,U),et=J.isSubplotConstrained,rt=A||et,nt=T||et;var o=t._fullLayout;at=o._has("scattergl"),it=o._hasOnlyLargeSploms,ot=it||o._has("splom"),lt=o._has("svg")}ft();var dt=function(t,e,r){return t?"nsew"===t?r?"":"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}(K+$,t._fullLayout.dragmode,ct),pt=L(e,T+A+"drag",dt,r,i,u,p);if(tt&&!ct)return pt.onmousedown=null,pt.style.pointerEvents="none",pt;var ht,gt,yt,vt,mt,xt,bt,_t,wt,kt,Mt={element:pt,gd:t,plotinfo:e};function Tt(){Mt.plotinfo.selection=!1,b(st)}function At(r,a){if(N(t),2!==r||ut||function(){if(!t._transitioningWithDuration){var e,r,n,a=t._context.doubleClick,i=($?G:[]).concat(K?Y:[]),l={};if("reset+autosize"===a)for(a="autosize",r=0;r<i.length;r++)if((e=i[r])._rangeInitial&&(e.range[0]!==e._rangeInitial[0]||e.range[1]!==e._rangeInitial[1])||!e._rangeInitial&&!e.autorange){a="reset";break}if("autosize"===a)for(r=0;r<i.length;r++)(e=i[r]).fixedrange||(l[e._name+".autorange"]=!0);else if("reset"===a)for(($||et)&&(i=i.concat(J.xaxes)),K&&!et&&(i=i.concat(J.yaxes)),et&&($?K||(i=i.concat(Y)):i=i.concat(G)),r=0;r<i.length;r++)(e=i[r])._rangeInitial?(n=e._rangeInitial,l[e._name+".range[0]"]=n[0],l[e._name+".range[1]"]=n[1]):l[e._name+".autorange"]=!0;t.emit("plotly_doubleclick",null),o.call("relayout",t,l)}}(),ct)d.click(t,a,e.id);else if(1===r&&ut){var i=T?q:I,l="s"===T||"w"===A?0:1,c=i._name+".range["+l+"]",u=function(t,e){var r,a=t.range[e],i=Math.abs(a-t.range[1-e]);return"date"===t.type?a:"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,n.format("."+r+"g")(Math.pow(10,a))):(r=Math.floor(Math.log(Math.abs(a))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,n.format("."+String(r)+"g")(a))}(i,l),f="left",p="middle";if(i.fixedrange)return;T?(p="n"===T?"top":"bottom","right"===i.side&&(f="right")):"e"===A&&(f="right"),t._context.showAxisRangeEntryBoxes&&n.select(pt).call(s.makeEditable,{gd:t,immediate:!0,background:t._fullLayout.paper_bgcolor,text:String(u),fill:i.tickfont?i.tickfont.color:"#444",horizontalAlign:f,verticalAlign:p}).on("edit",function(e){var r=i.d2r(e);void 0!==r&&o.call("relayout",t,c,r)})}}Mt.prepFn=function(e,r,n){var i=t._fullLayout.dragmode;ft(),tt||(ct?e.shiftKey?"pan"===i?i="zoom":F(i)||(i="pan"):e.ctrlKey&&(i="pan"):i="pan"),Mt.minDrag="lasso"===i?1:void 0,F(i)?(Mt.xaxes=G,Mt.yaxes=Y,x(e,r,n,Mt,i)):(Mt.clickFn=At,Tt(),tt||("zoom"===i?(Mt.moveFn=Ct,Mt.doneFn=St,Mt.minDrag=1,function(e,r,n){var i=pt.getBoundingClientRect();ht=r-i.left,gt=n-i.top,yt={l:ht,r:ht,w:0,t:gt,b:gt,h:0},vt=t._hmpixcount?t._hmlumcount/t._hmpixcount:a(t._fullLayout.plot_bgcolor).getLuminance(),xt=!1,bt="xy",kt=!1,_t=D(st,vt,X,Z,mt="M0,0H"+W+"V"+Q+"H0V0"),wt=z(st,X,Z)}(0,r,n)):"pan"===i&&(Mt.moveFn=Nt,Mt.doneFn=Ft)))},h.init(Mt);var Lt={};function Ct(e,r){if(t._transitioningWithDuration)return!1;var n=Math.max(0,Math.min(W,e+ht)),a=Math.max(0,Math.min(Q,r+gt)),i=Math.abs(n-ht),o=Math.abs(a-gt);function l(){bt="",yt.r=yt.l,yt.t=yt.b,wt.attr("d","M0,0Z")}yt.l=Math.min(ht,n),yt.r=Math.max(ht,n),yt.t=Math.min(gt,a),yt.b=Math.max(gt,a),et?i>M||o>M?(bt="xy",i/W>o/Q?(o=i*Q/W,gt>a?yt.t=gt-o:yt.b=gt+o):(i=o*W/Q,ht>n?yt.l=ht-i:yt.r=ht+i),wt.attr("d",j(yt))):l():!K||o<Math.min(Math.max(.6*i,k),M)?i<k||!$?l():(yt.t=0,yt.b=Q,bt="x",wt.attr("d",function(t,e){return"M"+(t.l-.5)+","+(e-M-.5)+"h-3v"+(2*M+1)+"h3ZM"+(t.r+.5)+","+(e-M-.5)+"h3v"+(2*M+1)+"h-3Z"}(yt,gt))):!$||i<Math.min(.6*o,M)?(yt.l=0,yt.r=W,bt="y",wt.attr("d",function(t,e){return"M"+(e-M-.5)+","+(t.t-.5)+"v-3h"+(2*M+1)+"v3ZM"+(e-M-.5)+","+(t.b+.5)+"v3h"+(2*M+1)+"v-3Z"}(yt,ht))):(bt="xy",wt.attr("d",j(yt))),yt.w=yt.r-yt.l,yt.h=yt.b-yt.t,bt&&(kt=!0),t._dragged=kt,E(_t,wt,yt,mt,xt,vt),xt=!0}function St(){if(Math.min(yt.h,yt.w)<2*k)return N(t);"xy"!==bt&&"x"!==bt||S(G,yt.l/W,yt.r/W,Lt,J.xaxes),"xy"!==bt&&"y"!==bt||S(Y,(Q-yt.b)/Q,(Q-yt.t)/Q,Lt,J.yaxes),N(t),Ft(),R(t)}var Ot,Pt,Dt=[0,0,W,Q],zt=null,Et=w.REDRAWDELAY,It=e.mainplot?t._fullLayout._plots[e.mainplot]:e;function Nt(e,r){if(!t._transitioningWithDuration){if("ew"===$||"ns"===K)return $&&O(G,e),K&&O(Y,r),jt([$?-e:0,K?-r:0,W,Q]),void Rt(K,$);if(et&&$&&K){var n="w"===$==("n"===K)?1:-1,a=(e/W+n*r/Q)/2;e=a*W,r=n*a*Q}"w"===$?e=s(G,0,e):"e"===$?e=s(G,1,-e):$||(e=0),"n"===K?r=s(Y,1,r):"s"===K?r=s(Y,0,-r):K||(r=0);var i="w"===$?e:0,o="n"===K?r:0;if(et){var l;if(!$&&1===K.length){for(l=0;l<G.length;l++)G[l].range=G[l]._r.slice(),_(G[l],1-r/Q);i=(e=r*W/Q)/2}if(!K&&1===$.length){for(l=0;l<Y.length;l++)Y[l].range=Y[l]._r.slice(),_(Y[l],1-e/W);o=(r=e*Q/W)/2}}jt([i,o,W-e,Q-r]),Rt(K,$)}function s(t,e,r){for(var n,a,i=1-e,o=0;o<t.length;o++){var l=t[o];if(!l.fixedrange){n=l,a=l._rl[i]+(l._rl[e]-l._rl[i])/P(r/l._length);var s=l.l2r(a);!1!==s&&void 0!==s&&(l.range[e]=s)}}return n._length*(n._rl[e]-a)/(n._rl[e]-n._rl[i])}}function Rt(e,r){var n,a=[];function i(t){for(n=0;n<t.length;n++)t[n].fixedrange||a.push(t[n]._id)}for(rt&&(i(G),i(J.xaxes)),nt&&(i(Y),i(J.yaxes)),Lt={},n=0;n<a.length;n++){var l=a[n];v(t,l,!0);var s=m(t,l);Lt[s._name+".range[0]"]=s.range[0],Lt[s._name+".range[1]"]=s.range[1]}function c(i,o,l){for(n=0;n<i.length;n++){var s=i[n];if((r&&-1!==a.indexOf(s.xref)||e&&-1!==a.indexOf(s.yref))&&(o(t,n),l))return}}c(t._fullLayout.annotations||[],o.getComponentMethod("annotations","drawOne")),c(t._fullLayout.shapes||[],o.getComponentMethod("shapes","drawOne")),c(t._fullLayout.images||[],o.getComponentMethod("images","draw"),!0)}function Ft(){jt([0,0,W,Q]),l.syncOrAsync([y.previousPromises,function(){o.call("relayout",t,Lt)}],t)}function jt(e){var r,n,a,i,s=t._fullLayout,u=s._plots,d=s._subplots.cartesian;if((ot||at)&&c(t),!ot||(o.subplotsRegistry.splom.drag(t),!it)){if(at)for(r=0;r<d.length;r++){a=(n=u[d[r]]).xaxis,i=n.yaxis;var p=n._scene;if(p){var h=l.simpleMap(a.range,a.r2l),g=l.simpleMap(i.range,i.r2l);p.update({range:[h[0],g[0],h[1],g[1]]})}}if(lt){var y=e[2]/I._length,v=e[3]/q._length;for(r=0;r<d.length;r++){a=(n=u[d[r]]).xaxis,i=n.yaxis;var m,x,b,_,w=rt&&!a.fixedrange&&V[a._id],k=nt&&!i.fixedrange&&U[i._id];if(w?(m=y,b=A?e[0]:qt(a,m)):b=Ht(a,m=Bt(a,y,v)),k?(x=v,_=T?e[1]:qt(i,x)):_=Ht(i,x=Bt(i,y,v)),m||x){m||(m=1),x||(x=1);var M=a._offset-b/m,L=i._offset-_/x;n.clipRect.call(f.setTranslate,b,_).call(f.setScale,m,x),n.plot.call(f.setTranslate,M,L).call(f.setScale,1/m,1/x),m===Ot&&x===Pt||(f.setPointGroupScale(n.zoomScalePts,m,x),f.setTextPointsScale(n.zoomScaleTxt,m,x)),f.hideOutsideRangePoints(n.clipOnAxisFalseTraces,n),Ot=m,Pt=x}}}}}function Bt(t,e,r){return t.fixedrange?0:rt&&J.xaHash[t._id]?e:nt&&(et?J.xaHash:J.yaHash)[t._id]?r:0}function Ht(t,e){return e?(t.range=t._r.slice(),_(t,e),qt(t,e)):0}function qt(t,e){return t._length*(1-e)*g[t.constraintoward||"middle"]}return T.length*A.length!=1&&B(pt,function(e){if(t._context.scrollZoom||t._fullLayout._enablescrollzoom){if(Tt(),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var r=t.querySelector(".plotly");if(ft(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(zt);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var a,i=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=It.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,c=(o.bottom-e.clientY)/o.height;if(rt){for(A||(s=.5),a=0;a<G.length;a++)u(G[a],s,i);Dt[2]*=i,Dt[0]+=Dt[2]*s*(1/i-1)}if(nt){for(T||(c=.5),a=0;a<Y.length;a++)u(Y[a],c,i);Dt[3]*=i,Dt[1]+=Dt[3]*(1-c)*(1/i-1)}jt(Dt),Rt(T,A),zt=setTimeout(function(){Dt=[0,0,W,Q],Ft()},Et),e.preventDefault()}else l.log("Did not find wheel motion attributes: ",e)}}function u(t,e,r){if(!t.fixedrange){var n=l.simpleMap(t.range,t.r2l),a=n[0]+(n[1]-n[0])*e;t.range=n.map(function(e){return t.l2r(a+(e-a)*r)})}}}),pt},makeDragger:A,makeRectDragger:L,makeZoombox:D,makeCorners:z,updateZoombox:E,xyCorners:j,transitionZoombox:I,removeZoombox:N,showDoubleClickNotifier:R,attachWheelEventHandler:B}},{"../../components/color":45,"../../components/dragelement":67,"../../components/drawing":70,"../../components/fx":87,"../../constants/alignment":143,"../../lib":163,"../../lib/clear_gl_canvases":152,"../../lib/setcursor":182,"../../lib/svg_text_utils":184,"../../registry":247,"../plots":239,"./axes":207,"./axis_ids":210,"./constants":212,"./scale_zoom":223,"./select":224,d3:10,"has-passive-events":16,tinycolor2:28}],216:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/fx"),i=t("../../components/dragelement"),o=t("../../lib/setcursor"),l=t("./dragbox").makeDragBox,s=t("./constants").DRAGGERSIZE;r.initInteractions=function(t){var e=t._fullLayout;if(t._context.staticPlot)n.select(t).selectAll(".drag").remove();else if(e._has("cartesian")||e._has("gl2d")||e._has("splom")){Object.keys(e._plots||{}).sort(function(t,r){if((e._plots[t].mainplot&&!0)===(e._plots[r].mainplot&&!0)){var n=t.split("y"),a=r.split("y");return n[0]===a[0]?Number(n[1]||1)-Number(a[1]||1):Number(n[0]||1)-Number(a[0]||1)}return e._plots[t].mainplot?1:-1}).forEach(function(r){var n=e._plots[r],o=n.xaxis,c=n.yaxis;if(!n.mainplot){var u=l(t,n,o._offset,c._offset,o._length,c._length,"ns","ew");u.onmousemove=function(e){t._fullLayout._rehover=function(){t._fullLayout._hoversubplot===r&&a.hover(t,e,r)},a.hover(t,e,r),t._fullLayout._lasthover=u,t._fullLayout._hoversubplot=r},u.onmouseout=function(e){t._dragging||(t._fullLayout._hoversubplot=null,i.unhover(t,e))},t._context.showAxisDragHandles&&(l(t,n,o._offset-s,c._offset-s,s,s,"n","w"),l(t,n,o._offset+o._length,c._offset-s,s,s,"n","e"),l(t,n,o._offset-s,c._offset+c._length,s,s,"s","w"),l(t,n,o._offset+o._length,c._offset+c._length,s,s,"s","e"))}if(t._context.showAxisDragHandles){if(r===o._mainSubplot){var f=o._mainLinePosition;"top"===o.side&&(f-=s),l(t,n,o._offset+.1*o._length,f,.8*o._length,s,"","ew"),l(t,n,o._offset,f,.1*o._length,s,"","w"),l(t,n,o._offset+.9*o._length,f,.1*o._length,s,"","e")}if(r===c._mainSubplot){var d=c._mainLinePosition;"right"!==c.side&&(d-=s),l(t,n,d,c._offset+.1*c._length,s,.8*c._length,"ns",""),l(t,n,d,c._offset+.9*c._length,s,.1*c._length,"s",""),l(t,n,d,c._offset,s,.1*c._length,"n","")}}});var o=e._hoverlayer.node();o.onmousemove=function(r){r.target=t._fullLayout._lasthover,a.hover(t,r,e._hoversubplot)},o.onclick=function(e){e.target=t._fullLayout._lasthover,a.click(t,e)},o.onmousedown=function(e){t._fullLayout._lasthover.onmousedown(e)},r.updateFx(e)}},r.updateFx=function(t){var e="pan"===t.dragmode?"move":"crosshair";o(t._draggers,e)}},{"../../components/dragelement":67,"../../components/fx":87,"../../lib/setcursor":182,"./constants":212,"./dragbox":215,d3:10}],217:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib");e.exports=function(t){return function(e,r){var i=e[t];if(Array.isArray(i))for(var o=n.subplotsRegistry.cartesian,l=o.idRegex,s=r._subplots,c=s.xaxis,u=s.yaxis,f=s.cartesian,d=r._has("cartesian")||r._has("gl2d"),p=0;p<i.length;p++){var h=i[p];if(a.isPlainObject(h)){var g=h.xref,y=h.yref,v=l.x.test(g),m=l.y.test(y);if(v||m){d||a.pushUnique(r._basePlotModules,o);var x=!1;v&&-1===c.indexOf(g)&&(c.push(g),x=!0),m&&-1===u.indexOf(y)&&(u.push(y),x=!0),x&&v&&m&&f.push(g+y)}}}}}},{"../../lib":163,"../../registry":247}],218:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../lib"),o=t("../plots"),l=t("../../components/drawing"),s=t("../get_data").getModuleCalcData,c=t("./axis_ids"),u=t("./constants"),f=t("../../constants/xmlns_namespaces"),d=i.ensureSingle;function p(t,e,r){return i.ensureSingle(t,e,r,function(t){t.datum(r)})}function h(t,e,r,i,o){for(var c,f,d,p=u.traceLayerClasses,h=t._fullLayout,g=h._modules,y=[],v=[],m=0;m<g.length;m++){var x=(c=g[m]).name,b=a.modules[x].categories;if(b.svg){var _=c.layerName||x+"layer",w=c.plot;d=(f=s(r,w))[0],r=f[1],d.length&&y.push({i:p.indexOf(_),className:_,plotMethod:w,cdModule:d}),b.zoomScale&&v.push("."+_)}}y.sort(function(t,e){return t.i-e.i});var k=e.plot.selectAll("g.mlayer").data(y,function(t){return t.className});if(k.enter().append("g").attr("class",function(t){return t.className}).classed("mlayer",!0),k.exit().remove(),k.order(),k.each(function(r){var a=n.select(this),s=r.className;r.plotMethod(t,e,r.cdModule,a,i,o),"scatterlayer"!==s&&"barlayer"!==s&&l.setClipUrl(a,e.layerClipId)}),h._has("scattergl")&&(c=a.getModule("scattergl"),d=s(r,c)[0],c.plot(t,e,d)),!t._context.staticPlot&&(e._hasClipOnAxisFalse&&(e.clipOnAxisFalseTraces=e.plot.selectAll(".scatterlayer, .barlayer").selectAll(".trace")),v.length)){var M=e.plot.selectAll(v.join(",")).selectAll(".trace");e.zoomScalePts=M.selectAll("path.point"),e.zoomScaleTxt=M.selectAll(".textpoint")}}function g(t,e){var r=e.plotgroup,n=e.id,a=u.layerValue2layerClass[e.xaxis.layer],i=u.layerValue2layerClass[e.yaxis.layer],o=t._fullLayout._hasOnlyLargeSploms;if(e.mainplot){var l=e.mainplotinfo,s=l.plotgroup,f=n+"-x",h=n+"-y";e.gridlayer=l.gridlayer,e.zerolinelayer=l.zerolinelayer,d(l.overlinesBelow,"path",f),d(l.overlinesBelow,"path",h),d(l.overaxesBelow,"g",f),d(l.overaxesBelow,"g",h),e.plot=d(l.overplot,"g",n),d(l.overlinesAbove,"path",f),d(l.overlinesAbove,"path",h),d(l.overaxesAbove,"g",f),d(l.overaxesAbove,"g",h),e.xlines=s.select(".overlines-"+a).select("."+f),e.ylines=s.select(".overlines-"+i).select("."+h),e.xaxislayer=s.select(".overaxes-"+a).select("."+f),e.yaxislayer=s.select(".overaxes-"+i).select("."+h)}else if(o)e.plot=d(r,"g","plot"),e.xlines=d(r,"path","xlines-above"),e.ylines=d(r,"path","ylines-above"),e.xaxislayer=d(r,"g","xaxislayer-above"),e.yaxislayer=d(r,"g","yaxislayer-above");else{var g=d(r,"g","layer-subplot");e.shapelayer=d(g,"g","shapelayer"),e.imagelayer=d(g,"g","imagelayer"),e.gridlayer=d(r,"g","gridlayer"),e.zerolinelayer=d(r,"g","zerolinelayer"),d(r,"path","xlines-below"),d(r,"path","ylines-below"),e.overlinesBelow=d(r,"g","overlines-below"),d(r,"g","xaxislayer-below"),d(r,"g","yaxislayer-below"),e.overaxesBelow=d(r,"g","overaxes-below"),e.plot=d(r,"g","plot"),e.overplot=d(r,"g","overplot"),e.xlines=d(r,"path","xlines-above"),e.ylines=d(r,"path","ylines-above"),e.overlinesAbove=d(r,"g","overlines-above"),d(r,"g","xaxislayer-above"),d(r,"g","yaxislayer-above"),e.overaxesAbove=d(r,"g","overaxes-above"),e.xlines=r.select(".xlines-"+a),e.ylines=r.select(".ylines-"+i),e.xaxislayer=r.select(".xaxislayer-"+a),e.yaxislayer=r.select(".yaxislayer-"+i)}o||(p(e.gridlayer,"g",e.xaxis._id),p(e.gridlayer,"g",e.yaxis._id),e.gridlayer.selectAll("g").sort(c.idSort)),e.xlines.style("fill","none").classed("crisp",!0),e.ylines.style("fill","none").classed("crisp",!0)}function y(t,e){if(t){var r={};for(var a in t.each(function(t){n.select(this).remove(),v(t,e),r[t]=!0}),e._plots)for(var i=e._plots[a].overlays||[],o=0;o<i.length;o++){var l=i[o];r[l.id]&&l.plot.selectAll(".trace").remove()}}}function v(t,e){e._draggers.selectAll("g."+t).remove(),e._defs.select("#clip"+e._uid+t+"plot").remove()}r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=u.idRegex,r.attrRegex=u.attrRegex,r.attributes=t("./attributes"),r.layoutAttributes=t("./layout_attributes"),r.supplyLayoutDefaults=t("./layout_defaults"),r.transitionAxes=t("./transition_axes"),r.finalizeSubplots=function(t,e){var r,n,a,o=e._subplots,l=o.xaxis,s=o.yaxis,f=o.cartesian,d=f.concat(o.gl2d||[]),p={},h={};for(r=0;r<d.length;r++){var g=d[r].split("y");p[g[0]]=1,h["y"+g[1]]=1}for(r=0;r<l.length;r++)p[n=l[r]]||(a=(t[c.id2name(n)]||{}).anchor,u.idRegex.y.test(a)||(a="y"),f.push(n+a),d.push(n+a),h[a]||(h[a]=1,i.pushUnique(s,a)));for(r=0;r<s.length;r++)h[a=s[r]]||(n=(t[c.id2name(a)]||{}).anchor,u.idRegex.x.test(n)||(n="x"),f.push(n+a),d.push(n+a),p[n]||(p[n]=1,i.pushUnique(l,n)));if(!d.length){for(var y in n="",a="",t){if(u.attrRegex.test(y))"x"===y.charAt(0)?(!n||+y.substr(5)<+n.substr(5))&&(n=y):(!a||+y.substr(5)<+a.substr(5))&&(a=y)}n=n?c.name2id(n):"x",a=a?c.name2id(a):"y",l.push(n),s.push(a),f.push(n+a)}},r.plot=function(t,e,r,n){var a,i=t._fullLayout,o=i._subplots.cartesian,l=t.calcdata;if(null!==e){if(!Array.isArray(e))for(e=[],a=0;a<l.length;a++)e.push(a);for(a=0;a<o.length;a++){for(var s,c=o[a],u=i._plots[c],f=[],d=0;d<l.length;d++){var p=l[d],g=p[0].trace;g.xaxis+g.yaxis===c&&((-1!==e.indexOf(g.index)||g.carpet)&&(s&&s[0].trace.xaxis+s[0].trace.yaxis===c&&-1!==["tonextx","tonexty","tonext"].indexOf(g.fill)&&-1===f.indexOf(s)&&f.push(s),f.push(p)),s=p)}h(t,u,f,r,n)}}},r.clean=function(t,e,r,n){var a,i,o,l=n._plots||{},s=e._plots||{},u=n._subplots||{};if(n._hasOnlyLargeSploms&&!e._hasOnlyLargeSploms)for(o in l)(a=l[o]).plotgroup&&a.plotgroup.remove();var f=n._has&&n._has("gl"),d=e._has&&e._has("gl");if(f&&!d)for(o in l)(a=l[o])._scene&&a._scene.destroy();if(u.xaxis&&u.yaxis){var p=c.listIds({_fullLayout:n});for(i=0;i<p.length;i++){var h=p[i];e[c.id2name(h)]||n._infolayer.selectAll(".g-"+h+"title").remove()}}var g=n._has&&n._has("cartesian"),m=e._has&&e._has("cartesian");if(g&&!m)y(n._cartesianlayer.selectAll(".subplot"),n),n._defs.selectAll(".axesclip").remove(),delete n._axisConstraintGroups;else if(u.cartesian)for(i=0;i<u.cartesian.length;i++){var x=u.cartesian[i];if(!s[x]){var b="."+x+",."+x+"-x,."+x+"-y";n._cartesianlayer.selectAll(b).remove(),v(x,n)}}},r.drawFramework=function(t){var e=t._fullLayout,r=function(t){var e=t._fullLayout,r=[],n=[];for(var a in e._plots){var i=e._plots[a],o=i.xaxis._mainAxis,l=i.yaxis._mainAxis,s=o._id+l._id;s!==a&&e._plots[s]?(i.mainplot=s,i.mainplotinfo=e._plots[s],n.push(a)):(r.push(a),i.mainplot=void 0)}return r=r.concat(n)}(t),a=e._cartesianlayer.selectAll(".subplot").data(r,i.identity);a.enter().append("g").attr("class",function(t){return"subplot "+t}),a.order(),a.exit().call(y,e),a.each(function(r){var a=e._plots[r];(a.plotgroup=n.select(this),a.overlays=[],g(t,a),a.mainplot)&&e._plots[a.mainplot].overlays.push(a);a.draglayer=d(e._draggers,"g",r)})},r.rangePlot=function(t,e,r){g(t,e),h(t,e,r),o.style(t)},r.toSVG=function(t){var e=t._fullLayout._glimages,r=n.select(t).selectAll(".svg-container");r.filter(function(t,e){return e===r.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");e.append("svg:image").attr({xmlns:f.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})})},r.updateFx=t("./graph_interact").updateFx},{"../../components/drawing":70,"../../constants/xmlns_namespaces":147,"../../lib":163,"../../registry":247,"../get_data":235,"../plots":239,"./attributes":205,"./axis_ids":210,"./constants":212,"./graph_interact":216,"./layout_attributes":219,"./layout_defaults":220,"./transition_axes":229,d3:10}],219:[function(t,e,r){"use strict";var n=t("../font_attributes"),a=t("../../components/color/attributes"),i=t("../../components/drawing/attributes").dash,o=t("../../lib/extend").extendFlat,l=t("../../plot_api/plot_template").templatedArray,s=t("./constants");e.exports={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:a.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks"},titlefont:n({editType:"ticks"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc",_noTemplating:!0},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"axrange",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"axrange",impliedEdits:{"^autorange":!1}}],editType:"axrange",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[s.idRegex.x.toString(),s.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks"},tick0:{valType:"any",editType:"ticks",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks"},ticktext:{valType:"data_array",editType:"ticks"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:a.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks"},automargin:{valType:"boolean",dflt:!1,editType:"ticks"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:o({},i,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:n({editType:"ticks"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks"},tickprefix:{valType:"string",dflt:"",editType:"ticks"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},ticksuffix:{valType:"string",dflt:"",editType:"ticks"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks"},tickformat:{valType:"string",dflt:"",editType:"ticks"},tickformatstops:l("tickformatstop",{enabled:{valType:"boolean",dflt:!0,editType:"ticks"},dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks"},{valType:"any",editType:"ticks"}],editType:"ticks"},value:{valType:"string",dflt:"",editType:"ticks"},editType:"ticks"}),hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:a.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:a.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:a.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",s.idRegex.x.toString(),s.idRegex.y.toString()],editType:"plot"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot"},overlaying:{valType:"enumerated",values:["free",s.idRegex.x.toString(),s.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot"},{valType:"number",min:0,max:1,editType:"plot"}],dflt:[0,1],editType:"plot"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks"}}}},{"../../components/color/attributes":44,"../../components/drawing/attributes":69,"../../lib/extend":157,"../../plot_api/plot_template":197,"../font_attributes":233,"./constants":212}],220:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../components/color"),o=t("../../plot_api/plot_template"),l=t("../layout_attributes"),s=t("./layout_attributes"),c=t("./type_defaults"),u=t("./axis_defaults"),f=t("./constraint_defaults"),d=t("./position_defaults"),p=t("./axis_ids");e.exports=function(t,e,r){var h,g={},y={},v={},m={};for(h=0;h<r.length;h++){var x=r[h];if(n.traceIs(x,"cartesian")||n.traceIs(x,"gl2d")){var b=p.id2name(x.xaxis),_=p.id2name(x.yaxis);if(n.traceIs(x,"carpet")&&("carpet"!==x.type||x._cheater)||b&&(y[b]=1),"carpet"===x.type&&x._cheater&&b&&(g[b]=1),n.traceIs(x,"2dMap")&&(v[b]=!0,v[_]=!0),n.traceIs(x,"oriented"))m["h"===x.orientation?_:b]=!0}}var w=e._subplots,k=w.xaxis,M=w.yaxis,T=a.simpleMap(k,p.id2name),A=a.simpleMap(M,p.id2name),L=T.concat(A),C=i.background;k.length&&M.length&&(C=a.coerce(t,e,l,"plot_bgcolor"));var S,O,P,D,z=i.combine(C,e.paper_bgcolor);function E(t,e){return a.coerce(P,D,s,t,e)}function I(t,e){return a.coerce2(P,D,s,t,e)}function N(t){return"x"===t?M:k}var R={x:N("x"),y:N("y")};function F(e,r){for(var n="x"===e?T:A,a=[],i=0;i<n.length;i++){var o=n[i];o===r||(t[o]||{}).overlaying||a.push(p.name2id(o))}return a}for(h=0;h<L.length;h++){O=(S=L[h]).charAt(0),a.isPlainObject(t[S])||(t[S]={}),P=t[S],D=o.newContainer(e,S,O+"axis"),c(P,D,E,r,S);var j=F(O,S),B={letter:O,font:e.font,outerTicks:v[S],showGrid:!m[S],data:r,bgColor:z,calendar:e.calendar,automargin:!0,cheateronly:"x"===O&&g[S]&&!y[S]};u(P,D,E,B,e);var H=I("spikecolor"),q=I("spikethickness"),V=I("spikedash"),U=I("spikemode"),G=I("spikesnap");E("showspikes",!!(H||q||V||U||G))||(delete D.spikecolor,delete D.spikethickness,delete D.spikedash,delete D.spikemode,delete D.spikesnap);var Y={letter:O,counterAxes:R[O],overlayableAxes:j,grid:e.grid};d(P,D,E,Y),D._input=P}var X=n.getComponentMethod("rangeslider","handleDefaults"),Z=n.getComponentMethod("rangeselector","handleDefaults");for(h=0;h<T.length;h++)S=T[h],P=t[S],D=e[S],X(t,e,S),"date"===D.type&&Z(P,D,e,A,D.calendar),E("fixedrange");for(h=0;h<A.length;h++){S=A[h],P=t[S],D=e[S];var W=e[p.id2name(D.anchor)];E("fixedrange",W&&W.rangeslider&&W.rangeslider.visible)}e._axisConstraintGroups=[];var Q=R.x.concat(R.y);for(h=0;h<L.length;h++)O=(S=L[h]).charAt(0),P=t[S],D=e[S],f(P,D,E,Q,e)}},{"../../components/color":45,"../../lib":163,"../../plot_api/plot_template":197,"../../registry":247,"../layout_attributes":237,"./axis_defaults":209,"./axis_ids":210,"./constraint_defaults":213,"./layout_attributes":219,"./position_defaults":222,"./type_defaults":230}],221:[function(t,e,r){"use strict";var n=t("tinycolor2").mix,a=t("../../components/color/attributes").lightFraction,i=t("../../lib");e.exports=function(t,e,r,o){var l=(o=o||{}).dfltColor;function s(r,n){return i.coerce2(t,e,o.attributes,r,n)}var c=s("linecolor",l),u=s("linewidth");r("showline",o.showLine||!!c||!!u)||(delete e.linecolor,delete e.linewidth);var f=s("gridcolor",n(l,o.bgColor,o.blend||a).toRgbString()),d=s("gridwidth");if(r("showgrid",o.showGrid||!!f||!!d)||(delete e.gridcolor,delete e.gridwidth),!o.noZeroLine){var p=s("zerolinecolor",l),h=s("zerolinewidth");r("zeroline",o.showGrid||!!p||!!h)||(delete e.zerolinecolor,delete e.zerolinewidth)}}},{"../../components/color/attributes":44,"../../lib":163,tinycolor2:28}],222:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib");e.exports=function(t,e,r,i){var o,l,s,c,u=i.counterAxes||[],f=i.overlayableAxes||[],d=i.letter,p=i.grid;p&&(l=p._domains[d][p._axisMap[e._id]],o=p._anchors[e._id],l&&(s=p[d+"side"].split(" ")[0],c=p.domain[d]["right"===s||"top"===s?1:0])),l=l||[0,1],o=o||(n(t.position)?"free":u[0]||"free"),s=s||("x"===d?"bottom":"left"),c=c||0,"free"===a.coerce(t,e,{anchor:{valType:"enumerated",values:["free"].concat(u),dflt:o}},"anchor")&&r("position",c),a.coerce(t,e,{side:{valType:"enumerated",values:"x"===d?["bottom","top"]:["left","right"],dflt:s}},"side");var h=!1;if(f.length&&(h=a.coerce(t,e,{overlaying:{valType:"enumerated",values:[!1].concat(f),dflt:!1}},"overlaying")),!h){var g=r("domain",l);g[0]>g[1]-.01&&(e.domain=l),a.noneOrAll(t.domain,e.domain,l)}return r("layer"),e}},{"../../lib":163,"fast-isnumeric":13}],223:[function(t,e,r){"use strict";var n=t("../../constants/alignment").FROM_BL;e.exports=function(t,e,r){void 0===r&&(r=n[t.constraintoward||"center"]);var a=[t.r2l(t.range[0]),t.r2l(t.range[1])],i=a[0]+(a[1]-a[0])*r;t.range=t._input.range=[t.l2r(i+(a[0]-i)*e),t.l2r(i+(a[1]-i)*e)]}},{"../../constants/alignment":143}],224:[function(t,e,r){"use strict";var n=t("polybooljs"),a=t("../../registry"),i=t("../../components/color"),o=t("../../components/fx"),l=t("../../lib/polygon"),s=t("../../lib/throttle"),c=t("../../components/fx/helpers").makeEventData,u=t("./axis_ids").getFromId,f=t("../sort_modules").sortModules,d=t("./constants"),p=d.MINSELECT,h=l.filter,g=l.tester,y=l.multitester;function v(t){return t._id}function m(t,e,r){var n,i,o,l;if(r){var s=r.points||[];for(n=0;n<e.length;n++)(l=e[n].cd[0].trace).selectedpoints=[],l._input.selectedpoints=[];for(n=0;n<s.length;n++){var c=s[n],u=c.data,d=c.fullData;c.pointIndices?([].push.apply(u.selectedpoints,c.pointIndices),[].push.apply(d.selectedpoints,c.pointIndices)):(u.selectedpoints.push(c.pointIndex),d.selectedpoints.push(c.pointIndex))}}else for(n=0;n<e.length;n++)delete(l=e[n].cd[0].trace).selectedpoints,delete l._input.selectedpoints;var p={};for(n=0;n<e.length;n++){var h=(o=e[n])._module.name;p[h]?p[h].push(o):p[h]=[o]}var g=Object.keys(p).sort(f);for(n=0;n<g.length;n++){var y=p[g[n]],v=y.length,m=y[0],x=m.cd[0].trace,b=m._module,_=b.styleOnSelect||b.style;if(a.traceIs(x,"regl")){var w=new Array(v);for(i=0;i<v;i++)w[i]=y[i].cd;_(t,w)}else for(i=0;i<v;i++)_(t,y[i].cd)}}function x(t,e){if(Array.isArray(t))for(var r=e.cd,n=e.cd[0].trace,a=0;a<t.length;a++)t[a]=c(t[a],n,r);return t}function b(t){t.selectAll(".select-outline").remove()}e.exports={prepSelect:function(t,e,r,a,l){var c,f,_,w,k,M,T,A,L,C=a.gd,S=C._fullLayout,O=S._zoomlayer,P=a.element.getBoundingClientRect(),D=a.plotinfo,z=D.xaxis._offset,E=D.yaxis._offset,I=e-P.left,N=r-P.top,R=I,F=N,j="M"+I+","+N,B=a.xaxes[0]._length,H=a.yaxes[0]._length,q=a.xaxes.map(v),V=a.yaxes.map(v),U=a.xaxes.concat(a.yaxes),G=t.altKey,Y=S._lastSelectedSubplot&&S._lastSelectedSubplot===D.id;Y&&(t.shiftKey||t.altKey)&&D.selection&&D.selection.polygons&&!a.polygons?(a.polygons=D.selection.polygons,a.mergedPolygons=D.selection.mergedPolygons):(!t.shiftKey&&!t.altKey||(t.shiftKey||t.altKey)&&!D.selection)&&(D.selection={},D.selection.polygons=a.polygons=[],D.selection.mergedPolygons=a.mergedPolygons=[]),Y||(b(O),S._lastSelectedSubplot=D.id),"lasso"===l&&(c=h([[I,N]],d.BENDPX));var X=O.selectAll("path.select-outline-"+D.id).data([1,2]);X.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+D.id}).attr("transform","translate("+z+", "+E+")").attr("d",j+"Z");var Z,W=O.append("path").attr("class","zoombox-corners").style({fill:i.background,stroke:i.defaultLine,"stroke-width":1}).attr("transform","translate("+z+", "+E+")").attr("d","M0,0Z"),Q=[],J=S._uid+d.SELECTID,$=[];for(k=0;k<C.calcdata.length;k++)if(!0===(T=(M=C.calcdata[k])[0].trace).visible&&T._module&&T._module.selectPoints)if(a.subplot)T.subplot!==a.subplot&&T.geo!==a.subplot||Q.push({_module:T._module,cd:M,xaxis:a.xaxes[0],yaxis:a.yaxes[0]});else if("splom"===T.type&&T._xaxes[q[0]]&&T._yaxes[V[0]])Q.push({_module:T._module,cd:M,xaxis:a.xaxes[0],yaxis:a.yaxes[0]});else{if(-1===q.indexOf(T.xaxis))continue;if(-1===V.indexOf(T.yaxis))continue;Q.push({_module:T._module,cd:M,xaxis:u(C,T.xaxis),yaxis:u(C,T.yaxis)})}function K(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function tt(t,e){return t-e}Z=D.fillRangeItems?D.fillRangeItems:"select"===l?function(t,e){var r=t.range={};for(k=0;k<U.length;k++){var n=U[k],a=n._id.charAt(0);r[n._id]=[n.p2d(e[a+"min"]),n.p2d(e[a+"max"])].sort(tt)}}:function(t,e,r){var n=t.lassoPoints={};for(k=0;k<U.length;k++){var a=U[k];n[a._id]=r.filtered.map(K(a))}},a.moveFn=function(t,e){R=Math.max(0,Math.min(B,t+I)),F=Math.max(0,Math.min(H,e+N));var r=Math.abs(R-I),i=Math.abs(F-N);if("select"===l){var o=S.selectdirection;"h"===(o="any"===S.selectdirection?i<Math.min(.6*r,p)?"h":r<Math.min(.6*i,p)?"v":"d":S.selectdirection)?((w=[[I,0],[I,H],[R,H],[R,0]]).xmin=Math.min(I,R),w.xmax=Math.max(I,R),w.ymin=Math.min(0,H),w.ymax=Math.max(0,H),W.attr("d","M"+w.xmin+","+(N-p)+"h-4v"+2*p+"h4ZM"+(w.xmax-1)+","+(N-p)+"h4v"+2*p+"h-4Z")):"v"===o?((w=[[0,N],[0,F],[B,F],[B,N]]).xmin=Math.min(0,B),w.xmax=Math.max(0,B),w.ymin=Math.min(N,F),w.ymax=Math.max(N,F),W.attr("d","M"+(I-p)+","+w.ymin+"v-4h"+2*p+"v4ZM"+(I-p)+","+(w.ymax-1)+"v4h"+2*p+"v-4Z")):"d"===o&&((w=[[I,N],[I,F],[R,F],[R,N]]).xmin=Math.min(I,R),w.xmax=Math.max(I,R),w.ymin=Math.min(N,F),w.ymax=Math.max(N,F),W.attr("d","M0,0Z"))}else"lasso"===l&&(c.addPt([R,F]),w=c.filtered);a.polygons&&a.polygons.length?(_=function(t,e,r){return r?n.difference({regions:t,inverted:!1},{regions:[e],inverted:!1}).regions:n.union({regions:t,inverted:!1},{regions:[e],inverted:!1}).regions}(a.mergedPolygons,w,G),w.subtract=G,f=y(a.polygons.concat([w]))):(_=[w],f=g(w));var u=[];for(k=0;k<_.length;k++){var h=_[k];u.push(h.join("L")+"L"+h[0])}X.attr("d","M"+u.join("M")+"Z"),s.throttle(J,d.SELECTDELAY,function(){$=[];var t,e,r=[];for(k=0;k<Q.length;k++)if(e=(A=Q[k])._module.selectPoints(A,f),r.push(e),t=x(e,A),$.length)for(var n=0;n<t.length;n++)$.push(t[n]);else $=t;m(C,Q,L={points:$}),Z(L,w,c),a.gd.emit("plotly_selecting",L)})},a.clickFn=function(t,e){W.remove(),s.done(J).then(function(){if(s.clear(J),2===t){for(X.remove(),k=0;k<Q.length;k++)(A=Q[k])._module.selectPoints(A,!1);m(C,Q),C.emit("plotly_deselect",null)}else C.emit("plotly_selected",void 0);o.click(C,e)})},a.doneFn=function(){W.remove(),s.done(J).then(function(){s.clear(J),a.gd.emit("plotly_selected",L),w&&a.polygons&&(w.subtract=G,a.polygons.push(w),a.mergedPolygons.length=0,[].push.apply(a.mergedPolygons,_))})}},clearSelect:b}},{"../../components/color":45,"../../components/fx":87,"../../components/fx/helpers":84,"../../lib/polygon":175,"../../lib/throttle":185,"../../registry":247,"../sort_modules":246,"./axis_ids":210,"./constants":212,polybooljs:19}],225:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../lib"),o=i.cleanNumber,l=i.ms2DateTime,s=i.dateTime2ms,c=i.ensureNumber,u=t("../../constants/numerical"),f=u.FP_SAFE,d=u.BADNUM,p=t("./constants"),h=t("./axis_ids");function g(t){return Math.pow(10,t)}e.exports=function(t,e){e=e||{};var r=(t._id||"x").charAt(0),u=10;function y(e,r){if(e>0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],a=t.range[1];return.5*(n+a-3*u*Math.abs(n-a))}return d}function v(e,r,n){var i=s(e,n||t.calendar);if(i===d){if(!a(e))return d;i=s(new Date(+e))}return i}function m(e,r,n){return l(e,r,n||t.calendar)}function x(e){return t._categories[Math.round(e)]}function b(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(a(e))return+e}function _(e){return a(e)?n.round(t._b+t._m*e,2):d}function w(e){return(e-t._b)/t._m}t.c2l="log"===t.type?y:c,t.l2c="log"===t.type?g:c,t.l2p=_,t.p2l=w,t.c2p="log"===t.type?function(t,e){return _(y(t,e))}:_,t.p2c="log"===t.type?function(t){return g(w(t))}:w,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=o,t.c2d=t.c2r=t.l2d=t.l2r=c,t.d2p=t.r2p=function(e){return t.l2p(o(e))},t.p2d=t.p2r=w,t.cleanPos=c):"log"===t.type?(t.d2r=t.d2l=function(t,e){return y(o(t),e)},t.r2d=t.r2c=function(t){return g(o(t))},t.d2c=t.r2l=o,t.c2d=t.l2r=c,t.c2r=y,t.l2d=g,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return g(w(t))},t.r2p=function(e){return t.l2p(o(e))},t.p2r=w,t.cleanPos=c):"date"===t.type?(t.d2r=t.r2d=i.identity,t.d2c=t.r2c=t.d2l=t.r2l=v,t.c2d=t.c2r=t.l2d=t.l2r=m,t.d2p=t.r2p=function(e,r,n){return t.l2p(v(e,0,n))},t.p2d=t.p2r=function(t,e,r){return m(w(t),e,r)},t.cleanPos=function(e){return i.cleanDate(e,d,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!=e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return d},t.r2d=t.c2d=t.l2d=x,t.d2r=t.d2l_noadd=b,t.r2c=function(e){var r=b(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=c,t.r2l=b,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return x(w(t))},t.r2p=t.d2p,t.p2r=w,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:c(t)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var o,l,s=i.nestedProperty(t,e).get();if(l=(l="date"===t.type?i.dfltRange(t.calendar):"y"===r?p.DFLTRANGEY:n.dfltRange||p.DFLTRANGEX).slice(),s&&2===s.length)for("date"===t.type&&(s[0]=i.cleanDate(s[0],d,t.calendar),s[1]=i.cleanDate(s[1],d,t.calendar)),o=0;o<2;o++)if("date"===t.type){if(!i.isDateTime(s[o],t.calendar)){t[e]=l;break}if(t.r2l(s[0])===t.r2l(s[1])){var c=i.constrain(t.r2l(s[0]),i.MIN_MS+1e3,i.MAX_MS-1e3);s[0]=t.l2r(c-1e3),s[1]=t.l2r(c+1e3);break}}else{if(!a(s[o])){if(!a(s[1-o])){t[e]=l;break}s[o]=s[1-o]*(o?10:.1)}if(s[o]<-f?s[o]=-f:s[o]>f&&(s[o]=f),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else i.nestedProperty(t,e).set(l)},t.setScale=function(n){var a=e._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=h.getFromId({_fullLayout:e},t.overlaying);t.domain=i.domain}var o=n&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===r?(t._offset=a.t+(1-t.domain[1])*a.h,t._length=a.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=a.l+t.domain[0]*a.w,t._length=a.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw e._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,a,o,l,s=t.type,c="date"===s&&e[r+"calendar"];if(r in e){if(n=e[r],l=e._length||n.length,i.isTypedArray(n)&&("linear"===s||"log"===s)){if(l===n.length)return n;if(n.subarray)return n.subarray(0,l)}for(a=new Array(l),o=0;o<l;o++)a[o]=t.d2c(n[o],0,c)}else{var u=r+"0"in e?t.d2c(e[r+"0"],0,c):0,f=e["d"+r]?Number(e["d"+r]):1;for(n=e[{x:"y",y:"x"}[r]],l=e._length||n.length,a=new Array(l),o=0;o<l;o++)a[o]=u+o*f}return a},t.isValidRange=function(e){return Array.isArray(e)&&2===e.length&&a(t.r2l(e[0]))&&a(t.r2l(e[1]))},t.isPtWithinRange=function(e,n){var a=t.c2l(e[r],null,n),i=t.r2l(t.range[0]),o=t.r2l(t.range[1]);return i<o?i<=a&&a<=o:o<=a&&a<=i},t.clearCalc=function(){t._min=[],t._max=[],t._categories=(t._initialCategories||[]).slice(),t._categoriesMap={};for(var e=0;e<t._categories.length;e++)t._categoriesMap[t._categories[e]]=e};var k=e._d3locale;"date"===t.type&&(t._dateFormat=k?k.timeFormat.utc:n.time.format.utc,t._extraFormat=e._extraFormat),t._separators=e.separators,t._numFormat=k?k.numberFormat:n.format,delete t._minDtick,delete t._forceTick0}},{"../../constants/numerical":145,"../../lib":163,"./axis_ids":210,"./constants":212,d3:10,"fast-isnumeric":13}],226:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes"),i=t("../array_container_defaults");function o(t,e){function r(r,i){return n.coerce(t,e,a.tickformatstops,r,i)}r("enabled")&&(r("dtickrange"),r("value"))}e.exports=function(t,e,r,l,s){var c=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",c),r("ticksuffix",s.tickSuffixDflt)&&r("showticksuffix",c),r("showticklabels")){var u=s.font||{},f=e.color!==a.color.dflt?e.color:u.color;if(n.coerceFont(r,"tickfont",{family:u.family,size:u.size,color:f}),r("tickangle"),"category"!==l){var d=r("tickformat"),p=t.tickformatstops;Array.isArray(p)&&p.length&&i(t,e,{name:"tickformatstops",inclusionAttr:"enabled",handleItemDefaults:o}),d||"date"===l||(r("showexponent",c),r("exponentformat"),r("separatethousands"))}}}},{"../../lib":163,"../array_container_defaults":203,"./layout_attributes":219}],227:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e,r,i){var o=n.coerce2(t,e,a,"ticklen"),l=n.coerce2(t,e,a,"tickwidth"),s=n.coerce2(t,e,a,"tickcolor",e.color);r("ticks",i.outerTicks||o||l||s?"outside":"")||(delete e.ticklen,delete e.tickwidth,delete e.tickcolor)}},{"../../lib":163,"./layout_attributes":219}],228:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../constants/numerical").ONEDAY;e.exports=function(t,e,r,o){var l;"array"!==t.tickmode||"log"!==o&&"date"!==o?l=r("tickmode",Array.isArray(t.tickvals)?"array":t.dtick?"linear":"auto"):l=e.tickmode="auto";if("auto"===l)r("nticks");else if("linear"===l){var s="date"===o?i:1,c=r("dtick",s);if(n(c))e.dtick=c>0?Number(c):s;else if("string"!=typeof c)e.dtick=s;else{var u=c.charAt(0),f=c.substr(1);((f=n(f)?Number(f):0)<=0||!("date"===o&&"M"===u&&f===Math.round(f)||"log"===o&&"L"===u||"log"===o&&"D"===u&&(1===f||2===f)))&&(e.dtick=s)}var d="date"===o?a.dateTick0(e.calendar):0,p=r("tick0",d);"date"===o?e.tick0=a.cleanDate(p,d):n(p)&&"D1"!==c&&"D2"!==c?e.tick0=Number(p):e.tick0=d}else{void 0===r("tickvals")?e.tickmode="auto":r("ticktext")}}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],229:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../components/drawing"),o=t("./axes"),l=t("./constants").attrRegex;e.exports=function(t,e,r,s){var c=t._fullLayout,u=[];var f,d,p,h,g=function(t){var e,r,n,a,i={};for(e in t)if((r=e.split("."))[0].match(l)){var o=e.charAt(0),s=r[0];if(n=c[s],a={},Array.isArray(t[e])?a.to=t[e].slice(0):Array.isArray(t[e].range)&&(a.to=t[e].range.slice(0)),!a.to)continue;a.axisName=s,a.length=n._length,u.push(o),i[o]=a}return i}(e),y=Object.keys(g),v=function(t,e,r){var n,a,i,o=t._plots,l=[];for(n in o){var s=o[n];if(-1===l.indexOf(s)){var c=s.xaxis._id,u=s.yaxis._id,f=s.xaxis.range,d=s.yaxis.range;s.xaxis._r=s.xaxis.range.slice(),s.yaxis._r=s.yaxis.range.slice(),a=r[c]?r[c].to:f,i=r[u]?r[u].to:d,f[0]===a[0]&&f[1]===a[1]&&d[0]===i[0]&&d[1]===i[1]||-1===e.indexOf(c)&&-1===e.indexOf(u)||l.push(s)}}return l}(c,y,g);if(!v.length)return function(){function e(e,r,n){for(var a=0;a<e.length;a++)if(r(t,a),n)return}e(c.annotations||[],a.getComponentMethod("annotations","drawOne")),e(c.shapes||[],a.getComponentMethod("shapes","drawOne")),e(c.images||[],a.getComponentMethod("images","draw"),!0)}(),!1;function m(t){var e=t.xaxis,r=t.yaxis;c._defs.select("#"+t.clipId+"> rect").call(i.setTranslate,0,0).call(i.setScale,1,1),t.plot.call(i.setTranslate,e._offset,r._offset).call(i.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(i.setPointGroupScale,1,1),n.selectAll(".textpoint").call(i.setTextPointsScale,1,1),n.call(i.hideOutsideRangePoints,t)}function x(e,r){var n,l,s,u=g[e.xaxis._id],f=g[e.yaxis._id],d=[];if(u){l=(n=t._fullLayout[u.axisName])._r,s=u.to,d[0]=(l[0]*(1-r)+r*s[0]-l[0])/(l[1]-l[0])*e.xaxis._length;var p=l[1]-l[0],h=s[1]-s[0];n.range[0]=l[0]*(1-r)+r*s[0],n.range[1]=l[1]*(1-r)+r*s[1],d[2]=e.xaxis._length*(1-r+r*h/p)}else d[0]=0,d[2]=e.xaxis._length;if(f){l=(n=t._fullLayout[f.axisName])._r,s=f.to,d[1]=(l[1]*(1-r)+r*s[1]-l[1])/(l[0]-l[1])*e.yaxis._length;var y=l[1]-l[0],v=s[1]-s[0];n.range[0]=l[0]*(1-r)+r*s[0],n.range[1]=l[1]*(1-r)+r*s[1],d[3]=e.yaxis._length*(1-r+r*v/y)}else d[1]=0,d[3]=e.yaxis._length;!function(e,r){var n,i=[];for(i=[e._id,r._id],n=0;n<i.length;n++)o.doTicksSingle(t,i[n],!0);function l(e,r,a){for(n=0;n<e.length;n++){var o=e[n];if(-1===i.indexOf(o.xref)&&-1===i.indexOf(o.yref)||r(t,n),a)return}}l(c.annotations||[],a.getComponentMethod("annotations","drawOne")),l(c.shapes||[],a.getComponentMethod("shapes","drawOne")),l(c.images||[],a.getComponentMethod("images","draw"),!0)}(e.xaxis,e.yaxis);var m=e.xaxis,x=e.yaxis,b=!!u,_=!!f,w=b?m._length/d[2]:1,k=_?x._length/d[3]:1,M=b?d[0]:0,T=_?d[1]:0,A=b?d[0]/d[2]*m._length:0,L=_?d[1]/d[3]*x._length:0,C=m._offset-A,S=x._offset-L;e.clipRect.call(i.setTranslate,M,T).call(i.setScale,1/w,1/k),e.plot.call(i.setTranslate,C,S).call(i.setScale,w,k),i.setPointGroupScale(e.zoomScalePts,1/w,1/k),i.setTextPointsScale(e.zoomScaleTxt,1/w,1/k)}s&&(f=s());var b=n.ease(r.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(h),h=null,function(){for(var e={},r=0;r<y.length;r++){var n=t._fullLayout[y[r]+"axis"];e[n._name+".range[0]"]=n.range[0],e[n._name+".range[1]"]=n.range[1],n.range=n._r.slice()}return a.call("relayout",t,e).then(function(){for(var t=0;t<v.length;t++)m(v[t])})}()}),d=Date.now(),h=window.requestAnimationFrame(function e(){p=Date.now();for(var n=Math.min(1,(p-d)/r.duration),i=b(n),o=0;o<v.length;o++)x(v[o],i);p-d>r.duration?(function(){for(var e={},r=0;r<y.length;r++){var n=t._fullLayout[g[y[r]].axisName],i=g[y[r]].to;e[n._name+".range[0]"]=i[0],e[n._name+".range[1]"]=i[1],n.range=i.slice()}f&&f(),a.call("relayout",t,e).then(function(){for(var t=0;t<v.length;t++)m(v[t])})}(),h=window.cancelAnimationFrame(e)):h=window.requestAnimationFrame(e)}),Promise.resolve()}},{"../../components/drawing":70,"../../registry":247,"./axes":207,"./constants":212,d3:10}],230:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./axis_autotype"),i=t("./axis_ids").name2id;function o(t){return{v:"x",h:"y"}[t.orientation||"v"]}function l(t,e){var r=o(t),a=n.traceIs(t,"box-violin"),i=n.traceIs(t._fullInput||{},"candlestick");return a&&!i&&e===r&&void 0===t[r]&&void 0===t[r+"0"]}e.exports=function(t,e,r,s,c){c&&(e._name=c,e._id=i(c)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,i=r.charAt(0);-1!==r.indexOf("scene")&&(r=i);var s=function(t,e,r){for(var n=0;n<t.length;n++){var a=t[n];if("splom"===a.type&&a._length>0&&a["_"+r+"axes"][e])return a;if((a[r+"axis"]||r)===e){if(l(a,r))return a;if((a[r]||[]).length||a[r+"0"])return a}}}(e,r,i);if(!s)return;if("histogram"===s.type&&i==={v:"y",h:"x"}[s.orientation||"v"])return void(t.type="linear");var c,u=i+"calendar",f=s[u];if(l(s,i)){var d=o(s),p=[];for(c=0;c<e.length;c++){var h=e[c];n.traceIs(h,"box-violin")&&(h[i+"axis"]||i)===r&&(void 0!==h[d]?p.push(h[d][0]):void 0!==h.name?p.push(h.name):p.push("text"),h[u]!==f&&(f=void 0))}t.type=a(p,f)}else if("splom"===s.type){var g=s.dimensions;for(c=0;c<g.length;c++){var y=g[c];if(y.visible){t.type=a(y.values,f);break}}}else t.type=a(s[i]||[s[i+"0"]],f)}(e,s),"-"===e.type?e.type="linear":t.type=e.type)}},{"../../registry":247,"./axis_autotype":208,"./axis_ids":210}],231:[function(t,e,r){"use strict";var n=t("../registry"),a=t("../lib");function i(t,e,r){var n,i,o,l=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=a.nestedProperty(n,e.prop).get(),(o=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&o[e.prop]!==i&&(l=!0),o[e.prop]=i,{changed:l,value:i}}function o(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!a.isPlainObject(n))return r;i=n}return s(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function l(t,e){var r,n,i,o,l=[];if(n=e[0],i=e[1],r=e[2],o={},"string"==typeof n)o[n]=i;else{if(!a.isPlainObject(n))return l;o=n,void 0===r&&(r=i)}return void 0===r&&(r=null),s(o,function(e,n,a){var i;if(Array.isArray(a)){var o=Math.min(a.length,t.data.length);r&&(o=Math.min(o,r.length)),i=[];for(var s=0;s<o;s++)i[s]=r?r[s]:s}else i=r?r.slice(0):null;if(null===i)Array.isArray(a)&&(a=a[0]);else if(Array.isArray(i)){if(!Array.isArray(a)){var c=a;a=[];for(var u=0;u<i.length;u++)a[u]=c}a.length=Math.min(i.length,a.length)}l.push({type:"data",prop:e,traces:i,value:a})},"",0),l}function s(t,e,r,n){Object.keys(t).forEach(function(i){var o=t[i];if("_"!==i[0]){var l=r+(n>0?".":"")+i;a.isPlainObject(o)?s(o,e,l,n+1):e(l,i,o)}})}r.manageCommandObserver=function(t,e,n,o){var l={},s=!0;e&&e._commandObserver&&(l=e._commandObserver),l.cache||(l.cache={}),l.lookupTable={};var c=r.hasSimpleAPICommandBindings(t,n,l.lookupTable);if(e&&e._commandObserver){if(c)return l;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,l}if(c){i(t,c,l.cache),l.check=function(){if(s){var e=i(t,c,l.cache);return e.changed&&o&&void 0!==l.lookupTable[e.value]&&(l.disable(),Promise.resolve(o({value:e.value,type:c.type,prop:c.prop,traces:c.traces,index:l.lookupTable[e.value]})).then(l.enable,l.enable)),e.changed}};for(var u=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],f=0;f<u.length;f++)t._internalOn(u[f],l.check);l.remove=function(){for(var e=0;e<u.length;e++)t._removeInternalListener(u[e],l.check)}}else a.log("Unable to automatically bind plot updates to API command"),l.lookupTable={},l.remove=function(){};return l.disable=function(){s=!1},l.enable=function(){s=!0},e&&(e._commandObserver=l),l},r.hasSimpleAPICommandBindings=function(t,e,n){var a,i,o=e.length;for(a=0;a<o;a++){var l,s=e[a],c=s.method,u=s.args;if(Array.isArray(u)||(u=[]),!c)return!1;var f=r.computeAPICommandBindings(t,c,u);if(1!==f.length)return!1;if(i){if((l=f[0]).type!==i.type)return!1;if(l.prop!==i.prop)return!1;if(Array.isArray(i.traces)){if(!Array.isArray(l.traces))return!1;l.traces.sort();for(var d=0;d<i.traces.length;d++)if(i.traces[d]!==l.traces[d])return!1}else if(l.prop!==i.prop)return!1}else i=f[0],Array.isArray(i.traces)&&i.traces.sort();var p=(l=f[0]).value;if(Array.isArray(p)){if(1!==p.length)return!1;p=p[0]}n&&(n[p]=a)}return i},r.executeAPICommand=function(t,e,r){if("skip"===e)return Promise.resolve();var i=n.apiMethodRegistry[e],o=[t];Array.isArray(r)||(r=[]);for(var l=0;l<r.length;l++)o.push(r[l]);return i.apply(null,o).catch(function(t){return a.warn("API call to Plotly."+e+" rejected.",t),Promise.reject(t)})},r.computeAPICommandBindings=function(t,e,r){var n;switch(Array.isArray(r)||(r=[]),e){case"restyle":n=l(t,r);break;case"relayout":n=o(t,r);break;case"update":n=l(t,[r[0],r[2]]).concat(o(t,[r[1]]));break;case"animate":n=function(t,e){return Array.isArray(e[0])&&1===e[0].length&&-1!==["string","number"].indexOf(typeof e[0][0])?[{type:"layout",prop:"_currentFrame",value:e[0][0].toString()}]:[]}(0,r);break;default:n=[]}return n}},{"../lib":163,"../registry":247}],232:[function(t,e,r){"use strict";var n=t("../lib/extend").extendFlat;r.attributes=function(t,e){e=e||{};var r={valType:"info_array",editType:(t=t||{}).editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},a=(t.name&&t.name,t.trace,e.description&&e.description,{x:n({},r,{}),y:n({},r,{}),editType:t.editType});return t.noGridCell||(a.row={valType:"integer",min:0,dflt:0,editType:t.editType},a.column={valType:"integer",min:0,dflt:0,editType:t.editType}),a},r.defaults=function(t,e,r,n){var a=n&&n.x||[0,1],i=n&&n.y||[0,1],o=e.grid;if(o){var l=r("domain.column");void 0!==l&&(l<o.columns?a=o._domains.x[l]:delete t.domain.column);var s=r("domain.row");void 0!==s&&(s<o.rows?i=o._domains.y[s]:delete t.domain.row)}r("domain.x",a),r("domain.y",i)}},{"../lib/extend":157}],233:[function(t,e,r){"use strict";e.exports=function(t){var e=t.editType,r=t.colorEditType;void 0===r&&(r=e);var n={family:{valType:"string",noBlank:!0,strict:!0,editType:e},size:{valType:"number",min:1,editType:e},color:{valType:"color",editType:r},editType:e};return t.arrayOk&&(n.family.arrayOk=!0,n.size.arrayOk=!0,n.color.arrayOk=!0),n}},{}],234:[function(t,e,r){"use strict";e.exports={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}}},{}],235:[function(t,e,r){"use strict";var n=t("../registry"),a=t("./cartesian/constants").SUBPLOT_PATTERN;r.getSubplotCalcData=function(t,e,r){var a=n.subplotsRegistry[e];if(!a)return[];for(var i=a.attr,o=[],l=0;l<t.length;l++){var s=t[l];s[0].trace[i]===r&&o.push(s)}return o},r.getModuleCalcData=function(t,e){var r,a=[],i=[];if(!(r="string"==typeof e?n.getModule(e).plot:"function"==typeof e?e:e.plot))return[a,t];for(var o=0;o<t.length;o++){var l=t[o],s=l[0].trace;!0===s.visible&&(s._module.plot===r?a.push(l):i.push(l))}return[a,i]},r.getSubplotData=function(t,e,r){if(!n.subplotsRegistry[e])return[];var i,o,l,s=n.subplotsRegistry[e].attr,c=[];if("gl2d"===e){var u=r.match(a);o="x"+u[1],l="y"+u[2]}for(var f=0;f<t.length;f++)i=t[f],"gl2d"===e&&n.traceIs(i,"gl2d")?i[s[0]]===o&&i[s[1]]===l&&c.push(i):i[s]===r&&c.push(i);return c},r.getUidsFromCalcData=function(t){for(var e={},r=0;r<t.length;r++){e[t[r][0].trace.uid]=1}return e}},{"../registry":247,"./cartesian/constants":212}],236:[function(t,e,r){"use strict";function n(t,e){var r,n,a=[0,0,0,0];for(r=0;r<4;++r)for(n=0;n<4;++n)a[n]+=t[4*r+n]*e[r];return a}e.exports=function(t,e){return n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])))}},{}],237:[function(t,e,r){"use strict";var n=t("./font_attributes"),a=t("../components/color/attributes"),i=n({editType:"calc"});i.family.dflt='"Open Sans", verdana, arial, sans-serif',i.size.dflt=12,i.color.dflt=a.defaultLine,e.exports={font:i,title:{valType:"string",editType:"layoutstyle"},titlefont:n({editType:"layoutstyle"}),autosize:{valType:"boolean",dflt:!1,editType:"none"},width:{valType:"number",min:10,dflt:700,editType:"plot"},height:{valType:"number",min:10,dflt:450,editType:"plot"},margin:{l:{valType:"number",min:0,dflt:80,editType:"plot"},r:{valType:"number",min:0,dflt:80,editType:"plot"},t:{valType:"number",min:0,dflt:100,editType:"plot"},b:{valType:"number",min:0,dflt:80,editType:"plot"},pad:{valType:"number",min:0,dflt:0,editType:"plot"},autoexpand:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},paper_bgcolor:{valType:"color",dflt:a.background,editType:"plot"},plot_bgcolor:{valType:"color",dflt:a.background,editType:"layoutstyle"},separators:{valType:"string",editType:"plot"},hidesources:{valType:"boolean",dflt:!1,editType:"plot"},showlegend:{valType:"boolean",editType:"legend"},colorway:{valType:"colorlist",dflt:a.defaults,editType:"calc"},datarevision:{valType:"any",editType:"calc"},template:{valType:"any",editType:"calc"}}},{"../components/color/attributes":44,"./font_attributes":233}],238:[function(t,e,r){"use strict";e.exports={t:{valType:"number",dflt:0,editType:"arraydraw"},r:{valType:"number",dflt:0,editType:"arraydraw"},b:{valType:"number",dflt:0,editType:"arraydraw"},l:{valType:"number",dflt:0,editType:"arraydraw"},editType:"arraydraw"}},{}],239:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../registry"),o=t("../plot_api/plot_schema"),l=t("../plot_api/plot_template"),s=t("../lib"),c=t("../components/color"),u=t("../constants/numerical").BADNUM,f=t("../plots/cartesian/axis_ids"),d=t("./sort_modules").sortBasePlotModules,p=t("./animation_attributes"),h=t("./frame_attributes"),g=s.relinkPrivateKeys,y=s._,v=e.exports={};s.extendFlat(v,i),v.attributes=t("./attributes"),v.attributes.type.values=v.allTypes,v.fontAttrs=t("./font_attributes"),v.layoutAttributes=t("./layout_attributes"),v.fontWeight="normal";var m=v.transformsRegistry,x=t("./command");v.executeAPICommand=x.executeAPICommand,v.computeAPICommandBindings=x.computeAPICommandBindings,v.manageCommandObserver=x.manageCommandObserver,v.hasSimpleAPICommandBindings=x.hasSimpleAPICommandBindings,v.redrawText=function(t){if(!((t=s.getGraphDiv(t)).data&&t.data[0]&&t.data[0].r))return new Promise(function(e){setTimeout(function(){i.getComponentMethod("annotations","draw")(t),i.getComponentMethod("legend","draw")(t),(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()}),e(v.previousPromises(t))},300)})},v.resize=function(t){return t=s.getGraphDiv(t),new Promise(function(e,r){function n(t){var e=window.getComputedStyle(t).display;return!e||"none"===e}t&&!n(t)||r(new Error("Resize must be passed a displayed plot div element.")),t._redrawTimer&&clearTimeout(t._redrawTimer),t._redrawTimer=setTimeout(function(){if(!t.layout||t.layout.width&&t.layout.height||n(t))e(t);else{delete t.layout.width,delete t.layout.height;var r=t.changed;t.autoplay=!0,i.call("relayout",t,{autosize:!0}).then(function(){t.changed=r,e(t)})}},100)})},v.previousPromises=function(t){if((t._promises||[]).length)return Promise.all(t._promises).then(function(){t._promises=[]})},v.addLinks=function(t){if(t._context.showLink||t._context.showSources){var e=t._fullLayout,r=s.ensureSingle(e._paper,"text","js-plot-link-container",function(t){t.style({"font-family":'"Open Sans", Arial, sans-serif',"font-size":"12px",fill:c.defaultLine,"pointer-events":"all"}).each(function(){var t=n.select(this);t.append("tspan").classed("js-link-to-tool",!0),t.append("tspan").classed("js-link-spacer",!0),t.append("tspan").classed("js-sourcelinks",!0)})}),a=r.node(),i={y:e._paper.attr("height")-9};document.body.contains(a)&&a.getComputedTextLength()>=e.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=e._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),u=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){v.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),a=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+a})}}(t,o),l.text(o.text()&&u.text()?" - ":"")}},v.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=(window.PLOTLYENV||{}).BASE_URL||t._context.plotlyServerURL,r=n.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=v.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var b,_=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],w=["year","month","dayMonth","dayMonthYear"];function k(t,e){var r=t._context.locale,n=!1,a={};function o(t){for(var r=!0,i=0;i<e.length;i++){var o=e[i];a[o]||(t[o]?a[o]=t[o]:r=!1)}r&&(n=!0)}for(var l=0;l<2;l++){for(var s=t._context.locales,c=0;c<2;c++){var u=(s[r]||{}).format;if(u&&(o(u),n))break;s=i.localeRegistry}var f=r.split("-")[0];if(n||f===r)break;r=f}return n||o(i.localeRegistry.en.format),a}function M(t,e,r,n){for(var a=t.transforms,i=[t],o=0;o<a.length;o++){var l=a[o],s=m[l.type];s&&s.transform&&(i=s.transform(i,{transform:l,fullTrace:t,fullData:e,layout:r,fullLayout:n,transformIndex:o}))}return i}function T(t){t._pushmargin||(t._pushmargin={}),t._pushmarginIds||(t._pushmarginIds={})}function A(t){for(var e=0;e<t.length;e++)t[e].clearCalc()}v.supplyDefaults=function(t,e){var r=e&&e.skipUpdateCalc,a=t._fullLayout||{};if(a._skipDefaults)delete a._skipDefaults;else{var o,l=t._fullLayout={},c=t.layout||{},u=t._fullData||[],p=t._fullData=[],h=t.data||[],m=t.calcdata||[],x=t._context||{};t._transitionData||v.createTransitionData(t),l._dfltTitle={plot:y(t,"Click to enter Plot title"),x:y(t,"Click to enter X axis title"),y:y(t,"Click to enter Y axis title"),colorbar:y(t,"Click to enter Colorscale title"),annotation:y(t,"new text")},l._traceWord=y(t,"trace");var M=k(t,_);if(l._mapboxAccessToken=x.mapboxAccessToken,a._initialAutoSizeIsDone){var T=a.width,A=a.height;v.supplyLayoutGlobalDefaults(c,l,M),c.width||(l.width=T),c.height||(l.height=A),v.sanitizeMargins(l)}else{v.supplyLayoutGlobalDefaults(c,l,M);var L=!c.width||!c.height,C=l.autosize,S=x.autosizable;L&&(C||S)?v.plotAutoSize(t,c,l):L&&v.sanitizeMargins(l),!C&&L&&(c.width=l.width,c.height=l.height)}l._d3locale=function(t,e){return t.decimal=e.charAt(0),t.thousands=e.charAt(1),n.locale(t)}(M,l.separators),l._extraFormat=k(t,w),l._initialAutoSizeIsDone=!0,l._dataLength=h.length,l._modules=[],l._basePlotModules=[];var O=l._subplots=function(){var t,e,r={};if(!b){b=[];var n=i.subplotsRegistry;for(var a in n){var o=n[a],l=o.attr;if(l&&(b.push(a),Array.isArray(l)))for(e=0;e<l.length;e++)s.pushUnique(b,l[e])}}for(t=0;t<b.length;t++)r[b[t]]=[];return r}(),P=l._splomAxes={x:{},y:{}},D=l._splomSubplots={};l._splomGridDflt={},l._requestRangeslider={},l._traceUids=function(t,e){var r,n,a=e.length,i=[];for(r=0;r<t.length;r++){var o=t[r]._fullInput;o!==n&&i.push(o),n=o}var l=i.length,c=new Array(a),u={};function f(t,e){c[e]=t,u[t]=1}function d(t,e){if(t&&"string"==typeof t&&!u[t])return f(t,e),!0}for(r=0;r<a;r++)d(e[r].uid,r)||r<l&&d(i[r].uid,r)||f(s.randstr(u),r);return c}(u,h),l._globalTransforms=(t._context||{}).globalTransforms,v.supplyDataDefaults(h,p,c,l);var z=Object.keys(P.x),E=Object.keys(P.y);if(z.length>1&&E.length>1){for(i.getComponentMethod("grid","sizeDefaults")(c,l),o=0;o<z.length;o++)s.pushUnique(O.xaxis,z[o]);for(o=0;o<E.length;o++)s.pushUnique(O.yaxis,E[o]);for(var I in D)s.pushUnique(O.cartesian,I)}l._has=v._hasPlotType.bind(l);var N=l._modules;for(o=0;o<N.length;o++){var R=N[o];R.cleanData&&R.cleanData(p)}if(u.length===p.length)for(o=0;o<p.length;o++)g(p[o],u[o]);v.supplyLayoutModuleDefaults(c,l,p,t._transitionData),l._hasOnlyLargeSploms=1===l._basePlotModules.length&&"splom"===l._basePlotModules[0].name&&z.length>15&&E.length>15&&0===l.shapes.length&&0===l.images.length,l._hasCartesian=l._has("cartesian"),l._hasGeo=l._has("geo"),l._hasGL3D=l._has("gl3d"),l._hasGL2D=l._has("gl2d"),l._hasTernary=l._has("ternary"),l._hasPie=l._has("pie"),v.linkSubplots(p,l,u,a),v.cleanPlot(p,l,u,a,m),g(l,a),v.doAutoMargin(t);var F=f.list(t);for(o=0;o<F.length;o++){F[o].setScale()}r||m.length!==p.length||v.supplyDefaultsUpdateCalc(m,p),l._basePlotModules.sort(d)}},v.supplyDefaultsUpdateCalc=function(t,e){for(var r=0;r<e.length;r++){var n=e[r],a=t[r][0];if(a&&a.trace){var i=a.trace;if(i._hasCalcTransform){var o,l,c,u=i._arrayAttrs;for(o=0;o<u.length;o++)l=u[o],c=s.nestedProperty(i,l).get().slice(),s.nestedProperty(n,l).set(c)}a.trace=n}}},v.createTransitionData=function(t){t._transitionData||(t._transitionData={}),t._transitionData._frames||(t._transitionData._frames=[]),t._transitionData._frameHash||(t._transitionData._frameHash={}),t._transitionData._counter||(t._transitionData._counter=0),t._transitionData._interruptCallbacks||(t._transitionData._interruptCallbacks=[])},v._hasPlotType=function(t){var e,r=this._basePlotModules||[];for(e=0;e<r.length;e++)if(r[e].name===t)return!0;var n=this._modules||[];for(e=0;e<n.length;e++){var a=n[e].name;if(a===t)return!0;var o=i.modules[a];if(o&&o.categories[t])return!0}return!1},v.cleanPlot=function(t,e,r,n,a){var i,o,l=n._basePlotModules||[];for(i=0;i<l.length;i++){var s=l[i];s.clean&&s.clean(t,e,r,n,a)}var c=n._has&&n._has("gl"),u=e._has&&e._has("gl");c&&!u&&void 0!==n._glcontainer&&(n._glcontainer.selectAll(".gl-canvas").remove(),n._glcontainer.selectAll(".no-webgl").remove(),n._glcanvas=null);var f=!!n._infolayer;t:for(i=0;i<r.length;i++){var d=r[i].uid;for(o=0;o<t.length;o++){if(d===t[o].uid)continue t}f&&n._infolayer.select(".cb"+d).remove()}n._zoomlayer&&n._zoomlayer.selectAll(".select-outline").remove()},v.linkSubplots=function(t,e,r,n){var a,i,o,l,s=n._plots||{},c=e._plots={},u=e._subplots,d={_fullData:t,_fullLayout:e},p=u.cartesian.concat(u.gl2d||[]);for(a=0;a<p.length;a++){var h,g=s[o=p[a]],y=f.getFromId(d,o,"x"),v=f.getFromId(d,o,"y");for(g?((h=c[o]=g).xaxis.layer!==y.layer&&(h.xlines.attr("d",null),h.xaxislayer.selectAll("*").remove()),h.yaxis.layer!==v.layer&&(h.ylines.attr("d",null),h.yaxislayer.selectAll("*").remove())):(h=c[o]={}).id=o,h.xaxis=y,h.yaxis=v,h._hasClipOnAxisFalse=!1,i=0;i<t.length;i++){var m=t[i];if(m.xaxis===h.xaxis._id&&m.yaxis===h.yaxis._id&&!1===m.cliponaxis){h._hasClipOnAxisFalse=!0;break}}}var x=f.list(d,null,!0);for(a=0;a<x.length;a++){var b=null;(l=x[a]).overlaying&&(b=f.getFromId(d,l.overlaying))&&b.overlaying&&(l.overlaying=!1,b=null),l._mainAxis=b||l,b&&(l.domain=b.domain.slice()),l._anchorAxis="free"===l.anchor?null:f.getFromId(d,l.anchor)}},v.clearExpandedTraceDefaultColors=function(t){var e,r,n;for(r=[],(e=t._module._colorAttrs)||(t._module._colorAttrs=e=[],o.crawl(t._module.attributes,function(t,n,a,i){r[i]=n,r.length=i+1,"color"===t.valType&&void 0===t.dflt&&e.push(r.join("."))})),n=0;n<e.length;n++){s.nestedProperty(t,"_input."+e[n]).get()||s.nestedProperty(t,e[n]).set(null)}},v.supplyDataDefaults=function(t,e,r,n){var a,o,c,u=n._modules,f=n._basePlotModules,d=0,p=0;function h(t){e.push(t);var r=t._module;r&&(!0===t.visible&&s.pushUnique(u,r),s.pushUnique(f,t._module.basePlotModule),d++,!1!==t._input.visible&&p++)}n._transformModules=[];var y={},m=[],x=(r.template||{}).data||{},b=l.traceTemplater(x);for(a=0;a<t.length;a++){if(c=t[a],(o=b.newTrace(c)).uid=n._traceUids[a],v.supplyTraceDefaults(c,o,p,n,a),o.uid=n._traceUids[a],o.index=a,o._input=c,o._expandedIndex=d,o.transforms&&o.transforms.length)for(var _=M(o,e,r,n),w=0;w<_.length;w++){var k=_[w],T={_template:o._template,type:o.type,uid:o.uid+w};v.supplyTraceDefaults(k,T,d,n,a),g(T,k),T.index=a,T._input=c,T._fullInput=o,T._expandedIndex=d,T._expandedInput=k,h(T)}else o._fullInput=o,o._expandedInput=o,h(o);i.traceIs(o,"carpetAxis")&&(y[o.carpet]=o),i.traceIs(o,"carpetDependent")&&m.push(a)}for(a=0;a<m.length;a++)if((o=e[m[a]]).visible){var A=y[o.carpet];o._carpet=A,A&&A.visible?(o.xaxis=A.xaxis,o.yaxis=A.yaxis):o.visible=!1}},v.supplyAnimationDefaults=function(t){var e;t=t||{};var r={};function n(e,n){return s.coerce(t||{},r,p,e,n)}if(n("mode"),n("direction"),n("fromcurrent"),Array.isArray(t.frame))for(r.frame=[],e=0;e<t.frame.length;e++)r.frame[e]=v.supplyAnimationFrameDefaults(t.frame[e]||{});else r.frame=v.supplyAnimationFrameDefaults(t.frame||{});if(Array.isArray(t.transition))for(r.transition=[],e=0;e<t.transition.length;e++)r.transition[e]=v.supplyAnimationTransitionDefaults(t.transition[e]||{});else r.transition=v.supplyAnimationTransitionDefaults(t.transition||{});return r},v.supplyAnimationFrameDefaults=function(t){var e={};function r(r,n){return s.coerce(t||{},e,p.frame,r,n)}return r("duration"),r("redraw"),e},v.supplyAnimationTransitionDefaults=function(t){var e={};function r(r,n){return s.coerce(t||{},e,p.transition,r,n)}return r("duration"),r("easing"),e},v.supplyFrameDefaults=function(t){var e={};function r(r,n){return s.coerce(t,e,h,r,n)}return r("group"),r("name"),r("traces"),r("baseframe"),r("data"),r("layout"),e},v.supplyTraceDefaults=function(t,e,r,n,a){var o,l=n.colorway||c.defaults,u=l[r%l.length];function f(r,n){return s.coerce(t,e,v.attributes,r,n)}var d=f("visible");f("type"),f("name",n._traceWord+" "+a);var p=v.getModule(e);if(e._module=p,p){var h=p.basePlotModule,g=h.attr,y=h.attributes;if(g&&y){var m=n._subplots,x="";if("gl2d"!==h.name||d){if(Array.isArray(g))for(o=0;o<g.length;o++){var b=g[o],_=s.coerce(t,e,y,b);m[b]&&s.pushUnique(m[b],_),x+=_}else x=s.coerce(t,e,y,g);m[h.name]&&s.pushUnique(m[h.name],x)}}}return d&&(f("customdata"),f("ids"),i.traceIs(e,"showLegend")&&(f("showlegend"),f("legendgroup")),i.getComponentMethod("fx","supplyDefaults")(t,e,u,n),p&&(p.supplyDefaults(t,e,u,n),s.coerceHoverinfo(t,e,n)),i.traceIs(e,"noOpacity")||f("opacity"),i.traceIs(e,"notLegendIsolatable")&&(e.visible=!!e.visible),p&&p.selectPoints&&f("selectedpoints"),v.supplyTransformDefaults(t,e,n)),e},v.supplyTransformDefaults=function(t,e,r){if(e._length||function(t){var e=t.transforms;if(Array.isArray(e)&&e.length)for(var r=0;r<e.length;r++){var n=m[e[r].type];if(n&&n.makesData)return!0}return!1}(t)){var n=r._globalTransforms||[],a=r._transformModules||[];if(Array.isArray(t.transforms)||0!==n.length)for(var i=t.transforms||[],o=n.concat(i),l=e.transforms=[],c=0;c<o.length;c++){var u,f=o[c],d=f.type,p=m[d],h=!(f._module&&f._module===p),g=p&&"function"==typeof p.transform;p||s.warn("Unrecognized transform type "+d+"."),p&&p.supplyDefaults&&(h||g)?((u=p.supplyDefaults(f,e,r,t)).type=d,u._module=p,s.pushUnique(a,p)):u=s.extendFlat({},f),l.push(u)}}},v.supplyLayoutGlobalDefaults=function(t,e,r){function n(r,n){return s.coerce(t,e,v.layoutAttributes,r,n)}var a=t.template;s.isPlainObject(a)&&(e.template=a,e._template=a.layout,e._dataTemplate=a.data);var o=s.coerceFont(n,"font");n("title",e._dfltTitle.plot),s.coerceFont(n,"titlefont",{family:o.family,size:Math.round(1.4*o.size),color:o.color}),n("autosize",!(t.width&&t.height)),n("width"),n("height"),n("margin.l"),n("margin.r"),n("margin.t"),n("margin.b"),n("margin.pad"),n("margin.autoexpand"),t.width&&t.height&&v.sanitizeMargins(e),i.getComponentMethod("grid","sizeDefaults")(t,e),n("paper_bgcolor"),n("separators",r.decimal+r.thousands),n("hidesources"),n("colorway"),n("datarevision"),i.getComponentMethod("calendars","handleDefaults")(t,e,"calendar"),i.getComponentMethod("fx","supplyLayoutGlobalDefaults")(t,e,n)},v.plotAutoSize=function(t,e,r){var n,i,o=t._context||{},l=o.frameMargins,c=s.isPlotDiv(t);if(c&&t.emit("plotly_autosize"),o.fillFrame)n=window.innerWidth,i=window.innerHeight,document.body.style.overflow="hidden";else if(a(l)&&l>0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),f=u.left+u.right,d=u.bottom+u.top,p=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};n=Math.round(p*(h.width-f)),i=Math.round(p*(h.height-d))}else{var g=c?window.getComputedStyle(t):{};n=parseFloat(g.width)||r.width,i=parseFloat(g.height)||r.height}var y=v.layoutAttributes.width.min,m=v.layoutAttributes.height.min;n<y&&(n=y),i<m&&(i=m);var x=!e.width&&Math.abs(r.width-n)>1,b=!e.height&&Math.abs(r.height-i)>1;(b||x)&&(x&&(r.width=n),b&&(r.height=i)),t._initialAutoSize||(t._initialAutoSize={width:n,height:i}),v.sanitizeMargins(r)},v.supplyLayoutModuleDefaults=function(t,e,r,n){var a,o,l,c=i.componentsRegistry,u=e._basePlotModules,f=i.subplotsRegistry.cartesian;for(a in c)(l=c[a]).includeBasePlot&&l.includeBasePlot(t,e);for(var d in u.length||u.push(f),e._has("cartesian")&&(i.getComponentMethod("grid","contentDefaults")(t,e),f.finalizeSubplots(t,e)),e._subplots)e._subplots[d].sort(s.subplotSort);for(o=0;o<u.length;o++)(l=u[o]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r);var p=e._modules;for(o=0;o<p.length;o++)(l=p[o]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r);var h=e._transformModules;for(o=0;o<h.length;o++)(l=h[o]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r,n);for(a in c)(l=c[a]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r)},v.purge=function(t){var e=t._fullLayout||{};void 0!==e._glcontainer&&(e._glcontainer.selectAll(".gl-canvas").remove(),e._glcontainer.remove(),e._glcanvas=null),void 0!==e._geocontainer&&e._geocontainer.remove(),e._modeBar&&e._modeBar.destroy(),t._transitionData&&(t._transitionData._interruptCallbacks&&(t._transitionData._interruptCallbacks.length=0),t._transitionData._animationRaf&&window.cancelAnimationFrame(t._transitionData._animationRaf)),s.clearThrottle(),delete t.data,delete t.layout,delete t._fullData,delete t._fullLayout,delete t.calcdata,delete t.framework,delete t.empty,delete t.fid,delete t.undoqueue,delete t.undonum,delete t.autoplay,delete t.changed,delete t._promises,delete t._redrawTimer,delete t.firstscatter,delete t._hmlumcount,delete t._hmpixcount,delete t._transitionData,delete t._transitioning,delete t._initialAutoSize,delete t._transitioningWithDuration,delete t._dragging,delete t._dragged,delete t._hoverdata,delete t._snapshotInProgress,delete t._editing,delete t._replotPending,delete t._mouseDownTime,delete t._legendMouseDownTime,t.removeAllListeners&&t.removeAllListeners()},v.style=function(t){var e,r=t._fullLayout._modules,n=[];for(e=0;e<r.length;e++){var a=r[e];a.style&&s.pushUnique(n,a.style)}for(e=0;e<n.length;e++)n[e](t)},v.sanitizeMargins=function(t){if(t&&t.margin){var e,r=t.width,n=t.height,a=t.margin,i=r-(a.l+a.r),o=n-(a.t+a.b);i<0&&(e=(r-1)/(a.l+a.r),a.l=Math.floor(e*a.l),a.r=Math.floor(e*a.r)),o<0&&(e=(n-1)/(a.t+a.b),a.t=Math.floor(e*a.t),a.b=Math.floor(e*a.b))}},v.clearAutoMarginIds=function(t){t._fullLayout._pushmarginIds={}},v.allowAutoMargin=function(t,e){t._fullLayout._pushmarginIds[e]=1},v.autoMargin=function(t,e,r){var n=t._fullLayout;T(n);var a=n._pushmargin,i=n._pushmarginIds;if(!1!==n.margin.autoexpand){if(r){var o=r.pad;if(void 0===o){var l=n.margin;o=Math.min(12,l.l,l.r,l.t,l.b)}r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0);var s=void 0!==r.xl?r.xl:r.x,c=void 0!==r.xr?r.xr:r.x,u=void 0!==r.yt?r.yt:r.y,f=void 0!==r.yb?r.yb:r.y;a[e]={l:{val:s,size:r.l+o},r:{val:c,size:r.r+o},b:{val:f,size:r.b+o},t:{val:u,size:r.t+o}},i[e]=1}else delete a[e],delete i[e];n._replotting||v.doAutoMargin(t)}},v.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),T(e);var r=e._size,n=JSON.stringify(r),o=Math.max(e.margin.l||0,0),l=Math.max(e.margin.r||0,0),s=Math.max(e.margin.t||0,0),c=Math.max(e.margin.b||0,0),u=e._pushmargin,f=e._pushmarginIds;if(!1!==e.margin.autoexpand){for(var d in u)f[d]||delete u[d];for(var p in u.base={l:{val:0,size:o},r:{val:1,size:l},t:{val:1,size:s},b:{val:0,size:c}},u){var h=u[p].l||{},g=u[p].b||{},y=h.val,v=h.size,m=g.val,x=g.size;for(var b in u){if(a(v)&&u[b].r){var _=u[b].r.val,w=u[b].r.size;if(_>y){var k=(v*_+(w-e.width)*y)/(_-y),M=(w*(1-y)+(v-e.width)*(1-_))/(_-y);k>=0&&M>=0&&k+M>o+l&&(o=k,l=M)}}if(a(x)&&u[b].t){var A=u[b].t.val,L=u[b].t.size;if(A>m){var C=(x*A+(L-e.height)*m)/(A-m),S=(L*(1-m)+(x-e.height)*(1-A))/(A-m);C>=0&&S>=0&&C+S>c+s&&(c=C,s=S)}}}}}if(r.l=Math.round(o),r.r=Math.round(l),r.t=Math.round(s),r.b=Math.round(c),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,!e._replotting&&"{}"!==n&&n!==JSON.stringify(e._size))return"_redrawFromAutoMarginCount"in e?e._redrawFromAutoMarginCount++:e._redrawFromAutoMarginCount=1,i.call("plot",t)},v.graphJson=function(t,e,r,n,a){(a&&e&&!t._fullData||a&&!e&&!t._fullLayout)&&v.supplyDefaults(t);var i=a?t._fullData:t.data,o=a?t._fullLayout:t.layout,l=(t._transitionData||{})._frames;function c(t){if("function"==typeof t)return null;if(s.isPlainObject(t)){var e,n,a={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!s.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;a[e]=c(t[e])}return a}return Array.isArray(t)?t.map(c):s.isJSDate(t)?s.ms2DateTimeLocal(+t):t}var u={data:(i||[]).map(function(t){var r=c(t);return e&&delete r.fit,r})};return e||(u.layout=c(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),l&&(u.frames=c(l)),"object"===n?u:JSON.stringify(u)},v.modifyFrames=function(t,e){var r,n,a,i=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r<e.length;r++)switch((n=e[r]).type){case"replace":a=n.value;var l=(i[n.index]||{}).name,s=a.name;i[n.index]=o[s]=a,s!==l&&(delete o[l],o[s]=a);break;case"insert":o[(a=n.value).name]=a,i.splice(n.index,0,a);break;case"delete":delete o[(a=i[n.index]).name],i.splice(n.index,1)}return Promise.resolve()},v.computeFrame=function(t,e){var r,n,a,i,o=t._transitionData._frameHash;if(!e)throw new Error("computeFrame must be given a string frame name");var l=o[e.toString()];if(!l)return!1;for(var s=[l],c=[l.name];l.baseframe&&(l=o[l.baseframe.toString()])&&-1===c.indexOf(l.name);)s.push(l),c.push(l.name);for(var u={};l=s.pop();)if(l.layout&&(u.layout=v.extendLayout(u.layout,l.layout)),l.data){if(u.data||(u.data=[]),!(n=l.traces))for(n=[],r=0;r<l.data.length;r++)n[r]=r;for(u.traces||(u.traces=[]),r=0;r<l.data.length;r++)null!=(a=n[r])&&(-1===(i=u.traces.indexOf(a))&&(i=u.data.length,u.traces[i]=a),u.data[i]=v.extendTrace(u.data[i],l.data[r]))}return u},v.recomputeFrameHash=function(t){for(var e=t._transitionData._frameHash={},r=t._transitionData._frames,n=0;n<r.length;n++){var a=r[n];a&&a.name&&(e[a.name]=a)}},v.extendObjectWithContainers=function(t,e,r){var n,a,i,o,l,c,u,f=s.extendDeepNoArrays({},e||{}),d=s.expandObjectPaths(f),p={};if(r&&r.length)for(i=0;i<r.length;i++)void 0===(a=(n=s.nestedProperty(d,r[i])).get())?s.nestedProperty(p,r[i]).set(null):(n.set(null),s.nestedProperty(p,r[i]).set(a));if(t=s.extendDeepNoArrays(t||{},d),r&&r.length)for(i=0;i<r.length;i++)if(c=s.nestedProperty(p,r[i]).get()){for(u=(l=s.nestedProperty(t,r[i])).get(),Array.isArray(u)||(u=[],l.set(u)),o=0;o<c.length;o++){var h=c[o];u[o]=null===h?null:v.extendObjectWithContainers(u[o],h)}l.set(u)}return t},v.dataArrayContainers=["transforms","dimensions"],v.layoutArrayContainers=i.layoutArrayContainers,v.extendTrace=function(t,e){return v.extendObjectWithContainers(t,e,v.dataArrayContainers)},v.extendLayout=function(t,e){return v.extendObjectWithContainers(t,e,v.layoutArrayContainers)},v.transition=function(t,e,r,n,a,o){var l,c,u=Array.isArray(e)?e.length:0,f=n.slice(0,u),d=[];var p=!1;for(l=0;l<f.length;l++){c=f[l];t._fullData[c]._module}var h=[v.previousPromises,function(){if(t._transitionData)return t._transitioning=!1,function(t){var e=Promise.resolve();if(!t)return e;for(;t.length;)e=e.then(t.shift());return e}(t._transitionData._interruptCallbacks)},function(){var n;for(n=0;n<f.length;n++){var a=f[n],o=t._fullData[a]._module;o&&(o.animatable&&d.push(a),t.data[f[n]]=v.extendTrace(t.data[f[n]],e[n]))}var l=s.expandObjectPaths(s.extendDeepNoArrays({},r)),c=/^[xy]axis[0-9]*$/;for(var u in l)c.test(u)&&delete l[u].range;return v.extendLayout(t.layout,l),delete t.calcdata,v.supplyDefaults(t),v.doCalcdata(t),v.doSetPositions(t),i.getComponentMethod("errorbars","calc")(t),Promise.resolve()},v.rehover,function(){return t.emit("plotly_transitioning",[]),new Promise(function(e){t._transitioning=!0,o.duration>0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){p=!0}),a.redraw&&t._transitionData._interruptCallbacks.push(function(){return i.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,l,c=0,u=0;function f(){return c++,function(){var r;u++,p||u!==c||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return i.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var h=t._fullLayout._basePlotModules,g=!1;if(r)for(l=0;l<h.length;l++)if(h[l].transitionAxes){var y=s.expandObjectPaths(r);g=h[l].transitionAxes(t,y,o,f)||g}for(g?((n=s.extendFlat({},o)).duration=0,d=null):n=o,l=0;l<h.length;l++)h[l].plot(t,d,n,f);setTimeout(f())})}],g=s.syncOrAsync(h,t);return g&&g.then||(g=Promise.resolve()),g.then(function(){return t})},v.doCalcdata=function(t,e){var r,n,a,l,s=f.list(t),c=t._fullData,d=t._fullLayout,p=new Array(c.length),h=(t.calcdata||[]).slice(0);for(t.calcdata=p,t.firstscatter=!0,d._numBoxes=0,d._numViolins=0,d._violinScaleGroupStats={},t._hmpixcount=0,t._hmlumcount=0,d._piecolormap={},d._piecolorway=null,d._piedefaultcolorcount=0,a=0;a<c.length;a++)Array.isArray(e)&&-1===e.indexOf(a)&&(p[a]=h[a]);for(a=0;a<c.length;a++)(r=c[a])._arrayAttrs=o.findArrayAttributes(r);var g=d._subplots.polar||[];for(a=0;a<g.length;a++)s.push(d[g[a]].radialaxis,d[g[a]].angularaxis);A(s);var y=!1;for(a=0;a<c.length;a++)if(!0===(r=c[a]).visible&&r.transforms){if((n=r._module)&&n.calc){var v=n.calc(t,r);v[0]&&v[0].t&&v[0].t._scene&&delete v[0].t._scene.dirty}for(l=0;l<r.transforms.length;l++){var x=r.transforms[l];(n=m[x.type])&&n.calcTransform&&(r._hasCalcTransform=!0,y=!0,n.calcTransform(t,r,x))}}function b(e,a){if(r=c[e],!!(n=r._module).isContainer===a){var i=[];if(!0===r.visible){delete r._indexToPoints;var o=r.transforms||[];for(l=o.length-1;l>=0;l--)if(o[l].enabled){r._indexToPoints=o[l]._indexToPoints;break}n&&n.calc&&(i=n.calc(t,r))}Array.isArray(i)&&i[0]||(i=[{x:u,y:u}]),i[0].t||(i[0].t={}),i[0].trace=r,p[e]=i}}for(y&&A(s),a=0;a<c.length;a++)b(a,!0);for(a=0;a<c.length;a++)b(a,!1);i.getComponentMethod("fx","calc")(t)},v.doSetPositions=function(t){var e,r,n=t._fullLayout,a=n._subplots.cartesian,i=n._modules,o=[];for(r=0;r<i.length;r++)s.pushUnique(o,i[r].setPositions);if(o.length)for(e=0;e<a.length;e++){var l=n._plots[a[e]];for(r=0;r<o.length;r++)o[r](t,l)}},v.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},v.generalUpdatePerTraceModule=function(t,e,r,n){var a,i=e.traceHash,o={};for(a=0;a<r.length;a++){var l=r[a],c=l[0].trace;c.visible&&(o[c.type]=o[c.type]||[],o[c.type].push(l))}for(var u in i)if(!o[u]){var f=i[u][0];f[0].trace.visible=!1,o[u]=[f]}for(var d in o){var p=o[d];p[0][0].trace._module.plot(t,e,s.filterVisible(p),n)}e.traceHash=o}},{"../components/color":45,"../constants/numerical":145,"../lib":163,"../plot_api/plot_schema":196,"../plot_api/plot_template":197,"../plots/cartesian/axis_ids":210,"../registry":247,"./animation_attributes":202,"./attributes":204,"./command":231,"./font_attributes":233,"./frame_attributes":234,"./layout_attributes":237,"./sort_modules":246,d3:10,"fast-isnumeric":13}],240:[function(t,e,r){"use strict";var n=t("../../../traces/scatter/attributes"),a=n.marker;e.exports={r:n.r,t:n.t,marker:{color:a.color,size:a.size,symbol:a.symbol,opacity:a.opacity,editType:"calc"}}},{"../../../traces/scatter/attributes":314}],241:[function(t,e,r){"use strict";var n=t("../../cartesian/layout_attributes"),a=t("../../../lib/extend").extendFlat,i=t("../../../plot_api/edit_types").overrideAll,o=a({},n.domain,{});function l(t,e){return a({},e,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}e.exports=i({radialaxis:l(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:l(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested")},{"../../../lib/extend":157,"../../../plot_api/edit_types":190,"../../cartesian/layout_attributes":219}],242:[function(t,e,r){"use strict";(e.exports=t("./micropolar")).manager=t("./micropolar_manager")},{"./micropolar":243,"./micropolar_manager":244}],243:[function(t,e,r){var n=t("d3"),a=t("../../../lib").extendDeepAll,i=t("../../../constants/alignment").MID_SHIFT,o=e.exports={version:"0.2.2"};o.Axis=function(){var t,e,r,l,s={data:[],layout:{}},c={},u={},f=n.dispatch("hover"),d={};return d.render=function(c){return function(c){e=c||e;var f=s.data,d=s.layout;("string"==typeof e||e.nodeName)&&(e=n.select(e)),e.datum(f).each(function(e,s){var c=e.slice();u={data:o.util.cloneJson(c),layout:o.util.cloneJson(d)};var f=0;c.forEach(function(t,e){t.color||(t.color=d.defaultColorRange[f],f=(f+1)%d.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:n.rgb(t.color).darker().toString()),u.data[e].color=t.color,u.data[e].strokeColor=t.strokeColor,u.data[e].strokeDash=t.strokeDash,u.data[e].strokeSize=t.strokeSize});var p=c.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||!0===r}),h=!1,g=p.map(function(t,e){return h=h||"undefined"!=typeof t.groupId,t});if(h){var y=n.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),v=[],m=y.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],v.push(r),r=o.util.sumArrays(t.r,r)}),t.values});p=n.merge(m)}p.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var x=Math.min(d.width-d.margin.left-d.margin.right,d.height-d.margin.top-d.margin.bottom)/2;x=Math.max(10,x);var b,_=[d.margin.left+x,d.margin.top+x];b=h?[0,n.max(o.util.sumArrays(o.util.arrayLast(p).r[0],o.util.arrayLast(v)))]:n.extent(o.util.flattenArray(p.map(function(t,e){return t.r}))),d.radialAxis.domain!=o.DATAEXTENT&&(b[0]=0),r=n.scale.linear().domain(d.radialAxis.domain!=o.DATAEXTENT&&d.radialAxis.domain?d.radialAxis.domain:b).range([0,x]),u.layout.radialAxis.domain=r.domain();var w,k=o.util.flattenArray(p.map(function(t,e){return t.t})),M="string"==typeof k[0];M&&(k=o.util.deduplicate(k),w=k.slice(),k=n.range(k.length),p=p.map(function(t,e){var r=t;return t.t=[k],h&&(r.yStack=t.yStack),r}));var T=p.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===p.length,A=null===d.needsEndSpacing?M||!T:d.needsEndSpacing,L=d.angularAxis.domain&&d.angularAxis.domain!=o.DATAEXTENT&&!M&&d.angularAxis.domain[0]>=0?d.angularAxis.domain:n.extent(k),C=Math.abs(k[1]-k[0]);T&&!M&&(C=0);var S=L.slice();A&&M&&(S[1]+=C);var O=d.angularAxis.ticksCount||4;O>8&&(O=O/(O/8)+O%8),d.angularAxis.ticksStep&&(O=(S[1]-S[0])/O);var P=d.angularAxis.ticksStep||(S[1]-S[0])/(O*(d.minorTicks+1));w&&(P=Math.max(Math.round(P),1)),S[2]||(S[2]=P);var D=n.range.apply(this,S);if(D=D.map(function(t,e){return parseFloat(t.toPrecision(12))}),l=n.scale.linear().domain(S.slice(0,2)).range("clockwise"===d.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=l.domain(),u.layout.angularAxis.endPadding=A?C:0,"undefined"==typeof(t=n.select(this).select("svg.chart-root"))||t.empty()){var z=(new DOMParser).parseFromString("<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>","application/xml"),E=this.appendChild(this.ownerDocument.importNode(z.documentElement,!0));t=n.select(E)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var I,N=t.select(".chart-group"),R={fill:"none",stroke:d.tickColor},F={"font-size":d.font.size,"font-family":d.font.family,fill:d.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+d.font.outlineColor}).join(",")};if(d.showLegend){I=t.select(".legend-group").attr({transform:"translate("+[x,d.margin.top]+")"}).style({display:"block"});var j=p.map(function(t,e){var r=o.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});o.Legend().config({data:p.map(function(t,e){return t.name||"Element"+e}),legendConfig:a({},o.Legend.defaultConfig().legendConfig,{container:I,elements:j,reverseOrder:d.legend.reverseOrder})})();var B=I.node().getBBox();x=Math.min(d.width-B.width-d.margin.left-d.margin.right,d.height-d.margin.top-d.margin.bottom)/2,x=Math.max(10,x),_=[d.margin.left+x,d.margin.top+x],r.range([0,x]),u.layout.radialAxis.domain=r.domain(),I.attr("transform","translate("+[_[0]+x,_[1]-x]+")")}else I=t.select(".legend-group").style({display:"none"});t.attr({width:d.width,height:d.height}).style({opacity:d.opacity}),N.attr("transform","translate("+_+")").style({cursor:"crosshair"});var H=[(d.width-(d.margin.left+d.margin.right+2*x+(B?B.width:0)))/2,(d.height-(d.margin.top+d.margin.bottom+2*x))/2];if(H[0]=Math.max(0,H[0]),H[1]=Math.max(0,H[1]),t.select(".outer-group").attr("transform","translate("+H+")"),d.title){var q=t.select("g.title-group text").style(F).text(d.title),V=q.node().getBBox();q.attr({x:_[0]-V.width/2,y:_[1]-x-20})}var U=t.select(".radial.axis-group");if(d.radialAxis.gridLinesVisible){var G=U.selectAll("circle.grid-circle").data(r.ticks(5));G.enter().append("circle").attr({class:"grid-circle"}).style(R),G.attr("r",r),G.exit().remove()}U.select("circle.outside-circle").attr({r:x}).style(R);var Y=t.select("circle.background-circle").attr({r:x}).style({fill:d.backgroundColor,stroke:d.stroke});function X(t,e){return l(t)%360+d.orientation}if(d.radialAxis.visible){var Z=n.svg.axis().scale(r).ticks(5).tickSize(5);U.call(Z).attr({transform:"rotate("+d.radialAxis.orientation+")"}),U.selectAll(".domain").style(R),U.selectAll("g>text").text(function(t,e){return this.textContent+d.radialAxis.ticksSuffix}).style(F).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===d.radialAxis.tickOrientation?"rotate("+-d.radialAxis.orientation+") translate("+[0,F["font-size"]]+")":"translate("+[0,F["font-size"]]+")"}}),U.selectAll("g>line").style({stroke:"black"})}var W=t.select(".angular.axis-group").selectAll("g.angular-tick").data(D),Q=W.enter().append("g").classed("angular-tick",!0);W.attr({transform:function(t,e){return"rotate("+X(t)+")"}}).style({display:d.angularAxis.visible?"block":"none"}),W.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(d.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(d.minorTicks+1)==0)}).style(R),Q.selectAll(".minor").style({stroke:d.minorTickColor}),W.select("line.grid-line").attr({x1:d.tickLength?x-d.tickLength:0,x2:x}).style({display:d.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(F);var J=W.select("text.axis-text").attr({x:x+d.labelOffset,dy:i+"em",transform:function(t,e){var r=X(t),n=x+d.labelOffset,a=d.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-r+" "+n+" 0)":"radial"==a?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:d.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(d.minorTicks+1)!=0?"":w?w[t]+d.angularAxis.ticksSuffix:t+d.angularAxis.ticksSuffix}).style(F);d.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(d.minorTicks+1)!=0?"":d.angularAxis.rewriteTicks(this.textContent,e)});var $=n.max(N.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));I.attr({transform:"translate("+[x+$,d.margin.top]+")"});var K=t.select("g.geometry-group").selectAll("g").size()>0,tt=t.select("g.geometry-group").selectAll("g.geometry").data(p);if(tt.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),tt.exit().remove(),p[0]||K){var et=[];p.forEach(function(t,e){var n={};n.radialScale=r,n.angularScale=l,n.container=tt.filter(function(t,r){return r==e}),n.geometry=t.geometry,n.orientation=d.orientation,n.direction=d.direction,n.index=e,et.push({data:t,geometryConfig:n})});var rt=n.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(et),nt=[];rt.forEach(function(t,e){"unstacked"===t.key?nt=nt.concat(t.values.map(function(t,e){return[t]})):nt.push(t.values)}),nt.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return a(o[r].defaultConfig(),t)});o[r]().config(n)()})}var at,it,ot=t.select(".guides-group"),lt=t.select(".tooltips-group"),st=o.tooltipPanel().config({container:lt,fontSize:8})(),ct=o.tooltipPanel().config({container:lt,fontSize:8})(),ut=o.tooltipPanel().config({container:lt,hasTick:!0})();if(!M){var ft=ot.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});N.on("mousemove.angular-guide",function(t,e){var r=o.util.getMousePos(Y).angle;ft.attr({x2:-x,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-d.orientation)%360;at=l.invert(n);var a=o.util.convertToCartesian(x+12,r+180);st.text(o.util.round(at)).move([a[0]+_[0],a[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){ot.select("line").style({opacity:0})})}var dt=ot.select("circle").style({stroke:"grey",fill:"none"});N.on("mousemove.radial-guide",function(t,e){var n=o.util.getMousePos(Y).radius;dt.attr({r:n}).style({opacity:.5}),it=r.invert(o.util.getMousePos(Y).radius);var a=o.util.convertToCartesian(n,d.radialAxis.orientation);ct.text(o.util.round(it)).move([a[0]+_[0],a[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){dt.style({opacity:0}),ut.hide(),st.hide(),ct.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(e,r){var a=n.select(this),i=this.style.fill,l="black",s=this.style.opacity||1;if(a.attr({"data-opacity":s}),i&&"none"!==i){a.attr({"data-fill":i}),l=n.hsl(i).darker().toString(),a.style({fill:l,opacity:1});var c={t:o.util.round(e[0]),r:o.util.round(e[1])};M&&(c.t=w[e[0]]);var u="t: "+c.t+", r: "+c.r,f=this.getBoundingClientRect(),d=t.node().getBoundingClientRect(),p=[f.left+f.width/2-H[0]-d.left,f.top+f.height/2-H[1]-d.top];ut.config({color:l}).text(u),ut.move(p)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),l=n.hsl(i).darker().toString(),a.style({stroke:l,opacity:1})}).on("mousemove.tooltip",function(t,e){if(0!=n.event.which)return!1;n.select(this).attr("data-fill")&&ut.show()}).on("mouseout.tooltip",function(t,e){ut.hide();var r=n.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(c),this},d.config=function(t){if(!arguments.length)return s;var e=o.util.cloneJson(t);return e.data.forEach(function(t,e){s.data[e]||(s.data[e]={}),a(s.data[e],o.Axis.defaultConfig().data[0]),a(s.data[e],t)}),a(s.layout,o.Axis.defaultConfig().layout),a(s.layout,e.layout),this},d.getLiveConfig=function(){return u},d.getinputConfig=function(){return c},d.radialScale=function(t){return r},d.angularScale=function(t){return l},d.svg=function(){return t},n.rebind(d,f,"on"),d},o.Axis.defaultConfig=function(t,e){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:n.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},o.util={},o.DATAEXTENT="dataExtent",o.AREA="AreaChart",o.LINE="LinePlot",o.DOT="DotPlot",o.BAR="BarChart",o.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},o.util._extend=function(t,e){for(var r in t)e[r]=t[r]},o.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},o.util.dataFromEquation2=function(t,e){var r=e||6;return n.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},o.util.dataFromEquation=function(t,e,r){var a=e||6,i=[],o=[];n.range(0,360+a,a).forEach(function(e,r){var n=e*Math.PI/180,a=t(n);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},o.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return n.range(e).map(function(t,e){return r[e]||r[0]})},o.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=o.util.ensureArray(t[e],r)}),t},o.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},o.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},o.util.sumArrays=function(t,e){return n.zip(t,e).map(function(t,e){return n.sum(t)})},o.util.arrayLast=function(t){return t[t.length-1]},o.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},o.util.flattenArray=function(t){for(var e=[];!o.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},o.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},o.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},o.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},o.util.getMousePos=function(t){var e=n.mouse(t.node()),r=e[0],a=e[1],i={};return i.x=r,i.y=a,i.pos=e,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},o.util.duplicatesCount=function(t){for(var e,r={},n={},a=0,i=t.length;a<i;a++)(e=t[a])in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},o.util.duplicates=function(t){return Object.keys(o.util.duplicatesCount(t))},o.util.translator=function(t,e,r,n){if(n){var a=r.slice();r=e,e=a}var i=e.reduce(function(t,e){if("undefined"!=typeof t)return t[e]},t);"undefined"!=typeof i&&(e.reduce(function(t,r,n){if("undefined"!=typeof t)return n===e.length-1&&delete t[r],t[r]},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=i),t[e]},t))},o.PolyChart=function(){var t=[o.PolyChart.defaultConfig()],e=n.dispatch("hover"),r={solid:"none",dash:[5,2],dot:[2,5]};function i(){var e=t[0].geometryConfig,a=e.container;"string"==typeof a&&(a=n.select(a)),a.datum(t).each(function(t,a){var i=!!t[0].data.yStack,o=t.map(function(t,e){return i?n.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):n.zip(t.data.t[0],t.data.r[0])}),l=e.angularScale,s=e.radialScale.domain()[0],c={bar:function(r,a,i){var o=t[i].data,s=e.radialScale(r[1])-e.radialScale(0),c=e.radialScale(r[2]||0),u=o.barWidth;n.select(this).attr({class:"mark bar",d:"M"+[[s+c,-u/2],[s+c,u/2],[c,u/2],[c,-u/2]].join("L")+"Z",transform:function(t,r){return"rotate("+(e.orientation+l(t[0]))+")"}})}};c.dot=function(r,a,i){var o=r[2]?[r[0],r[1]+r[2]]:r,l=n.svg.symbol().size(t[i].data.dotSize).type(t[i].data.dotType)(r,a);n.select(this).attr({class:"mark dot",d:l,transform:function(t,r){var n,a,i,l=(n=function(t,r){var n=e.radialScale(t[1]),a=(e.angularScale(t[0])+e.orientation)*Math.PI/180;return{r:n,t:a}}(o),a=n.r*Math.cos(n.t),i=n.r*Math.sin(n.t),{x:a,y:i});return"translate("+[l.x,l.y]+")"}})};var u=n.svg.line.radial().interpolate(t[0].data.lineInterpolation).radius(function(t){return e.radialScale(t[1])}).angle(function(t){return e.angularScale(t[0])*Math.PI/180});c.line=function(r,a,i){var l=r[2]?o[i].map(function(t,e){return[t[0],t[1]+t[2]]}):o[i];if(n.select(this).each(c.dot).style({opacity:function(e,r){return+t[i].data.dotVisible},fill:h.stroke(r,a,i)}).attr({class:"mark dot"}),!(a>0)){var s=n.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(t,r){return"rotate("+(e.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return h.fill(r,a,i)},"fill-opacity":0,stroke:function(t,e){return h.stroke(r,a,i)},"stroke-width":function(t,e){return h["stroke-width"](r,a,i)},"stroke-dasharray":function(t,e){return h["stroke-dasharray"](r,a,i)},opacity:function(t,e){return h.opacity(r,a,i)},display:function(t,e){return h.display(r,a,i)}})}};var f=e.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,p=n.svg.arc().startAngle(function(t){return-d/2}).endAngle(function(t){return d/2}).innerRadius(function(t){return e.radialScale(s+(t[2]||0))}).outerRadius(function(t){return e.radialScale(s+(t[2]||0))+e.radialScale(t[1])});c.arc=function(t,r,a){n.select(this).attr({class:"mark arc",d:p,transform:function(t,r){return"rotate("+(e.orientation+l(t[0])+90)+")"}})};var h={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return"undefined"==typeof t[n].data.visible||t[n].data.visible?"block":"none"}},g=n.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var y=g.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({class:"mark"}),y.style(h).each(c[e.geometryType]),y.exit().remove(),g.exit().remove()})}return i.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),a(t[r],o.PolyChart.defaultConfig()),a(t[r],e)}),this):t},i.getColorScale=function(){},n.rebind(i,e,"on"),i},o.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:n.scale.category20()}}},o.BarChart=function(){return o.PolyChart()},o.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},o.AreaChart=function(){return o.PolyChart()},o.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},o.DotPlot=function(){return o.PolyChart()},o.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},o.LinePlot=function(){return o.PolyChart()},o.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},o.Legend=function(){var t=o.Legend.defaultConfig(),e=n.dispatch("hover");function r(){var e=t.legendConfig,i=t.data.map(function(t,r){return[].concat(t).map(function(t,n){var i=a({},e.elements[r]);return i.name=t,i.color=[].concat(e.elements[r].color)[n],i})}),o=n.merge(i);o=o.filter(function(t,r){return e.elements[r]&&(e.elements[r].visibleInLegend||"undefined"==typeof e.elements[r].visibleInLegend)}),e.reverseOrder&&(o=o.reverse());var l=e.container;("string"==typeof l||l.nodeName)&&(l=n.select(l));var s=o.map(function(t,e){return t.color}),c=e.fontSize,u=null==e.isContinuous?"number"==typeof o[0]:e.isContinuous,f=u?e.height:c*o.length,d=l.classed("legend-group",!0).selectAll("svg").data([0]),p=d.enter().append("svg").attr({width:300,height:f+c,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});p.append("g").classed("legend-axis",!0),p.append("g").classed("legend-marks",!0);var h=n.range(o.length),g=n.scale[u?"linear":"ordinal"]().domain(h).range(s),y=n.scale[u?"linear":"ordinal"]().domain(h)[u?"range":"rangePoints"]([0,f]);if(u){var v=d.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),d.append("rect").classed("legend-mark",!0).attr({height:e.height,width:e.colorBandWidth,fill:"url(#grad1)"})}else{var m=d.select(".legend-marks").selectAll("path.legend-mark").data(o);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[c/2,y(e)+c/2]+")"},d:function(t,e){var r,a,i,o=t.symbol;return i=3*(a=c),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=n.svg.symbolTypes.indexOf(r)?n.svg.symbol().type(r).size(i)():n.svg.symbol().type("square").size(i)()},fill:function(t,e){return g(e)}}),m.exit().remove()}var x=n.svg.axis().scale(y).orient("right"),b=d.select("g.legend-axis").attr({transform:"translate("+[u?e.colorBandWidth:c,c/2]+")"}).call(x);return b.selectAll(".domain").style({fill:"none",stroke:"none"}),b.selectAll("line").style({fill:"none",stroke:u?e.textColor:"none"}),b.selectAll("text").style({fill:e.textColor,"font-size":e.fontSize}).text(function(t,e){return o[e].name}),r}return r.config=function(e){return arguments.length?(a(t,e),this):t},n.rebind(r,e,"on"),r},o.Legend.defaultConfig=function(t,e){return{data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}}},o.tooltipPanel=function(){var t,e,r,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},l="tooltip-"+o.tooltipPanel.uid++,s=10,c=function(){var n=(t=i.container.selectAll("g."+l).data([0])).enter().append("g").classed(l,!0).style({"pointer-events":"none",display:"none"});return r=n.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=n.append("text").attr({dx:i.padding+s,dy:.3*+i.fontSize}),c};return c.text=function(a){var o=n.hsl(i.color).l,l=o>=.5?"#aaa":"white",u=o>=.5?"black":"white",f=a||"";e.style({fill:u,"font-size":i.fontSize+"px"}).text(f);var d=i.padding,p=e.node().getBBox(),h={fill:i.color,stroke:l,"stroke-width":"2px"},g=p.width+2*d+s,y=p.height+2*d;return r.attr({d:"M"+[[s,-y/2],[s,-y/4],[i.hasTick?0:s,0],[s,y/4],[s,y/2],[g,y/2],[g,-y/2]].join("L")+"Z"}).style(h),t.attr({transform:"translate("+[s,-y/2+2*d]+")"}),t.style({display:"block"}),c},c.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),c},c.hide=function(){if(t)return t.style({display:"none"}),c},c.show=function(){if(t)return t.style({display:"block"}),c},c.config=function(t){return a(i,t),c},c},o.tooltipPanel.uid=1,o.adapter={},o.adapter.plotly=function(){var t={convert:function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=a({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var i=o.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var n=i.indexOf(t.geometry);-1!=n&&(r.data[e].groupId=n)})}if(t.layout){var l=a({},t.layout);if([[l,["plot_bgcolor"],["backgroundColor"]],[l,["showlegend"],["showLegend"]],[l,["radialaxis"],["radialAxis"]],[l,["angularaxis"],["angularAxis"]],[l.angularaxis,["showline"],["gridLinesVisible"]],[l.angularaxis,["showticklabels"],["labelsVisible"]],[l.angularaxis,["nticks"],["ticksCount"]],[l.angularaxis,["tickorientation"],["tickOrientation"]],[l.angularaxis,["ticksuffix"],["ticksSuffix"]],[l.angularaxis,["range"],["domain"]],[l.angularaxis,["endpadding"],["endPadding"]],[l.radialaxis,["showline"],["gridLinesVisible"]],[l.radialaxis,["tickorientation"],["tickOrientation"]],[l.radialaxis,["ticksuffix"],["ticksSuffix"]],[l.radialaxis,["range"],["domain"]],[l.angularAxis,["showline"],["gridLinesVisible"]],[l.angularAxis,["showticklabels"],["labelsVisible"]],[l.angularAxis,["nticks"],["ticksCount"]],[l.angularAxis,["tickorientation"],["tickOrientation"]],[l.angularAxis,["ticksuffix"],["ticksSuffix"]],[l.angularAxis,["range"],["domain"]],[l.angularAxis,["endpadding"],["endPadding"]],[l.radialAxis,["showline"],["gridLinesVisible"]],[l.radialAxis,["tickorientation"],["tickOrientation"]],[l.radialAxis,["ticksuffix"],["ticksSuffix"]],[l.radialAxis,["range"],["domain"]],[l.font,["outlinecolor"],["outlineColor"]],[l.legend,["traceorder"],["reverseOrder"]],[l,["labeloffset"],["labelOffset"]],[l,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof l.tickLength&&(l.angularaxis.ticklen=l.tickLength,delete l.tickLength),l.tickColor&&(l.angularaxis.tickcolor=l.tickColor,delete l.tickColor)):(l.angularAxis&&"undefined"!=typeof l.angularAxis.ticklen&&(l.tickLength=l.angularAxis.ticklen),l.angularAxis&&"undefined"!=typeof l.angularAxis.tickcolor&&(l.tickColor=l.angularAxis.tickcolor)),l.legend&&"boolean"!=typeof l.legend.reverseOrder&&(l.legend.reverseOrder="normal"!=l.legend.reverseOrder),l.legend&&"boolean"==typeof l.legend.traceorder&&(l.legend.traceorder=l.legend.traceorder?"reversed":"normal",delete l.legend.reverseOrder),l.margin&&"undefined"!=typeof l.margin.t){var s=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],u={};n.entries(l.margin).forEach(function(t,e){u[c[s.indexOf(t.key)]]=t.value}),l.margin=u}e&&(delete l.needsEndSpacing,delete l.minorTickColor,delete l.minorTicks,delete l.angularaxis.ticksCount,delete l.angularaxis.ticksCount,delete l.angularaxis.ticksStep,delete l.angularaxis.rewriteTicks,delete l.angularaxis.nticks,delete l.radialaxis.ticksCount,delete l.radialaxis.ticksCount,delete l.radialaxis.ticksStep,delete l.radialaxis.rewriteTicks,delete l.radialaxis.nticks),r.layout=l}return r}};return t}},{"../../../constants/alignment":143,"../../../lib":163,d3:10}],244:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../../lib"),i=t("../../../components/color"),o=t("./micropolar"),l=t("./undo_manager"),s=a.extendDeepAll,c=e.exports={};c.framework=function(t){var e,r,a,i,u,f=new l;function d(r,l){return l&&(u=l),n.select(n.select(u).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),e=e?s(e,r):r,a||(a=o.Axis()),i=o.adapter.plotly().convert(e),a.config(i).render(u),t.data=e.data,t.layout=e.layout,c.fillLayout(t),e}return d.isPolar=!0,d.svg=function(){return a.svg()},d.getConfig=function(){return e},d.getLiveConfig=function(){return o.adapter.plotly().convert(a.getLiveConfig(),!0)},d.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},d.setUndoPoint=function(){var t,n,a=this,i=o.util.cloneJson(e);t=i,n=r,f.add({undo:function(){n&&a(n)},redo:function(){a(t)}}),r=o.util.cloneJson(i)},d.undo=function(){f.undo()},d.redo=function(){f.redo()},d},c.fillLayout=function(t){var e=n.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:i.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../../components/color":45,"../../../lib":163,"./micropolar":243,"./undo_manager":245,d3:10}],245:[function(t,e,r){"use strict";e.exports=function(){var t,e=[],r=-1,n=!1;function a(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(a(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(a(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r<e.length-1},getCommands:function(){return e},getPreviousCommand:function(){return e[r-1]},getIndex:function(){return r}}}},{}],246:[function(t,e,r){"use strict";function n(t,e){return"splom"===t?-1:"splom"===e?1:0}e.exports={sortBasePlotModules:function(t,e){return n(t.name,e.name)},sortModules:n}},{}],247:[function(t,e,r){"use strict";var n=t("./lib/loggers"),a=t("./lib/noop"),i=t("./lib/push_unique"),o=t("./lib/is_plain_object"),l=t("./lib/extend"),s=t("./plots/attributes"),c=t("./plots/layout_attributes"),u=l.extendFlat,f=l.extendDeepAll;function d(t){var e=t.name,a=t.categories,i=t.meta;if(r.modules[e])n.log("Type "+e+" already registered");else{r.subplotsRegistry[t.basePlotModule.name]||function(t){var e=t.name;if(r.subplotsRegistry[e])return void n.log("Plot type "+e+" already registered.");for(var a in y(t),r.subplotsRegistry[e]=t,r.componentsRegistry)x(a,t.name)}(t.basePlotModule);for(var o={},l=0;l<a.length;l++)o[a[l]]=!0,r.allCategories[a[l]]=!0;for(var s in r.modules[e]={_module:t,categories:o},i&&Object.keys(i).length&&(r.modules[e].meta=i),r.allTypes.push(e),r.componentsRegistry)v(s,e);t.layoutAttributes&&u(r.traceLayoutAttributes,t.layoutAttributes)}}function p(t){if("string"!=typeof t.name)throw new Error("Component module *name* must be a string.");var e=t.name;for(var n in r.componentsRegistry[e]=t,t.layoutAttributes&&(t.layoutAttributes._isLinkedToArray&&i(r.layoutArrayContainers,e),y(t)),r.modules)v(e,n);for(var a in r.subplotsRegistry)x(e,a);for(var o in r.transformsRegistry)m(e,o);t.schema&&t.schema.layout&&f(c,t.schema.layout)}function h(t){if("string"!=typeof t.name)throw new Error("Transform module *name* must be a string.");var e="Transform module "+t.name,a="function"==typeof t.transform,i="function"==typeof t.calcTransform;if(!a&&!i)throw new Error(e+" is missing a *transform* or *calcTransform* method.");for(var l in a&&i&&n.log([e+" has both a *transform* and *calcTransform* methods.","Please note that all *transform* methods are executed","before all *calcTransform* methods."].join(" ")),o(t.attributes)||n.log(e+" registered without an *attributes* object."),"function"!=typeof t.supplyDefaults&&n.log(e+" registered without a *supplyDefaults* method."),r.transformsRegistry[t.name]=t,r.componentsRegistry)m(l,t.name)}function g(t){var e=t.name,n=e.split("-")[0],a=t.dictionary,i=t.format,o=a&&Object.keys(a).length,l=i&&Object.keys(i).length,s=r.localeRegistry,c=s[e];if(c||(s[e]=c={}),n!==e){var u=s[n];u||(s[n]=u={}),o&&u.dictionary===c.dictionary&&(u.dictionary=a),l&&u.format===c.format&&(u.format=i)}o&&(c.dictionary=a),l&&(c.format=i)}function y(t){if(t.layoutAttributes){var e=t.layoutAttributes._arrayAttrRegexps;if(e)for(var n=0;n<e.length;n++)i(r.layoutArrayRegexes,e[n])}}function v(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.traces){var a=n.traces[e];a&&f(r.modules[e]._module.attributes,a)}}function m(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.transforms){var a=n.transforms[e];a&&f(r.transformsRegistry[e].attributes,a)}}function x(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.subplots){var a=r.subplotsRegistry[e],i=a.layoutAttributes,o="subplot"===a.attr?a.name:a.attr;Array.isArray(o)&&(o=o[0]);var l=n.subplots[o];i&&l&&f(i,l)}}function b(t){return"object"==typeof t&&(t=t.type),t}r.modules={},r.allCategories={},r.allTypes=[],r.subplotsRegistry={},r.transformsRegistry={},r.componentsRegistry={},r.layoutArrayContainers=[],r.layoutArrayRegexes=[],r.traceLayoutAttributes={},r.localeRegistry={},r.apiMethodRegistry={},r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;e<t.length;e++){var n=t[e];if(!n)throw new Error("Invalid module was attempted to be registered!");switch(n.moduleType){case"trace":d(n);break;case"transform":h(n);break;case"component":p(n);break;case"locale":g(n);break;case"apiMethod":var a=n.name;r.apiMethodRegistry[a]=n.fn;break;default:throw new Error("Invalid module was attempted to be registered!")}}},r.getModule=function(t){var e=r.modules[b(t)];return!!e&&e._module},r.traceIs=function(t,e){if("various"===(t=b(t)))return!1;var a=r.modules[t];return a||(t&&"area"!==t&&n.log("Unrecognized trace type "+t+"."),a=r.modules[s.type.dflt]),!!a.categories[e]},r.getTransformIndices=function(t,e){for(var r=[],n=t.transforms||[],a=0;a<n.length;a++)n[a].type===e&&r.push(a);return r},r.hasTransform=function(t,e){for(var r=t.transforms||[],n=0;n<r.length;n++)if(r[n].type===e)return!0;return!1},r.getComponentMethod=function(t,e){var n=r.componentsRegistry[t];return n&&n[e]||a},r.call=function(){var t=arguments[0],e=[].slice.call(arguments,1);return r.apiMethodRegistry[t].apply(null,e)}},{"./lib/extend":157,"./lib/is_plain_object":165,"./lib/loggers":168,"./lib/noop":172,"./lib/push_unique":176,"./plots/attributes":204,"./plots/layout_attributes":237}],248:[function(t,e,r){"use strict";var n=t("../lib"),a=n.extendFlat,i=n.extendDeep;function o(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}e.exports=function(t,e){var r;t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var n,l=t.data,s=t.layout,c=i([],l),u=i({},s,o(e.tileClass)),f=t._context||{};if(e.width&&(u.width=e.width),e.height&&(u.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){u.annotations=[];var d=Object.keys(u);for(r=0;r<d.length;r++)n=d[r],["xaxis","yaxis","zaxis"].indexOf(n.slice(0,5))>-1&&(u[d[r]].title="");for(r=0;r<c.length;r++){var p=c[r];p.showscale=!1,p.marker&&(p.marker.showscale=!1),"pie"===p.type&&(p.textposition="none")}}if(Array.isArray(e.annotations))for(r=0;r<e.annotations.length;r++)u.annotations.push(e.annotations[r]);var h=Object.keys(u).filter(function(t){return t.match(/^scene\d*$/)});if(h.length){var g={};for("thumbnail"===e.tileClass&&(g={title:"",showaxeslabels:!1,showticklabels:!1,linetickenable:!1}),r=0;r<h.length;r++){var y=u[h[r]];y.xaxis||(y.xaxis={}),y.yaxis||(y.yaxis={}),y.zaxis||(y.zaxis={}),a(y.xaxis,g),a(y.yaxis,g),a(y.zaxis,g),y._scene=null}}var v=document.createElement("div");e.tileClass&&(v.className=e.tileClass);var m={gd:v,td:v,layout:u,data:c,config:{staticPlot:void 0===e.staticPlot||e.staticPlot,plotGlPixelRatio:void 0===e.plotGlPixelRatio?2:e.plotGlPixelRatio,displaylogo:e.displaylogo||!1,showLink:e.showLink||!1,showTips:e.showTips||!1,mapboxAccessToken:f.mapboxAccessToken}};return"transparent"!==e.setBackground&&(m.config.setBackground=e.setBackground||"opaque"),m.gd.defaultLayout=o(e.tileClass),m}},{"../lib":163}],249:[function(t,e,r){"use strict";var n=t("../plot_api/to_image"),a=t("../lib"),i=t("./filesaver");e.exports=function(t,e){return(e=e||{}).format=e.format||"png",new Promise(function(r,o){t._snapshotInProgress&&o(new Error("Snapshotting already in progress.")),a.isIE()&&"svg"!==e.format&&o(new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.")),t._snapshotInProgress=!0;var l=n(t,e),s=e.filename||t.fn||"newplot";s+="."+e.format,l.then(function(e){return t._snapshotInProgress=!1,i(e,s)}).then(function(t){r(t)}).catch(function(e){t._snapshotInProgress=!1,o(e)})})}},{"../lib":163,"../plot_api/to_image":200,"./filesaver":250}],250:[function(t,e,r){"use strict";e.exports=function(t,e){var r=document.createElement("a"),n="download"in r,a=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent);return new Promise(function(i,o){if("undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent)&&o(new Error("IE < 10 unsupported")),a&&(document.location.href="data:application/octet-stream"+t.slice(t.search(/[,;]/)),i(e)),e||(e="download"),n&&(r.href=t,r.download=e,document.body.appendChild(r),r.click(),document.body.removeChild(r),i(e)),"undefined"!=typeof navigator&&navigator.msSaveBlob){var l=t.split(/^data:image\/svg\+xml,/)[1],s=decodeURIComponent(l);navigator.msSaveBlob(new Blob([s]),e),i(e)}o(new Error("download error"))})}},{}],251:[function(t,e,r){"use strict";r.getDelay=function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},r.getRedrawFunc=function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},{}],252:[function(t,e,r){"use strict";var n=t("./helpers"),a={getDelay:n.getDelay,getRedrawFunc:n.getRedrawFunc,clone:t("./cloneplot"),toSVG:t("./tosvg"),svgToImg:t("./svgtoimg"),toImage:t("./toimage"),downloadImage:t("./download")};e.exports=a},{"./cloneplot":248,"./download":249,"./helpers":251,"./svgtoimg":253,"./toimage":254,"./tosvg":255}],253:[function(t,e,r){"use strict";var n=t("../lib"),a=t("events").EventEmitter;e.exports=function(t){var e=t.emitter||new a,r=new Promise(function(a,i){var o=window.Image,l=t.svg,s=t.format||"png";if(n.isIE()&&"svg"!==s){var c=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(c),t.promise?r:e.emit("error",c)}var u=t.canvas,f=t.scale||1,d=t.width||300,p=t.height||150,h=f*d,g=f*p,y=u.getContext("2d"),v=new o,m="data:image/svg+xml,"+encodeURIComponent(l);u.width=h,u.height=g,v.onload=function(){var r;switch("svg"!==s&&y.drawImage(v,0,0,h,g),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=m;break;default:var n="Image format is not jpeg, png, svg or webp.";if(i(new Error(n)),!t.promise)return e.emit("error",n)}a(r),t.promise||e.emit("success",r)},v.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},v.src=m});return t.promise?r:e}},{"../lib":163,events:12}],254:[function(t,e,r){"use strict";var n=t("events").EventEmitter,a=t("../registry"),i=t("../lib"),o=t("./helpers"),l=t("./cloneplot"),s=t("./tosvg"),c=t("./svgtoimg");e.exports=function(t,e){var r=new n,u=l(t,{format:"png"}),f=u.gd;f.style.position="absolute",f.style.left="-5000px",document.body.appendChild(f);var d=o.getRedrawFunc(f);return a.call("plot",f,u.data,u.layout,u.config).then(d).then(function(){var t=o.getDelay(f._fullLayout);setTimeout(function(){var t=s(f),n=document.createElement("canvas");n.id=i.randstr(),(r=c({format:e.format,width:f._fullLayout.width,height:f._fullLayout.height,canvas:n,emitter:r,svg:t})).clean=function(){f&&document.body.removeChild(f)}},t)}).catch(function(t){r.emit("error",t)}),r}},{"../lib":163,"../registry":247,"./cloneplot":248,"./helpers":251,"./svgtoimg":253,"./tosvg":255,events:12}],255:[function(t,e,r){"use strict";var n=t("d3"),a=t("../lib"),i=t("../components/drawing"),o=t("../components/color"),l=t("../constants/xmlns_namespaces"),s=/"/g,c=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");e.exports=function(t,e,r){var u,f=t._fullLayout,d=f._paper,p=f._toppaper,h=f.width,g=f.height;d.insert("rect",":first-child").call(i.setRect,0,0,h,g).call(o.fill,f.paper_bgcolor);var y=f._basePlotModules||[];for(u=0;u<y.length;u++){var v=y[u];v.toSVG&&v.toSVG(t)}if(p){var m=p.node().childNodes,x=Array.prototype.slice.call(m);for(u=0;u<x.length;u++){var b=x[u];b.childNodes.length&&d.node().appendChild(b)}}f._draggers&&f._draggers.remove(),d.node().style.background="",d.selectAll("text").attr({"data-unformatted":null,"data-math":null}).each(function(){var t=n.select(this);if("hidden"!==this.style.visibility&&"none"!==this.style.display){t.style({visibility:null,display:null});var e=this.style.fontFamily;e&&-1!==e.indexOf('"')&&t.style("font-family",e.replace(s,"TOBESTRIPPED"))}else t.remove()}),d.selectAll(".point,.scatterpts").each(function(){var t=n.select(this),e=this.style.fill;e&&-1!==e.indexOf("url(")&&t.style("fill",e.replace(s,"TOBESTRIPPED"))}),"pdf"!==e&&"eps"!==e||d.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width",0),d.node().setAttributeNS(l.xmlns,"xmlns",l.svg),d.node().setAttributeNS(l.xmlns,"xmlns:xlink",l.xlink),"svg"===e&&r&&(d.attr("width",r*h),d.attr("height",r*g),d.attr("viewBox","0 0 "+h+" "+g));var _=(new window.XMLSerializer).serializeToString(d.node());return _=function(t){var e=n.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"<"===t?"<":"&rt;"===t?">":-1!==t.indexOf("<")||-1!==t.indexOf(">")?"":e.html(t).text()});return e.remove(),r}(_),_=(_=_.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(c,"'"),a.isIE()&&(_=(_=(_=_.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),_}},{"../components/color":45,"../components/drawing":70,"../constants/xmlns_namespaces":147,"../lib":163,d3:10}],256:[function(t,e,r){"use strict";var n=t("../../lib").mergeArray;e.exports=function(t,e){for(var r=0;r<t.length;r++)t[r].i=r;n(e.text,t,"tx"),n(e.hovertext,t,"htx");var a=e.marker;if(a){n(a.opacity,t,"mo"),n(a.color,t,"mc");var i=a.line;i&&(n(i.color,t,"mlc"),n(i.width,t,"mlw"))}}},{"../../lib":163}],257:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),a=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),o=t("../../plots/font_attributes"),l=t("../../lib/extend").extendFlat,s=o({editType:"calc",arrayOk:!0}),c=l({},n.marker.line.width,{dflt:0}),u=l({width:c,editType:"calc"},a("marker.line")),f=l({line:u,editType:"calc"},a("marker"),{colorbar:i,opacity:{valType:"number",arrayOk:!0,dflt:1,min:0,max:1,editType:"style"}});e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:n.text,hovertext:n.hovertext,textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"none",arrayOk:!0,editType:"calc"},textfont:l({},s,{}),insidetextfont:l({},s,{}),outsidetextfont:l({},s,{}),constraintext:{valType:"enumerated",values:["inside","outside","both","none"],dflt:"both",editType:"calc"},cliponaxis:l({},n.cliponaxis,{}),orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},base:{valType:"any",dflt:null,arrayOk:!0,editType:"calc"},offset:{valType:"number",dflt:null,arrayOk:!0,editType:"calc"},width:{valType:"number",dflt:null,min:0,arrayOk:!0,editType:"calc"},marker:f,selected:{marker:{opacity:n.selected.marker.opacity,color:n.selected.marker.color,editType:"style"},textfont:n.selected.textfont,editType:"style"},unselected:{marker:{opacity:n.unselected.marker.opacity,color:n.unselected.marker.color,editType:"style"},textfont:n.unselected.textfont,editType:"style"},r:n.r,t:n.t,_deprecated:{bardir:{valType:"enumerated",editType:"calc",values:["v","h"]}}}},{"../../components/colorbar/attributes":46,"../../components/colorscale/attributes":52,"../../lib/extend":157,"../../plots/font_attributes":233,"../scatter/attributes":314}],258:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").isArrayOrTypedArray,i=t("../../plots/cartesian/axes"),o=t("../../components/colorscale/has_colorscale"),l=t("../../components/colorscale/calc"),s=t("./arrays_to_calcdata"),c=t("../scatter/calc_selection");e.exports=function(t,e){var r,u,f,d,p,h=i.getFromId(t,e.xaxis||"x"),g=i.getFromId(t,e.yaxis||"y");"h"===(e.orientation||(e.x&&!e.y?"h":"v"))?(r=h,f=h.makeCalcdata(e,"x"),u=g.makeCalcdata(e,"y"),p=e.xcalendar):(r=g,f=g.makeCalcdata(e,"y"),u=h.makeCalcdata(e,"x"),p=e.ycalendar);var y=Math.min(u.length,f.length),v=new Array(y);for(d=0;d<y;d++)v[d]={p:u[d],s:f[d]},e.ids&&(v[d].id=String(e.ids[d]));var m,x=e.base;if(a(x)){for(d=0;d<Math.min(x.length,v.length);d++)m=r.d2c(x[d],0,p),n(m)?(v[d].b=+m,v[d].hasB=1):v[d].b=0;for(;d<v.length;d++)v[d].b=0}else{m=r.d2c(x,0,p);var b=n(m);for(m=b?m:0,d=0;d<v.length;d++)v[d].b=m,b&&(v[d].hasB=1)}return o(e,"marker")&&l(e,e.marker.color,"marker","c"),o(e,"marker.line")&&l(e,e.marker.line.color,"marker.line","c"),s(v,e),c(v,e),v}},{"../../components/colorscale/calc":53,"../../components/colorscale/has_colorscale":59,"../../lib":163,"../../plots/cartesian/axes":207,"../scatter/calc_selection":316,"./arrays_to_calcdata":256,"fast-isnumeric":13}],259:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../components/color"),i=t("../../registry"),o=t("../scatter/xy_defaults"),l=t("../bar/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,c){function u(r,a){return n.coerce(t,e,s,r,a)}var f=n.coerceFont;if(o(t,e,c,u)){u("orientation",e.x&&!e.y?"h":"v"),u("base"),u("offset"),u("width"),u("text"),u("hovertext");var d=u("textposition"),p=Array.isArray(d)||"auto"===d,h=p||"inside"===d,g=p||"outside"===d;if(h||g){var y=f(u,"textfont",c.font);h&&f(u,"insidetextfont",y),g&&f(u,"outsidetextfont",y),u("constraintext"),u("selected.textfont.color"),u("unselected.textfont.color"),u("cliponaxis")}l(t,e,u,r,c);var v=i.getComponentMethod("errorbars","supplyDefaults");v(t,e,a.defaultLine,{axis:"y"}),v(t,e,a.defaultLine,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,u)}else e.visible=!1}},{"../../components/color":45,"../../lib":163,"../../registry":247,"../bar/style_defaults":269,"../scatter/xy_defaults":338,"./attributes":257}],260:[function(t,e,r){"use strict";var n=t("../../components/fx"),a=t("../../registry"),i=t("../../components/color"),o=t("../scatter/fill_hover_text");e.exports=function(t,e,r,l){var s,c,u,f,d,p,h,g=t.cd,y=g[0].trace,v=g[0].t,m="closest"===l,x=t.maxHoverDistance,b=t.maxSpikeDistance;function _(t){return t[u]-t.w/2}function w(t){return t[u]+t.w/2}var k=m?_:function(t){return Math.min(_(t),t.p-v.bardelta/2)},M=m?w:function(t){return Math.max(w(t),t.p+v.bardelta/2)};function T(t,e){return n.inbox(t-s,e-s,x+Math.min(1,Math.abs(e-t)/h)-1)}function A(t){return T(k(t),M(t))}function L(t){return n.inbox(t.b-c,t[f]-c,x+(t[f]-c)/(t[f]-t.b)-1)}"h"===y.orientation?(s=r,c=e,u="y",f="x",d=L,p=A):(s=e,c=r,u="x",f="y",p=L,d=A);var C=t[u+"a"],S=t[f+"a"];h=Math.abs(C.r2c(C.range[1])-C.r2c(C.range[0]));var O=n.getDistanceFunction(l,d,p,function(t){return(d(t)+p(t))/2});if(n.getClosest(g,O,t),!1!==t.index){m||(k=function(t){return Math.min(_(t),t.p-v.bargroupwidth/2)},M=function(t){return Math.max(w(t),t.p+v.bargroupwidth/2)});var P=g[t.index],D=P.mcc||y.marker.color,z=P.mlcc||y.marker.line.color,E=P.mlw||y.marker.line.width;i.opacity(D)?t.color=D:i.opacity(z)&&E&&(t.color=z);var I=y.base?P.b+P.s:P.s;t[f+"0"]=t[f+"1"]=S.c2p(P[f],!0),t[f+"LabelVal"]=I;var N=v.extents[v.extents.round(P.p)];return t[u+"0"]=C.c2p(m?k(P):N[0],!0),t[u+"1"]=C.c2p(m?M(P):N[1],!0),t[u+"LabelVal"]=P.p,t.spikeDistance=(L(P)+function(t){return T(_(t),w(t))}(P))/2+b-x,t[u+"Spike"]=C.c2p(P.p,!0),o(P,y,t),a.getComponentMethod("errorbars","hoverInfo")(P,y,t),[t]}}},{"../../components/color":45,"../../components/fx":87,"../../registry":247,"../scatter/fill_hover_text":321}],261:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/marker_colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","bar","oriented","errorBarsOK","showLegend","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":218,"../scatter/marker_colorbar":331,"./arrays_to_calcdata":256,"./attributes":257,"./calc":258,"./defaults":259,"./hover":260,"./layout_attributes":262,"./layout_defaults":263,"./plot":264,"./select":265,"./set_positions":266,"./style":268}],262:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group",editType:"calc"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:"",editType:"calc"},bargap:{valType:"number",min:0,max:1,editType:"calc"},bargroupgap:{valType:"number",min:0,max:1,dflt:0,editType:"calc"}}},{}],263:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../plots/cartesian/axes"),i=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function l(r,n){return i.coerce(t,e,o,r,n)}for(var s=!1,c=!1,u=!1,f={},d=0;d<r.length;d++){var p=r[d];if(n.traceIs(p,"bar")){if(s=!0,"overlay"!==t.barmode&&"stack"!==t.barmode){var h=p.xaxis+p.yaxis;f[h]&&(u=!0),f[h]=!0}if(p.visible&&"histogram"===p.type)"category"!==a.getFromId({_fullLayout:e},p["v"===p.orientation?"xaxis":"yaxis"]).type&&(c=!0)}}s&&("overlay"!==l("barmode")&&l("barnorm"),l("bargap",c&&!u?0:.2),l("bargroupgap"))}},{"../../lib":163,"../../plots/cartesian/axes":207,"../../registry":247,"./layout_attributes":262}],264:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("tinycolor2"),o=t("../../lib"),l=t("../../lib/svg_text_utils"),s=t("../../components/color"),c=t("../../components/drawing"),u=t("../../registry"),f=t("./attributes"),d=f.text,p=f.textposition,h=f.textfont,g=f.insidetextfont,y=f.outsidetextfont,v=3;function m(t,e,r,n,a,i){var o;return a<1?o="scale("+a+") ":(a=1,o=""),"translate("+(r-a*t)+" "+(n-a*e)+")"+o+(i?"rotate("+i+" "+t+" "+e+") ":"")}function x(t,e,r,n){var o=b((e=e||{}).family,r),l=b(e.size,r),s=b(e.color,r);return{family:_(t.family,o,n.family),size:function(t,e,r){if(a(e)){e=+e;var n=t.min,i=t.max,o=void 0!==n&&e<n||void 0!==i&&e>i;if(!o)return e}return void 0!==r?r:t.dflt}(t.size,l,n.size),color:function(t,e,r){return i(e).isValid()?e:void 0!==r?r:t.dflt}(t.color,s,n.color)}}function b(t,e){var r;return Array.isArray(t)?e<t.length&&(r=t[e]):r=t,r}function _(t,e,r){if("string"==typeof e){if(e||!t.noBlank)return e}else if("number"==typeof e&&!t.strict)return String(e);return void 0!==r?r:t.dflt}e.exports=function(t,e,r,i){var f=e.xaxis,w=e.yaxis,k=t._fullLayout,M=i.selectAll("g.trace.bars").data(r,function(t){return t[0].trace.uid});M.enter().append("g").attr("class","trace bars").append("g").attr("class","points"),M.exit().remove(),M.order(),M.each(function(r){var i=r[0],u=i.t,M=i.trace,T=n.select(this);e.isRangePlot||(i.node3=T);var A=u.poffset,L=Array.isArray(A),C=T.select("g.points").selectAll("g.point").data(o.identity);C.enter().append("g").classed("point",!0),C.exit().remove(),C.each(function(i,u){var T,C,S,O,P=n.select(this),D=i.p+(L?A[u]:A),z=D+i.w,E=i.b,I=E+i.s;if("h"===M.orientation?(S=w.c2p(D,!0),O=w.c2p(z,!0),T=f.c2p(E,!0),C=f.c2p(I,!0),i.ct=[C,(S+O)/2]):(T=f.c2p(D,!0),C=f.c2p(z,!0),S=w.c2p(E,!0),O=w.c2p(I,!0),i.ct=[(T+C)/2,O]),a(T)&&a(C)&&a(S)&&a(O)&&T!==C&&S!==O){var N=(i.mlw+1||M.marker.line.width+1||(i.trace?i.trace.marker.line.width:0)+1)-1,R=n.round(N/2%1,2);if(!t._context.staticPlot){var F=s.opacity(i.mc||M.marker.color)<1||N>.01?j:function(t,e){return Math.abs(t-e)>=2?j(t):t>e?Math.ceil(t):Math.floor(t)};T=F(T,C),C=F(C,T),S=F(S,O),O=F(O,S)}o.ensureSingle(P,"path").style("vector-effect","non-scaling-stroke").attr("d","M"+T+","+S+"V"+O+"H"+C+"V"+S+"Z").call(c.setClipUrl,e.layerClipId),function(t,e,r,n,a,i,s,u){var f;function w(e,r,n){var a=o.ensureSingle(e,"text").text(r).attr({class:"bartext bartext-"+f,transform:"","text-anchor":"middle","data-notex":1}).call(c.font,n).call(l.convertToTspans,t);return a}var k=r[0].trace,M=k.orientation,T=function(t,e){var r=b(t.text,e);return _(d,r)}(k,n);if(f=function(t,e){var r=b(t.textposition,e);return function(t,e,r){return t.coerceNumber&&(e=+e),-1!==t.values.indexOf(e)?e:void 0!==r?r:t.dflt}(p,r)}(k,n),!T||"none"===f)return void e.select("text").remove();var A,L,C,S,O,P,D=function(t,e,r){return x(h,t.textfont,e,r)}(k,n,t._fullLayout.font),z=function(t,e,r){return x(g,t.insidetextfont,e,r)}(k,n,D),E=function(t,e,r){return x(y,t.outsidetextfont,e,r)}(k,n,D),I=t._fullLayout.barmode,N="relative"===I,R="stack"===I||N,F=r[n],j=!R||F._outmost,B=Math.abs(i-a)-2*v,H=Math.abs(u-s)-2*v;"outside"===f&&(j||(f="inside"));if("auto"===f)if(j){f="inside",A=w(e,T,z),L=c.bBox(A.node()),C=L.width,S=L.height;var q=C>0&&S>0,V=C<=B&&S<=H,U=C<=H&&S<=B,G="h"===M?B>=C*(H/S):H>=S*(B/C);q&&(V||U||G)?f="inside":(f="outside",A.remove(),A=null)}else f="inside";if(!A&&(A=w(e,T,"outside"===f?E:z),L=c.bBox(A.node()),C=L.width,S=L.height,C<=0||S<=0))return void A.remove();"outside"===f?(P="both"===k.constraintext||"outside"===k.constraintext,O=function(t,e,r,n,a,i,o){var l,s="h"===i?Math.abs(n-r):Math.abs(e-t);s>2*v&&(l=v);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,p,h=(a.left+a.right)/2,g=(a.top+a.bottom)/2;u=c*a.width,f=c*a.height,"h"===i?e<t?(d=e-l-u/2,p=(r+n)/2):(d=e+l+u/2,p=(r+n)/2):n>r?(d=(t+e)/2,p=n+l+f/2):(d=(t+e)/2,p=n-l-f/2);return m(h,g,d,p,c,!1)}(a,i,s,u,L,M,P)):(P="both"===k.constraintext||"inside"===k.constraintext,O=function(t,e,r,n,a,i,o){var l,s,c,u,f,d,p,h=a.width,g=a.height,y=(a.left+a.right)/2,x=(a.top+a.bottom)/2,b=Math.abs(e-t),_=Math.abs(n-r);b>2*v&&_>2*v?(b-=2*(f=v),_-=2*f):f=0;h<=b&&g<=_?(d=!1,p=1):h<=_&&g<=b?(d=!0,p=1):h<g==b<_?(d=!1,p=o?Math.min(b/h,_/g):1):(d=!0,p=o?Math.min(_/h,b/g):1);d&&(d=90);d?(l=p*g,s=p*h):(l=p*h,s=p*g);"h"===i?e<t?(c=e+f+l/2,u=(r+n)/2):(c=e-f-l/2,u=(r+n)/2):n>r?(c=(t+e)/2,u=n-f-s/2):(c=(t+e)/2,u=n+f+s/2);return m(y,x,c,u,p,d)}(a,i,s,u,L,M,P));A.attr("transform",O)}(t,P,r,u,T,C,S,O),e.layerClipId&&c.hideOutsideRangePoint(r[u],P.select("text"),f,w,M.xcalendar,M.ycalendar)}else P.remove();function j(t){return 0===k.bargap&&0===k.bargroupgap?n.round(Math.round(t)-R,2):t}});var S=!1===r[0].trace.cliponaxis;c.setClipUrl(T,S?null:e.layerClipId)}),u.getComponentMethod("errorbars","plot")(M,e)}},{"../../components/color":45,"../../components/drawing":70,"../../lib":163,"../../lib/svg_text_utils":184,"../../registry":247,"./attributes":257,d3:10,"fast-isnumeric":13,tinycolor2:28}],265:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,a=t.xaxis,i=t.yaxis,o=[];if(!1===e)for(r=0;r<n.length;r++)n[r].selected=0;else for(r=0;r<n.length;r++){var l=n[r];e.contains(l.ct)?(o.push({pointNumber:r,x:a.c2d(l.x),y:i.c2d(l.y)}),l.selected=1):l.selected=0}return o}},{}],266:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").isArrayOrTypedArray,i=t("../../constants/numerical").BADNUM,o=t("../../registry"),l=t("../../plots/cartesian/axes"),s=t("./sieve.js");function c(t,e,r,a){if(a.length){var o,c,b,_,w=t._fullLayout.barmode,k="group"===w;if("overlay"===w)u(t,e,r,a);else if(k){for(o=[],c=[],b=0;b<a.length;b++)void 0===(_=a[b])[0].trace.offset?c.push(_):o.push(_);c.length&&function(t,e,r,n){var a=t._fullLayout.barnorm,i=new s(n,!1,!a);(function(t,e,r){var n,a,i,o,l=t._fullLayout,s=l.bargap,c=l.bargroupgap,u=r.positions,f=r.distinctPositions,g=r.minDiff,y=r.traces,v=u.length!==f.length,m=y.length,x=g*(1-s),b=v?x/m:x,_=b*(1-c);for(n=0;n<m;n++){a=y[n],i=a[0];var w=v?((2*n+1-m)*b-_)/2:-_/2;(o=i.t).barwidth=_,o.poffset=w,o.bargroupwidth=x,o.bardelta=g}r.binWidth=y[0][0].t.barwidth/100,d(r),p(t,e,r),h(t,e,r,v)})(t,e,i),a?(v(t,r,i),m(t,r,i)):y(t,r,i)}(t,e,r,c),o.length&&u(t,e,r,o)}else{for(o=[],c=[],b=0;b<a.length;b++)void 0===(_=a[b])[0].trace.base?c.push(_):o.push(_);c.length&&function(t,e,r,a){var o=t._fullLayout.barmode,c="stack"===o,u="relative"===o,d=t._fullLayout.barnorm,p=new s(a,u,!(d||c||u));f(t,e,p),function(t,e,r){var a,o,s,c,u=t._fullLayout.barnorm,f=x(e),d=r.traces,p=[null,null];for(a=0;a<d.length;a++)for(o=d[a],s=0;s<o.length;s++)if((c=o[s]).s!==i){var h=r.put(c.p,c.b+c.s),y=h+c.b+c.s;c.b=h,c[f]=y,u||(n(e.c2l(y))&&g(p,y),c.hasB&&n(e.c2l(h))&&g(p,h))}u||l.expand(e,p,{tozero:!0,padded:!0})}(t,r,p);for(var h=0;h<a.length;h++)for(var y=a[h],v=0;v<y.length;v++){var b=y[v];if(b.s!==i){var _=b.b+b.s===p.get(b.p,b.s);_&&(b._outmost=!0)}}d&&m(t,r,p)}(t,e,r,c),o.length&&u(t,e,r,o)}!function(t,e){var r,a,i,o=e._id.charAt(0),l={},s=1/0,c=-1/0;for(r=0;r<t.length;r++)for(i=t[r],a=0;a<i.length;a++){var u=i[a].p;n(u)&&(s=Math.min(s,u),c=Math.max(c,u))}var f=1e4/(c-s),d=l.round=function(t){return String(Math.round(f*(t-s)))};for(r=0;r<t.length;r++)for((i=t[r])[0].t.extents=l,a=0;a<i.length;a++){var p=i[a],h=p[o]-p.w/2;if(n(h)){var g=p[o]+p.w/2,y=d(p.p);l[y]?l[y]=[Math.min(h,l[y][0]),Math.max(g,l[y][1])]:l[y]=[h,g]}}}(a,e)}}function u(t,e,r,n){for(var a=t._fullLayout.barnorm,i=!a,o=0;o<n.length;o++){var l=n[o],c=new s([l],!1,i);f(t,e,c),a?(v(t,r,c),m(t,r,c)):y(t,r,c)}}function f(t,e,r){var n,a,i=t._fullLayout,o=i.bargap,l=i.bargroupgap,s=r.minDiff,c=r.traces,u=s*(1-o),f=u*(1-l),g=-f/2;for(n=0;n<c.length;n++)(a=c[n][0].t).barwidth=f,a.poffset=g,a.bargroupwidth=u,a.bardelta=s;r.binWidth=c[0][0].t.barwidth/100,d(r),p(t,e,r),h(t,e,r)}function d(t){var e,r,i,o,l,s,c=t.traces;for(e=0;e<c.length;e++){o=(i=(r=c[e])[0]).trace,s=i.t;var u,f=o.offset,d=s.poffset;if(a(f)){for(u=f.slice(0,r.length),l=0;l<u.length;l++)n(u[l])||(u[l]=d);for(l=u.length;l<r.length;l++)u.push(d);s.poffset=u}else void 0!==f&&(s.poffset=f);var p=o.width,h=s.barwidth;if(a(p)){var g=p.slice(0,r.length);for(l=0;l<g.length;l++)n(g[l])||(g[l]=h);for(l=g.length;l<r.length;l++)g.push(h);if(s.barwidth=g,void 0===f){for(u=[],l=0;l<r.length;l++)u.push(d+(h-g[l])/2);s.poffset=u}}else void 0!==p&&(s.barwidth=p,void 0===f&&(s.poffset=d+(h-p)/2))}}function p(t,e,r){for(var n=r.traces,a=x(e),i=0;i<n.length;i++)for(var o=n[i],l=o[0].t,s=l.poffset,c=Array.isArray(s),u=l.barwidth,f=Array.isArray(u),d=0;d<o.length;d++){var p=o[d],h=p.w=f?u[d]:u;p[a]=p.p+(c?s[d]:s)+h/2}}function h(t,e,r,n){var a=r.traces,i=r.distinctPositions,o=i[0],s=r.minDiff,c=s/2;l.minDtick(e,s,o,n);for(var u=Math.min.apply(Math,i)-c,f=Math.max.apply(Math,i)+c,d=0;d<a.length;d++){var p=a[d],h=p[0],g=h.trace;if(void 0!==g.width||void 0!==g.offset)for(var y=h.t,v=y.poffset,m=y.barwidth,x=Array.isArray(v),b=Array.isArray(m),_=0;_<p.length;_++){var w=p[_],k=x?v[_]:v,M=b?m[_]:m,T=w.p+k,A=T+M;u=Math.min(u,T),f=Math.max(f,A)}}l.expand(e,[u,f],{padded:!1})}function g(t,e){n(t[0])?t[0]=Math.min(t[0],e):t[0]=e,n(t[1])?t[1]=Math.max(t[1],e):t[1]=e}function y(t,e,r){for(var a=r.traces,i=x(e),o=[null,null],s=0;s<a.length;s++)for(var c=a[s],u=0;u<c.length;u++){var f=c[u],d=f.b,p=d+f.s;f[i]=p,n(e.c2l(p))&&g(o,p),f.hasB&&n(e.c2l(d))&&g(o,d)}l.expand(e,o,{tozero:!0,padded:!0})}function v(t,e,r){for(var n=r.traces,a=0;a<n.length;a++)for(var o=n[a],l=0;l<o.length;l++){var s=o[l];s.s!==i&&r.put(s.p,s.b+s.s)}}function m(t,e,r){var a=r.traces,o=x(e),s="fraction"===t._fullLayout.barnorm?1:100,c=s/1e9,u=e.l2c(e.c2l(0)),f="stack"===t._fullLayout.barmode?s:u,d=[u,f],p=!1;function h(t){n(e.c2l(t))&&(t<u-c||t>f+c||!n(u))&&(p=!0,g(d,t))}for(var y=0;y<a.length;y++)for(var v=a[y],m=0;m<v.length;m++){var b=v[m];if(b.s!==i){var _=Math.abs(s/r.get(b.p,b.s));b.b*=_,b.s*=_;var w=b.b,k=w+b.s;b[o]=k,h(k),b.hasB&&h(w)}}l.expand(e,d,{tozero:!0,padded:p})}function x(t){return t._id.charAt(0)}e.exports=function(t,e){var r,n=e.xaxis,a=e.yaxis,i=t._fullData,l=t.calcdata,s=[],u=[];for(r=0;r<i.length;r++){var f=i[r];!0===f.visible&&o.traceIs(f,"bar")&&f.xaxis===n._id&&f.yaxis===a._id&&("h"===f.orientation?s.push(l[r]):u.push(l[r]))}c(t,n,a,u),c(t,a,n,s)}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207,"../../registry":247,"./sieve.js":267,"fast-isnumeric":13}],267:[function(t,e,r){"use strict";e.exports=i;var n=t("../../lib"),a=t("../../constants/numerical").BADNUM;function i(t,e,r){this.traces=t,this.separateNegativeValues=e,this.dontMergeOverlappingData=r;for(var i=1/0,o=[],l=0;l<t.length;l++){for(var s=t[l],c=0;c<s.length;c++){var u=s[c];u.p!==a&&o.push(u.p)}s[0]&&s[0].width1&&(i=Math.min(s[0].width1,i))}this.positions=o;var f=n.distinctVals(o);this.distinctPositions=f.vals,1===f.vals.length&&i!==1/0?this.minDiff=i:this.minDiff=Math.min(f.minDiff,i),this.binWidth=this.minDiff,this.bins={}}i.prototype.put=function(t,e){var r=this.getLabel(t,e),n=this.bins[r]||0;return this.bins[r]=n+e,n},i.prototype.get=function(t,e){var r=this.getLabel(t,e);return this.bins[r]||0},i.prototype.getLabel=function(t,e){return(e<0&&this.separateNegativeValues?"v":"^")+(this.dontMergeOverlappingData?t:Math.round(t/this.binWidth))}},{"../../constants/numerical":145,"../../lib":163}],268:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/drawing"),i=t("../../registry");function o(t,e,r){var i=t.selectAll("path"),o=t.selectAll("text");a.pointStyle(i,e,r),o.each(function(t){var r,i=n.select(this);function o(e){var n=r[e];return Array.isArray(n)?n[t.i]:n}i.classed("bartext-inside")?r=e.insidetextfont:i.classed("bartext-outside")&&(r=e.outsidetextfont),r||(r=e.textfont),a.font(i,o("family"),o("size"),o("color"))})}e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.bars"),a=r.size(),l=t._fullLayout;r.style("opacity",function(t){return t[0].trace.opacity}).each(function(t){("stack"===l.barmode&&a>1||0===l.bargap&&0===l.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(e){o(n.select(this),e[0].trace,t)}),i.getComponentMethod("errorbars","style")(r)},styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace;n.selectedpoints?(a.selectedPointStyle(r.selectAll("path"),n),a.selectedTextStyle(r.selectAll("text"),n)):o(r,n,t)}}},{"../../components/drawing":70,"../../registry":247,d3:10}],269:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,l){r("marker.color",o),a(t,"marker")&&i(t,e,l,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),a(t,"marker.line")&&i(t,e,l,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width"),r("marker.opacity"),r("selected.marker.color"),r("unselected.marker.color")}},{"../../components/color":45,"../../components/colorscale/defaults":55,"../../components/colorscale/has_colorscale":59}],270:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),a=t("../../components/color/attributes"),i=t("../../lib/extend").extendFlat,o=n.marker,l=o.line;e.exports={y:{valType:"data_array",editType:"calc+clearAxisTypes"},x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",editType:"calc+clearAxisTypes"},y0:{valType:"any",editType:"calc+clearAxisTypes"},name:{valType:"string",editType:"calc+clearAxisTypes"},text:i({},n.text,{}),whiskerwidth:{valType:"number",min:0,max:1,dflt:.5,editType:"calcIfAutorange"},notched:{valType:"boolean",editType:"calcIfAutorange"},notchwidth:{valType:"number",min:0,max:.5,dflt:.25,editType:"calcIfAutorange"},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers",editType:"calcIfAutorange"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1,editType:"calcIfAutorange"},jitter:{valType:"number",min:0,max:1,editType:"calcIfAutorange"},pointpos:{valType:"number",min:-2,max:2,editType:"calcIfAutorange"},orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)",editType:"style"},symbol:i({},o.symbol,{arrayOk:!1,editType:"plot"}),opacity:i({},o.opacity,{arrayOk:!1,dflt:1,editType:"style"}),size:i({},o.size,{arrayOk:!1,editType:"calcIfAutorange"}),color:i({},o.color,{arrayOk:!1,editType:"style"}),line:{color:i({},l.color,{arrayOk:!1,dflt:a.defaultLine,editType:"style"}),width:i({},l.width,{arrayOk:!1,dflt:0,editType:"style"}),outliercolor:{valType:"color",editType:"style"},outlierwidth:{valType:"number",min:0,dflt:1,editType:"style"},editType:"style"},editType:"plot"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:n.fillcolor,selected:{marker:n.selected.marker,editType:"style"},unselected:{marker:n.unselected.marker,editType:"style"},hoveron:{valType:"flaglist",flags:["boxes","points"],dflt:"boxes+points",editType:"style"}}},{"../../components/color/attributes":44,"../../lib/extend":157,"../scatter/attributes":314}],271:[function(t,e,r){"use strict";e.exports={boxmode:{valType:"enumerated",values:["group","overlay"],dflt:"overlay",editType:"calc"},boxgap:{valType:"number",min:0,max:1,dflt:.3,editType:"calc"},boxgroupgap:{valType:"number",min:0,max:1,dflt:.3,editType:"calc"}}},{}],272:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("./layout_attributes");function o(t,e,r,a,i){for(var o,l=i+"Layout",s=0;s<r.length;s++)if(n.traceIs(r[s],l)){o=!0;break}o&&(a(i+"mode"),a(i+"gap"),a(i+"groupgap"))}e.exports={supplyLayoutDefaults:function(t,e,r){o(0,0,r,function(r,n){return a.coerce(t,e,i,r,n)},"box")},_supply:o}},{"../../lib":163,"../../registry":247,"./layout_attributes":271}],273:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib"),i=t("../../components/drawing"),o=5,l=.01;function s(t,e,r,i){var o,l,s=e.pos,c=e.val,u=i.bPos,f=i.wdPos||0,d=i.bPosPxOffset||0,p=r.whiskerwidth||0,h=r.notched||!1,g=h?1-2*r.notchwidth:1;Array.isArray(i.bdPos)?(o=i.bdPos[0],l=i.bdPos[1]):(o=i.bdPos,l=i.bdPos);var y=t.selectAll("path.box").data("violin"!==r.type||r.box?a.identity:[]);y.enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","box"),y.exit().remove(),y.each(function(t){var e=t.pos,i=s.c2p(e+u,!0)+d,y=s.c2p(e+u-o,!0)+d,v=s.c2p(e+u+l,!0)+d,m=s.c2p(e+u-f,!0)+d,x=s.c2p(e+u+f,!0)+d,b=s.c2p(e+u-o*g,!0)+d,_=s.c2p(e+u+l*g,!0)+d,w=c.c2p(t.q1,!0),k=c.c2p(t.q3,!0),M=a.constrain(c.c2p(t.med,!0),Math.min(w,k)+1,Math.max(w,k)-1),T=void 0===t.lf||!1===r.boxpoints,A=c.c2p(T?t.min:t.lf,!0),L=c.c2p(T?t.max:t.uf,!0),C=c.c2p(t.ln,!0),S=c.c2p(t.un,!0);"h"===r.orientation?n.select(this).attr("d","M"+M+","+b+"V"+_+"M"+w+","+y+"V"+v+(h?"H"+C+"L"+M+","+_+"L"+S+","+v:"")+"H"+k+"V"+y+(h?"H"+S+"L"+M+","+b+"L"+C+","+y:"")+"ZM"+w+","+i+"H"+A+"M"+k+","+i+"H"+L+(0===p?"":"M"+A+","+m+"V"+x+"M"+L+","+m+"V"+x)):n.select(this).attr("d","M"+b+","+M+"H"+_+"M"+y+","+w+"H"+v+(h?"V"+C+"L"+_+","+M+"L"+v+","+S:"")+"V"+k+"H"+y+(h?"V"+S+"L"+b+","+M+"L"+y+","+C:"")+"ZM"+i+","+w+"V"+A+"M"+i+","+k+"V"+L+(0===p?"":"M"+m+","+A+"H"+x+"M"+m+","+L+"H"+x))})}function c(t,e,r,n){var s=e.x,c=e.y,u=n.bdPos,f=n.bPos,d=r.boxpoints||r.points;a.seedPseudoRandom();var p=t.selectAll("g.points").data(d?function(t){return t.forEach(function(t){t.t=n,t.trace=r}),t}:[]);p.enter().append("g").attr("class","points"),p.exit().remove();var h=p.selectAll("path").data(function(t){var e,n,i="all"===d?t.pts:t.pts.filter(function(e){return e.v<t.lf||e.v>t.uf}),s=Math.max((t.max-t.min)/10,t.q3-t.q1),c=1e-9*s,p=s*l,h=[],g=0;if(r.jitter){if(0===s)for(g=1,h=new Array(i.length),e=0;e<i.length;e++)h[e]=1;else for(e=0;e<i.length;e++){var y=Math.max(0,e-o),v=i[y].v,m=Math.min(i.length-1,e+o),x=i[m].v;"all"!==d&&(i[e].v<t.lf?x=Math.min(x,t.lf):v=Math.max(v,t.uf));var b=Math.sqrt(p*(m-y)/(x-v+c))||0;b=a.constrain(Math.abs(b),0,1),h.push(b),g=Math.max(b,g)}n=2*r.jitter/(g||1)}for(e=0;e<i.length;e++){var _=i[e],w=_.v,k=r.jitter?n*h[e]*(a.pseudoRandom()-.5):0,M=t.pos+f+u*(r.pointpos+k);"h"===r.orientation?(_.y=M,_.x=w):(_.x=M,_.y=w),"suspectedoutliers"===d&&w<t.uo&&w>t.lo&&(_.so=!0)}return i});h.enter().append("path").classed("point",!0),h.exit().remove(),h.call(i.translatePoints,s,c)}function u(t,e,r,i){var o,l,s=e.pos,c=e.val,u=i.bPos,f=i.bPosPxOffset||0,d=r.boxmean||(r.meanline||{}).visible;Array.isArray(i.bdPos)?(o=i.bdPos[0],l=i.bdPos[1]):(o=i.bdPos,l=i.bdPos);var p=t.selectAll("path.mean").data("box"===r.type&&r.boxmean||"violin"===r.type&&r.box&&r.meanline?a.identity:[]);p.enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}),p.exit().remove(),p.each(function(t){var e=s.c2p(t.pos+u,!0)+f,a=s.c2p(t.pos+u-o,!0)+f,i=s.c2p(t.pos+u+l,!0)+f,p=c.c2p(t.mean,!0),h=c.c2p(t.mean-t.sd,!0),g=c.c2p(t.mean+t.sd,!0);"h"===r.orientation?n.select(this).attr("d","M"+p+","+a+"V"+i+("sd"===d?"m0,0L"+h+","+e+"L"+p+","+a+"L"+g+","+e+"Z":"")):n.select(this).attr("d","M"+a+","+p+"H"+i+("sd"===d?"m0,0L"+e+","+h+"L"+a+","+p+"L"+e+","+g+"Z":""))})}e.exports={plot:function(t,e,r,a){var i=t._fullLayout,o=e.xaxis,l=e.yaxis,f=a.selectAll("g.trace.boxes").data(r,function(t){return t[0].trace.uid});f.enter().append("g").attr("class","trace boxes"),f.exit().remove(),f.order(),f.each(function(t){var r=t[0],a=r.t,f=r.trace,d=n.select(this);e.isRangePlot||(r.node3=d);var p,h,g=i._numBoxes,y=1-i.boxgap,v="group"===i.boxmode&&g>1,m=a.dPos*y*(1-i.boxgroupgap)/(v?g:1),x=v?2*a.dPos*((a.num+.5)/g-.5)*y:0,b=m*f.whiskerwidth;!0!==f.visible||a.empty?d.remove():("h"===f.orientation?(p=l,h=o):(p=o,h=l),a.bPos=x,a.bdPos=m,a.wdPos=b,a.wHover=a.dPos*(v?y/g:1),s(d,{pos:p,val:h},f,a),c(d,{x:o,y:l},f,a),u(d,{pos:p,val:h},f,a))})},plotBoxAndWhiskers:s,plotPoints:c,plotBoxMean:u}},{"../../components/drawing":70,"../../lib":163,d3:10}],274:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),a=t("../../lib"),i=["v","h"];function o(t,e,r,i,o){var l,s,c,u=e.calcdata,f=e._fullLayout,d=[],p="violin"===t?"_numViolins":"_numBoxes";for(l=0;l<r.length;l++)for(c=u[r[l]],s=0;s<c.length;s++)d.push(c[s].pos);if(d.length){var h=a.distinctVals(d),g=h.minDiff/2;for(d.length===h.vals.length&&(f[p]=1),n.minDtick(i,h.minDiff,h.vals[0],!0),l=0;l<r.length;l++)(c=u[r[l]])[0].t.dPos=g;var y=(1-f[t+"gap"])*(1-f[t+"groupgap"])*g/f[p];n.expand(i,h.vals,{vpadminus:g+o[0]*y,vpadplus:g+o[1]*y})}}e.exports={setPositions:function(t,e){for(var r=t.calcdata,n=e.xaxis,a=e.yaxis,l=0;l<i.length;l++){for(var s=i[l],c="h"===s?a:n,u=[],f=0,d=0,p=0;p<r.length;p++){var h=r[p],g=h[0].t,y=h[0].trace;!0!==y.visible||"box"!==y.type&&"candlestick"!==y.type||g.empty||(y.orientation||"v")!==s||y.xaxis!==n._id||y.yaxis!==a._id||(u.push(p),y.boxpoints&&(f=Math.max(f,y.jitter-y.pointpos-1),d=Math.max(d,y.jitter+y.pointpos-1)))}o("box",t,u,c,[f,d])}},setPositionOffset:o}},{"../../lib":163,"../../plots/cartesian/axes":207}],275:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/color"),i=t("../../components/drawing");e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.boxes");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(e){var r=n.select(this),o=e[0].trace,l=o.line.width;function s(t,e,r,n){t.style("stroke-width",e+"px").call(a.stroke,r).call(a.fill,n)}var c=r.selectAll("path.box");if("candlestick"===o.type)c.each(function(t){var e=n.select(this),r=o[t.dir];s(e,r.line.width,r.line.color,r.fillcolor),e.style("opacity",o.selectedpoints&&!t.selected?.3:1)});else{s(c,l,o.line.color,o.fillcolor),r.selectAll("path.mean").style({"stroke-width":l,"stroke-dasharray":2*l+"px,"+l+"px"}).call(a.stroke,o.line.color);var u=r.selectAll("path.point");i.pointStyle(u,o,t)}})},styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace,a=r.selectAll("path.point");n.selectedpoints?i.selectedPointStyle(a,n):i.pointStyle(a,n,t)}}},{"../../components/color":45,"../../components/drawing":70,d3:10}],276:[function(t,e,r){"use strict";var n=t("../../lib").extendFlat,a=t("../ohlc/attributes"),i=t("../box/attributes");function o(t){return{line:{color:n({},i.line.color,{dflt:t}),width:i.line.width,editType:"style"},fillcolor:i.fillcolor,editType:"style"}}e.exports={x:a.x,open:a.open,high:a.high,low:a.low,close:a.close,line:{width:n({},i.line.width,{}),editType:"style"},increasing:o(a.increasing.line.color.dflt),decreasing:o(a.decreasing.line.color.dflt),text:a.text,whiskerwidth:n({},i.whiskerwidth,{dflt:0})}},{"../../lib":163,"../box/attributes":270,"../ohlc/attributes":292}],277:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../ohlc/calc").calcCommon;function o(t,e,r,n){return{min:r,q1:Math.min(t,n),med:n,q3:Math.max(t,n),max:e}}e.exports=function(t,e){var r=t._fullLayout,l=a.getFromId(t,e.xaxis),s=a.getFromId(t,e.yaxis),c=l.makeCalcdata(e,"x"),u=i(t,e,c,s,o);return u.length?(n.extendFlat(u[0].t,{num:r._numBoxes,dPos:n.distinctVals(c).minDiff/2,posLetter:"x",valLetter:"y"}),r._numBoxes++,u):[{t:{empty:!0}}]}},{"../../lib":163,"../../plots/cartesian/axes":207,"../ohlc/calc":293}],278:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../components/color"),i=t("../ohlc/ohlc_defaults"),o=t("./attributes");function l(t,e,r,n){var i=r(n+".line.color");r(n+".line.width",e.line.width),r(n+".fillcolor",a.addOpacity(i,.5))}e.exports=function(t,e,r,a){function s(r,a){return n.coerce(t,e,o,r,a)}i(t,e,s,a)?(s("line.width"),l(t,e,s,"increasing"),l(t,e,s,"decreasing"),s("text"),s("whiskerwidth"),a._requestRangeslider[e.xaxis]=!0):e.visible=!1}},{"../../components/color":45,"../../lib":163,"../ohlc/ohlc_defaults":297,"./attributes":276}],279:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"candlestick",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","showLegend","candlestick","boxLayout"],meta:{},attributes:t("./attributes"),layoutAttributes:t("../box/layout_attributes"),supplyLayoutDefaults:t("../box/layout_defaults").supplyLayoutDefaults,setPositions:t("../box/set_positions").setPositions,supplyDefaults:t("./defaults"),calc:t("./calc"),plot:t("../box/plot").plot,layerName:"boxlayer",style:t("../box/style").style,hoverPoints:t("../ohlc/hover"),selectPoints:t("../ohlc/select")}},{"../../plots/cartesian":218,"../box/layout_attributes":271,"../box/layout_defaults":272,"../box/plot":273,"../box/set_positions":274,"../box/style":275,"../ohlc/hover":295,"../ohlc/select":299,"./attributes":276,"./calc":277,"./defaults":278}],280:[function(t,e,r){"use strict";var n=t("../bar/attributes");function a(t){var e={};e["autobin"+t]=!1;var r={};return r["^autobin"+t]=!1,{start:{valType:"any",dflt:null,editType:"calc",impliedEdits:r},end:{valType:"any",dflt:null,editType:"calc",impliedEdits:r},size:{valType:"any",dflt:null,editType:"calc",impliedEdits:r},editType:"calc",impliedEdits:e}}e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},text:n.text,orientation:n.orientation,histfunc:{valType:"enumerated",values:["count","sum","avg","min","max"],dflt:"count",editType:"calc"},histnorm:{valType:"enumerated",values:["","percent","probability","density","probability density"],dflt:"",editType:"calc"},cumulative:{enabled:{valType:"boolean",dflt:!1,editType:"calc"},direction:{valType:"enumerated",values:["increasing","decreasing"],dflt:"increasing",editType:"calc"},currentbin:{valType:"enumerated",values:["include","exclude","half"],dflt:"include",editType:"calc"},editType:"calc"},autobinx:{valType:"boolean",dflt:null,editType:"calc",impliedEdits:{"xbins.start":void 0,"xbins.end":void 0,"xbins.size":void 0}},nbinsx:{valType:"integer",min:0,dflt:0,editType:"calc"},xbins:a("x"),autobiny:{valType:"boolean",dflt:null,editType:"calc",impliedEdits:{"ybins.start":void 0,"ybins.end":void 0,"ybins.size":void 0}},nbinsy:{valType:"integer",min:0,dflt:0,editType:"calc"},ybins:a("y"),marker:n.marker,selected:n.selected,unselected:n.unselected,_deprecated:{bardir:n._deprecated.bardir}}},{"../bar/attributes":257}],281:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=t.length,n=0,a=0;a<r;a++)e[a]?(t[a]/=e[a],n+=t[a]):t[a]=null;return n}},{}],282:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){r(t+"bins.start"),r(t+"bins.end"),r(t+"bins.size"),!1!==r("autobin"+t)&&r("nbins"+t)}),e}},{}],283:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,a){var i=a[e];return n(i)?(i=Number(i),r[t]+=i,i):0},avg:function(t,e,r,a,i){var o=a[e];return n(o)&&(o=Number(o),r[t]+=o,i[t]++),0},min:function(t,e,r,a){var i=a[e];if(n(i)){if(i=Number(i),!n(r[t]))return r[t]=i,i;if(r[t]>i){var o=i-r[t];return r[t]=i,o}}return 0},max:function(t,e,r,a){var i=a[e];if(n(i)){if(i=Number(i),!n(r[t]))return r[t]=i,i;if(r[t]<i){var o=i-r[t];return r[t]=i,o}}return 0}}},{"fast-isnumeric":13}],284:[function(t,e,r){"use strict";var n=t("../../constants/numerical"),a=n.ONEAVGYEAR,i=n.ONEAVGMONTH,o=n.ONEDAY,l=n.ONEHOUR,s=n.ONEMIN,c=n.ONESEC,u=t("../../plots/cartesian/axes").tickIncrement;function f(t,e,r,n){if(t*e<=0)return 1/0;for(var a=Math.abs(e-t),i="date"===r.type,o=d(a,i),l=0;l<10;l++){var s=d(80*o,i);if(o===s)break;if(!p(s,t,e,i,r,n))break;o=s}return o}function d(t,e){return e&&t>c?t>o?t>1.1*a?a:t>1.1*i?i:o:t>l?l:t>s?s:c:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function p(t,e,r,n,i,l){if(n&&t>o){var s=h(e,i,l),c=h(r,i,l),u=t===a?0:1;return s[u]!==c[u]}return Math.floor(r/t)-Math.floor(e/t)>.1}function h(t,e,r){var n=e.c2d(t,a,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}e.exports=function(t,e,r,n,i){var l,s,c=-1.1*e,d=-.1*e,p=t-d,h=r[0],g=r[1],y=Math.min(f(h+d,h+p,n,i),f(g+d,g+p,n,i)),v=Math.min(f(h+c,h+d,n,i),f(g+c,g+d,n,i));if(y>v&&v<Math.abs(g-h)/4e3?(l=y,s=!1):(l=Math.min(y,v),s=!0),"date"===n.type&&l>o){var m=l===a?1:6,x=l===a?"M12":"M1";return function(e,r){var o=n.c2d(e,a,i),l=o.indexOf("-",m);l>0&&(o=o.substr(0,l));var c=n.d2c(o,0,i);if(c<e){var f=u(c,x,!1,i);(c+f)/2<e+t&&(c=f)}return r&&s?u(c,x,!0,i):c}}return function(e,r){var n=l*Math.round(e/l);return n+l/10<e&&n+.9*l<e+t&&(n+=l),r&&s&&(n-=l),n}}},{"../../constants/numerical":145,"../../plots/cartesian/axes":207}],285:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../plots/cartesian/axes"),o=t("../bar/arrays_to_calcdata"),l=t("./bin_functions"),s=t("./norm_functions"),c=t("./average"),u=t("./clean_bins"),f=t("../../constants/numerical").ONEAVGMONTH,d=t("./bin_label_vals");function p(t,e,r,a,o){var l,s,c,u,f,d=a+"bins",p="overlay"===t._fullLayout.barmode;if(e._autoBinFinished)delete e._autoBinFinished;else{var v=p?[e]:g(t,e),m=[],x=1/0,b=1/0,_=-1/0,w="autobin"+a;for(l=0;l<v.length;l++){f=(s=v[l])._pos0=r.makeCalcdata(s,a);var k=s[d];if(s[w]||!k||null===k.start||null===k.end){c=s[a+"calendar"];var M=s.cumulative;if(k=i.autoBin(f,r,s["nbins"+a],!1,c),p&&0===k._dataSpan&&"category"!==r.type){if(o)return[k,f,!0];k=h(t,e,r,a,d)}M.enabled&&"include"!==M.currentbin&&("decreasing"===M.direction?b=Math.min(b,r.r2c(k.start,0,c)-k.size):_=Math.max(_,r.r2c(k.end,0,c)+k.size)),m.push(s)}else u||(u={size:k.size,start:r.r2c(k.start,0,c),end:r.r2c(k.end,0,c)});x=y(x,k.size),b=Math.min(b,r.r2c(k.start,0,c)),_=Math.max(_,r.r2c(k.end,0,c)),l&&(s._autoBinFinished=1)}if(u&&n(u.size)&&n(x)){x=x>u.size/1.9?u.size:u.size/Math.ceil(u.size/x);var T=u.start+(u.size-x)/2;b=T-x*Math.ceil((T-b)/x)}for(l=0;l<m.length;l++)c=(s=m[l])[a+"calendar"],s._input[d]=s[d]={start:r.c2r(b,0,c),end:r.c2r(_,0,c),size:x},s._input[w]=s[w]}return f=e._pos0,delete e._pos0,[e[d],f]}function h(t,e,r,n,i){var o,l,s=g(t,e),c=!1,u=1/0,f=[e];for(o=0;o<s.length;o++)if((l=s[o])===e)c=!0;else if(c){var d=p(t,l,r,n,!0),h=d[0],y=d[2];l._autoBinFinished=1,l._pos0=d[1],y?f.push(l):u=Math.min(u,h.size)}else u=Math.min(u,l[i].size);var v=new Array(f.length);for(o=0;o<f.length;o++)for(var m=f[o]._pos0,x=0;x<m.length;x++)if(void 0!==m[x]){v[o]=m[x];break}for(isFinite(u)||(u=a.distinctVals(v).minDiff),o=0;o<f.length;o++){var b=(l=f[o])[n+"calendar"];l._input[i]=l[i]={start:r.c2r(v[o]-u/2,0,b),end:r.c2r(v[o]+u/2,0,b),size:u}}return e[i]}function g(t,e){for(var r=e.xaxis,n=e.yaxis,a=e.orientation,i=[],o=t._fullData,l=0;l<o.length;l++){var s=o[l];"histogram"===s.type&&!0===s.visible&&s.orientation===a&&s.xaxis===r&&s.yaxis===n&&i.push(s)}return i}function y(t,e){if(t===1/0)return e;var r=v(t);return v(e)<r?e:t}function v(t){return n(t)?t:"string"==typeof t&&"M"===t.charAt(0)?f*+t.substr(1):1/0}e.exports=function(t,e){if(!0===e.visible){var r,f=[],h=[],g=i.getFromId(t,"h"===e.orientation?e.yaxis||"y":e.xaxis||"x"),y="h"===e.orientation?"y":"x",v={x:"y",y:"x"}[y],m=e[y+"calendar"],x=e.cumulative;u(e,g,y);var b,_,w,k=p(t,e,g,y),M=k[0],T=k[1],A="string"==typeof M.size,L=[],C=A?L:M,S=[],O=[],P=[],D=0,z=e.histnorm,E=e.histfunc,I=-1!==z.indexOf("density");x.enabled&&I&&(z=z.replace(/ ?density$/,""),I=!1);var N,R="max"===E||"min"===E?null:0,F=l.count,j=s[z],B=!1,H=function(t){return g.r2c(t,0,m)};for(a.isArrayOrTypedArray(e[v])&&"count"!==E&&(N=e[v],B="avg"===E,F=l[E]),r=H(M.start),_=H(M.end)+(r-i.tickIncrement(r,M.size,!1,m))/1e6;r<_&&f.length<1e6&&(b=i.tickIncrement(r,M.size,!1,m),f.push((r+b)/2),h.push(R),P.push([]),L.push(r),I&&S.push(1/(b-r)),B&&O.push(0),!(b<=r));)r=b;L.push(r),A||"date"!==g.type||(C={start:H(C.start),end:H(C.end),size:C.size});var q,V=h.length,U=!0,G=1/0,Y=1/0,X={};for(r=0;r<T.length;r++){var Z=T[r];(w=a.findBin(Z,C))>=0&&w<V&&(D+=F(w,r,h,N,O),U&&P[w].length&&Z!==T[P[w][0]]&&(U=!1),P[w].push(r),X[r]=w,G=Math.min(G,Z-L[w]),Y=Math.min(Y,L[w+1]-Z))}U||(q=d(G,Y,L,g,m)),B&&(D=c(h,O)),j&&j(h,D,S),x.enabled&&function(t,e,r){var n,a,i;function o(e){i=t[e],t[e]/=2}function l(e){a=t[e],t[e]=i+a/2,i+=a}if("half"===r)if("increasing"===e)for(o(0),n=1;n<t.length;n++)l(n);else for(o(t.length-1),n=t.length-2;n>=0;n--)l(n);else if("increasing"===e){for(n=1;n<t.length;n++)t[n]+=t[n-1];"exclude"===r&&(t.unshift(0),t.pop())}else{for(n=t.length-2;n>=0;n--)t[n]+=t[n+1];"exclude"===r&&(t.push(0),t.shift())}}(h,x.direction,x.currentbin);var W=Math.min(f.length,h.length),Q=[],J=0,$=W-1;for(r=0;r<W;r++)if(h[r]){J=r;break}for(r=W-1;r>=J;r--)if(h[r]){$=r;break}for(r=J;r<=$;r++)if(n(f[r])&&n(h[r])){var K={p:f[r],s:h[r],b:0};x.enabled||(K.pts=P[r],U?K.p0=K.p1=P[r].length?T[P[r][0]]:f[r]:(K.p0=q(L[r]),K.p1=q(L[r+1],!0))),Q.push(K)}return 1===Q.length&&(Q[0].width1=i.tickIncrement(Q[0].p,M.size,!1,m)-Q[0].p),o(Q,e),a.isArrayOrTypedArray(e.selectedpoints)&&a.tagSelected(Q,e,X),Q}}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207,"../bar/arrays_to_calcdata":256,"./average":281,"./bin_functions":283,"./bin_label_vals":284,"./clean_bins":286,"./norm_functions":291,"fast-isnumeric":13}],286:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").cleanDate,i=t("../../constants/numerical"),o=i.ONEDAY,l=i.BADNUM;e.exports=function(t,e,r){var i=e.type,s=r+"bins",c=t[s];c||(c=t[s]={});var u="date"===i?function(t){return t||0===t?a(t,l,c.calendar):null}:function(t){return n(t)?Number(t):null};c.start=u(c.start),c.end=u(c.end);var f="date"===i?o:1,d=c.size;if(n(d))c.size=d>0?Number(d):f;else if("string"!=typeof d)c.size=f;else{var p=d.charAt(0),h=d.substr(1);((h=n(h)?Number(h):0)<=0||"date"!==i||"M"!==p||h!==Math.round(h))&&(c.size=f)}var g="autobin"+r;"boolean"!=typeof t[g]&&(t[g]=t._fullInput[g]=t._input[g]=!((c.start||0===c.start)&&(c.end||0===c.end))),t[g]||(delete t["nbins"+r],delete t._fullInput["nbins"+r])}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],287:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../components/color"),o=t("./bin_defaults"),l=t("../bar/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,c){function u(r,n){return a.coerce(t,e,s,r,n)}var f=u("x"),d=u("y");u("cumulative.enabled")&&(u("cumulative.direction"),u("cumulative.currentbin")),u("text");var p=u("orientation",d&&!f?"h":"v"),h="v"===p?"x":"y",g="v"===p?"y":"x",y=f&&d?Math.min(f.length&&d.length):(e[h]||[]).length;if(y){e._length=y,n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],c),e[g]&&u("histfunc"),o(t,e,u,[h]),l(t,e,u,r,c);var v=n.getComponentMethod("errorbars","supplyDefaults");v(t,e,i.defaultLine,{axis:"y"}),v(t,e,i.defaultLine,{axis:"x",inherit:"y"}),a.coerceSelectionMarkerOpacity(e,u)}else e.visible=!1}},{"../../components/color":45,"../../lib":163,"../../registry":247,"../bar/style_defaults":269,"./attributes":280,"./bin_defaults":282}],288:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,a){if(t.x="xVal"in e?e.xVal:e.x,t.y="yVal"in e?e.yVal:e.y,e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),!(r.cumulative||{}).enabled){var i,o=Array.isArray(a)?n[0].pts[a[0]][a[1]]:n[a].pts;if(t.pointNumbers=o,t.binNumber=t.pointNumber,delete t.pointNumber,delete t.pointIndex,r._indexToPoints){i=[];for(var l=0;l<o.length;l++)i=i.concat(r._indexToPoints[o[l]])}else i=o;t.pointIndices=i}return t}},{}],289:[function(t,e,r){"use strict";var n=t("../bar/hover"),a=t("../../plots/cartesian/axes").hoverLabelText;e.exports=function(t,e,r,i){var o=n(t,e,r,i);if(o){var l=(t=o[0]).cd[t.index],s=t.cd[0].trace;if(!s.cumulative.enabled){var c="h"===s.orientation?"y":"x";t[c+"Label"]=a(t[c+"a"],l.p0,l.p1)}return o}}},{"../../plots/cartesian/axes":207,"../bar/hover":260}],290:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.layerName="barlayer",n.style=t("../bar/style").style,n.styleOnSelect=t("../bar/style").styleOnSelect,n.colorbar=t("../scatter/marker_colorbar"),n.hoverPoints=t("./hover"),n.selectPoints=t("../bar/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":218,"../bar/layout_attributes":262,"../bar/layout_defaults":263,"../bar/plot":264,"../bar/select":265,"../bar/set_positions":266,"../bar/style":268,"../scatter/marker_colorbar":331,"./attributes":280,"./calc":285,"./defaults":287,"./event_data":288,"./hover":289}],291:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,a=0;a<r;a++)t[a]*=n},probability:function(t,e){for(var r=t.length,n=0;n<r;n++)t[n]/=e},density:function(t,e,r,n){var a=t.length;n=n||1;for(var i=0;i<a;i++)t[i]*=r[i]*n},"probability density":function(t,e,r,n){var a=t.length;n&&(e/=n);for(var i=0;i<a;i++)t[i]*=r[i]/e}}},{}],292:[function(t,e,r){"use strict";var n=t("../../lib").extendFlat,a=t("../scatter/attributes"),i=t("../../components/drawing/attributes").dash,o=a.line;function l(t){return{line:{color:n({},o.color,{dflt:t}),width:o.width,dash:i,editType:"style"},editType:"style"}}e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},open:{valType:"data_array",editType:"calc"},high:{valType:"data_array",editType:"calc"},low:{valType:"data_array",editType:"calc"},close:{valType:"data_array",editType:"calc"},line:{width:n({},o.width,{}),dash:n({},i,{}),editType:"style"},increasing:l("#3D9970"),decreasing:l("#FF4136"),text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},tickwidth:{valType:"number",min:0,max:.5,dflt:.3,editType:"calcIfAutorange"}}},{"../../components/drawing/attributes":69,"../../lib":163,"../scatter/attributes":314}],293:[function(t,e,r){"use strict";var n=t("../../lib"),a=n._,i=t("../../plots/cartesian/axes"),o=t("../../constants/numerical").BADNUM;function l(t,e,r,n){return{o:t,h:e,l:r,c:n}}function s(t,e,r,n,l){for(var s=n.makeCalcdata(e,"open"),c=n.makeCalcdata(e,"high"),u=n.makeCalcdata(e,"low"),f=n.makeCalcdata(e,"close"),d=Array.isArray(e.text),p=!0,h=null,g=[],y=0;y<r.length;y++){var v=r[y],m=s[y],x=c[y],b=u[y],_=f[y];if(v!==o&&m!==o&&x!==o&&b!==o&&_!==o){_===m?null!==h&&_!==h&&(p=_>h):p=_>m,h=_;var w=l(m,x,b,_);w.pos=v,w.yc=(m+_)/2,w.i=y,w.dir=p?"increasing":"decreasing",d&&(w.tx=e.text[y]),g.push(w)}}return i.expand(n,u.concat(c),{padded:!0}),g.length&&(g[0].t={labels:{open:a(t,"open:")+" ",high:a(t,"high:")+" ",low:a(t,"low:")+" ",close:a(t,"close:")+" "}}),g}e.exports={calc:function(t,e){var r=i.getFromId(t,e.xaxis),a=i.getFromId(t,e.yaxis),o=function(t,e,r){var a=r._minDiff;if(!a){var i,o=t._fullData,l=[];for(a=1/0,i=0;i<o.length;i++){var s=o[i];if("ohlc"===s.type&&!0===s.visible&&s.xaxis===e._id){l.push(s);var c=e.makeCalcdata(s,"x");s._xcalc=c;var u=n.distinctVals(c).minDiff;u&&isFinite(u)&&(a=Math.min(a,u))}}for(a===1/0&&(a=1),i=0;i<l.length;i++)l[i]._minDiff=a}return a*r.tickwidth}(t,r,e),c=e._minDiff;e._minDiff=null;var u=e._xcalc;e._xcalc=null;var f=s(t,e,u,a,l);return i.expand(r,u,{vpad:c/2}),f.length?(n.extendFlat(f[0].t,{wHover:c/2,tickLen:o}),f):[{t:{empty:!0}}]},calcCommon:s}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207}],294:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./ohlc_defaults"),i=t("./attributes");function o(t,e,r,n){r(n+".line.color"),r(n+".line.width",e.line.width),r(n+".line.dash",e.line.dash)}e.exports=function(t,e,r,l){function s(r,a){return n.coerce(t,e,i,r,a)}a(t,e,s,l)?(s("line.width"),s("line.dash"),o(t,e,s,"increasing"),o(t,e,s,"decreasing"),s("text"),s("tickwidth"),l._requestRangeslider[e.xaxis]=!0):e.visible=!1}},{"../../lib":163,"./attributes":292,"./ohlc_defaults":297}],295:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),a=t("../../components/fx"),i=t("../../components/color"),o=t("../scatter/fill_hover_text"),l={increasing:"\u25b2",decreasing:"\u25bc"};e.exports=function(t,e,r,s){var c=t.cd,u=t.xa,f=t.ya,d=c[0].trace,p=c[0].t,h=d.type,g="ohlc"===h?"l":"min",y="ohlc"===h?"h":"max",v=p.bPos||0,m=e-v,x=p.bdPos||p.tickLen,b=p.wHover,_=Math.min(1,x/Math.abs(u.r2c(u.range[1])-u.r2c(u.range[0]))),w=t.maxHoverDistance-_,k=t.maxSpikeDistance-_;function M(t){var e=t.pos-m;return a.inbox(e-b,e+b,w)}function T(t){return a.inbox(t[g]-r,t[y]-r,w)}function A(t){return(M(t)+T(t))/2}var L=a.getDistanceFunction(s,M,T,A);if(a.getClosest(c,L,t),!1===t.index)return[];var C=c[t.index],S=t.index=C.i,O=C.dir,P=d[O],D=P.line.color;function z(t){return p.labels[t]+n.hoverLabelText(f,d[t][S])}i.opacity(D)&&P.line.width?t.color=D:t.color=P.fillcolor,t.x0=u.c2p(C.pos+v-x,!0),t.x1=u.c2p(C.pos+v+x,!0),t.xLabelVal=C.pos,t.spikeDistance=A(C)*k/w,t.xSpike=u.c2p(C.pos,!0);var E=d.hoverinfo,I=E.split("+"),N="all"===E,R=N||-1!==I.indexOf("y"),F=N||-1!==I.indexOf("text"),j=R?[z("open"),z("high"),z("low"),z("close")+" "+l[O]]:[];return F&&o(C,d,j),t.extraText=j.join("<br>"),t.y0=t.y1=f.c2p(C.yc,!0),[t]}},{"../../components/color":45,"../../components/fx":87,"../../plots/cartesian/axes":207,"../scatter/fill_hover_text":321}],296:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"ohlc",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","showLegend"],meta:{},attributes:t("./attributes"),supplyDefaults:t("./defaults"),calc:t("./calc").calc,plot:t("./plot"),style:t("./style"),hoverPoints:t("./hover"),selectPoints:t("./select")}},{"../../plots/cartesian":218,"./attributes":292,"./calc":293,"./defaults":294,"./hover":295,"./plot":298,"./select":299,"./style":300}],297:[function(t,e,r){"use strict";var n=t("../../registry");e.exports=function(t,e,r,a){var i=r("x"),o=r("open"),l=r("high"),s=r("low"),c=r("close");if(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x"],a),o&&l&&s&&c){var u=Math.min(o.length,l.length,s.length,c.length);return i&&(u=Math.min(u,i.length)),e._length=u,u}}},{"../../registry":247}],298:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib");e.exports=function(t,e,r,i){var o=e.xaxis,l=e.yaxis,s=i.selectAll("g.trace").data(r,function(t){return t[0].trace.uid});s.enter().append("g").attr("class","trace ohlc"),s.exit().remove(),s.order(),s.each(function(t){var r=t[0],i=r.t,s=r.trace,c=n.select(this);if(e.isRangePlot||(r.node3=c),!0!==s.visible||i.empty)c.remove();else{var u=i.tickLen,f=c.selectAll("path").data(a.identity);f.enter().append("path"),f.exit().remove(),f.attr("d",function(t){var e=o.c2p(t.pos,!0),r=o.c2p(t.pos-u,!0),n=o.c2p(t.pos+u,!0);return"M"+r+","+l.c2p(t.o,!0)+"H"+e+"M"+e+","+l.c2p(t.h,!0)+"V"+l.c2p(t.l,!0)+"M"+n+","+l.c2p(t.c,!0)+"H"+e})}})}},{"../../lib":163,d3:10}],299:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,a=t.xaxis,i=t.yaxis,o=[],l=n[0].t.bPos||0;if(!1===e)for(r=0;r<n.length;r++)n[r].selected=0;else for(r=0;r<n.length;r++){var s=n[r];e.contains([a.c2p(s.pos+l),i.c2p(s.yc)])?(o.push({pointNumber:s.i,x:a.c2d(s.pos),y:i.c2d(s.yc)}),s.selected=1):s.selected=0}return o}},{}],300:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/drawing"),i=t("../../components/color");e.exports=function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.ohlclayer").selectAll("g.trace");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(t){var e=t[0].trace;n.select(this).selectAll("path").each(function(t){var r=e[t.dir].line;n.select(this).style("fill","none").call(i.stroke,r.color).call(a.dashLine,r.dash,r.width).style("opacity",e.selectedpoints&&!t.selected?.3:1)})})}},{"../../components/color":45,"../../components/drawing":70,d3:10}],301:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),a=t("../../plots/font_attributes"),i=t("../../plots/attributes"),o=t("../../plots/domain").attributes,l=t("../../lib/extend").extendFlat,s=a({editType:"calc",colorEditType:"style"});e.exports={labels:{valType:"data_array",editType:"calc"},label0:{valType:"number",dflt:0,editType:"calc"},dlabel:{valType:"number",dflt:1,editType:"calc"},values:{valType:"data_array",editType:"calc"},marker:{colors:{valType:"data_array",editType:"calc"},line:{color:{valType:"color",dflt:n.defaultLine,arrayOk:!0,editType:"style"},width:{valType:"number",min:0,dflt:0,arrayOk:!0,editType:"style"},editType:"calc"},editType:"calc"},text:{valType:"data_array",editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:l({},i.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0,editType:"calc"},textfont:l({},s,{}),insidetextfont:l({},s,{}),outsidetextfont:l({},s,{}),domain:o({name:"pie",trace:!0,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:!0,editType:"calc"},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"number",min:-360,max:360,dflt:0,editType:"calc"},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0,editType:"calc"}}},{"../../components/color/attributes":44,"../../lib/extend":157,"../../plots/attributes":204,"../../plots/domain":232,"../../plots/font_attributes":233}],302:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../plots/get_data").getModuleCalcData;r.name="pie",r.plot=function(t){var e=n.getModule("pie"),r=a(t.calcdata,e)[0];r.length&&e.plot(t,r)},r.clean=function(t,e,r,n){var a=n._has&&n._has("pie"),i=e._has&&e._has("pie");a&&!i&&n._pielayer.selectAll("g.trace").remove()}},{"../../plots/get_data":235,"../../registry":247}],303:[function(t,e,r){"use strict";var n,a=t("fast-isnumeric"),i=t("../../lib").isArrayOrTypedArray,o=t("tinycolor2"),l=t("../../components/color"),s=t("./helpers");function c(t,e){if(!n){var r=l.defaults;n=u(r)}var a=e||n;return a[t%a.length]}function u(t){var e,r=t.slice();for(e=0;e<t.length;e++)r.push(o(t[e]).lighten(20).toHexString());for(e=0;e<t.length;e++)r.push(o(t[e]).darken(20).toHexString());return r}e.exports=function(t,e){var r,n,f,d,p,h=e.values,g=i(h)&&h.length,y=e.labels,v=e.marker.colors||[],m=[],x=t._fullLayout,b=x.colorway,_=x._piecolormap,w={},k=0,M=x.hiddenlabels||[];if(x._piecolorway||b===l.defaults||(x._piecolorway=u(b)),e.dlabel)for(y=new Array(h.length),r=0;r<h.length;r++)y[r]=String(e.label0+r*e.dlabel);function T(t,e){return!!t&&(!!(t=o(t)).isValid()&&(t=l.addOpacity(t,t.getAlpha()),_[e]||(_[e]=t),t))}var A=(g?h:y).length;for(r=0;r<A;r++){if(g){if(n=h[r],!a(n))continue;if((n=+n)<0)continue}else n=1;void 0!==(f=y[r])&&""!==f||(f=r);var L=w[f=String(f)];void 0===L?(w[f]=m.length,(d=-1!==M.indexOf(f))||(k+=n),m.push({v:n,label:f,color:T(v[r]),i:r,pts:[r],hidden:d})):((p=m[L]).v+=n,p.pts.push(r),p.hidden||(k+=n),!1===p.color&&v[r]&&(p.color=T(v[r],f)))}for(e.sort&&m.sort(function(t,e){return e.v-t.v}),r=0;r<m.length;r++)!1===(p=m[r]).color&&(_[p.label]?p.color=_[p.label]:(_[p.label]=p.color=c(x._piedefaultcolorcount,x._piecolorway),x._piedefaultcolorcount++));if(m[0]&&(m[0].vTotal=k),e.textinfo&&"none"!==e.textinfo){var C,S=-1!==e.textinfo.indexOf("label"),O=-1!==e.textinfo.indexOf("text"),P=-1!==e.textinfo.indexOf("value"),D=-1!==e.textinfo.indexOf("percent"),z=x.separators;for(r=0;r<m.length;r++){if(p=m[r],C=S?[p.label]:[],O){var E=s.getFirstFilled(e.text,p.pts);E&&C.push(E)}P&&C.push(s.formatPieValue(p.v,z)),D&&C.push(s.formatPiePercent(p.v/k,z)),p.text=C.join("<br>")}}return m}},{"../../components/color":45,"../../lib":163,"./helpers":306,"fast-isnumeric":13,tinycolor2:28}],304:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./attributes"),i=t("../../plots/domain").defaults;e.exports=function(t,e,r,o){function l(r,i){return n.coerce(t,e,a,r,i)}var s,c=n.coerceFont,u=l("values"),f=n.isArrayOrTypedArray(u),d=l("labels");if(Array.isArray(d)?(s=d.length,f&&(s=Math.min(s,u.length))):f&&(s=u.length,l("label0"),l("dlabel")),s){e._length=s,l("marker.line.width")&&l("marker.line.color"),l("marker.colors"),l("scalegroup");var p=l("text"),h=l("textinfo",Array.isArray(p)?"text+percent":"percent");if(l("hovertext"),h&&"none"!==h){var g=l("textposition"),y=Array.isArray(g)||"auto"===g,v=y||"inside"===g,m=y||"outside"===g;if(v||m){var x=c(l,"textfont",o.font);v&&c(l,"insidetextfont",x),m&&c(l,"outsidetextfont",x)}}i(e,o,l),l("hole"),l("sort"),l("direction"),l("rotation"),l("pull")}else e.visible=!1}},{"../../lib":163,"../../plots/domain":232,"./attributes":301}],305:[function(t,e,r){"use strict";var n=t("../../components/fx/helpers").appendArrayMultiPointValues;e.exports=function(t,e){var r={curveNumber:e.index,pointNumbers:t.pts,data:e._input,fullData:e,label:t.label,color:t.color,value:t.v,v:t.v};return 1===t.pts.length&&(r.pointNumber=r.i=t.pts[0]),n(r,e,t.pts),r}},{"../../components/fx/helpers":84}],306:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)},r.getFirstFilled=function(t,e){if(Array.isArray(t))for(var r=0;r<e.length;r++){var n=t[e[r]];if(n||0===n)return n}},r.castOption=function(t,e){return Array.isArray(t)?r.getFirstFilled(t,e):t||void 0}},{"../../lib":163}],307:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":301,"./base_plot":302,"./calc":303,"./defaults":304,"./layout_attributes":308,"./layout_defaults":309,"./plot":310,"./style":311,"./style_one":312}],308:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array",editType:"calc"}}},{}],309:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e){var r,i;r="hiddenlabels",n.coerce(t,e,a,r,i)}},{"../../lib":163,"./layout_attributes":308}],310:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/fx"),i=t("../../components/color"),o=t("../../components/drawing"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("./helpers"),u=t("./event_data");function f(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function d(t,e){var r=e.pxmid[0],n=e.pxmid[1],a=t.width/2,i=t.height/2;return r<0&&(a*=-1),n<0&&(i*=-1),{scale:1,rCenter:1,rotate:0,x:a+Math.abs(i)*(a>0?1:-1)/2,y:i/(1+r*r/(n*n)),outside:!0}}e.exports=function(t,e){var r=t._fullLayout;!function(t,e){var r,n,a,i,o,l,s,c,u,f=[];for(a=0;a<t.length;a++){if(o=t[a][0],l=o.trace,r=e.w*(l.domain.x[1]-l.domain.x[0]),n=e.h*(l.domain.y[1]-l.domain.y[0]),s=l.pull,Array.isArray(s))for(s=0,i=0;i<l.pull.length;i++)l.pull[i]>s&&(s=l.pull[i]);o.r=Math.min(r,n)/(2+2*s),o.cx=e.l+e.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=e.t+e.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;i<f.length;i++){for(u=1/0,c=f[i],a=0;a<t.length;a++)(o=t[a][0]).trace.scalegroup===c&&(u=Math.min(u,o.r*o.r/o.vTotal));for(a=0;a<t.length;a++)(o=t[a][0]).trace.scalegroup===c&&(o.r=Math.sqrt(u*o.vTotal))}}(e,r._size);var p=r._pielayer.selectAll("g.trace").data(e);p.enter().append("g").attr({"stroke-linejoin":"round",class:"trace"}),p.exit().remove(),p.order(),p.each(function(e){var p=n.select(this),h=e[0],g=h.trace;!function(t){var e,r,n,a=t[0],i=a.trace,o=i.rotation*Math.PI/180,l=2*Math.PI/a.vTotal,s="px0",c="px1";if("counterclockwise"===i.direction){for(e=0;e<t.length&&t[e].hidden;e++);if(e===t.length)return;o+=l*t[e].v,l*=-1,s="px1",c="px0"}function u(t){return[a.r*Math.sin(t),-a.r*Math.cos(t)]}for(n=u(o),e=0;e<t.length;e++)(r=t[e]).hidden||(r[s]=n,o+=l*r.v/2,r.pxmid=u(o),r.midangle=o,o+=l*r.v/2,n=u(o),r[c]=n,r.largeArc=r.v>a.vTotal/2?1:0)}(e),p.each(function(){var p=n.select(this).selectAll("g.slice").data(e);p.enter().append("g").classed("slice",!0),p.exit().remove();var y=[[[],[]],[[],[]]],v=!1;p.each(function(e){if(e.hidden)n.select(this).selectAll("path,g").remove();else{e.pointNumber=e.i,e.curveNumber=g.index,y[e.pxmid[1]<0?0:1][e.pxmid[0]<0?0:1].push(e);var i=h.cx,p=h.cy,m=n.select(this),x=m.selectAll("path.surface").data([e]),b=!1,_=!1;if(x.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),m.select("path.textline").remove(),m.on("mouseover",function(){var o=t._fullLayout,l=t._fullData[g.index];if(!t._dragging&&!1!==o.hovermode){var s=l.hoverinfo;if(Array.isArray(s)&&(s=a.castHoverinfo({hoverinfo:[c.castOption(s,e.pts)],_module:g._module},o,0)),"all"===s&&(s="label+text+value+percent+name"),"none"!==s&&"skip"!==s&&s){var d=f(e,h),y=i+e.pxmid[0]*(1-d),v=p+e.pxmid[1]*(1-d),m=r.separators,x=[];if(-1!==s.indexOf("label")&&x.push(e.label),-1!==s.indexOf("text")){var w=c.castOption(l.hovertext||l.text,e.pts);w&&x.push(w)}-1!==s.indexOf("value")&&x.push(c.formatPieValue(e.v,m)),-1!==s.indexOf("percent")&&x.push(c.formatPiePercent(e.v/h.vTotal,m));var k=g.hoverlabel,M=k.font;a.loneHover({x0:y-d*h.r,x1:y+d*h.r,y:v,text:x.join("<br>"),name:-1!==s.indexOf("name")?l.name:void 0,idealAlign:e.pxmid[0]<0?"left":"right",color:c.castOption(k.bgcolor,e.pts)||e.color,borderColor:c.castOption(k.bordercolor,e.pts),fontFamily:c.castOption(M.family,e.pts),fontSize:c.castOption(M.size,e.pts),fontColor:c.castOption(M.color,e.pts)},{container:o._hoverlayer.node(),outerContainer:o._paper.node(),gd:t}),b=!0}t.emit("plotly_hover",{points:[u(e,l)],event:n.event}),_=!0}}).on("mouseout",function(r){var i=t._fullLayout,o=t._fullData[g.index];_&&(r.originalEvent=n.event,t.emit("plotly_unhover",{points:[u(e,o)],event:n.event}),_=!1),b&&(a.loneUnhover(i._hoverlayer.node()),b=!1)}).on("click",function(){var r=t._fullLayout,i=t._fullData[g.index];t._dragging||!1===r.hovermode||(t._hoverdata=[u(e,i)],a.click(t,n.event))}),g.pull){var w=+c.castOption(g.pull,e.pts)||0;w>0&&(i+=w*e.pxmid[0],p+=w*e.pxmid[1])}e.cxFinal=i,e.cyFinal=p;var k=g.hole;if(e.v===h.vTotal){var M="M"+(i+e.px0[0])+","+(p+e.px0[1])+S(e.px0,e.pxmid,!0,1)+S(e.pxmid,e.px0,!0,1)+"Z";k?x.attr("d","M"+(i+k*e.px0[0])+","+(p+k*e.px0[1])+S(e.px0,e.pxmid,!1,k)+S(e.pxmid,e.px0,!1,k)+"Z"+M):x.attr("d",M)}else{var T=S(e.px0,e.px1,!0,1);if(k){var A=1-k;x.attr("d","M"+(i+k*e.px1[0])+","+(p+k*e.px1[1])+S(e.px1,e.px0,!1,k)+"l"+A*e.px0[0]+","+A*e.px0[1]+T+"Z")}else x.attr("d","M"+i+","+p+"l"+e.px0[0]+","+e.px0[1]+T+"Z")}var L=c.castOption(g.textposition,e.pts),C=m.selectAll("g.slicetext").data(e.text&&"none"!==L?[0]:[]);C.enter().append("g").classed("slicetext",!0),C.exit().remove(),C.each(function(){var r=l.ensureSingle(n.select(this),"text","",function(t){t.attr("data-notex",1)});r.text(e.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(o.font,"outside"===L?g.outsidetextfont:g.insidetextfont).call(s.convertToTspans,t);var a,c=o.bBox(r.node());"outside"===L?a=d(c,e):(a=function(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,i=Math.PI*Math.min(e.v/r.vTotal,.5),o=1-r.trace.hole,l=f(e,r),s={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),d={scale:2*u/t.height,rCenter:Math.cos(u/r.r)-u*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},p=1/a,h=p+1/(2*Math.tan(i)),g=r.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(p*p+o/2)+p)),y={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},v=y.scale>d.scale?y:d;return s.scale<1&&v.scale>s.scale?v:s}(c,e,h),"auto"===L&&a.scale<1&&(r.call(o.font,g.outsidetextfont),g.outsidetextfont.family===g.insidetextfont.family&&g.outsidetextfont.size===g.insidetextfont.size||(c=o.bBox(r.node())),a=d(c,e)));var u=i+e.pxmid[0]*a.rCenter+(a.x||0),y=p+e.pxmid[1]*a.rCenter+(a.y||0);a.outside&&(e.yLabelMin=y-c.height/2,e.yLabelMid=y,e.yLabelMax=y+c.height/2,e.labelExtraX=0,e.labelExtraY=0,v=!0),r.attr("transform","translate("+u+","+y+")"+(a.scale<1?"scale("+a.scale+")":"")+(a.rotate?"rotate("+a.rotate+")":"")+"translate("+-(c.left+c.right)/2+","+-(c.top+c.bottom)/2+")")})}function S(t,r,n,a){return"a"+a*h.r+","+a*h.r+" 0 "+e.largeArc+(n?" 1 ":" 0 ")+a*(r[0]-t[0])+","+a*(r[1]-t[1])}}),v&&function(t,e){var r,n,a,i,o,l,s,u,f,d,p,h,g;function y(t,e){return t.pxmid[1]-e.pxmid[1]}function v(t,e){return e.pxmid[1]-t.pxmid[1]}function m(t,r){r||(r={});var a,u,f,p,h,g,y=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),v=n?t.yLabelMin:t.yLabelMax,m=n?t.yLabelMax:t.yLabelMin,x=t.cyFinal+o(t.px0[1],t.px1[1]),b=y-v;if(b*s>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(u=0;u<d.length;u++)(f=d[u])===t||(c.castOption(e.pull,t.pts)||0)>=(c.castOption(e.pull,f.pts)||0)||((t.pxmid[1]-f.pxmid[1])*s>0?(p=f.cyFinal+o(f.px0[1],f.px1[1]),(b=p-v-t.labelExtraY)*s>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-x)*s>0&&(a=3*l*Math.abs(u-d.indexOf(t)),h=f.cxFinal+i(f.px0[0],f.px1[0]),(g=h+a-(t.cxFinal+t.pxmid[0])-t.labelExtraX)*l>0&&(t.labelExtraX+=g)))}for(n=0;n<2;n++)for(a=n?y:v,o=n?Math.max:Math.min,s=n?1:-1,r=0;r<2;r++){for(i=r?Math.max:Math.min,l=r?1:-1,(u=t[n][r]).sort(a),f=t[1-n][r],d=f.concat(u),h=[],p=0;p<u.length;p++)void 0!==u[p].yLabelMid&&h.push(u[p]);for(g=!1,p=0;n&&p<f.length;p++)if(void 0!==f[p].yLabelMid){g=f[p];break}for(p=0;p<h.length;p++){var x=p&&h[p-1];g&&!p&&(x=g),m(h[p],x)}}}(y,g),p.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=n.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var a=t.cxFinal+t.pxmid[0],o="M"+a+","+(t.cyFinal+t.pxmid[1]),l=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],c=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);Math.abs(s)>Math.abs(c)?o+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):o+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else o+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;e.append("path").classed("textline",!0).call(i.stroke,g.outsidetextfont.color).attr({"stroke-width":Math.min(2,g.outsidetextfont.size/8),d:o,fill:"none"})}})})}),setTimeout(function(){p.selectAll("tspan").each(function(){var t=n.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":45,"../../components/drawing":70,"../../components/fx":87,"../../lib":163,"../../lib/svg_text_utils":184,"./event_data":305,"./helpers":306,d3:10}],311:[function(t,e,r){"use strict";var n=t("d3"),a=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0].trace,r=n.select(this);r.style({opacity:e.opacity}),r.selectAll("path.surface").each(function(t){n.select(this).call(a,t,e)})})}},{"./style_one":312,d3:10}],312:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("./helpers").castOption;e.exports=function(t,e,r){var i=r.marker.line,o=a(i.color,e.pts)||n.defaultLine,l=a(i.width,e.pts)||0;t.style({"stroke-width":l}).call(n.fill,e.color).call(n.stroke,o)}},{"../../components/color":45,"./helpers":306}],313:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){for(var r=0;r<t.length;r++)t[r].i=r;n.mergeArray(e.text,t,"tx"),n.mergeArray(e.hovertext,t,"htx"),n.mergeArray(e.customdata,t,"data"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf"));var a=e.marker;if(a){n.mergeArray(a.size,t,"ms"),n.mergeArray(a.opacity,t,"mo"),n.mergeArray(a.symbol,t,"mx"),n.mergeArray(a.color,t,"mc");var i=a.line;a.line&&(n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw"));var o=a.gradient;o&&"none"!==o.type&&(n.mergeArray(o.type,t,"mgt"),n.mergeArray(o.color,t,"mgc"))}}},{"../../lib":163}],314:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),i=t("../../plots/font_attributes"),o=t("../../components/drawing/attributes").dash,l=t("../../components/drawing"),s=(t("./constants"),t("../../lib/extend").extendFlat);e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:s({},o,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:s({symbol:{valType:"enumerated",values:l.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},colorbar:a,line:s({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},n("marker.line")),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},n("marker")),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:i({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}}},{"../../components/colorbar/attributes":46,"../../components/colorscale/attributes":52,"../../components/drawing":70,"../../components/drawing/attributes":69,"../../lib/extend":157,"../../plots/font_attributes":233,"./constants":319}],315:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").isArrayOrTypedArray,i=t("../../plots/cartesian/axes"),o=t("../../constants/numerical").BADNUM,l=t("./subtypes"),s=t("./colorscale_calc"),c=t("./arrays_to_calcdata"),u=t("./calc_selection");function f(t,e,r,n,a,o,s){var c=e._length;r._minDtick=0,n._minDtick=0;var u={padded:!0},f={padded:!0};s&&(u.ppad=f.ppad=s),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||a[0]===a[c-1]&&o[0]===o[c-1]?(e.error_y||{}).visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(l.hasMarkers(e)||l.hasText(e))||(u.padded=!1,u.ppad=0):u.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||a[0]===a[c-1]&&o[0]===o[c-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(f.padded=!1):f.tozero=!0,i.expand(r,a,u),i.expand(n,o,f)}function d(t,e){if(l.hasMarkers(t)){var r,n=t.marker,o=1.6*(t.marker.sizeref||1);if(r="area"===t.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/o),3)}:function(t){return Math.max((t||0)/o,3)},a(n.size)){var s={type:"linear"};i.setConvert(s);for(var c=s.makeCalcdata(t.marker,"size"),u=new Array(e),f=0;f<e;f++)u[f]=r(c[f]);return u}return r(n.size)}}e.exports={calc:function(t,e){var r=i.getFromId(t,e.xaxis||"x"),a=i.getFromId(t,e.yaxis||"y"),l=r.makeCalcdata(e,"x"),p=a.makeCalcdata(e,"y"),h=e._length,g=new Array(h);f(t,e,r,a,l,p,d(e,h));for(var y=0;y<h;y++)g[y]=n(l[y])&&n(p[y])?{x:l[y],y:p[y]}:{x:o,y:o},e.ids&&(g[y].id=String(e.ids[y]));return c(g,e),s(e),u(g,e),t.firstscatter=!1,g},calcMarkerSize:d,calcAxisExpansion:f}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207,"./arrays_to_calcdata":313,"./calc_selection":316,"./colorscale_calc":318,"./subtypes":336,"fast-isnumeric":13}],316:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){n.isArrayOrTypedArray(e.selectedpoints)&&n.tagSelected(t,e)}},{"../../lib":163}],317:[function(t,e,r){"use strict";e.exports=function(t){for(var e=0;e<t.length;e++){var r=t[e];if("scatter"===r.type){var n=r.fill;if("none"!==n&&"toself"!==n&&(r.opacity=void 0,"tonexty"===n||"tonextx"===n))for(var a=e-1;a>=0;a--){var i=t[a];if("scatter"===i.type&&i.xaxis===r.xaxis&&i.yaxis===r.yaxis){i.opacity=void 0;break}}}}}},{}],318:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/calc"),i=t("./subtypes");e.exports=function(t){i.hasLines(t)&&n(t,"line")&&a(t,t.line.color,"line","c"),i.hasMarkers(t)&&(n(t,"marker")&&a(t,t.marker.color,"marker","c"),n(t,"marker.line")&&a(t,t.marker.line.color,"marker.line","c"))}},{"../../components/colorscale/calc":53,"../../components/colorscale/has_colorscale":59,"./subtypes":336}],319:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20}},{}],320:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry"),i=t("./attributes"),o=t("./constants"),l=t("./subtypes"),s=t("./xy_defaults"),c=t("./marker_defaults"),u=t("./line_defaults"),f=t("./line_shape_defaults"),d=t("./text_defaults"),p=t("./fillcolor_defaults");e.exports=function(t,e,r,h){function g(r,a){return n.coerce(t,e,i,r,a)}var y=s(t,e,h,g),v=y<o.PTS_LINESONLY?"lines+markers":"lines";if(y){g("text"),g("hovertext"),g("mode",v),l.hasLines(e)&&(u(t,e,r,h,g),f(t,e,g),g("connectgaps"),g("line.simplify")),l.hasMarkers(e)&&c(t,e,r,h,g,{gradient:!0}),l.hasText(e)&&d(t,e,h,g);var m=[];(l.hasMarkers(e)||l.hasText(e))&&(g("cliponaxis"),g("marker.maxdisplayed"),m.push("points")),g("fill"),"none"!==e.fill&&(p(t,e,r,g),l.hasLines(e)||f(t,e,g)),"tonext"!==e.fill&&"toself"!==e.fill||m.push("fills"),g("hoveron",m.join("+")||"points");var x=a.getComponentMethod("errorbars","supplyDefaults");x(t,e,r,{axis:"y"}),x(t,e,r,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,g)}else e.visible=!1}},{"../../lib":163,"../../registry":247,"./attributes":314,"./constants":319,"./fillcolor_defaults":322,"./line_defaults":326,"./line_shape_defaults":328,"./marker_defaults":332,"./subtypes":336,"./text_defaults":337,"./xy_defaults":338}],321:[function(t,e,r){"use strict";var n=t("../../lib");function a(t){return t||0===t}e.exports=function(t,e,r){var i=Array.isArray(r)?function(t){r.push(t)}:function(t){r.text=t},o=n.extractOption(t,e,"htx","hovertext");if(a(o))return i(o);var l=n.extractOption(t,e,"tx","text");return a(l)?i(l):void 0}},{"../../lib":163}],322:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r,i){var o=!1;if(e.marker){var l=e.marker.color,s=(e.marker.line||{}).color;l&&!a(l)?o=l:s&&!a(s)&&(o=s)}i("fillcolor",n.addOpacity((e.line||{}).color||o||r,.5))}},{"../../components/color":45,"../../lib":163}],323:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("./subtypes");e.exports=function(t,e){var r,i;if("lines"===t.mode)return(r=t.line.color)&&n.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var o=e.mcc||(t.marker||{}).color,l=e.mlcc||((t.marker||{}).line||{}).color;return(i=o&&n.opacity(o)?o:l&&n.opacity(l)&&(e.mlw||((t.marker||{}).line||{}).width)?l:"")?n.opacity(i)<.3?n.addOpacity(i,.3):i:(r=(t.line||{}).color)&&n.opacity(r)&&a.hasLines(t)&&t.line.width?r:t.fillcolor}},{"../../components/color":45,"./subtypes":336}],324:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../components/fx"),i=t("../../registry"),o=t("./get_trace_color"),l=t("../../components/color"),s=t("./fill_hover_text");e.exports=function(t,e,r,c){var u=t.cd,f=u[0].trace,d=t.xa,p=t.ya,h=d.c2p(e),g=p.c2p(r),y=[h,g],v=f.hoveron||"",m=-1!==f.mode.indexOf("markers")?3:.5;if(-1!==v.indexOf("points")){var x=function(t){var e=Math.max(m,t.mrc||0),r=d.c2p(t.x)-h,n=p.c2p(t.y)-g;return Math.max(Math.sqrt(r*r+n*n)-e,1-m/e)},b=a.getDistanceFunction(c,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(d.c2p(t.x)-h);return n<e?r*n/e:n-e+r},function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(p.c2p(t.y)-g);return n<e?r*n/e:n-e+r},x);if(a.getClosest(u,b,t),!1!==t.index){var _=u[t.index],w=d.c2p(_.x,!0),k=p.c2p(_.y,!0),M=_.mrc||1;return n.extendFlat(t,{color:o(f,_),x0:w-M,x1:w+M,xLabelVal:_.x,y0:k-M,y1:k+M,yLabelVal:_.y,spikeDistance:x(_)}),s(_,f,t),i.getComponentMethod("errorbars","hoverInfo")(_,f,t),[t]}}if(-1!==v.indexOf("fills")&&f._polygons){var T,A,L,C,S,O,P,D,z,E=f._polygons,I=[],N=!1,R=1/0,F=-1/0,j=1/0,B=-1/0;for(T=0;T<E.length;T++)(L=E[T]).contains(y)&&(N=!N,I.push(L),j=Math.min(j,L.ymin),B=Math.max(B,L.ymax));if(N){var H=((j=Math.max(j,0))+(B=Math.min(B,p._length)))/2;for(T=0;T<I.length;T++)for(C=I[T].pts,A=1;A<C.length;A++)(D=C[A-1][1])>H!=(z=C[A][1])>=H&&(O=C[A-1][0],P=C[A][0],z-D&&(S=O+(P-O)*(H-D)/(z-D),R=Math.min(R,S),F=Math.max(F,S)));R=Math.max(R,0),F=Math.min(F,d._length);var q=l.defaultLine;return l.opacity(f.fillcolor)?q=f.fillcolor:l.opacity((f.line||{}).color)&&(q=f.line.color),n.extendFlat(t,{distance:t.maxHoverDistance,x0:R,x1:F,y0:H,y1:H,color:q}),delete t.index,f.text&&!Array.isArray(f.text)?t.text=String(f.text):t.text=f.name,[t]}}}},{"../../components/color":45,"../../components/fx":87,"../../lib":163,"../../registry":247,"./fill_hover_text":321,"./get_trace_color":323}],325:[function(t,e,r){"use strict";var n={},a=t("./subtypes");n.hasLines=a.hasLines,n.hasMarkers=a.hasMarkers,n.hasText=a.hasText,n.isBubble=a.isBubble,n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.cleanData=t("./clean_data"),n.calc=t("./calc").calc,n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.colorbar=t("./marker_colorbar"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.animatable=!0,n.moduleType="trace",n.name="scatter",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","symbols","errorBarsOK","showLegend","scatter-like","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":218,"./arrays_to_calcdata":313,"./attributes":314,"./calc":315,"./clean_data":317,"./defaults":320,"./hover":324,"./marker_colorbar":331,"./plot":333,"./select":334,"./style":335,"./subtypes":336}],326:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray,a=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,l,s){var c=(t.marker||{}).color;(l("line.color",r),a(t,"line"))?i(t,e,o,l,{prefix:"line.",cLetter:"c"}):l("line.color",!n(c)&&c||r);l("line.width"),(s||{}).noDash||l("line.dash")}},{"../../components/colorscale/defaults":55,"../../components/colorscale/has_colorscale":59,"../../lib":163}],327:[function(t,e,r){"use strict";var n=t("../../constants/numerical").BADNUM,a=t("../../lib"),i=a.segmentsIntersect,o=a.constrain,l=t("./constants");e.exports=function(t,e){var r,s,c,u,f,d,p,h,g,y,v,m,x,b,_,w,k,M,T=e.xaxis,A=e.yaxis,L=e.connectGaps,C=e.baseTolerance,S=e.shape,O="linear"===S,P=[],D=l.minTolerance,z=new Array(t.length),E=0;function I(e){var r=t[e];if(!r)return!1;var a=T.c2p(r.x),i=A.c2p(r.y);return a===n||i===n?r.intoCenter||!1:[a,i]}function N(t,e,r,n){var a=r-t,i=n-e,o=.5-t,l=.5-e,s=a*a+i*i,c=a*o+i*l;if(c>0&&c<s){var u=o*i-l*a;if(u*u<s)return!0}}function R(t,e){var r=t[0]/T._length,n=t[1]/A._length,a=Math.max(0,-r,r-1,-n,n-1);return a&&void 0!==k&&N(r,n,k,M)&&(a=0),a&&e&&N(r,n,e[0]/T._length,e[1]/A._length)&&(a=0),(1+l.toleranceGrowth*a)*C}function F(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}var j,B,H,q,V,U,G,Y=l.maxScreensAway,X=-T._length*Y,Z=T._length*(1+Y),W=-A._length*Y,Q=A._length*(1+Y),J=[[X,W,Z,W],[Z,W,Z,Q],[Z,Q,X,Q],[X,Q,X,W]];function $(t){if(t[0]<X||t[0]>Z||t[1]<W||t[1]>Q)return[o(t[0],X,Z),o(t[1],W,Q)]}function K(t,e){return t[0]===e[0]&&(t[0]===X||t[0]===Z)||(t[1]===e[1]&&(t[1]===W||t[1]===Q)||void 0)}function tt(t,e,r){return function(n,i){var o=$(n),l=$(i),s=[];if(o&&l&&K(o,l))return s;o&&s.push(o),l&&s.push(l);var c=2*a.constrain((n[t]+i[t])/2,e,r)-((o||n)[t]+(l||i)[t]);c&&((o&&l?c>0==o[t]>l[t]?o:l:o||l)[t]+=c);return s}}function et(t){var e=t[0],r=t[1],n=e===z[E-1][0],a=r===z[E-1][1];if(!n||!a)if(E>1){var i=e===z[E-2][0],o=r===z[E-2][1];n&&(e===X||e===Z)&&i?o?E--:z[E-1]=t:a&&(r===W||r===Q)&&o?i?E--:z[E-1]=t:z[E++]=t}else z[E++]=t}function rt(t){z[E-1][0]!==t[0]&&z[E-1][1]!==t[1]&&et([H,q]),et(t),V=null,H=q=0}function nt(t){if(k=t[0]/T._length,M=t[1]/A._length,j=t[0]<X?X:t[0]>Z?Z:0,B=t[1]<W?W:t[1]>Q?Q:0,j||B){if(E)if(V){var e=G(V,t);e.length>1&&(rt(e[0]),z[E++]=e[1])}else U=G(z[E-1],t)[0],z[E++]=U;else z[E++]=[j||t[0],B||t[1]];var r=z[E-1];j&&B&&(r[0]!==j||r[1]!==B)?(V&&(H!==j&&q!==B?et(H&&q?(n=V,i=(a=t)[0]-n[0],o=(a[1]-n[1])/i,(n[1]*a[0]-a[1]*n[0])/i>0?[o>0?X:Z,Q]:[o>0?Z:X,W]):[H||j,q||B]):H&&q&&et([H,q])),et([j,B])):H-j&&q-B&&et([j||H,B||q]),V=t,H=j,q=B}else V&&rt(G(V,t)[0]),z[E++]=t;var n,a,i,o}for("linear"===S||"spline"===S?G=function(t,e){for(var r=[],n=0,a=0;a<4;a++){var o=J[a],l=i(t[0],t[1],e[0],e[1],o[0],o[1],o[2],o[3]);l&&(!n||Math.abs(l.x-r[0][0])>1||Math.abs(l.y-r[0][1])>1)&&(l=[l.x,l.y],n&&F(l,t)<F(r[0],t)?r.unshift(l):r.push(l),n++)}return r}:"hv"===S||"vh"===S?G=function(t,e){var r=[],n=$(t),a=$(e);return n&&a&&K(n,a)?r:(n&&r.push(n),a&&r.push(a),r)}:"hvh"===S?G=tt(0,X,Z):"vhv"===S&&(G=tt(1,W,Q)),r=0;r<t.length;r++)if(s=I(r)){for(E=0,V=null,nt(s),r++;r<t.length;r++){if(!(u=I(r))){if(L)continue;break}if(O&&e.simplify){var at=I(r+1);if(!((y=F(u,s))<R(u,at)*D)){for(h=[(u[0]-s[0])/y,(u[1]-s[1])/y],f=s,v=y,m=b=_=0,p=!1,c=u,r++;r<t.length;r++){if(d=at,at=I(r+1),!d){if(L)continue;break}if(w=(g=[d[0]-s[0],d[1]-s[1]])[0]*h[1]-g[1]*h[0],b=Math.min(b,w),(_=Math.max(_,w))-b>R(d,at))break;c=d,(x=g[0]*h[0]+g[1]*h[1])>v?(v=x,u=d,p=!1):x<m&&(m=x,f=d,p=!0)}if(p?(nt(u),c!==f&&nt(f)):(f!==s&&nt(f),c!==u&&nt(u)),nt(c),r>=t.length||!d)break;nt(d),s=d}}else nt(u)}V&&et([H||V[0],q||V[1]]),P.push(z.slice(0,E))}return P}},{"../../constants/numerical":145,"../../lib":163,"./constants":319}],328:[function(t,e,r){"use strict";e.exports=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")}},{}],329:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,a,i=null;for(a=0;a<r.length;++a)!0===(n=r[a][0].trace).visible?(n._nexttrace=null,-1!==["tonextx","tonexty","tonext"].indexOf(n.fill)&&(n._prevtrace=i,i&&(i._nexttrace=n)),i=n):n._prevtrace=n._nexttrace=null}},{}],330:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t){var e=t.marker,r=e.sizeref||1,a=e.sizemin||0,i="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=i(t/2);return n(e)&&e>0?Math.max(e,a):0}}},{"fast-isnumeric":13}],331:[function(t,e,r){"use strict";e.exports={container:"marker",min:"cmin",max:"cmax"}},{}],332:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,l,s,c){var u=o.isBubble(t),f=(t.line||{}).color;(c=c||{},f&&(r=f),s("marker.symbol"),s("marker.opacity",u?.7:1),s("marker.size"),s("marker.color",r),a(t,"marker")&&i(t,e,l,s,{prefix:"marker.",cLetter:"c"}),c.noSelect||(s("selected.marker.color"),s("unselected.marker.color"),s("selected.marker.size"),s("unselected.marker.size")),c.noLine||(s("marker.line.color",f&&!Array.isArray(f)&&e.marker.color!==f?f:u?n.background:n.defaultLine),a(t,"marker.line")&&i(t,e,l,s,{prefix:"marker.line.",cLetter:"c"}),s("marker.line.width",u?1:0)),u&&(s("marker.sizeref"),s("marker.sizemin"),s("marker.sizemode")),c.gradient)&&("none"!==s("marker.gradient.type")&&s("marker.gradient.color"))}},{"../../components/color":45,"../../components/colorscale/defaults":55,"../../components/colorscale/has_colorscale":59,"./subtypes":336}],333:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../lib"),o=t("../../components/drawing"),l=t("./subtypes"),s=t("./line_points"),c=t("./link_traces"),u=t("../../lib/polygon").tester;function f(t,e,r,c,f,d,p){var h,g;!function(t,e,r,a,o){var s=r.xaxis,c=r.yaxis,u=n.extent(i.simpleMap(s.range,s.r2c)),f=n.extent(i.simpleMap(c.range,c.r2c)),d=a[0].trace;if(!l.hasMarkers(d))return;var p=d.marker.maxdisplayed;if(0===p)return;var h=a.filter(function(t){return t.x>=u[0]&&t.x<=u[1]&&t.y>=f[0]&&t.y<=f[1]}),g=Math.ceil(h.length/p),y=0;o.forEach(function(t,r){var n=t[0].trace;l.hasMarkers(n)&&n.marker.maxdisplayed>0&&r<e&&y++});var v=Math.round(y*g/3+Math.floor(y/3)*g/7.1);a.forEach(function(t){delete t.vis}),h.forEach(function(t,e){0===Math.round((e+v)%g)&&(t.vis=!0)})}(0,e,r,c,f);var y=!!p&&p.duration>0;function v(t){return y?t.transition():t}var m=r.xaxis,x=r.yaxis,b=c[0].trace,_=b.line,w=n.select(d);if(a.getComponentMethod("errorbars","plot")(w,r,p),!0===b.visible){var k,M;v(w).style("opacity",b.opacity);var T=b.fill.charAt(b.fill.length-1);"x"!==T&&"y"!==T&&(T=""),r.isRangePlot||(c[0].node3=w);var A="",L=[],C=b._prevtrace;C&&(A=C._prevRevpath||"",M=C._nextFill,L=C._polygons);var S,O,P,D,z,E,I,N,R,F="",j="",B=[],H=i.noop;if(k=b._ownFill,l.hasLines(b)||"none"!==b.fill){for(M&&M.datum(c),-1!==["hv","vh","hvh","vhv"].indexOf(_.shape)?(P=o.steps(_.shape),D=o.steps(_.shape.split("").reverse().join(""))):P=D="spline"===_.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?o.smoothclosed(t.slice(1),_.smoothing):o.smoothopen(t,_.smoothing)}:function(t){return"M"+t.join("L")},z=function(t){return D(t.reverse())},B=s(c,{xaxis:m,yaxis:x,connectGaps:b.connectgaps,baseTolerance:Math.max(_.width||1,3)/4,shape:_.shape,simplify:_.simplify}),R=b._polygons=new Array(B.length),g=0;g<B.length;g++)b._polygons[g]=u(B[g]);B.length&&(E=B[0][0],N=(I=B[B.length-1])[I.length-1]),H=function(t){return function(e){if(S=P(e),O=z(e),F?T?(F+="L"+S.substr(1),j=O+"L"+j.substr(1)):(F+="Z"+S,j=O+"Z"+j):(F=S,j=O),l.hasLines(b)&&e.length>1){var r=n.select(this);if(r.datum(c),t)v(r.style("opacity",0).attr("d",S).call(o.lineGroupStyle)).style("opacity",1);else{var a=v(r);a.attr("d",S),o.singleLineStyle(c,a)}}}}}var q=w.selectAll(".js-line").data(B);v(q.exit()).style("opacity",0).remove(),q.each(H(!1)),q.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(o.lineGroupStyle).each(H(!0)),o.setClipUrl(q,r.layerClipId),B.length?(k?E&&N&&(T?("y"===T?E[1]=N[1]=x.c2p(0,!0):"x"===T&&(E[0]=N[0]=m.c2p(0,!0)),v(k).attr("d","M"+N+"L"+E+"L"+F.substr(1)).call(o.singleFillStyle)):v(k).attr("d",F+"Z").call(o.singleFillStyle)):M&&("tonext"===b.fill.substr(0,6)&&F&&A?("tonext"===b.fill?v(M).attr("d",F+"Z"+A+"Z").call(o.singleFillStyle):v(M).attr("d",F+"L"+A.substr(1)+"Z").call(o.singleFillStyle),b._polygons=b._polygons.concat(L)):(U(M),b._polygons=null)),b._prevRevpath=j,b._prevPolygons=R):(k?U(k):M&&U(M),b._polygons=b._prevRevpath=b._prevPolygons=null);var V=w.selectAll(".points");h=V.data([c]),V.each(W),h.enter().append("g").classed("points",!0).each(W),h.exit().remove(),h.each(function(t){var e=!1===t[0].trace.cliponaxis;o.setClipUrl(n.select(this),e?null:r.layerClipId)})}function U(t){v(t).attr("d","M0,0Z")}function G(t){return t.filter(function(t){return t.vis})}function Y(t){return t.id}function X(t){if(t.ids)return Y}function Z(){return!1}function W(e){var a,s=e[0].trace,c=n.select(this),u=l.hasMarkers(s),f=l.hasText(s),d=X(s),p=Z,h=Z;u&&(p=s.marker.maxdisplayed||s._needsCull?G:i.identity),f&&(h=s.marker.maxdisplayed||s._needsCull?G:i.identity);var g,b=(a=c.selectAll("path.point").data(p,d)).enter().append("path").classed("point",!0);y&&b.call(o.pointStyle,s,t).call(o.translatePoints,m,x).style("opacity",0).transition().style("opacity",1),a.order(),u&&(g=o.makePointStyleFns(s)),a.each(function(e){var a=n.select(this),i=v(a);o.translatePoint(e,i,m,x)?(o.singlePointStyle(e,i,s,g,t),r.layerClipId&&o.hideOutsideRangePoint(e,i,m,x,s.xcalendar,s.ycalendar),s.customdata&&a.classed("plotly-customdata",null!==e.data&&void 0!==e.data)):i.remove()}),y?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=c.selectAll("g").data(h,d)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var e=n.select(this),a=v(e.select("text"));o.translatePoint(t,a,m,x)?r.layerClipId&&o.hideOutsideRangePoint(t,e,m,x,s.xcalendar,s.ycalendar):e.remove()}),a.selectAll("text").call(o.textPointStyle,s,t).each(function(t){var e=m.c2p(t.x),r=x.c2p(t.y);n.select(this).selectAll("tspan.line").each(function(){v(n.select(this)).attr({x:e,y:r})})}),a.exit().remove()}}e.exports=function(t,e,r,a,i,l){var s,u,d,p,h=!i,g=!!i&&i.duration>0;for((d=a.selectAll("g.trace").data(r,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),c(t,e,r),function(t,e,r){var a;e.selectAll("g.trace").each(function(t){var e=n.select(this);if((a=t[0].trace)._nexttrace){if(a._nextFill=e.select(".js-fill.js-tonext"),!a._nextFill.size()){var i=":first-child";e.select(".js-fill.js-tozero").size()&&(i+=" + *"),a._nextFill=e.insert("path",i).attr("class","js-fill js-tonext")}}else e.selectAll(".js-fill.js-tonext").remove(),a._nextFill=null;a.fill&&("tozero"===a.fill.substr(0,6)||"toself"===a.fill||"to"===a.fill.substr(0,2)&&!a._prevtrace)?(a._ownFill=e.select(".js-fill.js-tozero"),a._ownFill.size()||(a._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),a._ownFill=null),e.selectAll(".js-fill").call(o.setClipUrl,r.layerClipId)})}(0,a,e),s=0,u={};s<r.length;s++)u[r[s][0].trace.uid]=s;(a.selectAll("g.trace").sort(function(t,e){return u[t[0].trace.uid]>u[e[0].trace.uid]?1:-1}),g)?(l&&(p=l()),n.transition().duration(i.duration).ease(i.easing).each("end",function(){p&&p()}).each("interrupt",function(){p&&p()}).each(function(){a.selectAll("g.trace").each(function(n,a){f(t,a,e,n,r,this,i)})})):a.selectAll("g.trace").each(function(n,a){f(t,a,e,n,r,this,i)});h&&d.exit().remove(),a.selectAll("path:not([d])").remove()}},{"../../components/drawing":70,"../../lib":163,"../../lib/polygon":175,"../../registry":247,"./line_points":327,"./link_traces":329,"./subtypes":336,d3:10}],334:[function(t,e,r){"use strict";var n=t("./subtypes");e.exports=function(t,e){var r,a,i,o,l=t.cd,s=t.xaxis,c=t.yaxis,u=[],f=l[0].trace;if(!n.hasMarkers(f)&&!n.hasText(f))return[];if(!1===e)for(r=0;r<l.length;r++)l[r].selected=0;else for(r=0;r<l.length;r++)a=l[r],i=s.c2p(a.x),o=c.c2p(a.y),e.contains([i,o])?(u.push({pointNumber:r,x:s.c2d(a.x),y:c.c2d(a.y)}),a.selected=1):a.selected=0;return u}},{"./subtypes":336}],335:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/drawing"),i=t("../../registry");function o(t,e,r){a.pointStyle(t.selectAll("path.point"),e,r),a.textPointStyle(t.selectAll("text"),e,r)}e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.scatter");r.style("opacity",function(t){return t[0].trace.opacity}),r.selectAll("g.points").each(function(e){o(n.select(this),e.trace||e[0].trace,t)}),r.selectAll("g.trace path.js-line").call(a.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(a.fillGroupStyle),i.getComponentMethod("errorbars","style")(r)},stylePoints:o,styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace;n.selectedpoints?(a.selectedPointStyle(r.selectAll("path.point"),n),a.selectedTextStyle(r.selectAll("text"),n)):o(r,n,t)}}},{"../../components/drawing":70,"../../registry":247,d3:10}],336:[function(t,e,r){"use strict";var n=t("../../lib");e.exports={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return n.isPlainObject(t.marker)&&n.isArrayOrTypedArray(t.marker.size)}}},{"../../lib":163}],337:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,a,i){i=i||{},a("textposition"),n.coerceFont(a,"textfont",r.font),i.noSelect||(a("selected.textfont.color"),a("unselected.textfont.color"))}},{"../../lib":163}],338:[function(t,e,r){"use strict";var n=t("../../registry");e.exports=function(t,e,r,a){var i,o=a("x"),l=a("y");if(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),o)l?i=Math.min(o.length,l.length):(i=o.length,a("y0"),a("dy"));else{if(!l)return 0;i=e.y.length,a("x0"),a("dx")}return e._length=i,i}},{"../../registry":247}]},{},[7])(7)}); |
src/svg-icons/navigation/fullscreen-exit.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationFullscreenExit = (props) => (
<SvgIcon {...props}>
<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>
</SvgIcon>
);
NavigationFullscreenExit = pure(NavigationFullscreenExit);
NavigationFullscreenExit.displayName = 'NavigationFullscreenExit';
export default NavigationFullscreenExit;
|
packages/wix-style-react/src/CarouselWIP/Slide/Slide.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import { DATA_HOOKS } from '../constants';
const Slide = ({
dataHook,
className,
children,
image,
width,
gutter,
imagePosition,
imageFit,
}) => (
<div
data-hook={dataHook}
className={className}
style={{
flex: '0 0 auto',
width,
marginInlineStart: gutter,
objectPosition: imagePosition,
objectFit: imageFit,
}}
>
{image ? (
<img data-hook={DATA_HOOKS.carouselImage} src={image.src} />
) : (
children
)}
</div>
);
Slide.propTypes = {
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** A css class to be applied to the slide element */
className: PropTypes.string,
/** Children to render inside the slide */
children: PropTypes.node,
/** Object containing the src for the slide image */
image: PropTypes.object,
/** Width of the slide */
width: PropTypes.string,
/** Width for spacing before the slide */
gutter: PropTypes.string,
/** Sets the image position */
imagePosition: PropTypes.string,
/** Sets the image fit */
imageFit: PropTypes.oneOf(['fill', 'contain', 'cover', 'none', 'scale-down']),
};
export default Slide;
|
examples/passing-props-to-children/app.js | MattSPalmer/react-router | import React from 'react';
import { Router, Route, Link, History } from 'react-router';
var App = React.createClass({
mixins: [ History ],
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
};
},
addTaco() {
var name = prompt('taco name?');
this.setState({
tacos: this.state.tacos.concat({name: name})
});
},
handleRemoveTaco(removedTaco) {
var tacos = this.state.tacos.filter(function (taco) {
return taco.name != removedTaco;
});
this.setState({tacos: tacos});
this.history.pushState(null, '/');
},
render() {
var links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
);
});
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
);
}
});
var Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name);
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'));
|
modules/gui/src/widget/listItem.js | openforis/sepal | import {Subject, animationFrameScheduler, debounceTime, delay, distinctUntilChanged, filter, fromEvent, interval, map, switchMap, takeUntil, timer} from 'rxjs'
import {compose} from 'compose'
import Hammer from 'hammerjs'
import Portal from 'widget/portal'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import lookStyles from 'style/look.module.css'
import styles from './listItem.module.css'
import withSubscriptions from 'subscription'
const EXPAND_DELAYED_TIMEOUT_MS = 1000
const CLICKABLE_PAN_THRESHOLD_PX = 10
class _ListItem extends React.Component {
draggable = React.createRef()
expand$ = new Subject()
state = {
expanded: false,
dragging: false,
position: null,
size: null
}
constructor() {
super()
this.onMouseOver = this.onMouseOver.bind(this)
this.onMouseOut = this.onMouseOut.bind(this)
this.onClick = this.onClick.bind(this)
this.onExpansionClick = this.onExpansionClick.bind(this)
this.onDragStart = this.onDragStart.bind(this)
this.onDragMove = this.onDragMove.bind(this)
this.onDragEnd = this.onDragEnd.bind(this)
}
getMainContent() {
const {main, children} = this.props
return main || children
}
getExpansionContent() {
const {expansion} = this.props
return expansion
}
hasExpansion() {
return !!this.getExpansionContent()
}
isExpanded() {
const {expanded: externallyExpanded} = this.props
const {expanded: internallyExpanded} = this.state
const expanded = _.isNil(externallyExpanded)
? internallyExpanded
: externallyExpanded
return expanded
}
isExpandable() {
const {clickToExpand, clickToToggle} = this.props
return this.hasExpansion() && !this.isExpanded() && (clickToExpand || clickToToggle)
}
isCollapsable() {
const {clickToCollapse, clickToToggle} = this.props
return this.hasExpansion() && this.isExpanded() && (clickToCollapse || clickToToggle)
}
isToggleable() {
return this.isExpandable() || this.isCollapsable()
}
isDisabled() {
const {disabled} = this.props
return disabled
}
isClickable() {
const {disabled, onClick} = this.props
return !disabled && (onClick || this.isToggleable())
}
isDraggable() {
const {disabled, drag$, onDragStart, onDrag, onDragEnd} = this.props
return !disabled && (drag$ || onDragStart || onDrag || onDragEnd)
}
isDragging() {
const {disabled, dragging} = this.state
return !disabled && dragging
}
toggleExpansion() {
const {onExpand} = this.props
this.setState(
({expanded}) => ({expanded: !expanded}),
() => {
const {expanded} = this.state
onExpand && onExpand(expanded)
this.expand$.next(expanded)
}
)
}
onMouseOver() {
const {onMouseOver} = this.props
onMouseOver && onMouseOver()
}
onMouseOut() {
const {onMouseOut} = this.props
onMouseOut && onMouseOut()
}
onClick() {
const {onClick} = this.props
if (!this.isDisabled() && !this.isDragging()) {
if (onClick) {
onClick()
} else if (this.isToggleable()) {
this.toggleExpansion()
}
}
}
onExpansionClick(e) {
const {expansionClickable} = this.props
expansionClickable || e.stopPropagation()
}
render() {
return (
<React.Fragment>
{this.renderStatic()}
{this.isDragging() ? this.renderClone() : null}
</React.Fragment>
)
}
renderStatic() {
return this.renderItem(true)
}
getSharedClassName(clickable) {
return _.flatten([
lookStyles.look,
lookStyles.transparent,
lookStyles.noTransitions,
clickable ? null : [lookStyles.noHover, lookStyles.nonClickable],
(this.isDragging() || this.isDraggable() && !this.isClickable()) ? lookStyles.draggable : null,
// this.isDisabled() ? lookStyles.nonInteractive : null
this.isDisabled() ? lookStyles.disabled : null
])
}
getItemClassName(original) {
const {className, expansionClickable} = this.props
return _.flatten([
expansionClickable ? this.getSharedClassName(this.isClickable()) : null,
styles.verticalWrapper,
original ? styles.original : styles.clone,
className
]).join(' ')
}
getMainClassName() {
const {expansionClickable} = this.props
return _.flatten([
expansionClickable ? null : this.getSharedClassName(this.isClickable()),
styles.main,
this.isExpanded() ? styles.expanded : null
]).join(' ')
}
getExpansionClassName() {
const {expansionClickable, expansionClassName} = this.props
return _.flatten([
expansionClickable ? null : this.getSharedClassName(false),
styles.expansion,
expansionClassName
]).join(' ')
}
renderItem(original) {
return (
<div
className={this.getItemClassName(original)}
onClick={this.onClick}
onMouseOver={this.onMouseOver}
onMouseOut={this.onMouseOut}>
<div className={styles.horizontalWrapper}>
{this.renderMain(original)}
{this.renderExpansion()}
</div>
</div>
)
}
renderMain(original) {
return (
<div ref={original ? this.draggable : null}
className={this.getMainClassName()}>
{this.isDraggable() ? this.renderDragHandle() : null}
<div className={styles.content}>
{this.getMainContent()}
</div>
</div>
)
}
renderDragHandle() {
return (
<div className={styles.dragHandle}/>
)
}
renderExpansion() {
return this.isExpanded()
? (
<div
className={this.getExpansionClassName()}
onClick={this.onExpansionClick}>
{this.getExpansionContent()}
</div>
)
: null
}
renderClone() {
const {position, size} = this.state
const {dragCloneClassName} = this.props
if (position && size) {
return (
<Portal type='global'>
<div className={styles.draggableContainer}>
<div
className={[styles.draggableClone, dragCloneClassName].join(' ')}
style={{
'--x': position.x,
'--y': position.y,
'--width': size.width,
'--height': size.height
}}>
{this.renderItem(false)}
</div>
</div>
</Portal>
)
}
}
initializeDraggable() {
const {addSubscription} = this.props
const draggable = this.draggable.current
const hammer = new Hammer(draggable)
hammer.get('pan').set({
direction: Hammer.DIRECTION_ALL,
threshold: this.isClickable() ? CLICKABLE_PAN_THRESHOLD_PX : 0
})
const pan$ = fromEvent(hammer, 'panstart panmove panend')
const panStart$ = pan$.pipe(filter(e => e.type === 'panstart'))
const panMove$ = pan$.pipe(filter(e => e.type === 'panmove'))
const panEnd$ = pan$.pipe(filter(e => e.type === 'panend'))
const animationFrame$ = interval(0, animationFrameScheduler)
const dragStart$ = panStart$.pipe(
map(({changedPointers}) => changedPointers[0]),
filter(({pageX, pageY} = {}) => pageX && pageY),
map(({pageX, pageY}) => {
const {x: clientX, y: clientY, width, height} = draggable.getBoundingClientRect()
const offset = {
x: Math.round(pageX - clientX),
y: Math.round(pageY - clientY)
}
return {
coords: {
x: pageX,
y: pageY
},
position: {
x: pageX - offset.x - 1,
y: pageY - offset.y - 1
},
size: {
width,
height
},
offset
}
})
)
const dragMove$ = dragStart$.pipe(
switchMap(({offset}) =>
animationFrame$.pipe(
switchMap(() =>
panMove$.pipe(
map(e => e.center)
)
),
debounceTime(10),
distinctUntilChanged(),
map(coords => ({
coords,
position: {
x: coords.x - offset.x - 1,
y: coords.y - offset.y - 1
}
}))
)
)
)
const dragEnd$ = panEnd$.pipe(
delay(50) // prevent click event on drag end
)
addSubscription(
dragStart$.subscribe(this.onDragStart),
dragMove$.subscribe(this.onDragMove),
dragEnd$.subscribe(this.onDragEnd)
)
}
onDragStart({coords, position, size}) {
const {drag$, dragValue, onDragStart} = this.props
this.setState({dragging: true, position, size}, () => {
drag$ && drag$.next({dragging: true, value: dragValue, coords})
onDragStart && onDragStart(dragValue)
})
}
onDragMove({coords, position}) {
const {drag$, onDrag} = this.props
drag$ && drag$.next({coords})
onDrag && onDrag(coords)
this.setState({position})
}
onDragEnd() {
const {drag$, onDragEnd} = this.props
this.setState({dragging: false, position: null, size: null}, () => {
drag$ && drag$.next({dragging: false})
onDragEnd && onDragEnd()
})
}
initializeExpandable() {
const {onExpandDelayed, addSubscription} = this.props
const expanded$ = this.expand$.pipe(
filter(expanded => expanded)
)
const collapsed$ = this.expand$.pipe(
filter(expanded => !expanded)
)
addSubscription(
expanded$.pipe(
switchMap(() =>
timer(EXPAND_DELAYED_TIMEOUT_MS).pipe(
takeUntil(collapsed$)
)
)
).subscribe(
() => onExpandDelayed && onExpandDelayed()
)
)
}
componentDidMount() {
if (this.isDraggable()) {
this.initializeDraggable()
}
if (this.isExpandable()) {
this.initializeExpandable()
}
}
}
export const ListItem = compose(
_ListItem,
withSubscriptions()
)
ListItem.propTypes = {
children: PropTypes.any,
className: PropTypes.string,
clickToCollapse: PropTypes.any,
clickToExpand: PropTypes.any,
clickToToggle: PropTypes.any,
disabled: PropTypes.any,
drag$: PropTypes.object,
dragCloneClassName: PropTypes.string,
dragTooltip: PropTypes.string,
dragValue: PropTypes.any,
expanded: PropTypes.any,
expansion: PropTypes.any,
expansionClassName: PropTypes.string,
expansionClickable: PropTypes.any,
main: PropTypes.any,
onClick: PropTypes.func,
onDrag: PropTypes.func,
onDragEnd: PropTypes.func,
onDragStart: PropTypes.func,
onExpand: PropTypes.func,
onExpandDelayed: PropTypes.func,
onMouseOut: PropTypes.func,
onMouseOver: PropTypes.func
}
|
client/src/components/GalleryItem/tests/SelectGalleryItemTracker.js | silverstripe/silverstripe-asset-admin | import React, { Component } from 'react';
import PropTypes from 'prop-types';
// eslint-disable-next-line import/no-extraneous-dependencies
import { action } from '@storybook/addon-actions';
const triggerAction = action('selected');
class SelectGalleryItemTracker extends Component {
constructor(props) {
super(props);
this.handleSelect = this.handleSelect.bind(this);
this.state = {
selected: props.item.selected,
};
}
handleSelect(event, item) {
triggerAction(this.state.selected ? 'unchecked' : 'checked', item.title);
this.setState({
selected: !this.state.selected,
});
}
render() {
const children = React.Children.map(this.props.children, (child) => (
React.cloneElement(child, {
item: {
...child.props.item,
selected: this.state.selected,
},
onSelect: (...args) => {
if (child.props.onSelect) {
child.props.onSelect(...args);
}
this.handleSelect(...args);
},
})
));
return <div>{children}</div>;
}
}
SelectGalleryItemTracker.propTypes = {
children: PropTypes.any,
item: PropTypes.shape({
selected: PropTypes.bool,
}),
};
SelectGalleryItemTracker.defaultProps = {
item: {
selected: null,
},
};
export default SelectGalleryItemTracker;
|
test/helpers/shallowRenderHelper.js | xunxunyao/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
ajax/libs/react-intl/1.1.0/react-intl-with-locales.min.js | tresni/cdnjs | (function(){"use strict";function a(a){var b,c,d,e,f=Array.prototype.slice.call(arguments,1);for(b=0,c=f.length;c>b;b+=1)if(d=f[b])for(e in d)o.call(d,e)&&(a[e]=d[e]);return a}function b(a,b,c){this.locales=a,this.formats=b,this.pluralFn=c}function c(a){this.id=a}function d(a,b,c,d){this.id=a,this.offset=b,this.options=c,this.pluralFn=d}function e(a,b,c,d){this.id=a,this.offset=b,this.numberFormat=c,this.string=d}function f(a,b){this.id=a,this.options=b}function g(a,b,c){var d="string"==typeof a?g.__parse(a):a;if(!d||"messageFormatPattern"!==d.type)throw new TypeError("A message must be provided as a String or AST.");c=this._mergeFormats(g.formats,c),q(this,"_locale",{value:this._resolveLocale(b)});var e=g.__localeData__[this._locale].pluralRuleFunction,f=this._compilePattern(d,b,c,e),h=this;this.format=function(a){return h._format(f,a)}}function h(a){return 400*a/146097}function i(a,b){b=b||{},D(a)&&(a=a.concat()),A(this,"_locale",{value:this._resolveLocale(a)}),A(this,"_locales",{value:a}),A(this,"_options",{value:{style:this._resolveStyle(b.style),units:this._isValidUnits(b.units)&&b.units}}),A(this,"_messages",{value:B(null)});var c=this;this.format=function(a){return c._format(a)}}function j(a){var b=R(null);return function(){var c=Array.prototype.slice.call(arguments),d=k(c),e=d&&b[d];return e||(e=R(a.prototype),a.apply(e,c),d&&(b[d]=e)),e}}function k(a){if("undefined"!=typeof JSON){var b,c,d,e=[];for(b=0,c=a.length;c>b;b+=1)d=a[b],e.push(d&&"object"==typeof d?l(d):d);return JSON.stringify(e)}}function l(a){var b,c,d,e,f=[],g=[];for(b in a)a.hasOwnProperty(b)&&g.push(b);var h=g.sort();for(c=0,d=h.length;d>c;c+=1)b=h[c],e={},e[b]=a[b],f[c]=e;return f}function m(a,b){if(!isFinite(a))throw new TypeError(b)}function n(a){w.__addLocaleData(a),L.__addLocaleData(a)}var o=Object.prototype.hasOwnProperty,p=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),q=(!p&&!Object.prototype.__defineGetter__,p?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!o.call(a,b)||"value"in c)&&(a[b]=c.value)}),r=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)o.call(b,e)&&q(d,e,b[e]);return d},s=b;b.prototype.compile=function(a){return this.pluralStack=[],this.currentPlural=null,this.pluralNumberFormat=null,this.compileMessage(a)},b.prototype.compileMessage=function(a){if(!a||"messageFormatPattern"!==a.type)throw new Error('Message AST is not of type: "messageFormatPattern"');var b,c,d,e=a.elements,f=[];for(b=0,c=e.length;c>b;b+=1)switch(d=e[b],d.type){case"messageTextElement":f.push(this.compileMessageText(d));break;case"argumentElement":f.push(this.compileArgument(d));break;default:throw new Error("Message element does not have a valid type")}return f},b.prototype.compileMessageText=function(a){return this.currentPlural&&/(^|[^\\])#/g.test(a.value)?(this.pluralNumberFormat||(this.pluralNumberFormat=new Intl.NumberFormat(this.locales)),new e(this.currentPlural.id,this.currentPlural.format.offset,this.pluralNumberFormat,a.value)):a.value.replace(/\\#/g,"#")},b.prototype.compileArgument=function(a){var b=a.format;if(!b)return new c(a.id);var e,g=this.formats,h=this.locales,i=this.pluralFn;switch(b.type){case"numberFormat":return e=g.number[b.style],{id:a.id,format:new Intl.NumberFormat(h,e).format};case"dateFormat":return e=g.date[b.style],{id:a.id,format:new Intl.DateTimeFormat(h,e).format};case"timeFormat":return e=g.time[b.style],{id:a.id,format:new Intl.DateTimeFormat(h,e).format};case"pluralFormat":return e=this.compileOptions(a),new d(a.id,b.offset,e,i);case"selectFormat":return e=this.compileOptions(a),new f(a.id,e);default:throw new Error("Message element does not have a valid format type")}},b.prototype.compileOptions=function(a){var b=a.format,c=b.options,d={};this.pluralStack.push(this.currentPlural),this.currentPlural="pluralFormat"===b.type?a:null;var e,f,g;for(e=0,f=c.length;f>e;e+=1)g=c[e],d[g.selector]=this.compileMessage(g.value);return this.currentPlural=this.pluralStack.pop(),d},c.prototype.format=function(a){return a?"string"==typeof a?a:String(a):""},d.prototype.getOption=function(a){var b=this.options,c=b["="+a]||b[this.pluralFn(a-this.offset)];return c||b.other},e.prototype.format=function(a){var b=this.numberFormat.format(a-this.offset);return this.string.replace(/(^|[^\\])#/g,"$1"+b).replace(/\\#/g,"#")},f.prototype.getOption=function(a){var b=this.options;return b[a]||b.other};var t=function(){function a(a,b){function c(){this.constructor=a}c.prototype=b.prototype,a.prototype=new c}function b(a,b,c,d,e,f){this.message=a,this.expected=b,this.found=c,this.offset=d,this.line=e,this.column=f,this.name="SyntaxError"}function c(a){function c(b){function c(b,c,d){var e,f;for(e=c;d>e;e++)f=a.charAt(e),"\n"===f?(b.seenCR||b.line++,b.column=1,b.seenCR=!1):"\r"===f||"\u2028"===f||"\u2029"===f?(b.line++,b.column=1,b.seenCR=!0):(b.column++,b.seenCR=!1)}return Ob!==b&&(Ob>b&&(Ob=0,Pb={line:1,column:1,seenCR:!1}),c(Pb,Ob,b),Ob=b),Pb}function d(a){Qb>Mb||(Mb>Qb&&(Qb=Mb,Rb=[]),Rb.push(a))}function e(d,e,f){function g(a){var b=1;for(a.sort(function(a,b){return a.description<b.description?-1:a.description>b.description?1:0});b<a.length;)a[b-1]===a[b]?a.splice(b,1):b++}function h(a,b){function c(a){function b(a){return a.charCodeAt(0).toString(16).toUpperCase()}return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,function(a){return"\\x0"+b(a)}).replace(/[\x10-\x1F\x80-\xFF]/g,function(a){return"\\x"+b(a)}).replace(/[\u0180-\u0FFF]/g,function(a){return"\\u0"+b(a)}).replace(/[\u1080-\uFFFF]/g,function(a){return"\\u"+b(a)})}var d,e,f,g=new Array(a.length);for(f=0;f<a.length;f++)g[f]=a[f].description;return d=a.length>1?g.slice(0,-1).join(", ")+" or "+g[a.length-1]:g[0],e=b?'"'+c(b)+'"':"end of input","Expected "+d+" but "+e+" found."}var i=c(f),j=f<a.length?a.charAt(f):null;return null!==e&&g(e),new b(null!==d?d:h(e,j),e,j,f,i.line,i.column)}function f(){var a;return a=g()}function g(){var a,b,c;for(a=Mb,b=[],c=h();c!==C;)b.push(c),c=h();return b!==C&&(Nb=a,b=F(b)),a=b}function h(){var a;return a=j(),a===C&&(a=l()),a}function i(){var b,c,d,e,f,g;if(b=Mb,c=[],d=Mb,e=u(),e!==C?(f=z(),f!==C?(g=u(),g!==C?(e=[e,f,g],d=e):(Mb=d,d=G)):(Mb=d,d=G)):(Mb=d,d=G),d!==C)for(;d!==C;)c.push(d),d=Mb,e=u(),e!==C?(f=z(),f!==C?(g=u(),g!==C?(e=[e,f,g],d=e):(Mb=d,d=G)):(Mb=d,d=G)):(Mb=d,d=G);else c=G;return c!==C&&(Nb=b,c=H(c)),b=c,b===C&&(b=Mb,c=t(),c!==C&&(c=a.substring(b,Mb)),b=c),b}function j(){var a,b;return a=Mb,b=i(),b!==C&&(Nb=a,b=I(b)),a=b}function k(){var b,c,e;if(b=x(),b===C){if(b=Mb,c=[],J.test(a.charAt(Mb))?(e=a.charAt(Mb),Mb++):(e=C,0===Sb&&d(K)),e!==C)for(;e!==C;)c.push(e),J.test(a.charAt(Mb))?(e=a.charAt(Mb),Mb++):(e=C,0===Sb&&d(K));else c=G;c!==C&&(c=a.substring(b,Mb)),b=c}return b}function l(){var b,c,e,f,g,h,i,j,l;return b=Mb,123===a.charCodeAt(Mb)?(c=L,Mb++):(c=C,0===Sb&&d(M)),c!==C?(e=u(),e!==C?(f=k(),f!==C?(g=u(),g!==C?(h=Mb,44===a.charCodeAt(Mb)?(i=O,Mb++):(i=C,0===Sb&&d(P)),i!==C?(j=u(),j!==C?(l=m(),l!==C?(i=[i,j,l],h=i):(Mb=h,h=G)):(Mb=h,h=G)):(Mb=h,h=G),h===C&&(h=N),h!==C?(i=u(),i!==C?(125===a.charCodeAt(Mb)?(j=Q,Mb++):(j=C,0===Sb&&d(R)),j!==C?(Nb=b,c=S(f,h),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function m(){var a;return a=n(),a===C&&(a=o(),a===C&&(a=p())),a}function n(){var b,c,e,f,g,h,i;return b=Mb,a.substr(Mb,6)===T?(c=T,Mb+=6):(c=C,0===Sb&&d(U)),c===C&&(a.substr(Mb,4)===V?(c=V,Mb+=4):(c=C,0===Sb&&d(W)),c===C&&(a.substr(Mb,4)===X?(c=X,Mb+=4):(c=C,0===Sb&&d(Y)))),c!==C?(e=u(),e!==C?(f=Mb,44===a.charCodeAt(Mb)?(g=O,Mb++):(g=C,0===Sb&&d(P)),g!==C?(h=u(),h!==C?(i=z(),i!==C?(g=[g,h,i],f=g):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G),f===C&&(f=N),f!==C?(Nb=b,c=Z(c,f),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function o(){var b,c,e,f,g,h,i,j,k;if(b=Mb,a.substr(Mb,6)===$?(c=$,Mb+=6):(c=C,0===Sb&&d(_)),c!==C)if(e=u(),e!==C)if(44===a.charCodeAt(Mb)?(f=O,Mb++):(f=C,0===Sb&&d(P)),f!==C)if(g=u(),g!==C)if(h=s(),h===C&&(h=N),h!==C)if(i=u(),i!==C){if(j=[],k=r(),k!==C)for(;k!==C;)j.push(k),k=r();else j=G;j!==C?(Nb=b,c=ab(h,j),b=c):(Mb=b,b=G)}else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;return b}function p(){var b,c,e,f,g,h,i;if(b=Mb,a.substr(Mb,6)===bb?(c=bb,Mb+=6):(c=C,0===Sb&&d(cb)),c!==C)if(e=u(),e!==C)if(44===a.charCodeAt(Mb)?(f=O,Mb++):(f=C,0===Sb&&d(P)),f!==C)if(g=u(),g!==C){if(h=[],i=r(),i!==C)for(;i!==C;)h.push(i),i=r();else h=G;h!==C?(Nb=b,c=db(h),b=c):(Mb=b,b=G)}else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;else Mb=b,b=G;return b}function q(){var b,c,e,f;return b=Mb,c=Mb,61===a.charCodeAt(Mb)?(e=eb,Mb++):(e=C,0===Sb&&d(fb)),e!==C?(f=x(),f!==C?(e=[e,f],c=e):(Mb=c,c=G)):(Mb=c,c=G),c!==C&&(c=a.substring(b,Mb)),b=c,b===C&&(b=z()),b}function r(){var b,c,e,f,h,i,j,k,l;return b=Mb,c=u(),c!==C?(e=q(),e!==C?(f=u(),f!==C?(123===a.charCodeAt(Mb)?(h=L,Mb++):(h=C,0===Sb&&d(M)),h!==C?(i=u(),i!==C?(j=g(),j!==C?(k=u(),k!==C?(125===a.charCodeAt(Mb)?(l=Q,Mb++):(l=C,0===Sb&&d(R)),l!==C?(Nb=b,c=gb(e,j),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function s(){var b,c,e,f;return b=Mb,a.substr(Mb,7)===hb?(c=hb,Mb+=7):(c=C,0===Sb&&d(ib)),c!==C?(e=u(),e!==C?(f=x(),f!==C?(Nb=b,c=jb(f),b=c):(Mb=b,b=G)):(Mb=b,b=G)):(Mb=b,b=G),b}function t(){var b,c;if(Sb++,b=[],lb.test(a.charAt(Mb))?(c=a.charAt(Mb),Mb++):(c=C,0===Sb&&d(mb)),c!==C)for(;c!==C;)b.push(c),lb.test(a.charAt(Mb))?(c=a.charAt(Mb),Mb++):(c=C,0===Sb&&d(mb));else b=G;return Sb--,b===C&&(c=C,0===Sb&&d(kb)),b}function u(){var b,c,e;for(Sb++,b=Mb,c=[],e=t();e!==C;)c.push(e),e=t();return c!==C&&(c=a.substring(b,Mb)),b=c,Sb--,b===C&&(c=C,0===Sb&&d(nb)),b}function v(){var b;return ob.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(pb)),b}function w(){var b;return qb.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(rb)),b}function x(){var b,c,e,f,g,h;if(b=Mb,48===a.charCodeAt(Mb)?(c=sb,Mb++):(c=C,0===Sb&&d(tb)),c===C){if(c=Mb,e=Mb,ub.test(a.charAt(Mb))?(f=a.charAt(Mb),Mb++):(f=C,0===Sb&&d(vb)),f!==C){for(g=[],h=v();h!==C;)g.push(h),h=v();g!==C?(f=[f,g],e=f):(Mb=e,e=G)}else Mb=e,e=G;e!==C&&(e=a.substring(c,Mb)),c=e}return c!==C&&(Nb=b,c=wb(c)),b=c}function y(){var b,c,e,f,g,h,i,j;return xb.test(a.charAt(Mb))?(b=a.charAt(Mb),Mb++):(b=C,0===Sb&&d(yb)),b===C&&(b=Mb,a.substr(Mb,2)===zb?(c=zb,Mb+=2):(c=C,0===Sb&&d(Ab)),c!==C&&(Nb=b,c=Bb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Cb?(c=Cb,Mb+=2):(c=C,0===Sb&&d(Db)),c!==C&&(Nb=b,c=Eb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Fb?(c=Fb,Mb+=2):(c=C,0===Sb&&d(Gb)),c!==C&&(Nb=b,c=Hb()),b=c,b===C&&(b=Mb,a.substr(Mb,2)===Ib?(c=Ib,Mb+=2):(c=C,0===Sb&&d(Jb)),c!==C?(e=Mb,f=Mb,g=w(),g!==C?(h=w(),h!==C?(i=w(),i!==C?(j=w(),j!==C?(g=[g,h,i,j],f=g):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G)):(Mb=f,f=G),f!==C&&(f=a.substring(e,Mb)),e=f,e!==C?(Nb=b,c=Kb(e),b=c):(Mb=b,b=G)):(Mb=b,b=G))))),b}function z(){var a,b,c;if(a=Mb,b=[],c=y(),c!==C)for(;c!==C;)b.push(c),c=y();else b=G;return b!==C&&(Nb=a,b=Lb(b)),a=b}var A,B=arguments.length>1?arguments[1]:{},C={},D={start:f},E=f,F=function(a){return{type:"messageFormatPattern",elements:a}},G=C,H=function(a){var b,c,d,e,f,g="";for(b=0,d=a.length;d>b;b+=1)for(e=a[b],c=0,f=e.length;f>c;c+=1)g+=e[c];return g},I=function(a){return{type:"messageTextElement",value:a}},J=/^[^ \t\n\r,.+={}#]/,K={type:"class",value:"[^ \\t\\n\\r,.+={}#]",description:"[^ \\t\\n\\r,.+={}#]"},L="{",M={type:"literal",value:"{",description:'"{"'},N=null,O=",",P={type:"literal",value:",",description:'","'},Q="}",R={type:"literal",value:"}",description:'"}"'},S=function(a,b){return{type:"argumentElement",id:a,format:b&&b[2]}},T="number",U={type:"literal",value:"number",description:'"number"'},V="date",W={type:"literal",value:"date",description:'"date"'},X="time",Y={type:"literal",value:"time",description:'"time"'},Z=function(a,b){return{type:a+"Format",style:b&&b[2]}},$="plural",_={type:"literal",value:"plural",description:'"plural"'},ab=function(a,b){return{type:"pluralFormat",offset:a||0,options:b}},bb="select",cb={type:"literal",value:"select",description:'"select"'},db=function(a){return{type:"selectFormat",options:a}},eb="=",fb={type:"literal",value:"=",description:'"="'},gb=function(a,b){return{type:"optionalFormatPattern",selector:a,value:b}},hb="offset:",ib={type:"literal",value:"offset:",description:'"offset:"'},jb=function(a){return a},kb={type:"other",description:"whitespace"},lb=/^[ \t\n\r]/,mb={type:"class",value:"[ \\t\\n\\r]",description:"[ \\t\\n\\r]"},nb={type:"other",description:"optionalWhitespace"},ob=/^[0-9]/,pb={type:"class",value:"[0-9]",description:"[0-9]"},qb=/^[0-9a-f]/i,rb={type:"class",value:"[0-9a-f]i",description:"[0-9a-f]i"},sb="0",tb={type:"literal",value:"0",description:'"0"'},ub=/^[1-9]/,vb={type:"class",value:"[1-9]",description:"[1-9]"},wb=function(a){return parseInt(a,10)},xb=/^[^{}\\\0-\x1F \t\n\r]/,yb={type:"class",value:"[^{}\\\\\\0-\\x1F \\t\\n\\r]",description:"[^{}\\\\\\0-\\x1F \\t\\n\\r]"},zb="\\#",Ab={type:"literal",value:"\\#",description:'"\\\\#"'},Bb=function(){return"\\#"},Cb="\\{",Db={type:"literal",value:"\\{",description:'"\\\\{"'},Eb=function(){return"{"},Fb="\\}",Gb={type:"literal",value:"\\}",description:'"\\\\}"'},Hb=function(){return"}"},Ib="\\u",Jb={type:"literal",value:"\\u",description:'"\\\\u"'},Kb=function(a){return String.fromCharCode(parseInt(a,16))},Lb=function(a){return a.join("")},Mb=0,Nb=0,Ob=0,Pb={line:1,column:1,seenCR:!1},Qb=0,Rb=[],Sb=0;if("startRule"in B){if(!(B.startRule in D))throw new Error("Can't start parsing from rule \""+B.startRule+'".');E=D[B.startRule]}if(A=E(),A!==C&&Mb===a.length)return A;throw A!==C&&Mb<a.length&&d({type:"end",description:"end of input"}),e(null,Rb,Qb)}return a(b,Error),{SyntaxError:b,parse:c}}(),u=g;q(g,"formats",{enumerable:!0,value:{number:{currency:{style:"currency"},percent:{style:"percent"}},date:{"short":{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},"long":{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{"short":{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},"long":{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}}}),q(g,"__localeData__",{value:r(null)}),q(g,"__addLocaleData",{value:function(a){if(!a||!a.locale)throw new Error("Locale data provided to IntlMessageFormat is missing a `locale` property");if(!a.pluralRuleFunction)throw new Error("Locale data provided to IntlMessageFormat is missing a `pluralRuleFunction` property");var b=a.locale.toLowerCase().split("-")[0];g.__localeData__[b]=a}}),q(g,"__parse",{value:t.parse}),q(g,"defaultLocale",{enumerable:!0,writable:!0,value:void 0}),g.prototype.resolvedOptions=function(){return{locale:this._locale}},g.prototype._compilePattern=function(a,b,c,d){var e=new s(b,c,d);return e.compile(a)},g.prototype._format=function(a,b){var c,d,e,f,g,h="";for(c=0,d=a.length;d>c;c+=1)if(e=a[c],"string"!=typeof e){if(f=e.id,!b||!o.call(b,f))throw new Error("A value must be provided for: "+f);g=b[f],h+=e.options?this._format(e.getOption(g),b):e.format(g)}else h+=e;return h},g.prototype._mergeFormats=function(b,c){var d,e,f={};for(d in b)o.call(b,d)&&(f[d]=e=r(b[d]),c&&o.call(c,d)&&a(e,c[d]));return f},g.prototype._resolveLocale=function(a){a||(a=g.defaultLocale),"string"==typeof a&&(a=[a]);var b,c,d,e=g.__localeData__;for(b=0,c=a.length;c>b;b+=1){if(d=a[b].split("-")[0].toLowerCase(),!/[a-z]{2,3}/.test(d))throw new Error("Language tag provided to IntlMessageFormat is not structrually valid: "+d);if(o.call(e,d))return d}throw new Error("No locale data has been added to IntlMessageFormat for: "+a.join(", "))};var v={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"}};u.__addLocaleData(v),u.defaultLocale="en";var w=u,x=Object.prototype.hasOwnProperty,y=Object.prototype.toString,z=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),A=(!z&&!Object.prototype.__defineGetter__,z?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!x.call(a,b)||"value"in c)&&(a[b]=c.value)}),B=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)x.call(b,e)&&A(d,e,b[e]);return d},C=Array.prototype.indexOf||function(a,b){var c=this;if(!c.length)return-1;for(var d=b||0,e=c.length;e>d;d++)if(c[d]===a)return d;return-1},D=Array.isArray||function(a){return"[object Array]"===y.call(a)},E=Date.now||function(){return(new Date).getTime()},F=Math.round,G=function(a,b){a=+a,b=+b;var c=F(b-a),d=F(c/1e3),e=F(d/60),f=F(e/60),g=F(f/24),i=F(g/7),j=h(g),k=F(12*j),l=F(j);return{millisecond:c,second:d,minute:e,hour:f,day:g,week:i,month:k,year:l}},H=i,I=["second","minute","hour","day","month","year"],J=["best fit","numeric"];A(i,"__localeData__",{value:B(null)}),A(i,"__addLocaleData",{value:function(a){if(!a||!a.locale)throw new Error("Locale data provided to IntlRelativeFormat is missing a `locale` property value");if(!a.fields)throw new Error("Locale data provided to IntlRelativeFormat is missing a `fields` property value");w.__addLocaleData(a);var b=a.locale.toLowerCase().split("-")[0];i.__localeData__[b]=a}}),A(i,"defaultLocale",{enumerable:!0,writable:!0,value:void 0}),A(i,"thresholds",{enumerable:!0,value:{second:45,minute:45,hour:22,day:26,month:11}}),i.prototype.resolvedOptions=function(){return{locale:this._locale,style:this._options.style,units:this._options.units}},i.prototype._compileMessage=function(a){var b,c=this._locales,d=this._locale,e=i.__localeData__,f=e[d].fields[a],g=f.relativeTime,h="",j="";for(b in g.future)g.future.hasOwnProperty(b)&&(h+=" "+b+" {"+g.future[b].replace("{0}","#")+"}");for(b in g.past)g.past.hasOwnProperty(b)&&(j+=" "+b+" {"+g.past[b].replace("{0}","#")+"}");var k="{when, select, future {{0, plural, "+h+"}}past {{0, plural, "+j+"}}}";return new w(k,c)},i.prototype._format=function(a){var b=E();if(void 0===a&&(a=b),!isFinite(a))throw new RangeError("The date value provided to IntlRelativeFormat#format() is not in valid range.");var c=G(b,a),d=this._options.units||this._selectUnits(c),e=c[d];if("numeric"!==this._options.style){var f=this._resolveRelativeUnits(e,d);if(f)return f}return this._resolveMessage(d).format({0:Math.abs(e),when:0>e?"past":"future"})},i.prototype._isValidUnits=function(a){if(!a||C.call(I,a)>=0)return!0;if("string"==typeof a){var b=/s$/.test(a)&&a.substr(0,a.length-1);if(b&&C.call(I,b)>=0)throw new Error('"'+a+'" is not a valid IntlRelativeFormat `units` value, did you mean: '+b)}throw new Error('"'+a+'" is not a valid IntlRelativeFormat `units` value, it must be one of: "'+I.join('", "')+'"')},i.prototype._resolveLocale=function(a){a||(a=i.defaultLocale),"string"==typeof a&&(a=[a]);var b,c,d,e=Object.prototype.hasOwnProperty,f=i.__localeData__;for(b=0,c=a.length;c>b;b+=1){if(d=a[b].split("-")[0].toLowerCase(),!/[a-z]{2,3}/.test(d))throw new Error("Language tag provided to IntlRelativeFormat is not structrually valid: "+d);if(e.call(f,d))return d}throw new Error("No locale data has been added to IntlRelativeFormat for: "+a.join(", "))},i.prototype._resolveMessage=function(a){var b=this._messages;return b[a]||(b[a]=this._compileMessage(a)),b[a]},i.prototype._resolveRelativeUnits=function(a,b){var c=i.__localeData__[this._locale].fields[b];return c.relative?c.relative[a]:void 0},i.prototype._resolveStyle=function(a){if(!a)return J[0];if(C.call(J,a)>=0)return a;throw new Error('"'+a+'" is not a valid IntlRelativeFormat `style` value, it must be one of: "'+J.join('", "')+'"')},i.prototype._selectUnits=function(a){var b,c,d;for(b=0,c=I.length;c>b&&(d=I[b],!(Math.abs(a[d])<i.thresholds[d]));b+=1);return d};var K={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}};H.__addLocaleData(K),H.defaultLocale="en";var L=H,M={locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}},N=React,O=Object.prototype.hasOwnProperty,P=function(){try{return!!Object.defineProperty({},"a",{})}catch(a){return!1}}(),Q=(!P&&!Object.prototype.__defineGetter__,P?Object.defineProperty:function(a,b,c){"get"in c&&a.__defineGetter__?a.__defineGetter__(b,c.get):(!O.call(a,b)||"value"in c)&&(a[b]=c.value)}),R=Object.create||function(a,b){function c(){}var d,e;c.prototype=a,d=new c;for(e in b)O.call(b,e)&&Q(d,e,b[e]);return d},S=j,T={locales:N.PropTypes.oneOfType([N.PropTypes.string,N.PropTypes.array]),formats:N.PropTypes.object,messages:N.PropTypes.object},U={statics:{filterFormatOptions:function(a,b){return b||(b={}),(this.formatOptions||[]).reduce(function(c,d){return a.hasOwnProperty(d)?c[d]=a[d]:b.hasOwnProperty(d)&&(c[d]=b[d]),c},{})}},propsTypes:T,contextTypes:T,childContextTypes:T,getNumberFormat:S(Intl.NumberFormat),getDateTimeFormat:S(Intl.DateTimeFormat),getMessageFormat:S(w),getRelativeFormat:S(L),getChildContext:function(){var a=this.context,b=this.props;return{locales:b.locales||a.locales,formats:b.formats||a.formats,messages:b.messages||a.messages}},formatDate:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatDate()"),this._format("date",a,b)},formatTime:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatTime()"),this._format("time",a,b)},formatRelative:function(a,b){return a=new Date(a),m(a,"A date or timestamp must be provided to formatRelative()"),this._format("relative",a,b)},formatNumber:function(a,b){return this._format("number",a,b)},formatMessage:function(a,b){var c=this.props.locales||this.context.locales,d=this.props.formats||this.context.formats;return"function"==typeof a?a(b):("string"==typeof a&&(a=this.getMessageFormat(a,c,d)),a.format(b))},getIntlMessage:function(a){var b,c=this.props.messages||this.context.messages,d=a.split(".");try{b=d.reduce(function(a,b){return a[b]},c)}finally{if(void 0===b)throw new ReferenceError("Could not find Intl message: "+a)}return b},getNamedFormat:function(a,b){var c=this.props.formats||this.context.formats,d=null;try{d=c[a][b]}finally{if(!d)throw new ReferenceError("No "+a+" format named: "+b)}return d},_format:function(a,b,c){var d=this.props.locales||this.context.locales;switch(c&&"string"==typeof c&&(c=this.getNamedFormat(a,c)),a){case"date":case"time":return this.getDateTimeFormat(d,c).format(b);case"number":return this.getNumberFormat(d,c).format(b);case"relative":return this.getRelativeFormat(d,c).format(b);default:throw new Error("Unrecognized format type: "+a)}}},V=N.createClass({displayName:"FormattedDate",mixins:[U],statics:{formatOptions:["localeMatcher","timeZone","hour12","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("date",c),e=V.filterFormatOptions(a,d);return N.DOM.span(null,this.formatDate(b,e))}}),W=V,X=N.createClass({displayName:"FormattedTime",mixins:[U],statics:{formatOptions:["localeMatcher","timeZone","hour12","formatMatcher","weekday","era","year","month","day","hour","minute","second","timeZoneName"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("time",c),e=X.filterFormatOptions(a,d);return N.DOM.span(null,this.formatTime(b,e))}}),Y=X,Z=N.createClass({displayName:"FormattedRelative",mixins:[U],statics:{formatOptions:["style","units"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("relative",c),e=Z.filterFormatOptions(a,d);return N.DOM.span(null,this.formatRelative(b,e))}}),$=Z,_=N.createClass({displayName:"FormattedNumber",mixins:[U],statics:{formatOptions:["localeMatcher","style","currency","currencyDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"]},propTypes:{format:N.PropTypes.string,value:N.PropTypes.any.isRequired},render:function(){var a=this.props,b=a.value,c=a.format,d=c&&this.getNamedFormat("number",c),e=_.filterFormatOptions(a,d);return N.DOM.span(null,this.formatNumber(b,e))}}),ab=_,bb=N.createClass({displayName:"FormattedMessage",mixins:[U],propTypes:{tagName:N.PropTypes.string,message:N.PropTypes.string.isRequired},getDefaultProps:function(){return{tagName:"span"}},render:function(){var a=this.props,b=a.tagName,c=a.message,d=Math.floor(1099511627776*Math.random()).toString(16),e=new RegExp("(@__ELEMENT-"+d+"-\\d+__@)","g"),f={},g=function(){var a=0;return function(){return"@__ELEMENT-"+d+"-"+(a+=1)+"__@"}}(),h=Object.keys(a).reduce(function(b,c){var d,e=a[c];return N.isValidElement(e)?(d=g(),b[c]=d,f[d]=e):b[c]=e,b},{}),i=this.formatMessage(c,h),j=i.split(e).filter(function(a){return!!a}).map(function(a){return f[a]||a}),k=[b,null].concat(j);return N.createElement.apply(null,k)}}),cb=bb,db={"&":"&",">":">","<":"<",'"':""","'":"'"},eb=/[&><"']/g,fb=function(a){return(""+a).replace(eb,function(a){return db[a]})},gb=N.createClass({displayName:"FormattedHTMLMessage",mixins:[U],propTypes:{tagName:N.PropTypes.string,message:N.PropTypes.string.isRequired},getDefaultProps:function(){return{tagName:"span"}},render:function(){var a=this.props,b=a.tagName,c=a.message,d=Object.keys(a).reduce(function(b,c){var d=a[c];return"string"==typeof d?d=fb(d):N.isValidElement(d)&&(d=N.renderToStaticMarkup(d)),b[c]=d,b},{});return N.DOM[b]({dangerouslySetInnerHTML:{__html:this.formatMessage(c,d)}})}}),hb=gb;n(M);var ib={IntlMixin:U,FormattedDate:W,FormattedTime:Y,FormattedRelative:$,FormattedNumber:ab,FormattedMessage:cb,FormattedHTMLMessage:hb,__addLocaleData:n};"undefined"!=typeof window&&(window.ReactIntlMixin=U,U.__addLocaleData=n),this.ReactIntl=ib}).call(this),ReactIntl.__addLocaleData({locale:"af",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekonde",relative:{0:"nou"},relativeTime:{future:{one:"Oor {0} sekonde",other:"Oor {0} sekondes"},past:{one:"{0} sekonde gelede",other:"{0} sekondes gelede"}}},minute:{displayName:"Minuut",relativeTime:{future:{one:"Oor {0} minuut",other:"Oor {0} minute"},past:{one:"{0} minuut gelede",other:"{0} minute gelede"}}},hour:{displayName:"Uur",relativeTime:{future:{one:"Oor {0} uur",other:"Oor {0} uur"},past:{one:"{0} uur gelede",other:"{0} uur gelede"}}},day:{displayName:"Dag",relative:{0:"vandag",1:"môre",2:"Die dag na môre","-2":"Die dag voor gister","-1":"gister"},relativeTime:{future:{one:"Oor {0} dag",other:"Oor {0} dae"},past:{one:"{0} dag gelede",other:"{0} dae gelede"}}},month:{displayName:"Maand",relative:{0:"vandeesmaand",1:"volgende maand","-1":"verlede maand"},relativeTime:{future:{one:"Oor {0} maand",other:"Oor {0} maande"},past:{one:"{0} maand gelede",other:"{0} maande gelede"}}},year:{displayName:"Jaar",relative:{0:"hierdie jaar",1:"volgende jaar","-1":"verlede jaar"},relativeTime:{future:{one:"Oor {0} jaar",other:"Oor {0} jaar"},past:{one:"{0} jaar gelede",other:"{0} jaar gelede"}}}}}),ReactIntl.__addLocaleData({locale:"ak",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a?"one":"other"},fields:{second:{displayName:"Sɛkɛnd",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Sema",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Dɔnhwer",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Da",relative:{0:"Ndɛ",1:"Ɔkyena","-1":"Ndeda"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Bosome",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Afe",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"am",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"ሰከንድ",relative:{0:"አሁን"},relativeTime:{future:{one:"በ{0} ሰከንድ ውስጥ",other:"በ{0} ሰከንዶች ውስጥ"},past:{one:"ከ{0} ሰከንድ በፊት",other:"ከ{0} ሰከንዶች በፊት"}}},minute:{displayName:"ደቂቃ",relativeTime:{future:{one:"በ{0} ደቂቃ ውስጥ",other:"በ{0} ደቂቃዎች ውስጥ"},past:{one:"ከ{0} ደቂቃ በፊት",other:"ከ{0} ደቂቃዎች በፊት"}}},hour:{displayName:"ሰዓት",relativeTime:{future:{one:"በ{0} ሰዓት ውስጥ",other:"በ{0} ሰዓቶች ውስጥ"},past:{one:"ከ{0} ሰዓት በፊት",other:"ከ{0} ሰዓቶች በፊት"}}},day:{displayName:"ቀን",relative:{0:"ዛሬ",1:"ነገ",2:"ከነገ ወዲያ","-2":"ከትናንት ወዲያ","-1":"ትናንት"},relativeTime:{future:{one:"በ{0} ቀን ውስጥ",other:"በ{0} ቀናት ውስጥ"},past:{one:"ከ{0} ቀን በፊት",other:"ከ{0} ቀናት በፊት"}}},month:{displayName:"ወር",relative:{0:"በዚህ ወር",1:"የሚቀጥለው ወር","-1":"ያለፈው ወር"},relativeTime:{future:{one:"በ{0} ወር ውስጥ",other:"በ{0} ወራት ውስጥ"},past:{one:"ከ{0} ወር በፊት",other:"ከ{0} ወራት በፊት"}}},year:{displayName:"ዓመት",relative:{0:"በዚህ ዓመት",1:"የሚቀጥለው ዓመት","-1":"ያለፈው ዓመት"},relativeTime:{future:{one:"በ{0} ዓመታት ውስጥ",other:"በ{0} ዓመታት ውስጥ"},past:{one:"ከ{0} ዓመት በፊት",other:"ከ{0} ዓመታት በፊት"}}}}}),ReactIntl.__addLocaleData({locale:"ar",pluralRuleFunction:function(a){return a=Math.floor(a),0===a?"zero":1===a?"one":2===a?"two":a%100===Math.floor(a%100)&&a%100>=3&&10>=a%100?"few":a%100===Math.floor(a%100)&&a%100>=11&&99>=a%100?"many":"other"},fields:{second:{displayName:"الثواني",relative:{0:"الآن"},relativeTime:{future:{zero:"خلال {0} من الثواني",one:"خلال {0} من الثواني",two:"خلال ثانيتين",few:"خلال {0} ثوانِ",many:"خلال {0} ثانية",other:"خلال {0} من الثواني"},past:{zero:"قبل {0} من الثواني",one:"قبل {0} من الثواني",two:"قبل ثانيتين",few:"قبل {0} ثوانِ",many:"قبل {0} ثانية",other:"قبل {0} من الثواني"}}},minute:{displayName:"الدقائق",relativeTime:{future:{zero:"خلال {0} من الدقائق",one:"خلال {0} من الدقائق",two:"خلال دقيقتين",few:"خلال {0} دقائق",many:"خلال {0} دقيقة",other:"خلال {0} من الدقائق"},past:{zero:"قبل {0} من الدقائق",one:"قبل {0} من الدقائق",two:"قبل دقيقتين",few:"قبل {0} دقائق",many:"قبل {0} دقيقة",other:"قبل {0} من الدقائق"}}},hour:{displayName:"الساعات",relativeTime:{future:{zero:"خلال {0} من الساعات",one:"خلال {0} من الساعات",two:"خلال ساعتين",few:"خلال {0} ساعات",many:"خلال {0} ساعة",other:"خلال {0} من الساعات"},past:{zero:"قبل {0} من الساعات",one:"قبل {0} من الساعات",two:"قبل ساعتين",few:"قبل {0} ساعات",many:"قبل {0} ساعة",other:"قبل {0} من الساعات"}}},day:{displayName:"يوم",relative:{0:"اليوم",1:"غدًا",2:"بعد الغد","-2":"أول أمس","-1":"أمس"},relativeTime:{future:{zero:"خلال {0} من الأيام",one:"خلال {0} من الأيام",two:"خلال يومين",few:"خلال {0} أيام",many:"خلال {0} يومًا",other:"خلال {0} من الأيام"},past:{zero:"قبل {0} من الأيام",one:"قبل {0} من الأيام",two:"قبل يومين",few:"قبل {0} أيام",many:"قبل {0} يومًا",other:"قبل {0} من الأيام"}}},month:{displayName:"الشهر",relative:{0:"هذا الشهر",1:"الشهر التالي","-1":"الشهر الماضي"},relativeTime:{future:{zero:"خلال {0} من الشهور",one:"خلال {0} من الشهور",two:"خلال شهرين",few:"خلال {0} شهور",many:"خلال {0} شهرًا",other:"خلال {0} من الشهور"},past:{zero:"قبل {0} من الشهور",one:"قبل {0} من الشهور",two:"قبل شهرين",few:"قبل {0} أشهر",many:"قبل {0} شهرًا",other:"قبل {0} من الشهور"}}},year:{displayName:"السنة",relative:{0:"هذه السنة",1:"السنة التالية","-1":"السنة الماضية"},relativeTime:{future:{zero:"خلال {0} من السنوات",one:"خلال {0} من السنوات",two:"خلال سنتين",few:"خلال {0} سنوات",many:"خلال {0} سنة",other:"خلال {0} من السنوات"},past:{zero:"قبل {0} من السنوات",one:"قبل {0} من السنوات",two:"قبل سنتين",few:"قبل {0} سنوات",many:"قبل {0} سنة",other:"قبل {0} من السنوات"}}}}}),ReactIntl.__addLocaleData({locale:"as",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;
return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"ছেকেণ্ড",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"মিনিট",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"ঘণ্টা",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"দিন",relative:{0:"today",1:"কাইলৈ",2:"পৰহিলৈ","-2":"পৰহি","-1":"কালি"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"মাহ",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"বছৰ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"asa",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Thekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Thaa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Thiku",relative:{0:"Iyoo",1:"Yavo","-1":"Ighuo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mweji",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Mwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ast",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"segundu",relative:{0:"now"},relativeTime:{future:{one:"En {0} segundu",other:"En {0} segundos"},past:{one:"Hai {0} segundu",other:"Hai {0} segundos"}}},minute:{displayName:"minutu",relativeTime:{future:{one:"En {0} minutu",other:"En {0} minutos"},past:{one:"Hai {0} minutu",other:"Hai {0} minutos"}}},hour:{displayName:"hora",relativeTime:{future:{one:"En {0} hora",other:"En {0} hores"},past:{one:"Hai {0} hora",other:"Hai {0} hores"}}},day:{displayName:"día",relative:{0:"güei",1:"mañana",2:"pasao mañana","-3":"antantayeri","-2":"antayeri","-1":"ayeri"},relativeTime:{future:{one:"En {0} dia",other:"En {0} díes"},past:{one:"Hai {0} dia",other:"Hai {0} díes"}}},month:{displayName:"mes",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"En {0} mes",other:"En {0} meses"},past:{one:"Hai {0} mes",other:"Hai {0} meses"}}},year:{displayName:"añu",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"En {0} añu",other:"En {0} años"},past:{one:"Hai {0} añu",other:"Hai {0} años"}}}}}),ReactIntl.__addLocaleData({locale:"az",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"saniyə",relative:{0:"indi"},relativeTime:{future:{one:"{0} saniyə ərzində",other:"{0} saniyə ərzində"},past:{one:"{0} saniyə öncə",other:"{0} saniyə öncə"}}},minute:{displayName:"dəqiqə",relativeTime:{future:{one:"{0} dəqiqə ərzində",other:"{0} dəqiqə ərzində"},past:{one:"{0} dəqiqə öncə",other:"{0} dəqiqə öncə"}}},hour:{displayName:"saat",relativeTime:{future:{one:"{0} saat ərzində",other:"{0} saat ərzində"},past:{one:"{0} saat öncə",other:"{0} saat öncə"}}},day:{displayName:"bu gün",relative:{0:"bu gün",1:"sabah","-1":"dünən"},relativeTime:{future:{one:"{0} gün ərində",other:"{0} gün ərində"},past:{one:"{0} gün öncə",other:"{0} gün öncə"}}},month:{displayName:"ay",relative:{0:"bu ay",1:"gələn ay","-1":"keçən ay"},relativeTime:{future:{one:"{0} ay ərzində",other:"{0} ay ərzində"},past:{one:"{0} ay öncə",other:"{0} ay öncə"}}},year:{displayName:"il",relative:{0:"bu il",1:"gələn il","-1":"keçən il"},relativeTime:{future:{one:"{0} il ərzində",other:"{0} il ərzində"},past:{one:"{0} il öncə",other:"{0} il öncə"}}}}}),ReactIntl.__addLocaleData({locale:"be",pluralRuleFunction:function(a){return a=Math.floor(a),a%10===1&&a%100!==11?"one":a%10===Math.floor(a%10)&&a%10>=2&&4>=a%10&&!(a%100>=12&&14>=a%100)?"few":a%10===0||a%10===Math.floor(a%10)&&a%10>=5&&9>=a%10||a%100===Math.floor(a%100)&&a%100>=11&&14>=a%100?"many":"other"},fields:{second:{displayName:"секунда",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"хвіліна",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"гадзіна",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"дзень",relative:{0:"сёння",1:"заўтра",2:"паслязаўтра","-2":"пазаўчора","-1":"учора"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"месяц",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"год",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"bem",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekondi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Mineti",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Insa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ubushiku",relative:{0:"Lelo",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Umweshi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Umwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"bez",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Sihu",relative:{0:"Neng'u ni",1:"Hilawu","-1":"Igolo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mwedzi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Mwaha",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"bg",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"секунда",relative:{0:"сега"},relativeTime:{future:{one:"след {0} секунда",other:"след {0} секунди"},past:{one:"преди {0} секунда",other:"преди {0} секунди"}}},minute:{displayName:"минута",relativeTime:{future:{one:"след {0} минута",other:"след {0} минути"},past:{one:"преди {0} минута",other:"преди {0} минути"}}},hour:{displayName:"час",relativeTime:{future:{one:"след {0} час",other:"след {0} часа"},past:{one:"преди {0} час",other:"преди {0} часа"}}},day:{displayName:"ден",relative:{0:"днес",1:"утре",2:"вдругиден","-2":"онзи ден","-1":"вчера"},relativeTime:{future:{one:"след {0} дни",other:"след {0} дни"},past:{one:"преди {0} ден",other:"преди {0} дни"}}},month:{displayName:"месец",relative:{0:"този месец",1:"следващият месец","-1":"миналият месец"},relativeTime:{future:{one:"след {0} месец",other:"след {0} месеца"},past:{one:"преди {0} месец",other:"преди {0} месеца"}}},year:{displayName:"година",relative:{0:"тази година",1:"следващата година","-1":"миналата година"},relativeTime:{future:{one:"след {0} година",other:"след {0} години"},past:{one:"преди {0} година",other:"преди {0} години"}}}}}),ReactIntl.__addLocaleData({locale:"bm",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"sekondi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"miniti",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"lɛrɛ",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"don",relative:{0:"bi",1:"sini","-1":"kunu"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"kalo",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"san",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"bn",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"সেকেন্ড",relative:{0:"এখন"},relativeTime:{future:{one:"{0} সেকেন্ডে",other:"{0} সেকেন্ডে"},past:{one:"{0} সেকেন্ড পূর্বে",other:"{0} সেকেন্ড পূর্বে"}}},minute:{displayName:"মিনিট",relativeTime:{future:{one:"{0} মিনিটে",other:"{0} মিনিটে"},past:{one:"{0} মিনিট পূর্বে",other:"{0} মিনিট পূর্বে"}}},hour:{displayName:"ঘন্টা",relativeTime:{future:{one:"{0} ঘন্টায়",other:"{0} ঘন্টায়"},past:{one:"{0} ঘন্টা আগে",other:"{0} ঘন্টা আগে"}}},day:{displayName:"দিন",relative:{0:"আজ",1:"আগামীকাল",2:"আগামী পরশু","-2":"গত পরশু","-1":"গতকাল"},relativeTime:{future:{one:"{0} দিনের মধ্যে",other:"{0} দিনের মধ্যে"},past:{one:"{0} দিন পূর্বে",other:"{0} দিন পূর্বে"}}},month:{displayName:"মাস",relative:{0:"এই মাস",1:"পরের মাস","-1":"গত মাস"},relativeTime:{future:{one:"{0} মাসে",other:"{0} মাসে"},past:{one:"{0} মাস পূর্বে",other:"{0} মাস পূর্বে"}}},year:{displayName:"বছর",relative:{0:"এই বছর",1:"পরের বছর","-1":"গত বছর"},relativeTime:{future:{one:"{0} বছরে",other:"{0} বছরে"},past:{one:"{0} বছর পূর্বে",other:"{0} বছর পূর্বে"}}}}}),ReactIntl.__addLocaleData({locale:"bo",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"སྐར་ཆ།",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"སྐར་མ།",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"ཆུ་ཙོ་",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"ཉིན།",relative:{0:"དེ་རིང་",1:"སང་ཉིན་",2:"གནངས་ཉིན་ཀ་","-2":"ཁས་ཉིན་ཀ་","-1":"ཁས་ས་"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"ཟླ་བ་",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ལོ།",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"br",pluralRuleFunction:function(a){return a=Math.floor(a),a%10===1&&a%100!==11&&a%100!==71&&a%100!==91?"one":a%10===2&&a%100!==12&&a%100!==72&&a%100!==92?"two":a%10===Math.floor(a%10)&&(a%10>=3&&4>=a%10||a%10===9)&&!(a%100>=10&&19>=a%100||a%100>=70&&79>=a%100||a%100>=90&&99>=a%100)?"few":0!==a&&a%1e6===0?"many":"other"},fields:{second:{displayName:"eilenn",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"munut",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"eur",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"hiziv",1:"warcʼhoazh","-2":"dercʼhent-decʼh","-1":"decʼh"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"miz",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"brx",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"सेखेन्द",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"मिनिथ",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"रिंगा",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"सान",relative:{0:"दिनै",1:"गाबोन","-1":"मैया"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"दान",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"बोसोर",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"bs",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length,d=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),0===c&&b%10===1&&(b%100!==11||d%10===1&&d%100!==11)?"one":0===c&&b%10===Math.floor(b%10)&&b%10>=2&&4>=b%10&&(!(b%100>=12&&14>=b%100)||d%10===Math.floor(d%10)&&d%10>=2&&4>=d%10&&!(d%100>=12&&14>=d%100))?"few":"other"},fields:{second:{displayName:"sekund",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"minut",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"čas",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"dan",relative:{0:"danas",1:"sutra",2:"prekosutra","-2":"prekjuče","-1":"juče"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"mesec",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"godina",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ca",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"segon",relative:{0:"ara"},relativeTime:{future:{one:"D'aquí a {0} segon",other:"D'aquí a {0} segons"},past:{one:"Fa {0} segon",other:"Fa {0} segons"}}},minute:{displayName:"minut",relativeTime:{future:{one:"D'aquí a {0} minut",other:"D'aquí a {0} minuts"},past:{one:"Fa {0} minut",other:"Fa {0} minuts"}}},hour:{displayName:"hora",relativeTime:{future:{one:"D'aquí a {0} hora",other:"D'aquí a {0} hores"},past:{one:"Fa {0} hora",other:"Fa {0} hores"}}},day:{displayName:"dia",relative:{0:"avui",1:"demà",2:"demà passat","-2":"abans-d'ahir","-1":"ahir"},relativeTime:{future:{one:"D'aquí a {0} dia",other:"D'aquí a {0} dies"},past:{one:"Fa {0} dia",other:"Fa {0} dies"}}},month:{displayName:"mes",relative:{0:"aquest mes",1:"el mes que ve","-1":"el mes passat"},relativeTime:{future:{one:"D'aquí a {0} mes",other:"D'aquí a {0} mesos"},past:{one:"Fa {0} mes",other:"Fa {0} mesos"}}},year:{displayName:"any",relative:{0:"enguany",1:"l'any que ve","-1":"l'any passat"},relativeTime:{future:{one:"D'aquí a {0} any",other:"D'aquí a {0} anys"},past:{one:"Fa {0} any",other:"Fa {0} anys"}}}}}),ReactIntl.__addLocaleData({locale:"cgg",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Obucweka/Esekendi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Edakiika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Shaaha",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Eizooba",relative:{0:"Erizooba",1:"Nyenkyakare","-1":"Nyomwabazyo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Omwezi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Omwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"chr",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"ᎠᏎᏢ",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"ᎢᏯᏔᏬᏍᏔᏅ",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"ᏑᏣᎶᏓ",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"ᏏᎦ",relative:{0:"ᎪᎯ ᎢᎦ",1:"ᏌᎾᎴᎢ","-1":"ᏒᎯ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"ᏏᏅᏓ",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ᏑᏕᏘᏴᏓ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"cs",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":b===Math.floor(b)&&b>=2&&4>=b&&0===c?"few":0!==c?"many":"other"},fields:{second:{displayName:"Sekunda",relative:{0:"nyní"},relativeTime:{future:{one:"za {0} sekundu",few:"za {0} sekundy",many:"za {0} sekundy",other:"za {0} sekund"},past:{one:"před {0} sekundou",few:"před {0} sekundami",many:"před {0} sekundou",other:"před {0} sekundami"}}},minute:{displayName:"Minuta",relativeTime:{future:{one:"za {0} minutu",few:"za {0} minuty",many:"za {0} minuty",other:"za {0} minut"},past:{one:"před {0} minutou",few:"před {0} minutami",many:"před {0} minutou",other:"před {0} minutami"}}},hour:{displayName:"Hodina",relativeTime:{future:{one:"za {0} hodinu",few:"za {0} hodiny",many:"za {0} hodiny",other:"za {0} hodin"},past:{one:"před {0} hodinou",few:"před {0} hodinami",many:"před {0} hodinou",other:"před {0} hodinami"}}},day:{displayName:"Den",relative:{0:"dnes",1:"zítra",2:"pozítří","-2":"předevčírem","-1":"včera"},relativeTime:{future:{one:"za {0} den",few:"za {0} dny",many:"za {0} dne",other:"za {0} dní"},past:{one:"před {0} dnem",few:"před {0} dny",many:"před {0} dnem",other:"před {0} dny"}}},month:{displayName:"Měsíc",relative:{0:"tento měsíc",1:"příští měsíc","-1":"minulý měsíc"},relativeTime:{future:{one:"za {0} měsíc",few:"za {0} měsíce",many:"za {0} měsíce",other:"za {0} měsíců"},past:{one:"před {0} měsícem",few:"před {0} měsíci",many:"před {0} měsícem",other:"před {0} měsíci"}}},year:{displayName:"Rok",relative:{0:"tento rok",1:"příští rok","-1":"minulý rok"},relativeTime:{future:{one:"za {0} rok",few:"za {0} roky",many:"za {0} roku",other:"za {0} let"},past:{one:"před {0} rokem",few:"před {0} lety",many:"před {0} rokem",other:"před {0} lety"}}}}}),ReactIntl.__addLocaleData({locale:"cy",pluralRuleFunction:function(a){return a=Math.floor(a),0===a?"zero":1===a?"one":2===a?"two":3===a?"few":6===a?"many":"other"},fields:{second:{displayName:"Eiliad",relative:{0:"nawr"},relativeTime:{future:{zero:"Ymhen {0} eiliad",one:"Ymhen eiliad",two:"Ymhen {0} eiliad",few:"Ymhen {0} eiliad",many:"Ymhen {0} eiliad",other:"Ymhen {0} eiliad"},past:{zero:"{0} eiliad yn ôl",one:"eiliad yn ôl",two:"{0} eiliad yn ôl",few:"{0} eiliad yn ôl",many:"{0} eiliad yn ôl",other:"{0} eiliad yn ôl"}}},minute:{displayName:"Munud",relativeTime:{future:{zero:"Ymhen {0} munud",one:"Ymhen munud",two:"Ymhen {0} funud",few:"Ymhen {0} munud",many:"Ymhen {0} munud",other:"Ymhen {0} munud"},past:{zero:"{0} munud yn ôl",one:"{0} munud yn ôl",two:"{0} funud yn ôl",few:"{0} munud yn ôl",many:"{0} munud yn ôl",other:"{0} munud yn ôl"}}},hour:{displayName:"Awr",relativeTime:{future:{zero:"Ymhen {0} awr",one:"Ymhen {0} awr",two:"Ymhen {0} awr",few:"Ymhen {0} awr",many:"Ymhen {0} awr",other:"Ymhen {0} awr"},past:{zero:"{0} awr yn ôl",one:"awr yn ôl",two:"{0} awr yn ôl",few:"{0} awr yn ôl",many:"{0} awr yn ôl",other:"{0} awr yn ôl"}}},day:{displayName:"Dydd",relative:{0:"heddiw",1:"yfory",2:"drennydd","-2":"echdoe","-1":"ddoe"},relativeTime:{future:{zero:"Ymhen {0} diwrnod",one:"Ymhen diwrnod",two:"Ymhen deuddydd",few:"Ymhen tridiau",many:"Ymhen {0} diwrnod",other:"Ymhen {0} diwrnod"},past:{zero:"{0} diwrnod yn ôl",one:"{0} diwrnod yn ôl",two:"{0} ddiwrnod yn ôl",few:"{0} diwrnod yn ôl",many:"{0} diwrnod yn ôl",other:"{0} diwrnod yn ôl"}}},month:{displayName:"Mis",relative:{0:"y mis hwn",1:"mis nesaf","-1":"mis diwethaf"},relativeTime:{future:{zero:"Ymhen {0} mis",one:"Ymhen mis",two:"Ymhen deufis",few:"Ymhen {0} mis",many:"Ymhen {0} mis",other:"Ymhen {0} mis"},past:{zero:"{0} mis yn ôl",one:"{0} mis yn ôl",two:"{0} fis yn ôl",few:"{0} mis yn ôl",many:"{0} mis yn ôl",other:"{0} mis yn ôl"}}},year:{displayName:"Blwyddyn",relative:{0:"eleni",1:"blwyddyn nesaf","-1":"llynedd"},relativeTime:{future:{zero:"Ymhen {0} mlynedd",one:"Ymhen blwyddyn",two:"Ymhen {0} flynedd",few:"Ymhen {0} blynedd",many:"Ymhen {0} blynedd",other:"Ymhen {0} mlynedd"},past:{zero:"{0} o flynyddoedd yn ôl",one:"blwyddyn yn ôl",two:"{0} flynedd yn ôl",few:"{0} blynedd yn ôl",many:"{0} blynedd yn ôl",other:"{0} o flynyddoedd yn ôl"}}}}}),ReactIntl.__addLocaleData({locale:"da",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=parseInt(a.toString().replace(/^[^.]*\.?|0+$/g,""),10);return a=Math.floor(a),1===a||0!==c&&(0===b||1===b)?"one":"other"},fields:{second:{displayName:"Sekund",relative:{0:"nu"},relativeTime:{future:{one:"om {0} sekund",other:"om {0} sekunder"},past:{one:"for {0} sekund siden",other:"for {0} sekunder siden"}}},minute:{displayName:"Minut",relativeTime:{future:{one:"om {0} minut",other:"om {0} minutter"},past:{one:"for {0} minut siden",other:"for {0} minutter siden"}}},hour:{displayName:"Time",relativeTime:{future:{one:"om {0} time",other:"om {0} timer"},past:{one:"for {0} time siden",other:"for {0} timer siden"}}},day:{displayName:"Dag",relative:{0:"i dag",1:"i morgen",2:"i overmorgen","-2":"i forgårs","-1":"i går"},relativeTime:{future:{one:"om {0} døgn",other:"om {0} døgn"},past:{one:"for {0} døgn siden",other:"for {0} døgn siden"}}},month:{displayName:"Måned",relative:{0:"denne måned",1:"næste måned","-1":"sidste måned"},relativeTime:{future:{one:"om {0} måned",other:"om {0} måneder"},past:{one:"for {0} måned siden",other:"for {0} måneder siden"}}},year:{displayName:"År",relative:{0:"i år",1:"næste år","-1":"sidste år"},relativeTime:{future:{one:"om {0} år",other:"om {0} år"},past:{one:"for {0} år siden",other:"for {0} år siden"}}}}}),ReactIntl.__addLocaleData({locale:"de",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"jetzt"},relativeTime:{future:{one:"In {0} Sekunde",other:"In {0} Sekunden"},past:{one:"Vor {0} Sekunde",other:"Vor {0} Sekunden"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"In {0} Minute",other:"In {0} Minuten"},past:{one:"Vor {0} Minute",other:"Vor {0} Minuten"}}},hour:{displayName:"Stunde",relativeTime:{future:{one:"In {0} Stunde",other:"In {0} Stunden"},past:{one:"Vor {0} Stunde",other:"Vor {0} Stunden"}}},day:{displayName:"Tag",relative:{0:"Heute",1:"Morgen",2:"Übermorgen","-2":"Vorgestern","-1":"Gestern"},relativeTime:{future:{one:"In {0} Tag",other:"In {0} Tagen"},past:{one:"Vor {0} Tag",other:"Vor {0} Tagen"}}},month:{displayName:"Monat",relative:{0:"Dieser Monat",1:"Nächster Monat","-1":"Letzter Monat"},relativeTime:{future:{one:"In {0} Monat",other:"In {0} Monaten"},past:{one:"Vor {0} Monat",other:"Vor {0} Monaten"}}},year:{displayName:"Jahr",relative:{0:"Dieses Jahr",1:"Nächstes Jahr","-1":"Letztes Jahr"},relativeTime:{future:{one:"In {0} Jahr",other:"In {0} Jahren"},past:{one:"Vor {0} Jahr",other:"Vor {0} Jahren"}}}}}),ReactIntl.__addLocaleData({locale:"dz",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"སྐར་ཆཱ་",relative:{0:"now"},relativeTime:{future:{other:"སྐར་ཆ་ {0} ནང་"},past:{other:"སྐར་ཆ་ {0} ཧེ་མ་"}}},minute:{displayName:"སྐར་མ",relativeTime:{future:{other:"སྐར་མ་ {0} ནང་"},past:{other:"སྐར་མ་ {0} ཧེ་མ་"}}},hour:{displayName:"ཆུ་ཚོད",relativeTime:{future:{other:"ཆུ་ཚོད་ {0} ནང་"},past:{other:"ཆུ་ཚོད་ {0} ཧེ་མ་"}}},day:{displayName:"ཚེས་",relative:{0:"ད་རིས་",1:"ནངས་པ་",2:"གནངས་ཚེ","-2":"ཁ་ཉིམ","-1":"ཁ་ཙ་"},relativeTime:{future:{other:"ཉིནམ་ {0} ནང་"},past:{other:"ཉིནམ་ {0} ཧེ་མ་"}}},month:{displayName:"ཟླ་ཝ་",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"ཟླཝ་ {0} ནང་"},past:{other:"ཟླཝ་ {0} ཧེ་མ་"}}},year:{displayName:"ལོ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"ལོ་འཁོར་ {0} ནང་"},past:{other:"ལོ་འཁོར་ {0} ཧེ་མ་"}}}}}),ReactIntl.__addLocaleData({locale:"ee",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"sekend",relative:{0:"fifi"},relativeTime:{future:{one:"le sekend {0} me",other:"le sekend {0} wo me"},past:{one:"sekend {0} si va yi",other:"sekend {0} si wo va yi"}}},minute:{displayName:"aɖabaƒoƒo",relativeTime:{future:{one:"le aɖabaƒoƒo {0} me",other:"le aɖabaƒoƒo {0} wo me"},past:{one:"aɖabaƒoƒo {0} si va yi",other:"aɖabaƒoƒo {0} si wo va yi"}}},hour:{displayName:"gaƒoƒo",relativeTime:{future:{one:"le gaƒoƒo {0} me",other:"le gaƒoƒo {0} wo me"},past:{one:"gaƒoƒo {0} si va yi",other:"gaƒoƒo {0} si wo va yi"}}},day:{displayName:"ŋkeke",relative:{0:"egbe",1:"etsɔ si gbɔna",2:"nyitsɔ si gbɔna","-2":"nyitsɔ si va yi","-1":"etsɔ si va yi"},relativeTime:{future:{one:"le ŋkeke {0} me",other:"le ŋkeke {0} wo me"},past:{one:"ŋkeke {0} si va yi",other:"ŋkeke {0} si wo va yi"}}},month:{displayName:"ɣleti",relative:{0:"ɣleti sia",1:"ɣleti si gbɔ na","-1":"ɣleti si va yi"},relativeTime:{future:{one:"le ɣleti {0} me",other:"le ɣleti {0} wo me"},past:{one:"ɣleti {0} si va yi",other:"ɣleti {0} si wo va yi"}}},year:{displayName:"ƒe",relative:{0:"ƒe sia",1:"ƒe si gbɔ na","-1":"ƒe si va yi"},relativeTime:{future:{one:"le ƒe {0} me",other:"le ƒe {0} wo me"},past:{one:"ƒe {0} si va yi",other:"ƒe {0} si wo va yi"}}}}}),ReactIntl.__addLocaleData({locale:"el",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Δευτερόλεπτο",relative:{0:"τώρα"},relativeTime:{future:{one:"Σε {0} δευτερόλεπτο",other:"Σε {0} δευτερόλεπτα"},past:{one:"Πριν από {0} δευτερόλεπτο",other:"Πριν από {0} δευτερόλεπτα"}}},minute:{displayName:"Λεπτό",relativeTime:{future:{one:"Σε {0} λεπτό",other:"Σε {0} λεπτά"},past:{one:"Πριν από {0} λεπτό",other:"Πριν από {0} λεπτά"}}},hour:{displayName:"Ώρα",relativeTime:{future:{one:"Σε {0} ώρα",other:"Σε {0} ώρες"},past:{one:"Πριν από {0} ώρα",other:"Πριν από {0} ώρες"}}},day:{displayName:"Ημέρα",relative:{0:"σήμερα",1:"αύριο",2:"μεθαύριο","-2":"προχθές","-1":"χθες"},relativeTime:{future:{one:"Σε {0} ημέρα",other:"Σε {0} ημέρες"},past:{one:"Πριν από {0} ημέρα",other:"Πριν από {0} ημέρες"}}},month:{displayName:"Μήνας",relative:{0:"τρέχων μήνας",1:"επόμενος μήνας","-1":"προηγούμενος μήνας"},relativeTime:{future:{one:"Σε {0} μήνα",other:"Σε {0} μήνες"},past:{one:"Πριν από {0} μήνα",other:"Πριν από {0} μήνες"}}},year:{displayName:"Έτος",relative:{0:"φέτος",1:"επόμενο έτος","-1":"προηγούμενο έτος"},relativeTime:{future:{one:"Σε {0} έτος",other:"Σε {0} έτη"},past:{one:"Πριν από {0} έτος",other:"Πριν από {0} έτη"}}}}}),ReactIntl.__addLocaleData({locale:"en",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"in {0} second",other:"in {0} seconds"},past:{one:"{0} second ago",other:"{0} seconds ago"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"in {0} minute",other:"in {0} minutes"},past:{one:"{0} minute ago",other:"{0} minutes ago"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"in {0} hour",other:"in {0} hours"},past:{one:"{0} hour ago",other:"{0} hours ago"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"in {0} day",other:"in {0} days"},past:{one:"{0} day ago",other:"{0} days ago"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"in {0} month",other:"in {0} months"},past:{one:"{0} month ago",other:"{0} months ago"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"in {0} year",other:"in {0} years"},past:{one:"{0} year ago",other:"{0} years ago"}}}}}),ReactIntl.__addLocaleData({locale:"eo",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"es",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"segundo",relative:{0:"ahora"},relativeTime:{future:{one:"dentro de {0} segundo",other:"dentro de {0} segundos"},past:{one:"hace {0} segundo",other:"hace {0} segundos"}}},minute:{displayName:"minuto",relativeTime:{future:{one:"dentro de {0} minuto",other:"dentro de {0} minutos"},past:{one:"hace {0} minuto",other:"hace {0} minutos"}}},hour:{displayName:"hora",relativeTime:{future:{one:"dentro de {0} hora",other:"dentro de {0} horas"},past:{one:"hace {0} hora",other:"hace {0} horas"}}},day:{displayName:"día",relative:{0:"hoy",1:"mañana",2:"pasado mañana","-2":"antes de ayer","-1":"ayer"},relativeTime:{future:{one:"dentro de {0} día",other:"dentro de {0} días"},past:{one:"hace {0} día",other:"hace {0} días"}}},month:{displayName:"mes",relative:{0:"este mes",1:"el próximo mes","-1":"el mes pasado"},relativeTime:{future:{one:"dentro de {0} mes",other:"dentro de {0} meses"},past:{one:"hace {0} mes",other:"hace {0} meses"}}},year:{displayName:"año",relative:{0:"este año",1:"el próximo año","-1":"el año pasado"},relativeTime:{future:{one:"dentro de {0} año",other:"dentro de {0} años"},past:{one:"hace {0} año",other:"hace {0} años"}}}}}),ReactIntl.__addLocaleData({locale:"et",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"sekund",relative:{0:"nüüd"},relativeTime:{future:{one:"{0} sekundi pärast",other:"{0} sekundi pärast"},past:{one:"{0} sekundi eest",other:"{0} sekundi eest"}}},minute:{displayName:"minut",relativeTime:{future:{one:"{0} minuti pärast",other:"{0} minuti pärast"},past:{one:"{0} minuti eest",other:"{0} minuti eest"}}},hour:{displayName:"tund",relativeTime:{future:{one:"{0} tunni pärast",other:"{0} tunni pärast"},past:{one:"{0} tunni eest",other:"{0} tunni eest"}}},day:{displayName:"päev",relative:{0:"täna",1:"homme",2:"ülehomme","-2":"üleeile","-1":"eile"},relativeTime:{future:{one:"{0} päeva pärast",other:"{0} päeva pärast"},past:{one:"{0} päeva eest",other:"{0} päeva eest"}}},month:{displayName:"kuu",relative:{0:"käesolev kuu",1:"järgmine kuu","-1":"eelmine kuu"},relativeTime:{future:{one:"{0} kuu pärast",other:"{0} kuu pärast"},past:{one:"{0} kuu eest",other:"{0} kuu eest"}}},year:{displayName:"aasta",relative:{0:"käesolev aasta",1:"järgmine aasta","-1":"eelmine aasta"},relativeTime:{future:{one:"{0} aasta pärast",other:"{0} aasta pärast"},past:{one:"{0} aasta eest",other:"{0} aasta eest"}}}}}),ReactIntl.__addLocaleData({locale:"eu",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"
},fields:{second:{displayName:"Segundoa",relative:{0:"orain"},relativeTime:{future:{one:"{0} segundo barru",other:"{0} segundo barru"},past:{one:"Duela {0} segundo",other:"Duela {0} segundo"}}},minute:{displayName:"Minutua",relativeTime:{future:{one:"{0} minutu barru",other:"{0} minutu barru"},past:{one:"Duela {0} minutu",other:"Duela {0} minutu"}}},hour:{displayName:"Ordua",relativeTime:{future:{one:"{0} ordu barru",other:"{0} ordu barru"},past:{one:"Duela {0} ordu",other:"Duela {0} ordu"}}},day:{displayName:"Eguna",relative:{0:"gaur",1:"bihar",2:"etzi","-2":"herenegun","-1":"atzo"},relativeTime:{future:{one:"{0} egun barru",other:"{0} egun barru"},past:{one:"Duela {0} egun",other:"Duela {0} egun"}}},month:{displayName:"Hilabetea",relative:{0:"hilabete hau",1:"hurrengo hilabetea","-1":"aurreko hilabetea"},relativeTime:{future:{one:"{0} hilabete barru",other:"{0} hilabete barru"},past:{one:"Duela {0} hilabete",other:"Duela {0} hilabete"}}},year:{displayName:"Urtea",relative:{0:"aurten",1:"hurrengo urtea","-1":"aurreko urtea"},relativeTime:{future:{one:"{0} urte barru",other:"{0} urte barru"},past:{one:"Duela {0} urte",other:"Duela {0} urte"}}}}}),ReactIntl.__addLocaleData({locale:"fa",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"ثانیه",relative:{0:"اکنون"},relativeTime:{future:{one:"{0} ثانیه بعد",other:"{0} ثانیه بعد"},past:{one:"{0} ثانیه پیش",other:"{0} ثانیه پیش"}}},minute:{displayName:"دقیقه",relativeTime:{future:{one:"{0} دقیقه بعد",other:"{0} دقیقه بعد"},past:{one:"{0} دقیقه پیش",other:"{0} دقیقه پیش"}}},hour:{displayName:"ساعت",relativeTime:{future:{one:"{0} ساعت بعد",other:"{0} ساعت بعد"},past:{one:"{0} ساعت پیش",other:"{0} ساعت پیش"}}},day:{displayName:"روز",relative:{0:"امروز",1:"فردا",2:"پسفردا","-2":"پریروز","-1":"دیروز"},relativeTime:{future:{one:"{0} روز بعد",other:"{0} روز بعد"},past:{one:"{0} روز پیش",other:"{0} روز پیش"}}},month:{displayName:"ماه",relative:{0:"این ماه",1:"ماه آینده","-1":"ماه گذشته"},relativeTime:{future:{one:"{0} ماه بعد",other:"{0} ماه بعد"},past:{one:"{0} ماه پیش",other:"{0} ماه پیش"}}},year:{displayName:"سال",relative:{0:"امسال",1:"سال آینده","-1":"سال گذشته"},relativeTime:{future:{one:"{0} سال بعد",other:"{0} سال بعد"},past:{one:"{0} سال پیش",other:"{0} سال پیش"}}}}}),ReactIntl.__addLocaleData({locale:"ff",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===b?"one":"other"},fields:{second:{displayName:"Majaango",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Hoƴom",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Waktu",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ñalnde",relative:{0:"Hannde",1:"Jaŋngo","-1":"Haŋki"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Lewru",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Hitaande",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"fi",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"sekunti",relative:{0:"nyt"},relativeTime:{future:{one:"{0} sekunnin päästä",other:"{0} sekunnin päästä"},past:{one:"{0} sekunti sitten",other:"{0} sekuntia sitten"}}},minute:{displayName:"minuutti",relativeTime:{future:{one:"{0} minuutin päästä",other:"{0} minuutin päästä"},past:{one:"{0} minuutti sitten",other:"{0} minuuttia sitten"}}},hour:{displayName:"tunti",relativeTime:{future:{one:"{0} tunnin päästä",other:"{0} tunnin päästä"},past:{one:"{0} tunti sitten",other:"{0} tuntia sitten"}}},day:{displayName:"päivä",relative:{0:"tänään",1:"huomenna",2:"ylihuomenna","-2":"toissapäivänä","-1":"eilen"},relativeTime:{future:{one:"{0} päivän päästä",other:"{0} päivän päästä"},past:{one:"{0} päivä sitten",other:"{0} päivää sitten"}}},month:{displayName:"kuukausi",relative:{0:"tässä kuussa",1:"ensi kuussa","-1":"viime kuussa"},relativeTime:{future:{one:"{0} kuukauden päästä",other:"{0} kuukauden päästä"},past:{one:"{0} kuukausi sitten",other:"{0} kuukautta sitten"}}},year:{displayName:"vuosi",relative:{0:"tänä vuonna",1:"ensi vuonna","-1":"viime vuonna"},relativeTime:{future:{one:"{0} vuoden päästä",other:"{0} vuoden päästä"},past:{one:"{0} vuosi sitten",other:"{0} vuotta sitten"}}}}}),ReactIntl.__addLocaleData({locale:"fil",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length,d=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),0===c&&(1===b||2===b||3===b||0===c&&(b%10!==4&&b%10!==6&&b%10!==9||0!==c&&d%10!==4&&d%10!==6&&d%10!==9))?"one":"other"},fields:{second:{displayName:"Segundo",relative:{0:"ngayon"},relativeTime:{future:{one:"Sa loob ng {0} segundo",other:"Sa loob ng {0} segundo"},past:{one:"{0} segundo ang nakalipas",other:"{0} segundo ang nakalipas"}}},minute:{displayName:"Minuto",relativeTime:{future:{one:"Sa loob ng {0} minuto",other:"Sa loob ng {0} minuto"},past:{one:"{0} minuto ang nakalipas",other:"{0} minuto ang nakalipas"}}},hour:{displayName:"Oras",relativeTime:{future:{one:"Sa loob ng {0} oras",other:"Sa loob ng {0} oras"},past:{one:"{0} oras ang nakalipas",other:"{0} oras ang nakalipas"}}},day:{displayName:"Araw",relative:{0:"Ngayon",1:"Bukas",2:"Samakalawa","-2":"Araw bago ang kahapon","-1":"Kahapon"},relativeTime:{future:{one:"Sa loob ng {0} araw",other:"Sa loob ng {0} araw"},past:{one:"{0} araw ang nakalipas",other:"{0} araw ang nakalipas"}}},month:{displayName:"Buwan",relative:{0:"ngayong buwan",1:"susunod na buwan","-1":"nakaraang buwan"},relativeTime:{future:{one:"Sa loob ng {0} buwan",other:"Sa loob ng {0} buwan"},past:{one:"{0} buwan ang nakalipas",other:"{0} buwan ang nakalipas"}}},year:{displayName:"Taon",relative:{0:"ngayong taon",1:"susunod na taon","-1":"nakaraang taon"},relativeTime:{future:{one:"Sa loob ng {0} taon",other:"Sa loob ng {0} taon"},past:{one:"{0} taon ang nakalipas",other:"{0} taon ang nakalipas"}}}}}),ReactIntl.__addLocaleData({locale:"fo",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"sekund",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"mínúta",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"klukkustund",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"dagur",relative:{0:"í dag",1:"á morgunn",2:"á yfirmorgunn","-2":"í fyrradag","-1":"í gær"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"mánuður",relative:{0:"henda mánuður",1:"næstu mánuður","-1":"síðstu mánuður"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ár",relative:{0:"hetta ár",1:"næstu ár","-1":"síðstu ár"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"fr",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===b?"one":"other"},fields:{second:{displayName:"seconde",relative:{0:"maintenant"},relativeTime:{future:{one:"dans {0} seconde",other:"dans {0} secondes"},past:{one:"il y a {0} seconde",other:"il y a {0} secondes"}}},minute:{displayName:"minute",relativeTime:{future:{one:"dans {0} minute",other:"dans {0} minutes"},past:{one:"il y a {0} minute",other:"il y a {0} minutes"}}},hour:{displayName:"heure",relativeTime:{future:{one:"dans {0} heure",other:"dans {0} heures"},past:{one:"il y a {0} heure",other:"il y a {0} heures"}}},day:{displayName:"jour",relative:{0:"aujourd’hui",1:"demain",2:"après-demain","-2":"avant-hier","-1":"hier"},relativeTime:{future:{one:"dans {0} jour",other:"dans {0} jours"},past:{one:"il y a {0} jour",other:"il y a {0} jours"}}},month:{displayName:"mois",relative:{0:"ce mois-ci",1:"le mois prochain","-1":"le mois dernier"},relativeTime:{future:{one:"dans {0} mois",other:"dans {0} mois"},past:{one:"il y a {0} mois",other:"il y a {0} mois"}}},year:{displayName:"année",relative:{0:"cette année",1:"l’année prochaine","-1":"l’année dernière"},relativeTime:{future:{one:"dans {0} an",other:"dans {0} ans"},past:{one:"il y a {0} an",other:"il y a {0} ans"}}}}}),ReactIntl.__addLocaleData({locale:"fur",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"secont",relative:{0:"now"},relativeTime:{future:{one:"ca di {0} secont",other:"ca di {0} seconts"},past:{one:"{0} secont indaûr",other:"{0} seconts indaûr"}}},minute:{displayName:"minût",relativeTime:{future:{one:"ca di {0} minût",other:"ca di {0} minûts"},past:{one:"{0} minût indaûr",other:"{0} minûts indaûr"}}},hour:{displayName:"ore",relativeTime:{future:{one:"ca di {0} ore",other:"ca di {0} oris"},past:{one:"{0} ore indaûr",other:"{0} oris indaûr"}}},day:{displayName:"dì",relative:{0:"vuê",1:"doman",2:"passantdoman","-2":"îr l'altri","-1":"îr"},relativeTime:{future:{one:"ca di {0} zornade",other:"ca di {0} zornadis"},past:{one:"{0} zornade indaûr",other:"{0} zornadis indaûr"}}},month:{displayName:"mês",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"ca di {0} mês",other:"ca di {0} mês"},past:{one:"{0} mês indaûr",other:"{0} mês indaûr"}}},year:{displayName:"an",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"ca di {0} an",other:"ca di {0} agns"},past:{one:"{0} an indaûr",other:"{0} agns indaûr"}}}}}),ReactIntl.__addLocaleData({locale:"fy",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Sekonde",relative:{0:"nu"},relativeTime:{future:{one:"Oer {0} sekonde",other:"Oer {0} sekonden"},past:{one:"{0} sekonde lyn",other:"{0} sekonden lyn"}}},minute:{displayName:"Minút",relativeTime:{future:{one:"Oer {0} minút",other:"Oer {0} minuten"},past:{one:"{0} minút lyn",other:"{0} minuten lyn"}}},hour:{displayName:"oere",relativeTime:{future:{one:"Oer {0} oere",other:"Oer {0} oere"},past:{one:"{0} oere lyn",other:"{0} oere lyn"}}},day:{displayName:"dei",relative:{0:"vandaag",1:"morgen",2:"Oermorgen","-2":"eergisteren","-1":"gisteren"},relativeTime:{future:{one:"Oer {0} dei",other:"Oer {0} deien"},past:{one:"{0} dei lyn",other:"{0} deien lyn"}}},month:{displayName:"Moanne",relative:{0:"dizze moanne",1:"folgjende moanne","-1":"foarige moanne"},relativeTime:{future:{one:"Oer {0} moanne",other:"Oer {0} moannen"},past:{one:"{0} moanne lyn",other:"{0} moannen lyn"}}},year:{displayName:"Jier",relative:{0:"dit jier",1:"folgjend jier","-1":"foarich jier"},relativeTime:{future:{one:"Oer {0} jier",other:"Oer {0} jier"},past:{one:"{0} jier lyn",other:"{0} jier lyn"}}}}}),ReactIntl.__addLocaleData({locale:"ga",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":2===a?"two":a===Math.floor(a)&&a>=3&&6>=a?"few":a===Math.floor(a)&&a>=7&&10>=a?"many":"other"},fields:{second:{displayName:"Soicind",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Nóiméad",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Uair",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Lá",relative:{0:"Inniu",1:"Amárach",2:"Arú amárach","-2":"Arú inné","-1":"Inné"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mí",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Bliain",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"gd",pluralRuleFunction:function(a){return a=Math.floor(a),1===a||11===a?"one":2===a||12===a?"two":a===Math.floor(a)&&(a>=3&&10>=a||a>=13&&19>=a)?"few":"other"},fields:{second:{displayName:"Diog",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Mionaid",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Uair a thìde",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Latha",relative:{0:"An-diugh",1:"A-màireach",2:"An-earar","-2":"A-bhòin-dè","-1":"An-dè"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mìos",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Bliadhna",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"gl",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Segundo",relative:{0:"agora"},relativeTime:{future:{one:"En {0} segundo",other:"En {0} segundos"},past:{one:"Hai {0} segundo",other:"Hai {0} segundos"}}},minute:{displayName:"Minuto",relativeTime:{future:{one:"En {0} minuto",other:"En {0} minutos"},past:{one:"Hai {0} minuto",other:"Hai {0} minutos"}}},hour:{displayName:"Hora",relativeTime:{future:{one:"En {0} hora",other:"En {0} horas"},past:{one:"Hai {0} hora",other:"Hai {0} horas"}}},day:{displayName:"Día",relative:{0:"hoxe",1:"mañá",2:"pasadomañá","-2":"antonte","-1":"onte"},relativeTime:{future:{one:"En {0} día",other:"En {0} días"},past:{one:"Hai {0} día",other:"Hai {0} días"}}},month:{displayName:"Mes",relative:{0:"este mes",1:"mes seguinte","-1":"mes pasado"},relativeTime:{future:{one:"En {0} mes",other:"En {0} meses"},past:{one:"Hai {0} mes",other:"Hai {0} meses"}}},year:{displayName:"Ano",relative:{0:"este ano",1:"seguinte ano","-1":"ano pasado"},relativeTime:{future:{one:"En {0} ano",other:"En {0} anos"},past:{one:"Hai {0} ano",other:"Hai {0} anos"}}}}}),ReactIntl.__addLocaleData({locale:"gsw",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minuute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Schtund",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Tag",relative:{0:"hüt",1:"moorn",2:"übermoorn","-2":"vorgeschter","-1":"geschter"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Monet",relative:{0:"diese Monet",1:"nächste Monet","-1":"letzte Monet"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Jaar",relative:{0:"diese Jaar",1:"nächste Jaar","-1":"letzte Jaar"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"gu",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"સેકન્ડ",relative:{0:"હમણાં"},relativeTime:{future:{one:"{0} સેકંડમાં",other:"{0} સેકંડમાં"},past:{one:"{0} સેકંડ પહેલા",other:"{0} સેકંડ પહેલા"}}},minute:{displayName:"મિનિટ",relativeTime:{future:{one:"{0} મિનિટમાં",other:"{0} મિનિટમાં"},past:{one:"{0} મિનિટ પહેલા",other:"{0} મિનિટ પહેલા"}}},hour:{displayName:"કલાક",relativeTime:{future:{one:"{0} કલાકમાં",other:"{0} કલાકમાં"},past:{one:"{0} કલાક પહેલા",other:"{0} કલાક પહેલા"}}},day:{displayName:"દિવસ",relative:{0:"આજે",1:"આવતીકાલે",2:"પરમદિવસે","-2":"ગયા પરમદિવસે","-1":"ગઈકાલે"},relativeTime:{future:{one:"{0} દિવસમાં",other:"{0} દિવસમાં"},past:{one:"{0} દિવસ પહેલા",other:"{0} દિવસ પહેલા"}}},month:{displayName:"મહિનો",relative:{0:"આ મહિને",1:"આવતા મહિને","-1":"ગયા મહિને"},relativeTime:{future:{one:"{0} મહિનામાં",other:"{0} મહિનામાં"},past:{one:"{0} મહિના પહેલા",other:"{0} મહિના પહેલા"}}},year:{displayName:"વર્ષ",relative:{0:"આ વર્ષે",1:"આવતા વર્ષે","-1":"ગયા વર્ષે"},relativeTime:{future:{one:"{0} વર્ષમાં",other:"{0} વર્ષમાં"},past:{one:"{0} વર્ષ પહેલા",other:"{0} વર્ષ પહેલા"}}}}}),ReactIntl.__addLocaleData({locale:"gv",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),0===c&&b%10===1?"one":0===c&&b%10===2?"two":0!==c||b%100!==0&&b%100!==20&&b%100!==40&&b%100!==60&&b%100!==80?0!==c?"many":"other":"few"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ha",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Daƙiƙa",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minti",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Awa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Kwana",relative:{0:"Yau",1:"Gobe","-1":"Jiya"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Wata",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Shekara",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"haw",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"he",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":2===b&&0===c?"two":0!==c||a>=0&&10>=a||a%10!==0?"other":"many"},fields:{second:{displayName:"שנייה",relative:{0:"עכשיו"},relativeTime:{future:{one:"בעוד שנייה {0}",two:"בעוד {0} שניות",many:"בעוד {0} שניות",other:"בעוד {0} שניות"},past:{one:"לפני שנייה {0}",two:"לפני {0} שניות",many:"לפני {0} שניות",other:"לפני {0} שניות"}}},minute:{displayName:"דקה",relativeTime:{future:{one:"בעוד דקה {0}",two:"בעוד {0} דקות",many:"בעוד {0} דקות",other:"בעוד {0} דקות"},past:{one:"לפני דקה {0}",two:"לפני {0} דקות",many:"לפני {0} דקות",other:"לפני {0} דקות"}}},hour:{displayName:"שעה",relativeTime:{future:{one:"בעוד שעה {0}",two:"בעוד {0} שעות",many:"בעוד {0} שעות",other:"בעוד {0} שעות"},past:{one:"לפני שעה {0}",two:"לפני {0} שעות",many:"לפני {0} שעות",other:"לפני {0} שעות"}}},day:{displayName:"יום",relative:{0:"היום",1:"מחר",2:"מחרתיים","-2":"שלשום","-1":"אתמול"},relativeTime:{future:{one:"בעוד יום {0}",two:"בעוד {0} ימים",many:"בעוד {0} ימים",other:"בעוד {0} ימים"},past:{one:"לפני יום {0}",two:"לפני {0} ימים",many:"לפני {0} ימים",other:"לפני {0} ימים"}}},month:{displayName:"חודש",relative:{0:"החודש",1:"החודש הבא","-1":"החודש שעבר"},relativeTime:{future:{one:"בעוד חודש {0}",two:"בעוד {0} חודשים",many:"בעוד {0} חודשים",other:"בעוד {0} חודשים"},past:{one:"לפני חודש {0}",two:"לפני {0} חודשים",many:"לפני {0} חודשים",other:"לפני {0} חודשים"}}},year:{displayName:"שנה",relative:{0:"השנה",1:"השנה הבאה","-1":"השנה שעברה"},relativeTime:{future:{one:"בעוד שנה {0}",two:"בעוד {0} שנים",many:"בעוד {0} שנים",other:"בעוד {0} שנים"},past:{one:"לפני שנה {0}",two:"לפני {0} שנים",many:"לפני {0} שנים",other:"לפני {0} שנים"}}}}}),ReactIntl.__addLocaleData({locale:"hi",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"सेकंड",relative:{0:"अब"},relativeTime:{future:{one:"{0} सेकंड में",other:"{0} सेकंड में"},past:{one:"{0} सेकंड पहले",other:"{0} सेकंड पहले"}}},minute:{displayName:"मिनट",relativeTime:{future:{one:"{0} मिनट में",other:"{0} मिनट में"},past:{one:"{0} मिनट पहले",other:"{0} मिनट पहले"}}},hour:{displayName:"घंटा",relativeTime:{future:{one:"{0} घंटे में",other:"{0} घंटे में"},past:{one:"{0} घंटे पहले",other:"{0} घंटे पहले"}}},day:{displayName:"दिन",relative:{0:"आज",1:"आने वाला कल",2:"परसों","-2":"बीता परसों","-1":"बीता कल"},relativeTime:{future:{one:"{0} दिन में",other:"{0} दिन में"},past:{one:"{0} दिन पहले",other:"{0} दिन पहले"}}},month:{displayName:"माह",relative:{0:"यह माह",1:"अगला माह","-1":"पिछला माह"},relativeTime:{future:{one:"{0} माह में",other:"{0} माह में"},past:{one:"{0} माह पहले",other:"{0} माह पहले"}}},year:{displayName:"वर्ष",relative:{0:"यह वर्ष",1:"अगला वर्ष","-1":"पिछला वर्ष"},relativeTime:{future:{one:"{0} वर्ष में",other:"{0} वर्ष में"},past:{one:"{0} वर्ष पहले",other:"{0} वर्ष पहले"}}}}}),ReactIntl.__addLocaleData({locale:"hr",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length,d=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),0===c&&b%10===1&&(b%100!==11||d%10===1&&d%100!==11)?"one":0===c&&b%10===Math.floor(b%10)&&b%10>=2&&4>=b%10&&(!(b%100>=12&&14>=b%100)||d%10===Math.floor(d%10)&&d%10>=2&&4>=d%10&&!(d%100>=12&&14>=d%100))?"few":"other"},fields:{second:{displayName:"Sekunda",relative:{0:"sada"},relativeTime:{future:{one:"za {0} sekundu",few:"za {0} sekunde",other:"za {0} sekundi"},past:{one:"prije {0} sekundu",few:"prije {0} sekunde",other:"prije {0} sekundi"}}},minute:{displayName:"Minuta",relativeTime:{future:{one:"za {0} minutu",few:"za {0} minute",other:"za {0} minuta"},past:{one:"prije {0} minutu",few:"prije {0} minute",other:"prije {0} minuta"}}},hour:{displayName:"Sat",relativeTime:{future:{one:"za {0} sat",few:"za {0} sata",other:"za {0} sati"},past:{one:"prije {0} sat",few:"prije {0} sata",other:"prije {0} sati"}}},day:{displayName:"Dan",relative:{0:"danas",1:"sutra",2:"prekosutra","-2":"prekjučer","-1":"jučer"},relativeTime:{future:{one:"za {0} dan",few:"za {0} dana",other:"za {0} dana"},past:{one:"prije {0} dan",few:"prije {0} dana",other:"prije {0} dana"}}},month:{displayName:"Mjesec",relative:{0:"ovaj mjesec",1:"sljedeći mjesec","-1":"prošli mjesec"},relativeTime:{future:{one:"za {0} mjesec",few:"za {0} mjeseca",other:"za {0} mjeseci"},past:{one:"prije {0} mjesec",few:"prije {0} mjeseca",other:"prije {0} mjeseci"}}},year:{displayName:"Godina",relative:{0:"ove godine",1:"sljedeće godine","-1":"prošle godine"},relativeTime:{future:{one:"za {0} godinu",few:"za {0} godine",other:"za {0} godina"},past:{one:"prije {0} godinu",few:"prije {0} godine",other:"prije {0} godina"}}}}}),ReactIntl.__addLocaleData({locale:"hu",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"másodperc",relative:{0:"most"},relativeTime:{future:{one:"{0} másodperc múlva",other:"{0} másodperc múlva"},past:{one:"{0} másodperccel ezelőtt",other:"{0} másodperccel ezelőtt"}}},minute:{displayName:"perc",relativeTime:{future:{one:"{0} perc múlva",other:"{0} perc múlva"},past:{one:"{0} perccel ezelőtt",other:"{0} perccel ezelőtt"}}},hour:{displayName:"óra",relativeTime:{future:{one:"{0} óra múlva",other:"{0} óra múlva"},past:{one:"{0} órával ezelőtt",other:"{0} órával ezelőtt"}}},day:{displayName:"nap",relative:{0:"ma",1:"holnap",2:"holnapután","-2":"tegnapelőtt","-1":"tegnap"},relativeTime:{future:{one:"{0} nap múlva",other:"{0} nap múlva"},past:{one:"{0} nappal ezelőtt",other:"{0} nappal ezelőtt"}}},month:{displayName:"hónap",relative:{0:"ez a hónap",1:"következő hónap","-1":"előző hónap"},relativeTime:{future:{one:"{0} hónap múlva",other:"{0} hónap múlva"},past:{one:"{0} hónappal ezelőtt",other:"{0} hónappal ezelőtt"}}},year:{displayName:"év",relative:{0:"ez az év",1:"következő év","-1":"előző év"},relativeTime:{future:{one:"{0} év múlva",other:"{0} év múlva"},past:{one:"{0} évvel ezelőtt",other:"{0} évvel ezelőtt"}}}}}),ReactIntl.__addLocaleData({locale:"hy",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===b?"one":"other"},fields:{second:{displayName:"Վայրկյան",relative:{0:"այժմ"},relativeTime:{future:{one:"{0} վայրկյան անց",other:"{0} վայրկյան անց"},past:{one:"{0} վայրկյան առաջ",other:"{0} վայրկյան առաջ"}}},minute:{displayName:"Րոպե",relativeTime:{future:{one:"{0} րոպե անց",other:"{0} րոպե անց"},past:{one:"{0} րոպե առաջ",other:"{0} րոպե առաջ"}}},hour:{displayName:"Ժամ",relativeTime:{future:{one:"{0} ժամ անց",other:"{0} ժամ անց"},past:{one:"{0} ժամ առաջ",other:"{0} ժամ առաջ"}}},day:{displayName:"Օր",relative:{0:"այսօր",1:"վաղը",2:"վաղը չէ մյուս օրը","-2":"երեկ չէ առաջի օրը","-1":"երեկ"},relativeTime:{future:{one:"{0} օր անց",other:"{0} օր անց"},past:{one:"{0} օր առաջ",other:"{0} օր առաջ"}}},month:{displayName:"Ամիս",relative:{0:"այս ամիս",1:"հաջորդ ամիս","-1":"անցյալ ամիս"},relativeTime:{future:{one:"{0} ամիս անց",other:"{0} ամիս անց"},past:{one:"{0} ամիս առաջ",other:"{0} ամիս առաջ"}}},year:{displayName:"Տարի",relative:{0:"այս տարի",1:"հաջորդ տարի","-1":"անցյալ տարի"},relativeTime:{future:{one:"{0} տարի անց",other:"{0} տարի անց"},past:{one:"{0} տարի առաջ",other:"{0} տարի առաջ"}}}}}),ReactIntl.__addLocaleData({locale:"id",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Detik",relative:{0:"sekarang"},relativeTime:{future:{other:"Dalam {0} detik"},past:{other:"{0} detik yang lalu"}}},minute:{displayName:"Menit",relativeTime:{future:{other:"Dalam {0} menit"},past:{other:"{0} menit yang lalu"}}},hour:{displayName:"Jam",relativeTime:{future:{other:"Dalam {0} jam"},past:{other:"{0} jam yang lalu"}}},day:{displayName:"Hari",relative:{0:"hari ini",1:"besok",2:"lusa","-2":"kemarin lusa","-1":"kemarin"},relativeTime:{future:{other:"Dalam {0} hari"},past:{other:"{0} hari yang lalu"}}},month:{displayName:"Bulan",relative:{0:"bulan ini",1:"Bulan berikutnya","-1":"bulan lalu"},relativeTime:{future:{other:"Dalam {0} bulan"},past:{other:"{0} bulan yang lalu"}}},year:{displayName:"Tahun",relative:{0:"tahun ini",1:"tahun depan","-1":"tahun lalu"},relativeTime:{future:{other:"Dalam {0} tahun"},past:{other:"{0} tahun yang lalu"}}}}}),ReactIntl.__addLocaleData({locale:"ig",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Nkejinta",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Nkeji",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Elekere",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ụbọchị",relative:{0:"Taata",1:"Echi","-1":"Nnyaafụ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Ọnwa",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Afọ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ii",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"ꇙ",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"ꃏ",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"ꄮꈉ",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"ꑍ",relative:{0:"ꀃꑍ",1:"ꃆꏂꑍ",2:"ꌕꀿꑍ","-2":"ꎴꂿꋍꑍ","-1":"ꀋꅔꉈ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"ꆪ",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ꈎ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"is",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=parseInt(a.toString().replace(/^[^.]*\.?|0+$/g,""),10);return a=Math.floor(a),0!==c||b%10!==1||b%100===11&&0===c?"other":"one"},fields:{second:{displayName:"sekúnda",relative:{0:"núna"},relativeTime:{future:{one:"eftir {0} sekúndu",other:"eftir {0} sekúndur"},past:{one:"fyrir {0} sekúndu",other:"fyrir {0} sekúndum"}}},minute:{displayName:"mínúta",relativeTime:{future:{one:"eftir {0} mínútu",other:"eftir {0} mínútur"},past:{one:"fyrir {0} mínútu",other:"fyrir {0} mínútum"}}},hour:{displayName:"klukkustund",relativeTime:{future:{one:"eftir {0} klukkustund",other:"eftir {0} klukkustundir"},past:{one:"fyrir {0} klukkustund",other:"fyrir {0} klukkustundum"}}},day:{displayName:"dagur",relative:{0:"í dag",1:"á morgun",2:"eftir tvo daga","-2":"í fyrradag","-1":"í gær"},relativeTime:{future:{one:"eftir {0} dag",other:"eftir {0} daga"},past:{one:"fyrir {0} degi",other:"fyrir {0} dögum"}}},month:{displayName:"mánuður",relative:{0:"í þessum mánuði",1:"í næsta mánuði","-1":"í síðasta mánuði"},relativeTime:{future:{one:"eftir {0} mánuð",other:"eftir {0} mánuði"},past:{one:"fyrir {0} mánuði",other:"fyrir {0} mánuðum"}}},year:{displayName:"ár",relative:{0:"á þessu ári",1:"á næsta ári","-1":"á síðasta ári"},relativeTime:{future:{one:"eftir {0} ár",other:"eftir {0} ár"},past:{one:"fyrir {0} ári",other:"fyrir {0} árum"}}}}}),ReactIntl.__addLocaleData({locale:"it",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"secondo",relative:{0:"ora"},relativeTime:{future:{one:"tra {0} secondo",other:"tra {0} secondi"},past:{one:"{0} secondo fa",other:"{0} secondi fa"}}},minute:{displayName:"minuto",relativeTime:{future:{one:"tra {0} minuto",other:"tra {0} minuti"},past:{one:"{0} minuto fa",other:"{0} minuti fa"}}},hour:{displayName:"ora",relativeTime:{future:{one:"tra {0} ora",other:"tra {0} ore"},past:{one:"{0} ora fa",other:"{0} ore fa"}}},day:{displayName:"giorno",relative:{0:"oggi",1:"domani",2:"dopodomani","-2":"l'altro ieri","-1":"ieri"},relativeTime:{future:{one:"tra {0} giorno",other:"tra {0} giorni"},past:{one:"{0} giorno fa",other:"{0} giorni fa"}}},month:{displayName:"mese",relative:{0:"questo mese",1:"mese prossimo","-1":"mese scorso"},relativeTime:{future:{one:"tra {0} mese",other:"tra {0} mesi"},past:{one:"{0} mese fa",other:"{0} mesi fa"}}},year:{displayName:"anno",relative:{0:"quest'anno",1:"anno prossimo","-1":"anno scorso"},relativeTime:{future:{one:"tra {0} anno",other:"tra {0} anni"},past:{one:"{0} anno fa",other:"{0} anni fa"}}}}}),ReactIntl.__addLocaleData({locale:"ja",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"秒",relative:{0:"今すぐ"},relativeTime:{future:{other:"{0} 秒後"},past:{other:"{0} 秒前"}}},minute:{displayName:"分",relativeTime:{future:{other:"{0} 分後"},past:{other:"{0} 分前"}}},hour:{displayName:"時",relativeTime:{future:{other:"{0} 時間後"},past:{other:"{0} 時間前"}}},day:{displayName:"日",relative:{0:"今日",1:"明日",2:"明後日","-2":"一昨日","-1":"昨日"},relativeTime:{future:{other:"{0} 日後"},past:{other:"{0} 日前"}}},month:{displayName:"月",relative:{0:"今月",1:"翌月","-1":"先月"},relativeTime:{future:{other:"{0} か月後"},past:{other:"{0} か月前"}}},year:{displayName:"年",relative:{0:"今年",1:"翌年","-1":"昨年"},relativeTime:{future:{other:"{0} 年後"},past:{other:"{0} 年前"}}}}}),ReactIntl.__addLocaleData({locale:"jgo",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"
},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"nǔu {0} minút",other:"nǔu {0} minút"},past:{one:"ɛ́ gɛ́ mɔ́ minút {0}",other:"ɛ́ gɛ́ mɔ́ minút {0}"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"nǔu háwa {0}",other:"nǔu háwa {0}"},past:{one:"ɛ́ gɛ mɔ́ {0} háwa",other:"ɛ́ gɛ mɔ́ {0} háwa"}}},day:{displayName:"Day",relative:{0:"lɔꞋɔ",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{one:"Nǔu lɛ́Ꞌ {0}",other:"Nǔu lɛ́Ꞌ {0}"},past:{one:"Ɛ́ gɛ́ mɔ́ lɛ́Ꞌ {0}",other:"Ɛ́ gɛ́ mɔ́ lɛ́Ꞌ {0}"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"Nǔu {0} saŋ",other:"Nǔu {0} saŋ"},past:{one:"ɛ́ gɛ́ mɔ́ pɛsaŋ {0}",other:"ɛ́ gɛ́ mɔ́ pɛsaŋ {0}"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"Nǔu ŋguꞋ {0}",other:"Nǔu ŋguꞋ {0}"},past:{one:"Ɛ́gɛ́ mɔ́ ŋguꞋ {0}",other:"Ɛ́gɛ́ mɔ́ ŋguꞋ {0}"}}}}}),ReactIntl.__addLocaleData({locale:"jmc",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakyika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Mfiri",relative:{0:"Inu",1:"Ngama","-1":"Ukou"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mori",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Maka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ka",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"წამი",relative:{0:"ახლა"},relativeTime:{future:{one:"{0} წამში",other:"{0} წამში"},past:{one:"{0} წამის წინ",other:"{0} წამის წინ"}}},minute:{displayName:"წუთი",relativeTime:{future:{one:"{0} წუთში",other:"{0} წუთში"},past:{one:"{0} წუთის წინ",other:"{0} წუთის წინ"}}},hour:{displayName:"საათი",relativeTime:{future:{one:"{0} საათში",other:"{0} საათში"},past:{one:"{0} საათის წინ",other:"{0} საათის წინ"}}},day:{displayName:"დღე",relative:{0:"დღეს",1:"ხვალ",2:"ზეგ","-2":"გუშინწინ","-1":"გუშინ"},relativeTime:{future:{one:"{0} დღეში",other:"{0} დღეში"},past:{one:"{0} დღის წინ",other:"{0} დღის წინ"}}},month:{displayName:"თვე",relative:{0:"ამ თვეში",1:"მომავალ თვეს","-1":"გასულ თვეს"},relativeTime:{future:{one:"{0} თვეში",other:"{0} თვეში"},past:{one:"{0} თვის წინ",other:"{0} თვის წინ"}}},year:{displayName:"წელი",relative:{0:"ამ წელს",1:"მომავალ წელს","-1":"გასულ წელს"},relativeTime:{future:{one:"{0} წელიწადში",other:"{0} წელიწადში"},past:{one:"{0} წლის წინ",other:"{0} წლის წინ"}}}}}),ReactIntl.__addLocaleData({locale:"kab",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===b?"one":"other"},fields:{second:{displayName:"Tasint",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Tamrect",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Tamert",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ass",relative:{0:"Ass-a",1:"Azekka","-1":"Iḍelli"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Aggur",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Aseggas",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"kde",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Lihiku",relative:{0:"Nelo",1:"Nundu","-1":"Lido"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mwedi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Mwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"kea",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Sigundu",relative:{0:"now"},relativeTime:{future:{other:"di li {0} sigundu"},past:{other:"a ten {0} sigundu"}}},minute:{displayName:"Minutu",relativeTime:{future:{other:"di li {0} minutu"},past:{other:"a ten {0} minutu"}}},hour:{displayName:"Ora",relativeTime:{future:{other:"di li {0} ora"},past:{other:"a ten {0} ora"}}},day:{displayName:"Dia",relative:{0:"Oji",1:"Manha","-1":"Onti"},relativeTime:{future:{other:"di li {0} dia"},past:{other:"a ten {0} dia"}}},month:{displayName:"Mes",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"di li {0} mes"},past:{other:"a ten {0} mes"}}},year:{displayName:"Anu",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"di li {0} anu"},past:{other:"a ten {0} anu"}}}}}),ReactIntl.__addLocaleData({locale:"kk",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"секунд",relative:{0:"қазір"},relativeTime:{future:{one:"{0} секундтан кейін",other:"{0} секундтан кейін"},past:{one:"{0} секунд бұрын",other:"{0} секунд бұрын"}}},minute:{displayName:"минут",relativeTime:{future:{one:"{0} минуттан кейін",other:"{0} минуттан кейін"},past:{one:"{0} минут бұрын",other:"{0} минут бұрын"}}},hour:{displayName:"сағат",relativeTime:{future:{one:"{0} сағаттан кейін",other:"{0} сағаттан кейін"},past:{one:"{0} сағат бұрын",other:"{0} сағат бұрын"}}},day:{displayName:"күн",relative:{0:"бүгін",1:"ертең",2:"арғы күні","-2":"алдыңғы күні","-1":"кеше"},relativeTime:{future:{one:"{0} күннен кейін",other:"{0} күннен кейін"},past:{one:"{0} күн бұрын",other:"{0} күн бұрын"}}},month:{displayName:"ай",relative:{0:"осы ай",1:"келесі ай","-1":"өткен ай"},relativeTime:{future:{one:"{0} айдан кейін",other:"{0} айдан кейін"},past:{one:"{0} ай бұрын",other:"{0} ай бұрын"}}},year:{displayName:"жыл",relative:{0:"биылғы жыл",1:"келесі жыл","-1":"былтырғы жыл"},relativeTime:{future:{one:"{0} жылдан кейін",other:"{0} жылдан кейін"},past:{one:"{0} жыл бұрын",other:"{0} жыл бұрын"}}}}}),ReactIntl.__addLocaleData({locale:"kkj",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"muka",1:"nɛmɛnɔ","-1":"kwey"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"kl",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"sekundi",relative:{0:"now"},relativeTime:{future:{one:"om {0} sekundi",other:"om {0} sekundi"},past:{one:"for {0} sekundi siden",other:"for {0} sekundi siden"}}},minute:{displayName:"minutsi",relativeTime:{future:{one:"om {0} minutsi",other:"om {0} minutsi"},past:{one:"for {0} minutsi siden",other:"for {0} minutsi siden"}}},hour:{displayName:"nalunaaquttap-akunnera",relativeTime:{future:{one:"om {0} nalunaaquttap-akunnera",other:"om {0} nalunaaquttap-akunnera"},past:{one:"for {0} nalunaaquttap-akunnera siden",other:"for {0} nalunaaquttap-akunnera siden"}}},day:{displayName:"ulloq",relative:{0:"ullumi",1:"aqagu",2:"aqaguagu","-2":"ippassaani","-1":"ippassaq"},relativeTime:{future:{one:"om {0} ulloq unnuarlu",other:"om {0} ulloq unnuarlu"},past:{one:"for {0} ulloq unnuarlu siden",other:"for {0} ulloq unnuarlu siden"}}},month:{displayName:"qaammat",relative:{0:"manna qaammat",1:"tulleq qaammat","-1":"kingulleq qaammat"},relativeTime:{future:{one:"om {0} qaammat",other:"om {0} qaammat"},past:{one:"for {0} qaammat siden",other:"for {0} qaammat siden"}}},year:{displayName:"ukioq",relative:{0:"manna ukioq",1:"tulleq ukioq","-1":"kingulleq ukioq"},relativeTime:{future:{one:"om {0} ukioq",other:"om {0} ukioq"},past:{one:"for {0} ukioq siden",other:"for {0} ukioq siden"}}}}}),ReactIntl.__addLocaleData({locale:"km",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"វិនាទី",relative:{0:"ឥឡូវ"},relativeTime:{future:{other:"ក្នុងរយៈពេល {0} វិនាទី"},past:{other:"{0} វិនាទីមុន"}}},minute:{displayName:"នាទី",relativeTime:{future:{other:"ក្នុងរយៈពេល {0} នាទី"},past:{other:"{0} នាទីមុន"}}},hour:{displayName:"ម៉ោង",relativeTime:{future:{other:"ក្នុងរយៈពេល {0} ម៉ោង"},past:{other:"{0} ម៉ោងមុន"}}},day:{displayName:"ថ្ងៃ",relative:{0:"ថ្ងៃនេះ",1:"ថ្ងៃស្អែក",2:"ខានស្អែក","-2":"ម្សិលម៉្ងៃ","-1":"ម្សិលមិញ"},relativeTime:{future:{other:"ក្នុងរយៈពេល {0} ថ្ងៃ"},past:{other:"{0} ថ្ងៃមុន"}}},month:{displayName:"ខែ",relative:{0:"ខែនេះ",1:"ខែក្រោយ","-1":"ខែមុន"},relativeTime:{future:{other:"ក្នុងរយៈពេល {0} ខែ"},past:{other:"{0} ខែមុន"}}},year:{displayName:"ឆ្នាំ",relative:{0:"ឆ្នាំនេះ",1:"ឆ្នាំក្រោយ","-1":"ឆ្នាំមុន"},relativeTime:{future:{other:"ក្នុងរយៈពេល {0} ឆ្នាំ"},past:{other:"{0} ឆ្នាំមុន"}}}}}),ReactIntl.__addLocaleData({locale:"kn",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"ಸೆಕೆಂಡ್",relative:{0:"ಇದೀಗ"},relativeTime:{future:{one:"{0} ಸೆಕೆಂಡ್ಗಳಲ್ಲಿ",other:"{0} ಸೆಕೆಂಡ್ಗಳಲ್ಲಿ"},past:{one:"{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ",other:"{0} ಸೆಕೆಂಡುಗಳ ಹಿಂದೆ"}}},minute:{displayName:"ನಿಮಿಷ",relativeTime:{future:{one:"{0} ನಿಮಿಷಗಳಲ್ಲಿ",other:"{0} ನಿಮಿಷಗಳಲ್ಲಿ"},past:{one:"{0} ನಿಮಿಷಗಳ ಹಿಂದೆ",other:"{0} ನಿಮಿಷಗಳ ಹಿಂದೆ"}}},hour:{displayName:"ಗಂಟೆ",relativeTime:{future:{one:"{0} ಗಂಟೆಗಳಲ್ಲಿ",other:"{0} ಗಂಟೆಗಳಲ್ಲಿ"},past:{one:"{0} ಗಂಟೆಗಳ ಹಿಂದೆ",other:"{0} ಗಂಟೆಗಳ ಹಿಂದೆ"}}},day:{displayName:"ದಿನ",relative:{0:"ಇಂದು",1:"ನಾಳೆ",2:"ನಾಡಿದ್ದು","-2":"ಮೊನ್ನೆ","-1":"ನಿನ್ನೆ"},relativeTime:{future:{one:"{0} ದಿನಗಳಲ್ಲಿ",other:"{0} ದಿನಗಳಲ್ಲಿ"},past:{one:"{0} ದಿನಗಳ ಹಿಂದೆ",other:"{0} ದಿನಗಳ ಹಿಂದೆ"}}},month:{displayName:"ತಿಂಗಳು",relative:{0:"ಈ ತಿಂಗಳು",1:"ಮುಂದಿನ ತಿಂಗಳು","-1":"ಕಳೆದ ತಿಂಗಳು"},relativeTime:{future:{one:"{0} ತಿಂಗಳುಗಳಲ್ಲಿ",other:"{0} ತಿಂಗಳುಗಳಲ್ಲಿ"},past:{one:"{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ",other:"{0} ತಿಂಗಳುಗಳ ಹಿಂದೆ"}}},year:{displayName:"ವರ್ಷ",relative:{0:"ಈ ವರ್ಷ",1:"ಮುಂದಿನ ವರ್ಷ","-1":"ಕಳೆದ ವರ್ಷ"},relativeTime:{future:{one:"{0} ವರ್ಷಗಳಲ್ಲಿ",other:"{0} ವರ್ಷಗಳಲ್ಲಿ"},past:{one:"{0} ವರ್ಷಗಳ ಹಿಂದೆ",other:"{0} ವರ್ಷಗಳ ಹಿಂದೆ"}}}}}),ReactIntl.__addLocaleData({locale:"ko",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"초",relative:{0:"지금"},relativeTime:{future:{other:"{0}초 후"},past:{other:"{0}초 전"}}},minute:{displayName:"분",relativeTime:{future:{other:"{0}분 후"},past:{other:"{0}분 전"}}},hour:{displayName:"시",relativeTime:{future:{other:"{0}시간 후"},past:{other:"{0}시간 전"}}},day:{displayName:"일",relative:{0:"오늘",1:"내일",2:"모레","-2":"그저께","-1":"어제"},relativeTime:{future:{other:"{0}일 후"},past:{other:"{0}일 전"}}},month:{displayName:"월",relative:{0:"이번 달",1:"다음 달","-1":"지난달"},relativeTime:{future:{other:"{0}개월 후"},past:{other:"{0}개월 전"}}},year:{displayName:"년",relative:{0:"올해",1:"내년","-1":"지난해"},relativeTime:{future:{other:"{0}년 후"},past:{other:"{0}년 전"}}}}}),ReactIntl.__addLocaleData({locale:"ks",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"سٮ۪کَنڑ",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"مِنَٹ",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"گٲنٛٹہٕ",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"دۄہ",relative:{0:"اَز",1:"پگاہ","-1":"راتھ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"رٮ۪تھ",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ؤری",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ksb",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Siku",relative:{0:"Evi eo",1:"Keloi","-1":"Ghuo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Ng'ezi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Ng'waka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ksh",pluralRuleFunction:function(a){return a=Math.floor(a),0===a?"zero":1===a?"one":"other"},fields:{second:{displayName:"Sekond",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Menutt",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Schtund",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Daach",relative:{0:"hück",1:"morje",2:"övvermorje","-2":"vörjestere","-1":"jestere"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mohnd",relative:{0:"diese Mohnd",1:"nächste Mohnd","-1":"lätzde Mohnd"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Johr",relative:{0:"diese Johr",1:"nächste Johr","-1":"läz Johr"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"kw",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":2===a?"two":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Eur",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Dedh",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mis",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Bledhen",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ky",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"секунд",relative:{0:"азыр"},relativeTime:{future:{one:"{0} секунддан кийин",other:"{0} секунддан кийин"},past:{one:"{0} секунд мурун",other:"{0} секунд мурун"}}},minute:{displayName:"мүнөт",relativeTime:{future:{one:"{0} мүнөттөн кийин",other:"{0} мүнөттөн кийин"},past:{one:"{0} мүнөт мурун",other:"{0} мүнөт мурун"}}},hour:{displayName:"саат",relativeTime:{future:{one:"{0} сааттан кийин",other:"{0} сааттан кийин"},past:{one:"{0} саат мурун",other:"{0} саат мурун"}}},day:{displayName:"күн",relative:{0:"бүгүн",1:"эртеӊ",2:"бүрсүгүнү","-2":"мурдагы күнү","-1":"кечээ"},relativeTime:{future:{one:"{0} күндөн кийин",other:"{0} күндөн кийин"},past:{one:"{0} күн мурун",other:"{0} күн мурун"}}},month:{displayName:"ай",relative:{0:"бул айда",1:"эмдиги айда","-1":"өткөн айда"},relativeTime:{future:{one:"{0} айдан кийин",other:"{0} айдан кийин"},past:{one:"{0} ай мурун",other:"{0} ай мурун"}}},year:{displayName:"жыл",relative:{0:"быйыл",1:"эмдиги жылы","-1":"былтыр"},relativeTime:{future:{one:"{0} жылдан кийин",other:"{0} жылдан кийин"},past:{one:"{0} жыл мурун",other:"{0} жыл мурун"}}}}}),ReactIntl.__addLocaleData({locale:"lag",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===a?"zero":0!==b&&1!==b||0===a?"other":"one"},fields:{second:{displayName:"Sekúunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakíka",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Sáa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Sikʉ",relative:{0:"Isikʉ",1:"Lamʉtoondo","-1":"Niijo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mweéri",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Mwaáka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"lg",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Kasikonda",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakiika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saawa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Lunaku",relative:{0:"Lwaleero",1:"Nkya","-1":"Ggulo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mwezi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Mwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"lkt",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Okpí",relative:{0:"now"},relativeTime:{future:{other:"Letáŋhaŋ okpí {0} kiŋháŋ"},past:{other:"Hékta okpí {0} k’uŋ héhaŋ"}}},minute:{displayName:"Owápȟe oȟʼáŋkȟo",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Owápȟe",relativeTime:{future:{other:"Letáŋhaŋ owápȟe {0} kiŋháŋ"},past:{other:"Hékta owápȟe {0} kʼuŋ héhaŋ"}}},day:{displayName:"Aŋpétu",relative:{0:"Lé aŋpétu kiŋ",1:"Híŋhaŋni kiŋháŋ","-1":"Lé aŋpétu kiŋ"},relativeTime:{future:{other:"Letáŋhaŋ {0}-čháŋ kiŋháŋ"},past:{other:"Hékta {0}-čháŋ k’uŋ héhaŋ"}}},month:{displayName:"Wí",relative:{0:"Lé wí kiŋ",1:"Wí kiŋháŋ","-1":"Wí kʼuŋ héhaŋ"},relativeTime:{future:{other:"Letáŋhaŋ wíyawapi {0} kiŋháŋ"},past:{other:"Hékta wíyawapi {0} kʼuŋ héhaŋ"}}},year:{displayName:"Ómakȟa",relative:{0:"Lé ómakȟa kiŋ",1:"Tȟokáta ómakȟa kiŋháŋ","-1":"Ómakȟa kʼuŋ héhaŋ"},relativeTime:{future:{other:"Letáŋhaŋ ómakȟa {0} kiŋháŋ"},past:{other:"Hékta ómakȟa {0} kʼuŋ héhaŋ"}}}}}),ReactIntl.__addLocaleData({locale:"ln",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a?"one":"other"},fields:{second:{displayName:"Sɛkɔ́ndɛ",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Monúti",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Ngonga",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Mokɔlɔ",relative:{0:"Lɛlɔ́",1:"Lóbi ekoyâ","-1":"Lóbi elékí"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Sánzá",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Mobú",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"lo",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"ວິນາທີ",relative:{0:"ຕອນນີ້"},relativeTime:{future:{other:"ໃນອີກ {0} ວິນາທີ"},past:{other:"{0} ວິນາທີກ່ອນ"}}},minute:{displayName:"ນາທີ",relativeTime:{future:{other:"{0} ໃນອີກ 0 ນາທີ"},past:{other:"{0} ນາທີກ່ອນ"}}},hour:{displayName:"ຊົ່ວໂມງ",relativeTime:{future:{other:"ໃນອີກ {0} ຊົ່ວໂມງ"},past:{other:"{0} ຊົ່ວໂມງກ່ອນ"}}},day:{displayName:"ມື້",relative:{0:"ມື້ນີ້",1:"ມື້ອື່ນ",2:"ມື້ຮື","-2":"ມື້ກ່ອນ","-1":"ມື້ວານ"},relativeTime:{future:{other:"ໃນອີກ {0} ມື້"},past:{other:"{0} ມື້ກ່ອນ"}}},month:{displayName:"ເດືອນ",relative:{0:"ເດືອນນີ້",1:"ເດືອນໜ້າ","-1":"ເດືອນແລ້ວ"},relativeTime:{future:{other:"ໃນອີກ {0} ເດືອນ"},past:{other:"{0} ເດືອນກ່ອນ"}}},year:{displayName:"ປີ",relative:{0:"ປີນີ້",1:"ປີໜ້າ","-1":"ປີກາຍ"},relativeTime:{future:{other:"ໃນອີກ {0} ປີ"},past:{other:"{0} ປີກ່ອນ"}}}}}),ReactIntl.__addLocaleData({locale:"lt",pluralRuleFunction:function(a){var b=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),a%10!==1||a%100>=11&&19>=a%100?a%10===Math.floor(a%10)&&a%10>=2&&9>=a%10&&!(a%100>=11&&19>=a%100)?"few":0!==b?"many":"other":"one"},fields:{second:{displayName:"Sekundė",relative:{0:"dabar"},relativeTime:{future:{one:"po {0} sekundės",few:"po {0} sekundžių",many:"po {0} sekundės",other:"po {0} sekundžių"},past:{one:"prieš {0} sekundę",few:"prieš {0} sekundes",many:"prieš {0} sekundės",other:"prieš {0} sekundžių"}}},minute:{displayName:"Minutė",relativeTime:{future:{one:"po {0} minutės",few:"po {0} minučių",many:"po {0} minutės",other:"po {0} minučių"},past:{one:"prieš {0} minutę",few:"prieš {0} minutes",many:"prieš {0} minutės",other:"prieš {0} minučių"}}},hour:{displayName:"Valanda",relativeTime:{future:{one:"po {0} valandos",few:"po {0} valandų",many:"po {0} valandos",other:"po {0} valandų"},past:{one:"prieš {0} valandą",few:"prieš {0} valandas",many:"prieš {0} valandos",other:"prieš {0} valandų"}}},day:{displayName:"Diena",relative:{0:"šiandien",1:"rytoj",2:"poryt","-2":"užvakar","-1":"vakar"},relativeTime:{future:{one:"po {0} dienos",few:"po {0} dienų",many:"po {0} dienos",other:"po {0} dienų"},past:{one:"prieš {0} dieną",few:"prieš {0} dienas",many:"prieš {0} dienos",other:"prieš {0} dienų"}}},month:{displayName:"Mėnuo",relative:{0:"šį mėnesį",1:"kitą mėnesį","-1":"praėjusį mėnesį"},relativeTime:{future:{one:"po {0} mėnesio",few:"po {0} mėnesių",many:"po {0} mėnesio",other:"po {0} mėnesių"},past:{one:"prieš {0} mėnesį",few:"prieš {0} mėnesius",many:"prieš {0} mėnesio",other:"prieš {0} mėnesių"}}},year:{displayName:"Metai",relative:{0:"šiais metais",1:"kitais metais","-1":"praėjusiais metais"},relativeTime:{future:{one:"po {0} metų",few:"po {0} metų",many:"po {0} metų",other:"po {0} metų"},past:{one:"prieš {0} metus",few:"prieš {0} metus",many:"prieš {0} metų",other:"prieš {0} metų"}}}}}),ReactIntl.__addLocaleData({locale:"lv",pluralRuleFunction:function(a){var b=a.toString().replace(/^[^.]*\.?/,"").length,c=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),a%10===0||a%100===Math.floor(a%100)&&a%100>=11&&19>=a%100||2===b&&c%100===Math.floor(c%100)&&c%100>=11&&19>=c%100?"zero":a%10===1&&(a%100!==11||2===b&&c%10===1&&(c%100!==11||2!==b&&c%10===1))?"one":"other"},fields:{second:{displayName:"Sekundes",relative:{0:"tagad"},relativeTime:{future:{zero:"Pēc {0} sekundēm",one:"Pēc {0} sekundes",other:"Pēc {0} sekundēm"},past:{zero:"Pirms {0} sekundēm",one:"Pirms {0} sekundes",other:"Pirms {0} sekundēm"}}},minute:{displayName:"Minūtes",relativeTime:{future:{zero:"Pēc {0} minūtēm",one:"Pēc {0} minūtes",other:"Pēc {0} minūtēm"},past:{zero:"Pirms {0} minūtēm",one:"Pirms {0} minūtes",other:"Pirms {0} minūtēm"}}},hour:{displayName:"Stundas",relativeTime:{future:{zero:"Pēc {0} stundām",one:"Pēc {0} stundas",other:"Pēc {0} stundām"},past:{zero:"Pirms {0} stundām",one:"Pirms {0} stundas",other:"Pirms {0} stundām"}}},day:{displayName:"Diena",relative:{0:"šodien",1:"rīt",2:"parīt","-2":"aizvakar","-1":"vakar"},relativeTime:{future:{zero:"Pēc {0} dienām",one:"Pēc {0} dienas",other:"Pēc {0} dienām"},past:{zero:"Pirms {0} dienām",one:"Pirms {0} dienas",other:"Pirms {0} dienām"}}},month:{displayName:"Mēnesis",relative:{0:"šomēnes",1:"nākammēnes","-1":"pagājušajā mēnesī"},relativeTime:{future:{zero:"Pēc {0} mēnešiem",one:"Pēc {0} mēneša",other:"Pēc {0} mēnešiem"},past:{zero:"Pirms {0} mēnešiem",one:"Pirms {0} mēneša",other:"Pirms {0} mēnešiem"}}},year:{displayName:"Gads",relative:{0:"šogad",1:"nākamgad","-1":"pagājušajā gadā"},relativeTime:{future:{zero:"Pēc {0} gadiem",one:"Pēc {0} gada",other:"Pēc {0} gadiem"},past:{zero:"Pirms {0} gadiem",one:"Pirms {0} gada",other:"Pirms {0} gadiem"}}}}}),ReactIntl.__addLocaleData({locale:"mas",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Oldákikaè",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Ɛ́sáâ",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ɛnkɔlɔ́ŋ",relative:{0:"Táatá",1:"Tááisérè","-1":"Ŋolé"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Ɔlápà",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Ɔlárì",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"mg",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a?"one":"other"},fields:{second:{displayName:"Segondra",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minitra",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Ora",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Andro",relative:{0:"Anio",1:"Rahampitso","-1":"Omaly"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Volana",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Taona",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"mgo",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{one:"+{0} s",other:"+{0} s"},past:{one:"-{0} s",other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{one:"+{0} min",other:"+{0} min"},past:{one:"-{0} min",other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{one:"+{0} h",other:"+{0} h"},past:{one:"-{0} h",other:"-{0} h"}}},day:{displayName:"anəg",relative:{0:"tèchɔ̀ŋ",1:"isu",2:"isu ywi","-1":"ikwiri"},relativeTime:{future:{one:"+{0} d",other:"+{0} d"},past:{one:"-{0} d",other:"-{0} d"}}},month:{displayName:"iməg",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"+{0} m",other:"+{0} m"},past:{one:"-{0} m",other:"-{0} m"}}},year:{displayName:"fituʼ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"mk",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length,d=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),0!==c||b%10!==1&&d%10!==1?"other":"one"},fields:{second:{displayName:"Секунда",relative:{0:"сега"},relativeTime:{future:{one:"За {0} секунда",other:"За {0} секунди"},past:{one:"Пред {0} секунда",other:"Пред {0} секунди"}}},minute:{displayName:"Минута",relativeTime:{future:{one:"За {0} минута",other:"За {0} минути"},past:{one:"Пред {0} минута",other:"Пред {0} минути"}}},hour:{displayName:"Час",relativeTime:{future:{one:"За {0} час",other:"За {0} часа"},past:{one:"Пред {0} час",other:"Пред {0} часа"}}},day:{displayName:"ден",relative:{0:"Денес",1:"утре",2:"задутре","-2":"завчера","-1":"вчера"},relativeTime:{future:{one:"За {0} ден",other:"За {0} дена"},past:{one:"Пред {0} ден",other:"Пред {0} дена"}}},month:{displayName:"Месец",relative:{0:"овој месец",1:"следниот месец","-1":"минатиот месец"},relativeTime:{future:{one:"За {0} месец",other:"За {0} месеци"},past:{one:"Пред {0} месец",other:"Пред {0} месеци"}}},year:{displayName:"година",relative:{0:"оваа година",1:"следната година","-1":"минатата година"},relativeTime:{future:{one:"За {0} година",other:"За {0} години"},past:{one:"Пред {0} година",other:"Пред {0} години"}}}}}),ReactIntl.__addLocaleData({locale:"ml",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"സെക്കൻറ്",relative:{0:"ഇപ്പോൾ"},relativeTime:{future:{one:"{0} സെക്കൻഡിൽ",other:"{0} സെക്കൻഡിൽ"},past:{one:"{0} സെക്കൻറ് മുമ്പ്",other:"{0} സെക്കൻറ് മുമ്പ്"}}},minute:{displayName:"മിനിട്ട്",relativeTime:{future:{one:"{0} മിനിറ്റിൽ",other:"{0} മിനിറ്റിനുള്ളിൽ"},past:{one:"{0} മിനിറ്റ് മുമ്പ്",other:"{0} മിനിറ്റ് മുമ്പ്"}}},hour:{displayName:"മണിക്കൂർ",relativeTime:{future:{one:"{0} മണിക്കൂറിൽ",other:"{0} മണിക്കൂറിൽ"},past:{one:"{0} മണിക്കൂർ മുമ്പ്",other:"{0} മണിക്കൂർ മുമ്പ്"}}},day:{displayName:"ദിവസം",relative:{0:"ഇന്ന്",1:"നാളെ",2:"മറ്റന്നാൾ","-2":"മിനിഞ്ഞാന്ന്","-1":"ഇന്നലെ"},relativeTime:{future:{one:"{0} ദിവസത്തിൽ",other:"{0} ദിവസത്തിൽ"},past:{one:"{0} ദിവസം മുമ്പ്",other:"{0} ദിവസം മുമ്പ്"}}},month:{displayName:"മാസം",relative:{0:"ഈ മാസം",1:"അടുത്ത മാസം","-1":"കഴിഞ്ഞ മാസം"},relativeTime:{future:{one:"{0} മാസത്തിൽ",other:"{0} മാസത്തിൽ"},past:{one:"{0} മാസം മുമ്പ്",other:"{0} മാസം മുമ്പ്"}}},year:{displayName:"വർഷം",relative:{0:"ഈ വർഷം",1:"അടുത്തവർഷം","-1":"കഴിഞ്ഞ വർഷം"},relativeTime:{future:{one:"{0} വർഷത്തിൽ",other:"{0} വർഷത്തിൽ"},past:{one:"{0} വർഷം മുമ്പ്",other:"{0} വർഷം മുമ്പ്"}}}}}),ReactIntl.__addLocaleData({locale:"mn",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Секунд",relative:{0:"Одоо"},relativeTime:{future:{one:"{0} секундын дараа",other:"{0} секундын дараа"},past:{one:"{0} секундын өмнө",other:"{0} секундын өмнө"}}},minute:{displayName:"Минут",relativeTime:{future:{one:"{0} минутын дараа",other:"{0} минутын дараа"},past:{one:"{0} минутын өмнө",other:"{0} минутын өмнө"}}},hour:{displayName:"Цаг",relativeTime:{future:{one:"{0} цагийн дараа",other:"{0} цагийн дараа"},past:{one:"{0} цагийн өмнө",other:"{0} цагийн өмнө"}}},day:{displayName:"Өдөр",relative:{0:"өнөөдөр",1:"маргааш",2:"Нөгөөдөр","-2":"Уржигдар","-1":"өчигдөр"},relativeTime:{future:{one:"{0} өдрийн дараа",other:"{0} өдрийн дараа"},past:{one:"{0} өдрийн өмнө",other:"{0} өдрийн өмнө"}}},month:{displayName:"Сар",relative:{0:"энэ сар",1:"ирэх сар","-1":"өнгөрсөн сар"},relativeTime:{future:{one:"{0} сарын дараа",other:"{0} сарын дараа"},past:{one:"{0} сарын өмнө",other:"{0} сарын өмнө"}}},year:{displayName:"Жил",relative:{0:"энэ жил",1:"ирэх жил","-1":"өнгөрсөн жил"},relativeTime:{future:{one:"{0} жилийн дараа",other:"{0} жилийн дараа"},past:{one:"{0} жилийн өмнө",other:"{0} жилийн өмнө"}}}}}),ReactIntl.__addLocaleData({locale:"mr",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"सेकंद",relative:{0:"आत्ता"},relativeTime:{future:{one:"{0} सेकंदामध्ये",other:"{0} सेकंदांमध्ये"},past:{one:"{0} सेकंदापूर्वी",other:"{0} सेकंदांपूर्वी"}}},minute:{displayName:"मिनिट",relativeTime:{future:{one:"{0} मिनिटामध्ये",other:"{0} मिनिटांमध्ये"},past:{one:"{0} मिनिटापूर्वी",other:"{0} मिनिटांपूर्वी"}}},hour:{displayName:"तास",relativeTime:{future:{one:"{0} तासामध्ये",other:"{0} तासांमध्ये"},past:{one:"{0} तासापूर्वी",other:"{0} तासांपूर्वी"}}},day:{displayName:"दिवस",relative:{0:"आज",1:"उद्या","-1":"काल"},relativeTime:{future:{one:"{0} दिवसामध्ये",other:"{0} दिवसांमध्ये"},past:{one:"{0} दिवसापूर्वी",other:"{0} दिवसांपूर्वी"}}},month:{displayName:"महिना",relative:{0:"हा महिना",1:"पुढील महिना","-1":"मागील महिना"},relativeTime:{future:{one:"{0} महिन्यामध्ये",other:"{0} महिन्यांमध्ये"},past:{one:"{0} महिन्यापूर्वी",other:"{0} महिन्यांपूर्वी"}}},year:{displayName:"वर्ष",relative:{0:"हे वर्ष",1:"पुढील वर्ष","-1":"मागील वर्ष"},relativeTime:{future:{one:"{0} वर्षामध्ये",other:"{0} वर्षांमध्ये"},past:{one:"{0} वर्षापूर्वी",other:"{0} वर्षांपूर्वी"}}}}}),ReactIntl.__addLocaleData({locale:"ms",pluralRuleFunction:function(){return"other"
},fields:{second:{displayName:"Kedua",relative:{0:"sekarang"},relativeTime:{future:{other:"Dalam {0} saat"},past:{other:"{0} saat lalu"}}},minute:{displayName:"Minit",relativeTime:{future:{other:"Dalam {0} minit"},past:{other:"{0} minit lalu"}}},hour:{displayName:"Jam",relativeTime:{future:{other:"Dalam {0} jam"},past:{other:"{0} jam lalu"}}},day:{displayName:"Hari",relative:{0:"Hari ini",1:"Esok",2:"Hari selepas esok","-2":"Hari sebelum semalam","-1":"Semalam"},relativeTime:{future:{other:"Dalam {0} hari"},past:{other:"{0} hari lalu"}}},month:{displayName:"Bulan",relative:{0:"bulan ini",1:"bulan depan","-1":"bulan lalu"},relativeTime:{future:{other:"Dalam {0} bulan"},past:{other:"{0} bulan lalu"}}},year:{displayName:"Tahun",relative:{0:"tahun ini",1:"tahun depan","-1":"tahun lepas"},relativeTime:{future:{other:"Dalam {0} tahun"},past:{other:"{0} tahun lalu"}}}}}),ReactIntl.__addLocaleData({locale:"mt",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":0===a||a%100===Math.floor(a%100)&&a%100>=2&&10>=a%100?"few":a%100===Math.floor(a%100)&&a%100>=11&&19>=a%100?"many":"other"},fields:{second:{displayName:"Sekonda",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minuta",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Siegħa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Jum",relative:{0:"Illum",1:"Għada","-1":"Ilbieraħ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Xahar",relative:{0:"Dan ix-xahar",1:"Ix-xahar id-dieħel","-1":"Ix-xahar li għadda"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Sena",relative:{0:"Din is-sena",1:"Is-sena d-dieħla","-1":"Is-sena li għaddiet"},relativeTime:{past:{one:"{0} sena ilu",few:"{0} snin ilu",many:"{0} snin ilu",other:"{0} snin ilu"},future:{other:"+{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"my",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"စက္ကန့်",relative:{0:"ယခု"},relativeTime:{future:{other:"{0}စက္ကန့်အတွင်း"},past:{other:"လွန်ခဲ့သော{0}စက္ကန့်"}}},minute:{displayName:"မိနစ်",relativeTime:{future:{other:"{0}မိနစ်အတွင်း"},past:{other:"လွန်ခဲ့သော{0}မိနစ်"}}},hour:{displayName:"နာရီ",relativeTime:{future:{other:"{0}နာရီအတွင်း"},past:{other:"လွန်ခဲ့သော{0}နာရီ"}}},day:{displayName:"ရက်",relative:{0:"ယနေ့",1:"မနက်ဖြန်",2:"သဘက်ခါ","-2":"တနေ့က","-1":"မနေ့က"},relativeTime:{future:{other:"{0}ရက်အတွင်း"},past:{other:"လွန်ခဲ့သော{0}ရက်"}}},month:{displayName:"လ",relative:{0:"ယခုလ",1:"နောက်လ","-1":"ယမန်လ"},relativeTime:{future:{other:"{0}လအတွင်း"},past:{other:"လွန်ခဲ့သော{0}လ"}}},year:{displayName:"နှစ်",relative:{0:"ယခုနှစ်",1:"နောက်နှစ်","-1":"ယမန်နှစ်"},relativeTime:{future:{other:"{0}နှစ်အတွင်း"},past:{other:"လွန်ခဲ့သော{0}နှစ်"}}}}}),ReactIntl.__addLocaleData({locale:"naq",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":2===a?"two":"other"},fields:{second:{displayName:"ǀGâub",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Haib",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Iiri",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Tsees",relative:{0:"Neetsee",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"ǁKhâb",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Kurib",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"nb",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekund",relative:{0:"nå"},relativeTime:{future:{one:"om {0} sekund",other:"om {0} sekunder"},past:{one:"for {0} sekund siden",other:"for {0} sekunder siden"}}},minute:{displayName:"Minutt",relativeTime:{future:{one:"om {0} minutt",other:"om {0} minutter"},past:{one:"for {0} minutt siden",other:"for {0} minutter siden"}}},hour:{displayName:"Time",relativeTime:{future:{one:"om {0} time",other:"om {0} timer"},past:{one:"for {0} time siden",other:"for {0} timer siden"}}},day:{displayName:"Dag",relative:{0:"i dag",1:"i morgen",2:"i overmorgen","-2":"i forgårs","-1":"i går"},relativeTime:{future:{one:"om {0} døgn",other:"om {0} døgn"},past:{one:"for {0} døgn siden",other:"for {0} døgn siden"}}},month:{displayName:"Måned",relative:{0:"Denne måneden",1:"Neste måned","-1":"Sist måned"},relativeTime:{future:{one:"om {0} måned",other:"om {0} måneder"},past:{one:"for {0} måned siden",other:"for {0} måneder siden"}}},year:{displayName:"År",relative:{0:"Dette året",1:"Neste år","-1":"I fjor"},relativeTime:{future:{one:"om {0} år",other:"om {0} år"},past:{one:"for {0} år siden",other:"for {0} år siden"}}}}}),ReactIntl.__addLocaleData({locale:"nd",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Isekendi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Umuzuzu",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Ihola",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ilanga",relative:{0:"Lamuhla",1:"Kusasa","-1":"Izolo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Inyangacale",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Umnyaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ne",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"दोस्रो",relative:{0:"अब"},relativeTime:{future:{one:"{0} सेकेण्डमा",other:"{0} सेकेण्डमा"},past:{one:"{0} सेकेण्ड पहिले",other:"{0} सेकेण्ड पहिले"}}},minute:{displayName:"मिनेट",relativeTime:{future:{one:"{0} मिनेटमा",other:"{0} मिनेटमा"},past:{one:"{0} मिनेट पहिले",other:"{0} मिनेट पहिले"}}},hour:{displayName:"घण्टा",relativeTime:{future:{one:"{0} घण्टामा",other:"{0} घण्टामा"},past:{one:"{0} घण्टा पहिले",other:"{0} घण्टा पहिले"}}},day:{displayName:"बार",relative:{0:"आज",1:"भोली","-2":"अस्ति","-1":"हिजो"},relativeTime:{future:{one:"{0} दिनमा",other:"{0} दिनमा"},past:{one:"{0} दिन पहिले",other:"{0} दिन पहिले"}}},month:{displayName:"महिना",relative:{0:"यो महिना",1:"अर्को महिना","-1":"गएको महिना"},relativeTime:{future:{one:"{0} महिनामा",other:"{0} महिनामा"},past:{one:"{0} महिना पहिले",other:"{0} महिना पहिले"}}},year:{displayName:"बर्ष",relative:{0:"यो वर्ष",1:"अर्को वर्ष","-1":"पहिलो वर्ष"},relativeTime:{future:{one:"{0} वर्षमा",other:"{0} वर्षमा"},past:{one:"{0} वर्ष अघि",other:"{0} वर्ष अघि"}}}}}),ReactIntl.__addLocaleData({locale:"nl",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Seconde",relative:{0:"nu"},relativeTime:{future:{one:"Over {0} seconde",other:"Over {0} seconden"},past:{one:"{0} seconde geleden",other:"{0} seconden geleden"}}},minute:{displayName:"Minuut",relativeTime:{future:{one:"Over {0} minuut",other:"Over {0} minuten"},past:{one:"{0} minuut geleden",other:"{0} minuten geleden"}}},hour:{displayName:"Uur",relativeTime:{future:{one:"Over {0} uur",other:"Over {0} uur"},past:{one:"{0} uur geleden",other:"{0} uur geleden"}}},day:{displayName:"Dag",relative:{0:"vandaag",1:"morgen",2:"overmorgen","-2":"eergisteren","-1":"gisteren"},relativeTime:{future:{one:"Over {0} dag",other:"Over {0} dagen"},past:{one:"{0} dag geleden",other:"{0} dagen geleden"}}},month:{displayName:"Maand",relative:{0:"deze maand",1:"volgende maand","-1":"vorige maand"},relativeTime:{future:{one:"Over {0} maand",other:"Over {0} maanden"},past:{one:"{0} maand geleden",other:"{0} maanden geleden"}}},year:{displayName:"Jaar",relative:{0:"dit jaar",1:"volgend jaar","-1":"vorig jaar"},relativeTime:{future:{one:"Over {0} jaar",other:"Over {0} jaar"},past:{one:"{0} jaar geleden",other:"{0} jaar geleden"}}}}}),ReactIntl.__addLocaleData({locale:"nn",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"sekund",relative:{0:"now"},relativeTime:{future:{one:"om {0} sekund",other:"om {0} sekunder"},past:{one:"for {0} sekund siden",other:"for {0} sekunder siden"}}},minute:{displayName:"minutt",relativeTime:{future:{one:"om {0} minutt",other:"om {0} minutter"},past:{one:"for {0} minutt siden",other:"for {0} minutter siden"}}},hour:{displayName:"time",relativeTime:{future:{one:"om {0} time",other:"om {0} timer"},past:{one:"for {0} time siden",other:"for {0} timer siden"}}},day:{displayName:"dag",relative:{0:"i dag",1:"i morgon",2:"i overmorgon","-2":"i forgårs","-1":"i går"},relativeTime:{future:{one:"om {0} døgn",other:"om {0} døgn"},past:{one:"for {0} døgn siden",other:"for {0} døgn siden"}}},month:{displayName:"månad",relative:{0:"denne månad",1:"neste månad","-1":"forrige månad"},relativeTime:{future:{one:"om {0} måned",other:"om {0} måneder"},past:{one:"for {0} måned siden",other:"for {0} måneder siden"}}},year:{displayName:"år",relative:{0:"dette år",1:"neste år","-1":"i fjor"},relativeTime:{future:{one:"om {0} år",other:"om {0} år"},past:{one:"for {0} år siden",other:"for {0} år siden"}}}}}),ReactIntl.__addLocaleData({locale:"nnh",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"fʉ̀ʼ nèm",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"lyɛ̌ʼ",relative:{0:"lyɛ̌ʼɔɔn",1:"jǔɔ gẅie à ne ntóo","-1":"jǔɔ gẅie à ka tɔ̌g"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ngùʼ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"nr",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"nso",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"nyn",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Obucweka/Esekendi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Edakiika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Shaaha",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Eizooba",relative:{0:"Erizooba",1:"Nyenkyakare","-1":"Nyomwabazyo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Omwezi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Omwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"om",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"or",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"os",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Секунд",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Минут",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Сахат",relativeTime:{future:{one:"{0} сахаты фӕстӕ",other:"{0} сахаты фӕстӕ"},past:{one:"{0} сахаты размӕ",other:"{0} сахаты размӕ"}}},day:{displayName:"Бон",relative:{0:"Абон",1:"Сом",2:"Иннӕбон","-2":"Ӕндӕрӕбон","-1":"Знон"},relativeTime:{future:{one:"{0} боны фӕстӕ",other:"{0} боны фӕстӕ"},past:{one:"{0} бон раздӕр",other:"{0} боны размӕ"}}},month:{displayName:"Мӕй",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Аз",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"pa",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a?"one":"other"},fields:{second:{displayName:"ਸਕਿੰਟ",relative:{0:"ਹੁਣ"},relativeTime:{future:{one:"{0} ਸਕਿੰਟ ਵਿਚ",other:"{0} ਸਕਿੰਟ ਵਿਚ"},past:{one:"{0} ਸਕਿੰਟ ਪਹਿਲਾਂ",other:"{0} ਸਕਿੰਟ ਪਹਿਲਾਂ"}}},minute:{displayName:"ਮਿੰਟ",relativeTime:{future:{one:"{0} ਮਿੰਟ ਵਿਚ",other:"{0} ਮਿੰਟ ਵਿਚ"},past:{one:"{0} ਮਿੰਟ ਪਹਿਲਾਂ",other:"{0} ਮਿੰਟ ਪਹਿਲਾਂ"}}},hour:{displayName:"ਘੰਟਾ",relativeTime:{future:{one:"{0} ਘੰਟੇ ਵਿਚ",other:"{0} ਘੰਟੇ ਵਿਚ"},past:{one:"{0} ਘੰਟਾ ਪਹਿਲਾਂ",other:"{0} ਘੰਟੇ ਪਹਿਲਾਂ"}}},day:{displayName:"ਦਿਨ",relative:{0:"ਅੱਜ",1:"ਭਲਕੇ","-1":"ਲੰਘਿਆ ਕੱਲ"},relativeTime:{future:{one:"{0} ਦਿਨ ਵਿਚ",other:"{0} ਦਿਨਾਂ ਵਿਚ"},past:{one:"{0} ਦਿਨ ਪਹਿਲਾਂ",other:"{0} ਦਿਨ ਪਹਿਲਾਂ"}}},month:{displayName:"ਮਹੀਨਾ",relative:{0:"ਇਹ ਮਹੀਨਾ",1:"ਅਗਲਾ ਮਹੀਨਾ","-1":"ਪਿਛਲਾ ਮਹੀਨਾ"},relativeTime:{future:{one:"{0} ਮਹੀਨੇ ਵਿਚ",other:"{0} ਮਹੀਨੇ ਵਿਚ"},past:{one:"{0} ਮਹੀਨੇ ਪਹਿਲਾਂ",other:"{0} ਮਹੀਨੇ ਪਹਿਲਾਂ"}}},year:{displayName:"ਸਾਲ",relative:{0:"ਇਹ ਸਾਲ",1:"ਅਗਲਾ ਸਾਲ","-1":"ਪਿਛਲਾ ਸਾਲ"},relativeTime:{future:{one:"{0} ਸਾਲ ਵਿਚ",other:"{0} ਸਾਲ ਵਿਚ"},past:{one:"{0} ਸਾਲ ਪਹਿਲਾਂ",other:"{0} ਸਾਲ ਪਹਿਲਾਂ"}}}}}),ReactIntl.__addLocaleData({locale:"pl",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":0===c&&b%10===Math.floor(b%10)&&b%10>=2&&4>=b%10&&!(b%100>=12&&14>=b%100)?"few":0===c&&1!==b&&(b%10===Math.floor(b%10)&&b%10>=0&&1>=b%10||0===c&&(b%10===Math.floor(b%10)&&b%10>=5&&9>=b%10||0===c&&b%100===Math.floor(b%100)&&b%100>=12&&14>=b%100))?"many":"other"},fields:{second:{displayName:"sekunda",relative:{0:"teraz"},relativeTime:{future:{one:"Za {0} sekundę",few:"Za {0} sekundy",many:"Za {0} sekund",other:"Za {0} sekundy"},past:{one:"{0} sekundę temu",few:"{0} sekundy temu",many:"{0} sekund temu",other:"{0} sekundy temu"}}},minute:{displayName:"minuta",relativeTime:{future:{one:"Za {0} minutę",few:"Za {0} minuty",many:"Za {0} minut",other:"Za {0} minuty"},past:{one:"{0} minutę temu",few:"{0} minuty temu",many:"{0} minut temu",other:"{0} minuty temu"}}},hour:{displayName:"godzina",relativeTime:{future:{one:"Za {0} godzinę",few:"Za {0} godziny",many:"Za {0} godzin",other:"Za {0} godziny"},past:{one:"{0} godzinę temu",few:"{0} godziny temu",many:"{0} godzin temu",other:"{0} godziny temu"}}},day:{displayName:"dzień",relative:{0:"dzisiaj",1:"jutro",2:"pojutrze","-2":"przedwczoraj","-1":"wczoraj"},relativeTime:{future:{one:"Za {0} dzień",few:"Za {0} dni",many:"Za {0} dni",other:"Za {0} dnia"},past:{one:"{0} dzień temu",few:"{0} dni temu",many:"{0} dni temu",other:"{0} dnia temu"}}},month:{displayName:"miesiąc",relative:{0:"w tym miesiącu",1:"w przyszłym miesiącu","-1":"w zeszłym miesiącu"},relativeTime:{future:{one:"Za {0} miesiąc",few:"Za {0} miesiące",many:"Za {0} miesięcy",other:"Za {0} miesiąca"},past:{one:"{0} miesiąc temu",few:"{0} miesiące temu",many:"{0} miesięcy temu",other:"{0} miesiąca temu"}}},year:{displayName:"rok",relative:{0:"w tym roku",1:"w przyszłym roku","-1":"w zeszłym roku"},relativeTime:{future:{one:"Za {0} rok",few:"Za {0} lata",many:"Za {0} lat",other:"Za {0} roku"},past:{one:"{0} rok temu",few:"{0} lata temu",many:"{0} lat temu",other:"{0} roku temu"}}}}}),ReactIntl.__addLocaleData({locale:"ps",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"pt",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length,d=parseInt(a.toString().replace(/^[^.]*\.?|0+$/g,""),10);return a=Math.floor(a),1===b&&(0===c||0===b&&1===d)?"one":"other"},fields:{second:{displayName:"Segundo",relative:{0:"agora"},relativeTime:{future:{one:"Dentro de {0} segundo",other:"Dentro de {0} segundos"},past:{one:"Há {0} segundo",other:"Há {0} segundos"}}},minute:{displayName:"Minuto",relativeTime:{future:{one:"Dentro de {0} minuto",other:"Dentro de {0} minutos"},past:{one:"Há {0} minuto",other:"Há {0} minutos"}}},hour:{displayName:"Hora",relativeTime:{future:{one:"Dentro de {0} hora",other:"Dentro de {0} horas"},past:{one:"Há {0} hora",other:"Há {0} horas"}}},day:{displayName:"Dia",relative:{0:"hoje",1:"amanhã",2:"depois de amanhã","-2":"anteontem","-1":"ontem"},relativeTime:{future:{one:"Dentro de {0} dia",other:"Dentro de {0} dias"},past:{one:"Há {0} dia",other:"Há {0} dias"}}},month:{displayName:"Mês",relative:{0:"este mês",1:"próximo mês","-1":"mês passado"},relativeTime:{future:{one:"Dentro de {0} mês",other:"Dentro de {0} meses"},past:{one:"Há {0} mês",other:"Há {0} meses"}}},year:{displayName:"Ano",relative:{0:"este ano",1:"próximo ano","-1":"ano passado"},relativeTime:{future:{one:"Dentro de {0} ano",other:"Dentro de {0} anos"},past:{one:"Há {0} ano",other:"Há {0} anos"}}}}}),ReactIntl.__addLocaleData({locale:"rm",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"secunda",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"minuta",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"ura",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Tag",relative:{0:"oz",1:"damaun",2:"puschmaun","-2":"stersas","-1":"ier"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"mais",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"onn",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ro",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":0!==c||0===a||1!==a&&a%100===Math.floor(a%100)&&a%100>=1&&19>=a%100?"few":"other"},fields:{second:{displayName:"secundă",relative:{0:"acum"},relativeTime:{future:{one:"Peste {0} secundă",few:"Peste {0} secunde",other:"Peste {0} de secunde"},past:{one:"Acum {0} secundă",few:"Acum {0} secunde",other:"Acum {0} de secunde"}}},minute:{displayName:"minut",relativeTime:{future:{one:"Peste {0} minut",few:"Peste {0} minute",other:"Peste {0} de minute"},past:{one:"Acum {0} minut",few:"Acum {0} minute",other:"Acum {0} de minute"}}},hour:{displayName:"oră",relativeTime:{future:{one:"Peste {0} oră",few:"Peste {0} ore",other:"Peste {0} de ore"},past:{one:"Acum {0} oră",few:"Acum {0} ore",other:"Acum {0} de ore"}}},day:{displayName:"zi",relative:{0:"azi",1:"mâine",2:"poimâine","-2":"alaltăieri","-1":"ieri"},relativeTime:{future:{one:"Peste {0} zi",few:"Peste {0} zile",other:"Peste {0} de zile"},past:{one:"Acum {0} zi",few:"Acum {0} zile",other:"Acum {0} de zile"}}},month:{displayName:"lună",relative:{0:"luna aceasta",1:"luna viitoare","-1":"luna trecută"},relativeTime:{future:{one:"Peste {0} lună",few:"Peste {0} luni",other:"Peste {0} de luni"},past:{one:"Acum {0} lună",few:"Acum {0} luni",other:"Acum {0} de luni"}}},year:{displayName:"an",relative:{0:"anul acesta",1:"anul viitor","-1":"anul trecut"},relativeTime:{future:{one:"Peste {0} an",few:"Peste {0} ani",other:"Peste {0} de ani"},past:{one:"Acum {0} an",few:"Acum {0} ani",other:"Acum {0} de ani"}}}}}),ReactIntl.__addLocaleData({locale:"rof",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Isaa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Mfiri",relative:{0:"Linu",1:"Ng'ama","-1":"Hiyo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mweri",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Muaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ru",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),0===c&&b%10===1&&b%100!==11?"one":0===c&&b%10===Math.floor(b%10)&&b%10>=2&&4>=b%10&&!(b%100>=12&&14>=b%100)?"few":0===c&&(b%10===0||0===c&&(b%10===Math.floor(b%10)&&b%10>=5&&9>=b%10||0===c&&b%100===Math.floor(b%100)&&b%100>=11&&14>=b%100))?"many":"other"},fields:{second:{displayName:"Секунда",relative:{0:"сейчас"},relativeTime:{future:{one:"Через {0} секунду",few:"Через {0} секунды",many:"Через {0} секунд",other:"Через {0} секунды"},past:{one:"{0} секунду назад",few:"{0} секунды назад",many:"{0} секунд назад",other:"{0} секунды назад"}}},minute:{displayName:"Минута",relativeTime:{future:{one:"Через {0} минуту",few:"Через {0} минуты",many:"Через {0} минут",other:"Через {0} минуты"},past:{one:"{0} минуту назад",few:"{0} минуты назад",many:"{0} минут назад",other:"{0} минуты назад"}}},hour:{displayName:"Час",relativeTime:{future:{one:"Через {0} час",few:"Через {0} часа",many:"Через {0} часов",other:"Через {0} часа"},past:{one:"{0} час назад",few:"{0} часа назад",many:"{0} часов назад",other:"{0} часа назад"}}},day:{displayName:"День",relative:{0:"сегодня",1:"завтра",2:"послезавтра","-2":"позавчера","-1":"вчера"},relativeTime:{future:{one:"Через {0} день",few:"Через {0} дня",many:"Через {0} дней",other:"Через {0} дня"},past:{one:"{0} день назад",few:"{0} дня назад",many:"{0} дней назад",other:"{0} дня назад"}}},month:{displayName:"Месяц",relative:{0:"в этом месяце",1:"в следующем месяце","-1":"в прошлом месяце"},relativeTime:{future:{one:"Через {0} месяц",few:"Через {0} месяца",many:"Через {0} месяцев",other:"Через {0} месяца"},past:{one:"{0} месяц назад",few:"{0} месяца назад",many:"{0} месяцев назад",other:"{0} месяца назад"}}},year:{displayName:"Год",relative:{0:"в этому году",1:"в следующем году","-1":"в прошлом году"},relativeTime:{future:{one:"Через {0} год",few:"Через {0} года",many:"Через {0} лет",other:"Через {0} года"},past:{one:"{0} год назад",few:"{0} года назад",many:"{0} лет назад",other:"{0} года назад"}}}}}),ReactIntl.__addLocaleData({locale:"rwk",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakyika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Mfiri",relative:{0:"Inu",1:"Ngama","-1":"Ukou"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mori",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Maka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"sah",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Сөкүүндэ",relative:{0:"now"},relativeTime:{future:{other:"{0} сөкүүндэннэн"},past:{other:"{0} сөкүүндэ ынараа өттүгэр"}}},minute:{displayName:"Мүнүүтэ",relativeTime:{future:{other:"{0} мүнүүтэннэн"},past:{other:"{0} мүнүүтэ ынараа өттүгэр"}}},hour:{displayName:"Чаас",relativeTime:{future:{other:"{0} чааһынан"},past:{other:"{0} чаас ынараа өттүгэр"}}},day:{displayName:"Күн",relative:{0:"Бүгүн",1:"Сарсын",2:"Өйүүн","-2":"Иллэрээ күн","-1":"Бэҕэһээ"},relativeTime:{future:{other:"{0} күнүнэн"},past:{other:"{0} күн ынараа өттүгэр"}}},month:{displayName:"Ый",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"{0} ыйынан"},past:{other:"{0} ый ынараа өттүгэр"}}},year:{displayName:"Сыл",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"{0} сылынан"},past:{other:"{0} сыл ынараа өттүгэр"}}}}}),ReactIntl.__addLocaleData({locale:"saq",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Isekondi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Idakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saai",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Mpari",relative:{0:"Duo",1:"Taisere","-1":"Ng'ole"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Lapa",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Lari",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"se",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":2===a?"two":"other"},fields:{second:{displayName:"sekunda",relative:{0:"now"},relativeTime:{future:{one:"{0} sekunda maŋŋilit",two:"{0} sekundda maŋŋilit",other:"{0} sekundda maŋŋilit"},past:{one:"{0} sekunda árat",two:"{0} sekundda árat",other:"{0} sekundda árat"}}},minute:{displayName:"minuhtta",relativeTime:{future:{one:"{0} minuhta maŋŋilit",two:"{0} minuhtta maŋŋilit",other:"{0} minuhtta maŋŋilit"},past:{one:"{0} minuhta árat",two:"{0} minuhtta árat",other:"{0} minuhtta árat"}}},hour:{displayName:"diibmu",relativeTime:{future:{one:"{0} diibmu maŋŋilit",two:"{0} diibmur maŋŋilit",other:"{0} diibmur maŋŋilit"},past:{one:"{0} diibmu árat",two:"{0} diibmur árat",other:"{0} diibmur árat"}}},day:{displayName:"beaivi",relative:{0:"odne",1:"ihttin",2:"paijeelittáá","-2":"oovdebpeivvi","-1":"ikte"},relativeTime:{future:{one:"{0} jándor maŋŋilit",two:"{0} jándor amaŋŋilit",other:"{0} jándora maŋŋilit"},past:{one:"{0} jándor árat",two:"{0} jándora árat",other:"{0} jándora árat"}}},month:{displayName:"mánnu",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"{0} mánotbadji maŋŋilit",two:"{0} mánotbadji maŋŋilit",other:"{0} mánotbadji maŋŋilit"},past:{one:"{0} mánotbadji árat",two:"{0} mánotbadji árat",other:"{0} mánotbadji árat"}}},year:{displayName:"jáhki",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"{0} jahki maŋŋilit",two:"{0} jahkki maŋŋilit",other:"{0} jahkki maŋŋilit"},past:{one:"{0} jahki árat",two:"{0} jahkki árat",other:"{0} jahkki árat"}}}}}),ReactIntl.__addLocaleData({locale:"seh",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Segundo",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minuto",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hora",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ntsiku",relative:{0:"Lero",1:"Manguana","-1":"Zuro"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mwezi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Chaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ses",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Miti",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Miniti",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Guuru",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Zaari",relative:{0:"Hõo",1:"Suba","-1":"Bi"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Handu",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Jiiri",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"sg",pluralRuleFunction:function(){return"other"
},fields:{second:{displayName:"Nzîna ngbonga",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Ndurü ngbonga",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Ngbonga",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Lâ",relative:{0:"Lâsô",1:"Kêkerêke","-1":"Bîrï"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Nze",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Ngû",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"shi",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":a===Math.floor(a)&&a>=2&&10>=a?"few":"other"},fields:{second:{displayName:"ⵜⴰⵙⵉⵏⵜ",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"ⵜⵓⵙⴷⵉⴷⵜ",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"ⵜⴰⵙⵔⴰⴳⵜ",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"ⴰⵙⵙ",relative:{0:"ⴰⵙⵙⴰ",1:"ⴰⵙⴽⴽⴰ","-1":"ⵉⴹⵍⵍⵉ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"ⴰⵢⵢⵓⵔ",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"ⴰⵙⴳⴳⵯⴰⵙ",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"si",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),0===a||1===a||0===b&&1===c?"one":"other"},fields:{second:{displayName:"තත්පරය",relative:{0:"දැන්"},relativeTime:{future:{one:"තත්පර {0} කින්",other:"තත්පර {0} කින්"},past:{one:"තත්පර {0}කට පෙර",other:"තත්පර {0}කට පෙර"}}},minute:{displayName:"මිනිත්තුව",relativeTime:{future:{one:"මිනිත්තු {0} කින්",other:"මිනිත්තු {0} කින්"},past:{one:"මිනිත්තු {0}ට පෙර",other:"මිනිත්තු {0}ට පෙර"}}},hour:{displayName:"පැය",relativeTime:{future:{one:"පැය {0} කින්",other:"පැය {0} කින්"},past:{one:"පැය {0}ට පෙර",other:"පැය {0}ට පෙර"}}},day:{displayName:"දිනය",relative:{0:"අද",1:"හෙට",2:"අනිද්දා","-2":"පෙරේදා","-1":"ඊයෙ"},relativeTime:{future:{one:"දින {0}න්",other:"දින {0}න්"},past:{one:"දින {0} ට පෙර",other:"දින {0} ට පෙර"}}},month:{displayName:"මාසය",relative:{0:"මෙම මාසය",1:"ඊළඟ මාසය","-1":"පසුගිය මාසය"},relativeTime:{future:{one:"මාස {0}කින්",other:"මාස {0}කින්"},past:{one:"මාස {0}කට පෙර",other:"මාස {0}කට පෙර"}}},year:{displayName:"වර්ෂය",relative:{0:"මෙම වසර",1:"ඊළඟ වසර","-1":"පසුගිය වසර"},relativeTime:{future:{one:"වසර {0} කින්",other:"වසර {0} කින්"},past:{one:"වසර {0}ට පෙර",other:"වසර {0}ට පෙර"}}}}}),ReactIntl.__addLocaleData({locale:"sk",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":b===Math.floor(b)&&b>=2&&4>=b&&0===c?"few":0!==c?"many":"other"},fields:{second:{displayName:"Sekunda",relative:{0:"teraz"},relativeTime:{future:{one:"O {0} sekundu",few:"O {0} sekundy",many:"O {0} sekundy",other:"O {0} sekúnd"},past:{one:"Pred {0} sekundou",few:"Pred {0} sekundami",many:"Pred {0} sekundami",other:"Pred {0} sekundami"}}},minute:{displayName:"Minúta",relativeTime:{future:{one:"O {0} minútu",few:"O {0} minúty",many:"O {0} minúty",other:"O {0} minút"},past:{one:"Pred {0} minútou",few:"Pred {0} minútami",many:"Pred {0} minútami",other:"Pred {0} minútami"}}},hour:{displayName:"Hodina",relativeTime:{future:{one:"O {0} hodinu",few:"O {0} hodiny",many:"O {0} hodiny",other:"O {0} hodín"},past:{one:"Pred {0} hodinou",few:"Pred {0} hodinami",many:"Pred {0} hodinami",other:"Pred {0} hodinami"}}},day:{displayName:"Deň",relative:{0:"Dnes",1:"Zajtra",2:"Pozajtra","-2":"Predvčerom","-1":"Včera"},relativeTime:{future:{one:"O {0} deň",few:"O {0} dni",many:"O {0} dňa",other:"O {0} dní"},past:{one:"Pred {0} dňom",few:"Pred {0} dňami",many:"Pred {0} dňami",other:"Pred {0} dňami"}}},month:{displayName:"Mesiac",relative:{0:"Tento mesiac",1:"Budúci mesiac","-1":"Posledný mesiac"},relativeTime:{future:{one:"O {0} mesiac",few:"O {0} mesiace",many:"O {0} mesiaca",other:"O {0} mesiacov"},past:{one:"Pred {0} mesiacom",few:"Pred {0} mesiacmi",many:"Pred {0} mesiacmi",other:"Pred {0} mesiacmi"}}},year:{displayName:"Rok",relative:{0:"Tento rok",1:"Budúci rok","-1":"Minulý rok"},relativeTime:{future:{one:"O {0} rok",few:"O {0} roky",many:"O {0} roka",other:"O {0} rokov"},past:{one:"Pred {0} rokom",few:"Pred {0} rokmi",many:"Pred {0} rokmi",other:"Pred {0} rokmi"}}}}}),ReactIntl.__addLocaleData({locale:"sl",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),0===c&&b%100===1?"one":0===c&&b%100===2?"two":0===c&&(b%100===Math.floor(b%100)&&b%100>=3&&4>=b%100||0!==c)?"few":"other"},fields:{second:{displayName:"Sekunda",relative:{0:"zdaj"},relativeTime:{future:{one:"Čez {0} sekundo",two:"Čez {0} sekundi",few:"Čez {0} sekunde",other:"Čez {0} sekundi"},past:{one:"Pred {0} sekundo",two:"Pred {0} sekundama",few:"Pred {0} sekundami",other:"Pred {0} sekundami"}}},minute:{displayName:"Minuta",relativeTime:{future:{one:"Čez {0} min.",two:"Čez {0} min.",few:"Čez {0} min.",other:"Čez {0} min."},past:{one:"Pred {0} min.",two:"Pred {0} min.",few:"Pred {0} min.",other:"Pred {0} min."}}},hour:{displayName:"Ura",relativeTime:{future:{one:"Čez {0} h",two:"Čez {0} h",few:"Čez {0} h",other:"Čez {0} h"},past:{one:"Pred {0} h",two:"Pred {0} h",few:"Pred {0} h",other:"Pred {0} h"}}},day:{displayName:"Dan",relative:{0:"Danes",1:"Jutri",2:"Pojutrišnjem","-2":"Predvčerajšnjim","-1":"Včeraj"},relativeTime:{future:{one:"Čez {0} dan",two:"Čez {0} dni",few:"Čez {0} dni",other:"Čez {0} dni"},past:{one:"Pred {0} dnevom",two:"Pred {0} dnevoma",few:"Pred {0} dnevi",other:"Pred {0} dnevi"}}},month:{displayName:"Mesec",relative:{0:"Ta mesec",1:"Naslednji mesec","-1":"Prejšnji mesec"},relativeTime:{future:{one:"Čez {0} mesec",two:"Čez {0} meseca",few:"Čez {0} mesece",other:"Čez {0} mesecev"},past:{one:"Pred {0} mesecem",two:"Pred {0} meseci",few:"Pred {0} meseci",other:"Pred {0} meseci"}}},year:{displayName:"Leto",relative:{0:"Letos",1:"Naslednje leto","-1":"Lani"},relativeTime:{future:{one:"Čez {0} leto",two:"Čez {0} leti",few:"Čez {0} leta",other:"Čez {0} let"},past:{one:"Pred {0} letom",two:"Pred {0} leti",few:"Pred {0} leti",other:"Pred {0} leti"}}}}}),ReactIntl.__addLocaleData({locale:"sn",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekondi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Mineti",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Awa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Zuva",relative:{0:"Nhasi",1:"Mangwana","-1":"Nezuro"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mwedzi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Gore",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"so",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Il biriqsi",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Daqiiqad",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saacad",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Maalin",relative:{0:"Maanta",1:"Berri","-1":"Shalay"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Bil",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Sanad",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"sq",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"sekondë",relative:{0:"tani"},relativeTime:{future:{one:"pas {0} sekonde",other:"pas {0} sekondash"},past:{one:"para {0} sekonde",other:"para {0} sekondash"}}},minute:{displayName:"minutë",relativeTime:{future:{one:"pas {0} minute",other:"pas {0} minutash"},past:{one:"para {0} minute",other:"para {0} minutash"}}},hour:{displayName:"orë",relativeTime:{future:{one:"pas {0} ore",other:"pas {0} orësh"},past:{one:"para {0} ore",other:"para {0} orësh"}}},day:{displayName:"ditë",relative:{0:"sot",1:"nesër","-1":"dje"},relativeTime:{future:{one:"pas {0} dite",other:"pas {0} ditësh"},past:{one:"para {0} dite",other:"para {0} ditësh"}}},month:{displayName:"muaj",relative:{0:"këtë muaj",1:"muajin e ardhshëm","-1":"muajin e kaluar"},relativeTime:{future:{one:"pas {0} muaji",other:"pas {0} muajsh"},past:{one:"para {0} muaji",other:"para {0} muajsh"}}},year:{displayName:"vit",relative:{0:"këtë vit",1:"vitin e ardhshëm","-1":"vitin e kaluar"},relativeTime:{future:{one:"pas {0} viti",other:"pas {0} vjetësh"},past:{one:"para {0} viti",other:"para {0} vjetësh"}}}}}),ReactIntl.__addLocaleData({locale:"sr",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length,d=parseInt(a.toString().replace(/^[^.]*\.?/,""),10);return a=Math.floor(a),0===c&&b%10===1&&(b%100!==11||d%10===1&&d%100!==11)?"one":0===c&&b%10===Math.floor(b%10)&&b%10>=2&&4>=b%10&&(!(b%100>=12&&14>=b%100)||d%10===Math.floor(d%10)&&d%10>=2&&4>=d%10&&!(d%100>=12&&14>=d%100))?"few":"other"},fields:{second:{displayName:"секунд",relative:{0:"сада"},relativeTime:{future:{one:"за {0} секунду",few:"за {0} секунде",other:"за {0} секунди"},past:{one:"пре {0} секунде",few:"пре {0} секунде",other:"пре {0} секунди"}}},minute:{displayName:"минут",relativeTime:{future:{one:"за {0} минут",few:"за {0} минута",other:"за {0} минута"},past:{one:"пре {0} минута",few:"пре {0} минута",other:"пре {0} минута"}}},hour:{displayName:"час",relativeTime:{future:{one:"за {0} сат",few:"за {0} сата",other:"за {0} сати"},past:{one:"пре {0} сата",few:"пре {0} сата",other:"пре {0} сати"}}},day:{displayName:"дан",relative:{0:"данас",1:"сутра",2:"прекосутра","-2":"прекјуче","-1":"јуче"},relativeTime:{future:{one:"за {0} дан",few:"за {0} дана",other:"за {0} дана"},past:{one:"пре {0} дана",few:"пре {0} дана",other:"пре {0} дана"}}},month:{displayName:"месец",relative:{0:"Овог месеца",1:"Следећег месеца","-1":"Прошлог месеца"},relativeTime:{future:{one:"за {0} месец",few:"за {0} месеца",other:"за {0} месеци"},past:{one:"пре {0} месеца",few:"пре {0} месеца",other:"пре {0} месеци"}}},year:{displayName:"година",relative:{0:"Ове године",1:"Следеће године","-1":"Прошле године"},relativeTime:{future:{one:"за {0} годину",few:"за {0} године",other:"за {0} година"},past:{one:"пре {0} године",few:"пре {0} године",other:"пре {0} година"}}}}}),ReactIntl.__addLocaleData({locale:"ss",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ssy",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"st",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"sv",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Sekund",relative:{0:"nu"},relativeTime:{future:{one:"om {0} sekund",other:"om {0} sekunder"},past:{one:"för {0} sekund sedan",other:"för {0} sekunder sedan"}}},minute:{displayName:"Minut",relativeTime:{future:{one:"om {0} minut",other:"om {0} minuter"},past:{one:"för {0} minut sedan",other:"för {0} minuter sedan"}}},hour:{displayName:"timme",relativeTime:{future:{one:"om {0} timme",other:"om {0} timmar"},past:{one:"för {0} timme sedan",other:"för {0} timmar sedan"}}},day:{displayName:"Dag",relative:{0:"i dag",1:"i morgon",2:"i övermorgon","-2":"i förrgår","-1":"i går"},relativeTime:{future:{one:"om {0} dag",other:"om {0} dagar"},past:{one:"för {0} dag sedan",other:"för {0} dagar sedan"}}},month:{displayName:"Månad",relative:{0:"denna månad",1:"nästa månad","-1":"förra månaden"},relativeTime:{future:{one:"om {0} månad",other:"om {0} månader"},past:{one:"för {0} månad sedan",other:"för {0} månader sedan"}}},year:{displayName:"År",relative:{0:"i år",1:"nästa år","-1":"i fjol"},relativeTime:{future:{one:"om {0} år",other:"om {0} år"},past:{one:"för {0} år sedan",other:"för {0} år sedan"}}}}}),ReactIntl.__addLocaleData({locale:"sw",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"sasa"},relativeTime:{future:{one:"Baada ya sekunde {0}",other:"Baada ya sekunde {0}"},past:{one:"Sekunde {0} iliyopita",other:"Sekunde {0} zilizopita"}}},minute:{displayName:"Dakika",relativeTime:{future:{one:"Baada ya dakika {0}",other:"Baada ya dakika {0}"},past:{one:"Dakika {0} iliyopita",other:"Dakika {0} zilizopita"}}},hour:{displayName:"Saa",relativeTime:{future:{one:"Baada ya saa {0}",other:"Baada ya saa {0}"},past:{one:"Saa {0} iliyopita",other:"Saa {0} zilizopita"}}},day:{displayName:"Siku",relative:{0:"leo",1:"kesho",2:"kesho kutwa","-2":"juzi","-1":"jana"},relativeTime:{future:{one:"Baada ya siku {0}",other:"Baada ya siku {0}"},past:{one:"Siku {0} iliyopita",other:"Siku {0} zilizopita"}}},month:{displayName:"Mwezi",relative:{0:"mwezi huu",1:"mwezi ujao","-1":"mwezi uliopita"},relativeTime:{future:{one:"Baada ya mwezi {0}",other:"Baada ya miezi {0}"},past:{one:"Miezi {0} iliyopita",other:"Miezi {0} iliyopita"}}},year:{displayName:"Mwaka",relative:{0:"mwaka huu",1:"mwaka ujao","-1":"mwaka uliopita"},relativeTime:{future:{one:"Baada ya mwaka {0}",other:"Baada ya miaka {0}"},past:{one:"Mwaka {0} uliopita",other:"Miaka {0} iliyopita"}}}}}),ReactIntl.__addLocaleData({locale:"ta",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"வினாடி",relative:{0:"இப்போது"},relativeTime:{future:{one:"{0} வினாடியில்",other:"{0} விநாடிகளில்"},past:{one:"{0} வினாடிக்கு முன்",other:"{0} வினாடிக்கு முன்"}}},minute:{displayName:"நிமிடம்",relativeTime:{future:{one:"{0} நிமிடத்தில்",other:"{0} நிமிடங்களில்"},past:{one:"{0} நிமிடத்திற்கு முன்",other:"{0} நிமிடங்களுக்கு முன்"}}},hour:{displayName:"மணி",relativeTime:{future:{one:"{0} மணிநேரத்தில்",other:"{0} மணிநேரத்தில்"},past:{one:"{0} மணிநேரம் முன்",other:"{0} மணிநேரம் முன்"}}},day:{displayName:"நாள்",relative:{0:"இன்று",1:"நாளை",2:"நாளை மறுநாள்","-2":"நேற்று முன் தினம்","-1":"நேற்று"},relativeTime:{future:{one:"{0} நாளில்",other:"{0} நாட்களில்"},past:{one:"{0} நாளுக்கு முன்",other:"{0} நாட்களுக்கு முன்"}}},month:{displayName:"மாதம்",relative:{0:"இந்த மாதம்",1:"அடுத்த மாதம்","-1":"கடந்த மாதம்"},relativeTime:{future:{one:"{0} மாதத்தில்",other:"{0} மாதங்களில்"},past:{one:"{0} மாதத்துக்கு முன்",other:"{0} மாதங்களுக்கு முன்"}}},year:{displayName:"ஆண்டு",relative:{0:"இந்த ஆண்டு",1:"அடுத்த ஆண்டு","-1":"கடந்த ஆண்டு"},relativeTime:{future:{one:"{0} ஆண்டில்",other:"{0} ஆண்டுகளில்"},past:{one:"{0} ஆண்டிற்கு முன்",other:"{0} ஆண்டுகளுக்கு முன்"}}}}}),ReactIntl.__addLocaleData({locale:"te",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"క్షణం",relative:{0:"ప్రస్తుతం"},relativeTime:{future:{one:"{0} సెకన్లో",other:"{0} సెకన్లలో"},past:{one:"{0} సెకను క్రితం",other:"{0} సెకన్ల క్రితం"}}},minute:{displayName:"నిమిషము",relativeTime:{future:{one:"{0} నిమిషంలో",other:"{0} నిమిషాల్లో"},past:{one:"{0} నిమిషం క్రితం",other:"{0} నిమిషాల క్రితం"}}},hour:{displayName:"గంట",relativeTime:{future:{one:"{0} గంటలో",other:"{0} గంటల్లో"},past:{one:"{0} గంట క్రితం",other:"{0} గంటల క్రితం"}}},day:{displayName:"దినం",relative:{0:"ఈ రోజు",1:"రేపు",2:"ఎల్లుండి","-2":"మొన్న","-1":"నిన్న"},relativeTime:{future:{one:"{0} రోజులో",other:"{0} రోజుల్లో"},past:{one:"{0} రోజు క్రితం",other:"{0} రోజుల క్రితం"}}},month:{displayName:"నెల",relative:{0:"ఈ నెల",1:"తదుపరి నెల","-1":"గత నెల"},relativeTime:{future:{one:"{0} నెలలో",other:"{0} నెలల్లో"},past:{one:"{0} నెల క్రితం",other:"{0} నెలల క్రితం"}}},year:{displayName:"సంవత్సరం",relative:{0:"ఈ సంవత్సరం",1:"తదుపరి సంవత్సరం","-1":"గత సంవత్సరం"},relativeTime:{future:{one:"{0} సంవత్సరంలో",other:"{0} సంవత్సరాల్లో"},past:{one:"{0} సంవత్సరం క్రితం",other:"{0} సంవత్సరాల క్రితం"}}}}}),ReactIntl.__addLocaleData({locale:"teo",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Isekonde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Idakika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Esaa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Aparan",relative:{0:"Lolo",1:"Moi","-1":"Jaan"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Elap",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Ekan",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"th",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"วินาที",relative:{0:"ขณะนี้"},relativeTime:{future:{other:"ในอีก {0} วินาที"},past:{other:"{0} วินาทีที่ผ่านมา"}}},minute:{displayName:"นาที",relativeTime:{future:{other:"ในอีก {0} นาที"},past:{other:"{0} นาทีที่ผ่านมา"}}},hour:{displayName:"ชั่วโมง",relativeTime:{future:{other:"ในอีก {0} ชั่วโมง"},past:{other:"{0} ชั่วโมงที่ผ่านมา"}}},day:{displayName:"วัน",relative:{0:"วันนี้",1:"พรุ่งนี้",2:"มะรืนนี้","-2":"เมื่อวานซืน","-1":"เมื่อวาน"},relativeTime:{future:{other:"ในอีก {0} วัน"},past:{other:"{0} วันที่ผ่านมา"}}},month:{displayName:"เดือน",relative:{0:"เดือนนี้",1:"เดือนหน้า","-1":"เดือนที่แล้ว"},relativeTime:{future:{other:"ในอีก {0} เดือน"},past:{other:"{0} เดือนที่ผ่านมา"}}},year:{displayName:"ปี",relative:{0:"ปีนี้",1:"ปีหน้า","-1":"ปีที่แล้ว"},relativeTime:{future:{other:"ในอีก {0} ปี"},past:{other:"{0} ปีที่แล้ว"}}}}}),ReactIntl.__addLocaleData({locale:"ti",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"tig",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"tn",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"to",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"sekoni",relative:{0:"taimiʻni"},relativeTime:{future:{other:"ʻi he sekoni ʻe {0}"},past:{other:"sekoni ʻe {0} kuoʻosi"}}},minute:{displayName:"miniti",relativeTime:{future:{other:"ʻi he miniti ʻe {0}"},past:{other:"miniti ʻe {0} kuoʻosi"}}},hour:{displayName:"houa",relativeTime:{future:{other:"ʻi he houa ʻe {0}"},past:{other:"houa ʻe {0} kuoʻosi"}}},day:{displayName:"ʻaho",relative:{0:"ʻaho⸍ni",1:"ʻapongipongi",2:"ʻahepongipongi","-2":"ʻaneheafi","-1":"ʻaneafi"},relativeTime:{future:{other:"ʻi he ʻaho ʻe {0}"},past:{other:"ʻaho ʻe {0} kuoʻosi"}}},month:{displayName:"māhina",relative:{0:"māhina⸍ni",1:"māhina kahaʻu","-1":"māhina kuoʻosi"},relativeTime:{future:{other:"ʻi he māhina ʻe {0}"},past:{other:"māhina ʻe {0} kuoʻosi"}}},year:{displayName:"taʻu",relative:{0:"taʻu⸍ni",1:"taʻu kahaʻu","-1":"taʻu kuoʻosi"},relativeTime:{future:{other:"ʻi he taʻu ʻe {0}"},past:{other:"taʻu ʻe {0} kuo hili"}}}}}),ReactIntl.__addLocaleData({locale:"tr",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Saniye",relative:{0:"şimdi"},relativeTime:{future:{one:"{0} saniye sonra",other:"{0} saniye sonra"},past:{one:"{0} saniye önce",other:"{0} saniye önce"}}},minute:{displayName:"Dakika",relativeTime:{future:{one:"{0} dakika sonra",other:"{0} dakika sonra"},past:{one:"{0} dakika önce",other:"{0} dakika önce"}}},hour:{displayName:"Saat",relativeTime:{future:{one:"{0} saat sonra",other:"{0} saat sonra"},past:{one:"{0} saat önce",other:"{0} saat önce"}}},day:{displayName:"Gün",relative:{0:"bugün",1:"yarın",2:"öbür gün","-2":"evvelsi gün","-1":"dün"},relativeTime:{future:{one:"{0} gün sonra",other:"{0} gün sonra"},past:{one:"{0} gün önce",other:"{0} gün önce"}}},month:{displayName:"Ay",relative:{0:"bu ay",1:"gelecek ay","-1":"geçen ay"},relativeTime:{future:{one:"{0} ay sonra",other:"{0} ay sonra"},past:{one:"{0} ay önce",other:"{0} ay önce"}}},year:{displayName:"Yıl",relative:{0:"bu yıl",1:"gelecek yıl","-1":"geçen yıl"},relativeTime:{future:{one:"{0} yıl sonra",other:"{0} yıl sonra"},past:{one:"{0} yıl önce",other:"{0} yıl önce"}}}}}),ReactIntl.__addLocaleData({locale:"ts",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"tzm",pluralRuleFunction:function(a){return a=Math.floor(a),a===Math.floor(a)&&a>=0&&1>=a||a===Math.floor(a)&&a>=11&&99>=a?"one":"other"},fields:{second:{displayName:"Tusnat",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Tusdat",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Tasragt",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ass",relative:{0:"Assa",1:"Asekka","-1":"Assenaṭ"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Ayur",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Asseggas",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"ug",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"سېكۇنت",relative:{0:"now"},relativeTime:{future:{one:"{0} سېكۇنتتىن كېيىن",other:"{0} سېكۇنتتىن كېيىن"},past:{one:"{0} سېكۇنت ئىلگىرى",other:"{0} سېكۇنت ئىلگىرى"}}},minute:{displayName:"مىنۇت",relativeTime:{future:{one:"{0} مىنۇتتىن كېيىن",other:"{0} مىنۇتتىن كېيىن"},past:{one:"{0} مىنۇت ئىلگىرى",other:"{0} مىنۇت ئىلگىرى"}}},hour:{displayName:"سائەت",relativeTime:{future:{one:"{0} سائەتتىن كېيىن",other:"{0} سائەتتىن كېيىن"},past:{one:"{0} سائەت ئىلگىرى",other:"{0} سائەت ئىلگىرى"}}},day:{displayName:"كۈن",relative:{0:"بۈگۈن",1:"ئەتە","-1":"تۈنۈگۈن"},relativeTime:{future:{one:"{0} كۈندىن كېيىن",other:"{0} كۈندىن كېيىن"},past:{one:"{0} كۈن ئىلگىرى",other:"{0} كۈن ئىلگىرى"}}},month:{displayName:"ئاي",relative:{0:"بۇ ئاي",1:"كېلەر ئاي","-1":"ئۆتكەن ئاي"},relativeTime:{future:{one:"{0} ئايدىن كېيىن",other:"{0} ئايدىن كېيىن"},past:{one:"{0} ئاي ئىلگىرى",other:"{0} ئاي ئىلگىرى"}}},year:{displayName:"يىل",relative:{0:"بۇ يىل",1:"كېلەر يىل","-1":"ئۆتكەن يىل"},relativeTime:{future:{one:"{0} يىلدىن كېيىن",other:"{0} يىلدىن كېيىن"},past:{one:"{0} يىل ئىلگىرى",other:"{0} يىل ئىلگىرى"}}}}}),ReactIntl.__addLocaleData({locale:"uk",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),0===c&&b%10===1&&b%100!==11?"one":0===c&&b%10===Math.floor(b%10)&&b%10>=2&&4>=b%10&&!(b%100>=12&&14>=b%100)?"few":0===c&&(b%10===0||0===c&&(b%10===Math.floor(b%10)&&b%10>=5&&9>=b%10||0===c&&b%100===Math.floor(b%100)&&b%100>=11&&14>=b%100))?"many":"other"},fields:{second:{displayName:"Секунда",relative:{0:"зараз"},relativeTime:{future:{one:"Через {0} секунду",few:"Через {0} секунди",many:"Через {0} секунд",other:"Через {0} секунди"},past:{one:"{0} секунду тому",few:"{0} секунди тому",many:"{0} секунд тому",other:"{0} секунди тому"}}},minute:{displayName:"Хвилина",relativeTime:{future:{one:"Через {0} хвилину",few:"Через {0} хвилини",many:"Через {0} хвилин",other:"Через {0} хвилини"},past:{one:"{0} хвилину тому",few:"{0} хвилини тому",many:"{0} хвилин тому",other:"{0} хвилини тому"}}},hour:{displayName:"Година",relativeTime:{future:{one:"Через {0} годину",few:"Через {0} години",many:"Через {0} годин",other:"Через {0} години"},past:{one:"{0} годину тому",few:"{0} години тому",many:"{0} годин тому",other:"{0} години тому"}}},day:{displayName:"День",relative:{0:"сьогодні",1:"завтра",2:"післязавтра","-2":"позавчора","-1":"учора"},relativeTime:{future:{one:"Через {0} день",few:"Через {0} дні",many:"Через {0} днів",other:"Через {0} дня"},past:{one:"{0} день тому",few:"{0} дні тому",many:"{0} днів тому",other:"{0} дня тому"}}},month:{displayName:"Місяць",relative:{0:"цього місяця",1:"наступного місяця","-1":"минулого місяця"},relativeTime:{future:{one:"Через {0} місяць",few:"Через {0} місяці",many:"Через {0} місяців",other:"Через {0} місяця"},past:{one:"{0} місяць тому",few:"{0} місяці тому",many:"{0} місяців тому",other:"{0} місяця тому"}}},year:{displayName:"Рік",relative:{0:"цього року",1:"наступного року","-1":"минулого року"},relativeTime:{future:{one:"Через {0} рік",few:"Через {0} роки",many:"Через {0} років",other:"Через {0} року"},past:{one:"{0} рік тому",few:"{0} роки тому",many:"{0} років тому",other:"{0} року тому"}}}}}),ReactIntl.__addLocaleData({locale:"ur",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a)),c=a.toString().replace(/^[^.]*\.?/,"").length;return a=Math.floor(a),1===b&&0===c?"one":"other"},fields:{second:{displayName:"سیکنڈ",relative:{0:"اب"},relativeTime:{future:{one:"{0} سیکنڈ میں",other:"{0} سیکنڈ میں"},past:{one:"{0} سیکنڈ پہلے",other:"{0} سیکنڈ پہلے"}}},minute:{displayName:"منٹ",relativeTime:{future:{one:"{0} منٹ میں",other:"{0} منٹ میں"},past:{one:"{0} منٹ پہلے",other:"{0} منٹ پہلے"}}},hour:{displayName:"گھنٹہ",relativeTime:{future:{one:"{0} گھنٹہ میں",other:"{0} گھنٹے میں"},past:{one:"{0} گھنٹہ پہلے",other:"{0} گھنٹے پہلے"}}},day:{displayName:"دن",relative:{0:"آج",1:"آئندہ کل",2:"آنے والا پرسوں","-2":"گزشتہ پرسوں","-1":"گزشتہ کل"},relativeTime:{future:{one:"{0} دن میں",other:"{0} دن میں"},past:{one:"{0} دن پہلے",other:"{0} دن پہلے"}}},month:{displayName:"مہینہ",relative:{0:"اس مہینہ",1:"اگلے مہینہ","-1":"پچھلے مہینہ"},relativeTime:{future:{one:"{0} مہینہ میں",other:"{0} مہینے میں"},past:{one:"{0} مہینہ پہلے",other:"{0} مہینے پہلے"}}},year:{displayName:"سال",relative:{0:"اس سال",1:"اگلے سال","-1":"پچھلے سال"},relativeTime:{future:{one:"{0} سال میں",other:"{0} سال میں"},past:{one:"{0} سال پہلے",other:"{0} سال پہلے"}}}}}),ReactIntl.__addLocaleData({locale:"uz",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"
},fields:{second:{displayName:"Soniya",relative:{0:"hozir"},relativeTime:{future:{one:"{0} soniyadan soʻng",other:"{0} soniyadan soʻng"},past:{one:"{0} soniya oldin",other:"{0} soniya oldin"}}},minute:{displayName:"Daqiqa",relativeTime:{future:{one:"{0} daqiqadan soʻng",other:"{0} daqiqadan soʻng"},past:{one:"{0} daqiqa oldin",other:"{0} daqiqa oldin"}}},hour:{displayName:"Soat",relativeTime:{future:{one:"{0} soatdan soʻng",other:"{0} soatdan soʻng"},past:{one:"{0} soat oldin",other:"{0} soat oldin"}}},day:{displayName:"Kun",relative:{0:"bugun",1:"ertaga","-1":"kecha"},relativeTime:{future:{one:"{0} kundan soʻng",other:"{0} kundan soʻng"},past:{one:"{0} kun oldin",other:"{0} kun oldin"}}},month:{displayName:"Oy",relative:{0:"bu oy",1:"keyingi oy","-1":"oʻtgan oy"},relativeTime:{future:{one:"{0} oydan soʻng",other:"{0} oydan soʻng"},past:{one:"{0} oy avval",other:"{0} oy avval"}}},year:{displayName:"Yil",relative:{0:"bu yil",1:"keyingi yil","-1":"oʻtgan yil"},relativeTime:{future:{one:"{0} yildan soʻng",other:"{0} yildan soʻng"},past:{one:"{0} yil avval",other:"{0} yil avval"}}}}}),ReactIntl.__addLocaleData({locale:"ve",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"vi",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Giây",relative:{0:"bây giờ"},relativeTime:{future:{other:"Trong {0} giây nữa"},past:{other:"{0} giây trước"}}},minute:{displayName:"Phút",relativeTime:{future:{other:"Trong {0} phút nữa"},past:{other:"{0} phút trước"}}},hour:{displayName:"Giờ",relativeTime:{future:{other:"Trong {0} giờ nữa"},past:{other:"{0} giờ trước"}}},day:{displayName:"Ngày",relative:{0:"Hôm nay",1:"Ngày mai",2:"Ngày kia","-2":"Hôm kia","-1":"Hôm qua"},relativeTime:{future:{other:"Trong {0} ngày nữa"},past:{other:"{0} ngày trước"}}},month:{displayName:"Tháng",relative:{0:"tháng này",1:"tháng sau","-1":"tháng trước"},relativeTime:{future:{other:"Trong {0} tháng nữa"},past:{other:"{0} tháng trước"}}},year:{displayName:"Năm",relative:{0:"năm nay",1:"năm sau","-1":"năm ngoái"},relativeTime:{future:{other:"Trong {0} năm nữa"},past:{other:"{0} năm trước"}}}}}),ReactIntl.__addLocaleData({locale:"vo",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"sekun",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"minut",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"düp",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Tag",relative:{0:"adelo",1:"odelo",2:"udelo","-2":"edelo","-1":"ädelo"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"mul",relative:{0:"amulo",1:"omulo","-1":"ämulo"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"yel",relative:{0:"ayelo",1:"oyelo","-1":"äyelo"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"vun",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunde",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Dakyika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Saa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Mfiri",relative:{0:"Inu",1:"Ngama","-1":"Ukou"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Mori",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Maka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"wae",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Sekunda",relative:{0:"now"},relativeTime:{future:{one:"i {0} sekund",other:"i {0} sekunde"},past:{one:"vor {0} sekund",other:"vor {0} sekunde"}}},minute:{displayName:"Mínütta",relativeTime:{future:{one:"i {0} minüta",other:"i {0} minüte"},past:{one:"vor {0} minüta",other:"vor {0} minüte"}}},hour:{displayName:"Schtund",relativeTime:{future:{one:"i {0} stund",other:"i {0} stunde"},past:{one:"vor {0} stund",other:"vor {0} stunde"}}},day:{displayName:"Tag",relative:{0:"Hitte",1:"Móre",2:"Ubermóre","-2":"Vorgešter","-1":"Gešter"},relativeTime:{future:{one:"i {0} tag",other:"i {0} täg"},past:{one:"vor {0} tag",other:"vor {0} täg"}}},month:{displayName:"Mánet",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{one:"I {0} mánet",other:"I {0} mánet"},past:{one:"vor {0} mánet",other:"vor {0} mánet"}}},year:{displayName:"Jár",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{one:"I {0} jár",other:"I {0} jár"},past:{one:"vor {0} jár",other:"cor {0} jár"}}}}}),ReactIntl.__addLocaleData({locale:"xh",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Second",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Minute",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Hour",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Day",relative:{0:"today",1:"tomorrow","-1":"yesterday"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Month",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Year",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"xog",pluralRuleFunction:function(a){return a=Math.floor(a),1===a?"one":"other"},fields:{second:{displayName:"Obutikitiki",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Edakiika",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"Essawa",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Olunaku",relative:{0:"Olwaleelo (leelo)",1:"Enkyo","-1":"Edho"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Omwezi",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Omwaka",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"yo",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"Ìsẹ́jú Ààyá",relative:{0:"now"},relativeTime:{future:{other:"+{0} s"},past:{other:"-{0} s"}}},minute:{displayName:"Ìsẹ́jú",relativeTime:{future:{other:"+{0} min"},past:{other:"-{0} min"}}},hour:{displayName:"wákàtí",relativeTime:{future:{other:"+{0} h"},past:{other:"-{0} h"}}},day:{displayName:"Ọjọ́",relative:{0:"Òní",1:"Ọ̀la",2:"òtúùnla","-2":"íjẹta","-1":"Àná"},relativeTime:{future:{other:"+{0} d"},past:{other:"-{0} d"}}},month:{displayName:"Osù",relative:{0:"this month",1:"next month","-1":"last month"},relativeTime:{future:{other:"+{0} m"},past:{other:"-{0} m"}}},year:{displayName:"Ọdún",relative:{0:"this year",1:"next year","-1":"last year"},relativeTime:{future:{other:"+{0} y"},past:{other:"-{0} y"}}}}}),ReactIntl.__addLocaleData({locale:"zh",pluralRuleFunction:function(){return"other"},fields:{second:{displayName:"秒钟",relative:{0:"现在"},relativeTime:{future:{other:"{0}秒钟后"},past:{other:"{0}秒钟前"}}},minute:{displayName:"分钟",relativeTime:{future:{other:"{0}分钟后"},past:{other:"{0}分钟前"}}},hour:{displayName:"小时",relativeTime:{future:{other:"{0}小时后"},past:{other:"{0}小时前"}}},day:{displayName:"日",relative:{0:"今天",1:"明天",2:"后天","-2":"前天","-1":"昨天"},relativeTime:{future:{other:"{0}天后"},past:{other:"{0}天前"}}},month:{displayName:"月",relative:{0:"本月",1:"下个月","-1":"上个月"},relativeTime:{future:{other:"{0}个月后"},past:{other:"{0}个月前"}}},year:{displayName:"年",relative:{0:"今年",1:"明年","-1":"去年"},relativeTime:{future:{other:"{0}年后"},past:{other:"{0}年前"}}}}}),ReactIntl.__addLocaleData({locale:"zu",pluralRuleFunction:function(a){var b=Math.floor(Math.abs(a));return a=Math.floor(a),0===b||1===a?"one":"other"},fields:{second:{displayName:"Isekhondi",relative:{0:"manje"},relativeTime:{future:{one:"Kusekhondi elingu-{0}",other:"Kumasekhondi angu-{0}"},past:{one:"isekhondi elingu-{0} eledlule",other:"amasekhondi angu-{0} adlule"}}},minute:{displayName:"Iminithi",relativeTime:{future:{one:"Kumunithi engu-{0}",other:"Emaminithini angu-{0}"},past:{one:"eminithini elingu-{0} eledlule",other:"amaminithi angu-{0} adlule"}}},hour:{displayName:"Ihora",relativeTime:{future:{one:"Ehoreni elingu-{0}",other:"Emahoreni angu-{0}"},past:{one:"ehoreni eligu-{0} eledluli",other:"emahoreni angu-{0} edlule"}}},day:{displayName:"Usuku",relative:{0:"namhlanje",1:"kusasa",2:"Usuku olulandela olakusasa","-2":"Usuku olwandulela olwayizolo","-1":"izolo"},relativeTime:{future:{one:"Osukwini olungu-{0}",other:"Ezinsukwini ezingu-{0}"},past:{one:"osukwini olungu-{0} olwedlule",other:"ezinsukwini ezingu-{0} ezedlule."}}},month:{displayName:"Inyanga",relative:{0:"le nyanga",1:"inyanga ezayo","-1":"inyanga edlule"},relativeTime:{future:{one:"Enyangeni engu-{0}",other:"Ezinyangeni ezingu-{0}"},past:{one:"enyangeni engu-{0} eyedlule",other:"ezinyangeni ezingu-{0} ezedlule"}}},year:{displayName:"Unyaka",relative:{0:"kulo nyaka",1:"unyaka ozayo","-1":"onyakeni odlule"},relativeTime:{future:{one:"Onyakeni ongu-{0}",other:"Eminyakeni engu-{0}"},past:{one:"enyakeni ongu-{0} owedlule",other:"iminyaka engu-{0} eyedlule"}}}}});
//# sourceMappingURL=react-intl-with-locales.min.js.map |
packages/reactor-kitchensink/src/examples/PivotGrid/Collapsible/Collapsible.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Container, PivotGrid, Toolbar, Button, Menu, MenuRadioItem } from '@extjs/reactor/modern';
import { generateData, randomDate } from '../generateSaleData';
import SaleModel from '../SaleModel';
// TODO - EXTJS-25191 MenuRadioItem in ExtReact throws error when it tries to reference getParent()
// use items array in Menu to avoid this issue for now.
export default class Collapsible extends Component {
constructor() {
super();
this.loadData();
}
store = Ext.create('Ext.data.Store', {
model: SaleModel
})
loadData = () => {
const data = generateData(20);
for(let i=0; i<data.length; i++) {
data[i].company = 'Dell';
data[i].date = randomDate(new Date(2016, 0, 1), new Date(2016, 0, 31));
}
this.store.loadData(data);
}
monthLabelRenderer = value => Ext.Date.monthNames[value]
state = {
collapsibleRows: false,
collapsibleColumns: false
}
render() {
const { collapsibleRows, collapsibleColumns } = this.state;
return (
<Container layout="fit" padding={10}>
<PivotGrid
shadow
ref="pivotgrid"
matrix={{
type: 'local',
// set to "false" to make groups on rows uncollapsible
collapsibleRows,
// set to "none" to disable subtotals for groups on rows
rowSubTotalsPosition: 'none',
// set to "false" to make groups on columns uncollapsible
collapsibleColumns,
// set to "none" to disable subtotals for groups on columns
colSubTotalsPosition: 'none',
// Set layout type to "tabular". If this config is missing then the
// default layout is "outline"
viewLayoutType: 'tabular',
store: this.store,
// Configure the aggregate dimensions. Multiple dimensions are
// supported.
aggregate: [{
dataIndex: 'value',
header: 'Total',
aggregator: 'sum',
width: 90
}],
// Configure the left axis dimensions that will be used to generate the
// grid rows
leftAxis: [{
dataIndex: 'person',
header: 'Person'
}, {
dataIndex: 'company',
header: 'Company'
}, {
dataIndex: 'year',
header: 'Year'
}],
// Configure the top axis dimensions that will be used to generate the
// grid columns
topAxis: [{
dataIndex: 'country',
header: 'Country'
}, {
dataIndex: 'month',
labelRenderer: this.monthLabelRenderer,
header: 'Month'
}]
}}
/>
<Toolbar
shadow={false}
docked="top"
ui="app-transparent-toolbar"
padding="5 8"
layout={{
type: 'hbox',
align: 'stretch'
}}
defaults={{
margin: '0 10 0 0',
shadow: true,
ui: 'action'
}}
>
<Button text="Collapsible">
<Menu
defaults={{
group: 'collapsible',
xtype: 'menuradioitem'
}}
items={[{
text: 'None',
checked: (!collapsibleColumns && !collapsibleRows),
handler: () => { this.setState({ collapsibleColumns: false, collapsibleRows: false })}
}, {
text: 'Rows only',
checked: (collapsibleRows && !collapsibleColumns),
handler: () => { this.setState({ collapsibleColumns: false, collapsibleRows: true })}
}, {
text: 'Columns only',
checked: (collapsibleColumns && !collapsibleRows),
handler: () => { this.setState({ collapsibleColumns: true, collapsibleRows: false })}
}, {
text: 'Rows & Columns',
checked: (collapsibleColumns && collapsibleRows),
handler: () => { this.setState({ collapsibleColumns: true, collapsibleRows: true })}
}]}
/>
</Button>
</Toolbar>
</Container>
)
}
} |
ajax/libs/react-textarea-autosize/5.0.4/react-textarea-autosize.js | BenjaminVanRyseghem/cdnjs | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('prop-types')) :
typeof define === 'function' && define.amd ? define(['react', 'prop-types'], factory) :
(global.TextareaAutosize = factory(global.React,global.PropTypes));
}(this, (function (React,PropTypes) { 'use strict';
React = 'default' in React ? React['default'] : React;
PropTypes = 'default' in PropTypes ? PropTypes['default'] : PropTypes;
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var isIE = isBrowser ? !!document.documentElement.currentStyle : false;
var hiddenTextarea = isBrowser && document.createElement('textarea');
var HIDDEN_TEXTAREA_STYLE = {
'min-height': '0',
'max-height': 'none',
height: '0',
visibility: 'hidden',
overflow: 'hidden',
position: 'absolute',
'z-index': '-1000',
top: '0',
right: '0'
};
var SIZING_STYLE = ['letter-spacing', 'line-height', 'font-family', 'font-weight', 'font-size', 'text-rendering', 'text-transform', 'width', 'text-indent', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width', 'box-sizing'];
var computedStyleCache = {};
function calculateNodeHeight(uiTextNode, uid) {
var useCache = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var minRows = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var maxRows = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
if (hiddenTextarea.parentNode === null) {
document.body.appendChild(hiddenTextarea);
}
// Copy all CSS properties that have an impact on the height of the content in
// the textbox
var nodeStyling = calculateNodeStyling(uiTextNode, useCache);
if (nodeStyling === null) {
return null;
}
var paddingSize = nodeStyling.paddingSize,
borderSize = nodeStyling.borderSize,
boxSizing = nodeStyling.boxSizing,
sizingStyle = nodeStyling.sizingStyle;
// Need to have the overflow attribute to hide the scrollbar otherwise
// text-lines will not calculated properly as the shadow will technically be
// narrower for content
Object.keys(sizingStyle).forEach(function (key) {
hiddenTextarea.style[key] = sizingStyle[key];
});
Object.keys(HIDDEN_TEXTAREA_STYLE).forEach(function (key) {
hiddenTextarea.style.setProperty(key, HIDDEN_TEXTAREA_STYLE[key], 'important');
});
hiddenTextarea.value = uiTextNode.value || uiTextNode.placeholder || 'x';
var minHeight = -Infinity;
var maxHeight = Infinity;
var height = hiddenTextarea.scrollHeight;
if (boxSizing === 'border-box') {
// border-box: add border, since height = content + padding + border
height = height + borderSize;
} else if (boxSizing === 'content-box') {
// remove padding, since height = content
height = height - paddingSize;
}
// measure height of a textarea with a single row
hiddenTextarea.value = 'x';
var singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
if (minRows !== null || maxRows !== null) {
if (minRows !== null) {
minHeight = singleRowHeight * minRows;
if (boxSizing === 'border-box') {
minHeight = minHeight + paddingSize + borderSize;
}
height = Math.max(minHeight, height);
}
if (maxRows !== null) {
maxHeight = singleRowHeight * maxRows;
if (boxSizing === 'border-box') {
maxHeight = maxHeight + paddingSize + borderSize;
}
height = Math.min(maxHeight, height);
}
}
var rowCount = Math.floor(height / singleRowHeight);
return { height: height, minHeight: minHeight, maxHeight: maxHeight, rowCount: rowCount };
}
function calculateNodeStyling(node, uid) {
var useCache = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (useCache && computedStyleCache[uid]) {
return computedStyleCache[uid];
}
var style = window.getComputedStyle(node);
if (style === null) {
return null;
}
var sizingStyle = SIZING_STYLE.reduce(function (obj, name) {
obj[name] = style.getPropertyValue(name);
return obj;
}, {});
var boxSizing = sizingStyle['box-sizing'];
// IE (Edge has already correct behaviour) returns content width as computed width
// so we need to add manually padding and border widths
if (isIE && boxSizing === 'border-box') {
sizingStyle.width = parseFloat(sizingStyle.width) + parseFloat(style['border-right-width']) + parseFloat(style['border-left-width']) + parseFloat(style['padding-right']) + parseFloat(style['padding-left']) + 'px';
}
var paddingSize = parseFloat(sizingStyle['padding-bottom']) + parseFloat(sizingStyle['padding-top']);
var borderSize = parseFloat(sizingStyle['border-bottom-width']) + parseFloat(sizingStyle['border-top-width']);
var nodeInfo = {
sizingStyle: sizingStyle,
paddingSize: paddingSize,
borderSize: borderSize,
boxSizing: boxSizing
};
if (useCache) {
computedStyleCache[uid] = nodeInfo;
}
return nodeInfo;
}
var purgeCache = function purgeCache(uid) {
return delete computedStyleCache[uid];
};
function autoInc() {
var seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return function () {
return ++seed;
};
}
var uid = autoInc();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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 get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var inherits = function (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 objectWithoutProperties = function (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 possibleConstructorReturn = function (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;
};
var set = function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
setter.call(receiver, value);
}
}
return value;
};
/**
* <TextareaAutosize />
*/
var noop = function noop() {};
var _ref = isBrowser && window.requestAnimationFrame ? [window.requestAnimationFrame, window.cancelAnimationFrame] : [setTimeout, clearTimeout];
var onNextFrame = _ref[0];
var clearNextFrameAction = _ref[1];
var TextareaAutosize = function (_React$Component) {
inherits(TextareaAutosize, _React$Component);
function TextareaAutosize(props) {
classCallCheck(this, TextareaAutosize);
var _this = possibleConstructorReturn(this, _React$Component.call(this, props));
_this._resizeLock = false;
_this._onRootDOMNode = function (node) {
_this._rootDOMNode = node;
if (_this.props.inputRef) {
_this.props.inputRef(node);
}
};
_this._onChange = function (event) {
if (!_this._controlled) {
_this._resizeComponent();
}
_this.props.onChange(event);
};
_this._resizeComponent = function () {
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop;
if (typeof _this._rootDOMNode === 'undefined') {
return;
}
var nodeHeight = calculateNodeHeight(_this._rootDOMNode, _this._uid, _this.props.useCacheForDOMMeasurements, _this.props.minRows, _this.props.maxRows);
if (nodeHeight === null) {
return;
}
var height = nodeHeight.height,
minHeight = nodeHeight.minHeight,
maxHeight = nodeHeight.maxHeight,
rowCount = nodeHeight.rowCount;
_this.rowCount = rowCount;
if (_this.state.height !== height || _this.state.minHeight !== minHeight || _this.state.maxHeight !== maxHeight) {
_this.setState({ height: height, minHeight: minHeight, maxHeight: maxHeight }, callback);
}
};
_this.state = {
height: props.style && props.style.height || 0,
minHeight: -Infinity,
maxHeight: Infinity
};
_this._uid = uid();
_this._controlled = typeof props.value === 'string';
return _this;
}
TextareaAutosize.prototype.render = function render() {
var _props = this.props,
_minRows = _props.minRows,
_maxRows = _props.maxRows,
_onHeightChange = _props.onHeightChange,
_useCacheForDOMMeasurements = _props.useCacheForDOMMeasurements,
_inputRef = _props.inputRef,
props = objectWithoutProperties(_props, ['minRows', 'maxRows', 'onHeightChange', 'useCacheForDOMMeasurements', 'inputRef']);
props.style = _extends({}, props.style, {
height: this.state.height
});
var maxHeight = Math.max(props.style.maxHeight || Infinity, this.state.maxHeight);
if (maxHeight < this.state.height) {
props.style.overflow = 'hidden';
}
return React.createElement('textarea', _extends({}, props, {
onChange: this._onChange,
ref: this._onRootDOMNode
}));
};
TextareaAutosize.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
this._resizeComponent();
// Working around Firefox bug which runs resize listeners even when other JS is running at the same moment
// causing competing rerenders (due to setState in the listener) in React.
// More can be found here - facebook/react#6324
this._resizeListener = function () {
if (_this2._resizeLock) {
return;
}
_this2._resizeLock = true;
_this2._resizeComponent(function () {
return _this2._resizeLock = false;
});
};
window.addEventListener('resize', this._resizeListener);
};
TextareaAutosize.prototype.componentWillReceiveProps = function componentWillReceiveProps() {
var _this3 = this;
this._clearNextFrame();
this._onNextFrameActionId = onNextFrame(function () {
return _this3._resizeComponent();
});
};
TextareaAutosize.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
if (this.state.height !== prevState.height) {
this.props.onHeightChange(this.state.height, this);
}
};
TextareaAutosize.prototype.componentWillUnmount = function componentWillUnmount() {
this._clearNextFrame();
window.removeEventListener('resize', this._resizeListener);
purgeCache(this._uid);
};
TextareaAutosize.prototype._clearNextFrame = function _clearNextFrame() {
clearNextFrameAction(this._onNextFrameActionId);
};
return TextareaAutosize;
}(React.Component);
TextareaAutosize.propTypes = {
value: PropTypes.string,
onChange: PropTypes.func,
onHeightChange: PropTypes.func,
useCacheForDOMMeasurements: PropTypes.bool,
minRows: PropTypes.number,
maxRows: PropTypes.number,
inputRef: PropTypes.func
};
TextareaAutosize.defaultProps = {
onChange: noop,
onHeightChange: noop,
useCacheForDOMMeasurements: false
};
return TextareaAutosize;
})));
|
app/components/confirmModal/index.js | MakersLab/farm-client | import React from 'react';
import style from './style.css';
import modalStyle from '../fileUploadModal/style.css';
import Modal from 'react-modal';
import H1 from '../h1';
import ControllButton from '../controllButton';
import SelectedPrinters from '../selectedPrinters';
const PrinterActionConfirmModal = ({ isOpen, onYes, onNo, children, selectedPrinters }) => (
<Modal
isOpen={isOpen}
className={modalStyle.modal}
overlayClassName={modalStyle.modalOverlay}
onRequestClose={onNo}
contentLabel="PrinterActionConfirm"
>
<H1>{children}</H1>
<SelectedPrinters selectedPrinters={selectedPrinters} />
<ControllButton onClick={onYes}>Yes</ControllButton>
<ControllButton onClick={onNo}>No</ControllButton>
</Modal>
)
export default PrinterActionConfirmModal;
|
src/browser/app/App.js | robinpokorny/este | // @flow
import type { State } from '../../common/types';
import type { Theme } from './themes/types';
import * as themes from './themes';
import Footer from './Footer';
import Header from './Header';
import Helmet from 'react-helmet';
import React from 'react';
import favicon from '../../common/app/favicon';
import start from '../../common/app/start';
import { Match } from '../../common/app/components';
import { Miss } from 'react-router';
import { compose } from 'ramda';
import { connect } from 'react-redux';
import {
Baseline,
Box,
Container,
ThemeProvider,
} from './components';
// Pages
import FieldsPage from '../fields/FieldsPage';
import HomePage from '../home/HomePage';
import IntlPage from '../intl/IntlPage';
import MePage from '../me/MePage';
import NotFoundPage from '../notfound/NotFoundPage';
import OfflinePage from '../offline/OfflinePage';
import SignInPage from '../auth/SignInPage';
import TodosPage from '../todos/TodosPage';
import UsersPage from '../users/UsersPage';
type AppProps = {
currentLocale: string,
themeName: string,
theme: Theme,
};
const App = ({
currentLocale,
theme,
themeName,
}: AppProps) => (
<ThemeProvider
key={themeName} // Enforce rerender.
theme={theme}
>
<Baseline lineHeight={theme.typography.lineHeight}>
<Container>
<Helmet
htmlAttributes={{ lang: currentLocale }}
meta={[
// v4-alpha.getbootstrap.com/getting-started/introduction/#starter-template
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1, shrink-to-fit=no' },
{ 'http-equiv': 'x-ua-compatible', content: 'ie=edge' },
...favicon.meta,
]}
link={[
...favicon.link,
]}
/>
<Header />
<Box
flex={1} // make footer sticky
>
<Match exactly pattern="/" component={HomePage} />
<Match pattern="/users" component={UsersPage} />
<Match pattern="/todos" component={TodosPage} />
<Match pattern="/fields" component={FieldsPage} />
<Match pattern="/intl" component={IntlPage} />
<Match pattern="/offline" component={OfflinePage} />
<Match pattern="/signin" component={SignInPage} />
<Match authorized pattern="/me" component={MePage} />
<Miss component={NotFoundPage} />
</Box>
<Footer />
</Container>
</Baseline>
</ThemeProvider>
);
export default compose(
connect(
(state: State) => ({
currentLocale: state.intl.currentLocale,
themeName: state.app.currentTheme,
theme: themes[state.app.currentTheme] || themes.defaultTheme,
}),
),
start,
)(App);
|
src/theme/bootstrap.config.js | sanyamagrawal/royalgeni | /**
* Bootstrap configuration for bootstrap-sass-loader
*
* Scripts are disabled to not load jQuery.
* If you depend on Bootstrap scripts consider react-bootstrap instead.
* https://github.com/react-bootstrap/react-bootstrap
*
* In order to keep the bundle size low in production
* disable components you don't use.
*
*/
module.exports = {
preBootstrapCustomizations: './src/theme/variables.scss',
mainSass: './src/theme/bootstrap.overrides.scss',
verbose: false,
debug: false,
scripts: {
transition: false,
alert: false,
button: false,
carousel: false,
collapse: false,
dropdown: false,
modal: false,
tooltip: false,
popover: false,
scrollspy: false,
tab: false,
affix: false
},
styles: {
mixins: true,
normalize: true,
print: true,
glyphicons: true,
scaffolding: true,
type: true,
code: true,
grid: true,
tables: true,
forms: true,
buttons: true,
'component-animations': true,
dropdowns: true,
'button-groups': true,
'input-groups': true,
navs: true,
navbar: true,
breadcrumbs: true,
pagination: true,
pager: true,
labels: true,
badges: true,
jumbotron: true,
thumbnails: true,
alerts: true,
'progress-bars': true,
media: true,
'list-group': true,
panels: true,
wells: true,
'responsive-embed': true,
close: true,
modals: true,
tooltip: true,
popovers: true,
carousel: true,
utilities: true,
'responsive-utilities': true
}
};
|
src/renderers/shared/reconciler/__tests__/ReactMultiChild-test.js | negativetwelve/react | /**
* 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.
*
* @emails react-core
*/
'use strict';
var mocks = require('mocks');
describe('ReactMultiChild', function() {
var React;
beforeEach(function() {
require('mock-modules').dumpCache();
React = require('React');
});
describe('reconciliation', function() {
it('should update children when possible', function() {
var container = document.createElement('div');
var mockMount = mocks.getMockFunction();
var mockUpdate = mocks.getMockFunction();
var mockUnmount = mocks.getMockFunction();
var MockComponent = React.createClass({
componentDidMount: mockMount,
componentDidUpdate: mockUpdate,
componentWillUnmount: mockUnmount,
render: function() {
return <span />;
},
});
expect(mockMount.mock.calls.length).toBe(0);
expect(mockUpdate.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<div><MockComponent /></div>, container);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUpdate.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<div><MockComponent /></div>, container);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUpdate.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
});
it('should replace children with different constructors', function() {
var container = document.createElement('div');
var mockMount = mocks.getMockFunction();
var mockUnmount = mocks.getMockFunction();
var MockComponent = React.createClass({
componentDidMount: mockMount,
componentWillUnmount: mockUnmount,
render: function() {
return <span />;
},
});
expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<div><MockComponent /></div>, container);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<div><span /></div>, container);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(1);
});
it('should NOT replace children with different owners', function() {
var container = document.createElement('div');
var mockMount = mocks.getMockFunction();
var mockUnmount = mocks.getMockFunction();
var MockComponent = React.createClass({
componentDidMount: mockMount,
componentWillUnmount: mockUnmount,
render: function() {
return <span />;
},
});
var WrapperComponent = React.createClass({
render: function() {
return this.props.children || <MockComponent />;
},
});
expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<WrapperComponent />, container);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(
<WrapperComponent><MockComponent /></WrapperComponent>,
container
);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
});
it('should replace children with different keys', function() {
var container = document.createElement('div');
var mockMount = mocks.getMockFunction();
var mockUnmount = mocks.getMockFunction();
var MockComponent = React.createClass({
componentDidMount: mockMount,
componentWillUnmount: mockUnmount,
render: function() {
return <span />;
},
});
expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<div><MockComponent key="A" /></div>, container);
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
React.render(<div><MockComponent key="B" /></div>, container);
expect(mockMount.mock.calls.length).toBe(2);
expect(mockUnmount.mock.calls.length).toBe(1);
});
});
describe('innerHTML', function() {
var setInnerHTML;
// Only run this suite if `Element.prototype.innerHTML` can be spied on.
var innerHTMLDescriptor = Object.getOwnPropertyDescriptor(
Element.prototype,
'innerHTML'
);
if (!innerHTMLDescriptor) {
return;
}
beforeEach(function() {
Object.defineProperty(Element.prototype, 'innerHTML', {
set: setInnerHTML = jasmine.createSpy().andCallFake(
innerHTMLDescriptor.set
),
});
});
it('should only set `innerHTML` once on update', function() {
var container = document.createElement('div');
React.render(
<div>
<p><span /></p>
<p><span /></p>
<p><span /></p>
</div>,
container
);
// Warm the cache used by `getMarkupWrap`.
React.render(
<div>
<p><span /><span /></p>
<p><span /><span /></p>
<p><span /><span /></p>
</div>,
container
);
expect(setInnerHTML).toHaveBeenCalled();
var callCountOnMount = setInnerHTML.calls.length;
React.render(
<div>
<p><span /><span /><span /></p>
<p><span /><span /><span /></p>
<p><span /><span /><span /></p>
</div>,
container
);
expect(setInnerHTML.calls.length).toBe(callCountOnMount + 1);
});
});
});
|
ajax/libs/instantsearch.js/1.8.12/instantsearch-preact.js | kennynaoh/cdnjs | /*! instantsearch.js 1.8.12 | © Algolia Inc. and other contributors; Licensed MIT | github.com/algolia/instantsearch.js */(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["instantsearch"] = factory();
else
root["instantsearch"] = factory();
})(this, function() {
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 _main = __webpack_require__(1);
var _main2 = _interopRequireDefault(_main);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = _main2.default; // we need to export using commonjs for ease of usage in all
// JavaScript environments
/* eslint-disable import/no-commonjs */
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
__webpack_require__(2);
__webpack_require__(3);
var _toFactory = __webpack_require__(4);
var _toFactory2 = _interopRequireDefault(_toFactory);
var _InstantSearch = __webpack_require__(5);
var _InstantSearch2 = _interopRequireDefault(_InstantSearch);
var _algoliasearchHelper = __webpack_require__(32);
var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper);
var _clearAll = __webpack_require__(332);
var _clearAll2 = _interopRequireDefault(_clearAll);
var _currentRefinedValues = __webpack_require__(349);
var _currentRefinedValues2 = _interopRequireDefault(_currentRefinedValues);
var _hierarchicalMenu = __webpack_require__(353);
var _hierarchicalMenu2 = _interopRequireDefault(_hierarchicalMenu);
var _hits = __webpack_require__(357);
var _hits2 = _interopRequireDefault(_hits);
var _hitsPerPageSelector = __webpack_require__(362);
var _hitsPerPageSelector2 = _interopRequireDefault(_hitsPerPageSelector);
var _menu = __webpack_require__(366);
var _menu2 = _interopRequireDefault(_menu);
var _refinementList = __webpack_require__(370);
var _refinementList2 = _interopRequireDefault(_refinementList);
var _numericRefinementList = __webpack_require__(372);
var _numericRefinementList2 = _interopRequireDefault(_numericRefinementList);
var _numericSelector = __webpack_require__(374);
var _numericSelector2 = _interopRequireDefault(_numericSelector);
var _pagination = __webpack_require__(375);
var _pagination2 = _interopRequireDefault(_pagination);
var _priceRanges = __webpack_require__(384);
var _priceRanges2 = _interopRequireDefault(_priceRanges);
var _searchBox = __webpack_require__(389);
var _searchBox2 = _interopRequireDefault(_searchBox);
var _rangeSlider = __webpack_require__(391);
var _rangeSlider2 = _interopRequireDefault(_rangeSlider);
var _sortBySelector = __webpack_require__(395);
var _sortBySelector2 = _interopRequireDefault(_sortBySelector);
var _starRating = __webpack_require__(396);
var _starRating2 = _interopRequireDefault(_starRating);
var _stats = __webpack_require__(399);
var _stats2 = _interopRequireDefault(_stats);
var _toggle = __webpack_require__(402);
var _toggle2 = _interopRequireDefault(_toggle);
var _version = __webpack_require__(329);
var _version2 = _interopRequireDefault(_version);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// required for IE <= 10 since move to babel6
var instantsearch = (0, _toFactory2.default)(_InstantSearch2.default); // required for browsers not supporting Object.freeze (helper requirement)
instantsearch.widgets = {
clearAll: _clearAll2.default,
currentRefinedValues: _currentRefinedValues2.default,
hierarchicalMenu: _hierarchicalMenu2.default,
hits: _hits2.default,
hitsPerPageSelector: _hitsPerPageSelector2.default,
menu: _menu2.default,
refinementList: _refinementList2.default,
numericRefinementList: _numericRefinementList2.default,
numericSelector: _numericSelector2.default,
pagination: _pagination2.default,
priceRanges: _priceRanges2.default,
searchBox: _searchBox2.default,
rangeSlider: _rangeSlider2.default,
sortBySelector: _sortBySelector2.default,
starRating: _starRating2.default,
stats: _stats2.default,
toggle: _toggle2.default
};
instantsearch.version = _version2.default;
instantsearch.createQueryString = _algoliasearchHelper2.default.url.getQueryStringFromState;
exports.default = instantsearch;
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
// https://github.com/es-shims/es5-shim/blob/bf48788c724f255275a801a371c4a3adc304b34c/es5-sham.js#L473
// Object.freeze is used in various places in our code and is not polyfilled by
// polyfill.io (because not doable): https://github.com/Financial-Times/polyfill-service/issues/232
// So we "sham" it, which means that the API is here but it just returns the object.
if (!Object.freeze) {
Object.freeze = function freeze(object) {
if (Object(object) !== object) {
throw new TypeError('Object.freeze can only be called on Objects.');
}
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
/***/ },
/* 3 */
/***/ function(module, exports) {
"use strict";
/* eslint-disable */
// FIX IE <= 10 babel6:
// - https://phabricator.babeljs.io/T3041
// - https://phabricator.babeljs.io/T3041#70671
var testObject = {};
if (!(Object.setPrototypeOf || testObject.__proto__)) {
(function () {
var nativeGetPrototypeOf = Object.getPrototypeOf;
Object.getPrototypeOf = function (object) {
if (object.__proto__) {
return object.__proto__;
} else {
return nativeGetPrototypeOf.call(Object, object);
}
};
})();
}
/***/ },
/* 4 */
/***/ function(module, exports) {
"use strict";
var _bind = Function.prototype.bind;
function toFactory(Class) {
var Factory = function Factory() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new (_bind.apply(Class, [null].concat(args)))();
};
Factory.__proto__ = Class;
Factory.prototype = Class.prototype;
return Factory;
}
module.exports = toFactory;
/***/ },
/* 5 */
/***/ 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 _algoliasearchLite = __webpack_require__(6);
var _algoliasearchLite2 = _interopRequireDefault(_algoliasearchLite);
var _algoliasearchHelper = __webpack_require__(32);
var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper);
var _forEach = __webpack_require__(164);
var _forEach2 = _interopRequireDefault(_forEach);
var _mergeWith = __webpack_require__(310);
var _mergeWith2 = _interopRequireDefault(_mergeWith);
var _union = __webpack_require__(311);
var _union2 = _interopRequireDefault(_union);
var _clone = __webpack_require__(314);
var _clone2 = _interopRequireDefault(_clone);
var _isPlainObject = __webpack_require__(234);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _events = __webpack_require__(294);
var _urlSync = __webpack_require__(328);
var _urlSync2 = _interopRequireDefault(_urlSync);
var _version = __webpack_require__(329);
var _version2 = _interopRequireDefault(_version);
var _createHelpers = __webpack_require__(331);
var _createHelpers2 = _interopRequireDefault(_createHelpers);
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 _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; } // we use the fullpath to the lite build to solve a meteor.js issue:
// https://github.com/algolia/instantsearch.js/issues/1024#issuecomment-221618284
function defaultCreateURL() {
return '#';
}
/**
* @function instantsearch
* @param {string} options.appId The Algolia application ID
* @param {string} options.apiKey The Algolia search-only API key
* @param {string} options.indexName The name of the main index
* @param {string} [options.numberLocale] The locale used to display numbers. This will be passed
* to Number.prototype.toLocaleString()
* @param {function} [options.searchFunction] A hook that will be called each time a search needs to be done, with the
* helper as a parameter. It's your responsibility to call helper.search(). This option allows you to avoid doing
* searches at page load for example.
* @param {Object} [options.searchParameters] Additional parameters to pass to
* the Algolia API.
* [Full documentation](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchparameters)
* @param {Object|boolean} [options.urlSync] Url synchronization configuration.
* Setting to `true` will synchronize the needed search parameters with the browser url.
* @param {Object} [options.urlSync.mapping] Object used to define replacement query
* parameter to use in place of another. Keys are current query parameters
* and value the new value, e.g. `{ q: 'query' }`.
* @param {number} [options.urlSync.threshold] Idle time in ms after which a new
* state is created in the browser history. The default value is 700. The url is always updated at each keystroke
* but we only create a "previous search state" (activated when click on back button) every 700ms of idle time.
* @param {string[]} [options.urlSync.trackedParameters] Parameters that will
* be synchronized in the URL. Default value is `['query', 'attribute:*',
* 'index', 'page', 'hitsPerPage']`. `attribute:*` means all the faceting attributes will be tracked. You
* can track only some of them by using [..., 'attribute:color', 'attribute:categories']. All other possible
* values are all the [attributes of the Helper SearchParameters](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchparameters).
*
* There's a special `is_v` parameter that will get added everytime, it tracks the version of instantsearch.js
* linked to the url.
* @param {boolean} [options.urlSync.useHash] If set to true, the url will be
* hash based. Otherwise, it'll use the query parameters using the modern
* history API.
* @param {function} [options.urlSync.getHistoryState] Pass this function to override the
* default history API state we set to `null`. For example this could be used to force passing
* {turbolinks: true} to the history API every time we update it.
* @return {Object} the instantsearch instance
*/
var InstantSearch = function (_EventEmitter) {
_inherits(InstantSearch, _EventEmitter);
function InstantSearch(_ref) {
var _ref$appId = _ref.appId;
var appId = _ref$appId === undefined ? null : _ref$appId;
var _ref$apiKey = _ref.apiKey;
var apiKey = _ref$apiKey === undefined ? null : _ref$apiKey;
var _ref$indexName = _ref.indexName;
var indexName = _ref$indexName === undefined ? null : _ref$indexName;
var numberLocale = _ref.numberLocale;
var _ref$searchParameters = _ref.searchParameters;
var searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters;
var _ref$urlSync = _ref.urlSync;
var urlSync = _ref$urlSync === undefined ? null : _ref$urlSync;
var searchFunction = _ref.searchFunction;
_classCallCheck(this, InstantSearch);
var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this));
if (appId === null || apiKey === null || indexName === null) {
var usage = '\nUsage: instantsearch({\n appId: \'my_application_id\',\n apiKey: \'my_search_api_key\',\n indexName: \'my_index_name\'\n});';
throw new Error(usage);
}
var client = (0, _algoliasearchLite2.default)(appId, apiKey);
client.addAlgoliaAgent('instantsearch.js ' + _version2.default);
_this.client = client;
_this.helper = null;
_this.indexName = indexName;
_this.searchParameters = _extends({}, searchParameters, { index: indexName });
_this.widgets = [];
_this.templatesConfig = {
helpers: (0, _createHelpers2.default)({ numberLocale: numberLocale }),
compileOptions: {}
};
if (searchFunction) {
_this._searchFunction = searchFunction;
}
_this.urlSync = urlSync === true ? {} : urlSync;
return _this;
}
/**
* Add a widget
* @param {Object} [widget] The widget to add
* @param {function} [widget.render] Called after each search response has been received
* @param {function} [widget.getConfiguration] Let the widget update the configuration
* of the search with new parameters
* @param {function} [widget.init] Called once before the first search
* @return {Object} the added widget
*/
_createClass(InstantSearch, [{
key: 'addWidget',
value: function addWidget(widget) {
// Add the widget to the list of widget
if (widget.render === undefined && widget.init === undefined) {
throw new Error('Widget definition missing render or init method');
}
this.widgets.push(widget);
}
}, {
key: 'start',
value: function start() {
var _this2 = this;
if (!this.widgets) throw new Error('No widgets were added to instantsearch.js');
var searchParametersFromUrl = void 0;
if (this.urlSync) {
var syncWidget = (0, _urlSync2.default)(this.urlSync);
this._createURL = syncWidget.createURL.bind(syncWidget);
this._createAbsoluteURL = function (relative) {
return _this2._createURL(relative, { absolute: true });
};
this._onHistoryChange = syncWidget.onHistoryChange.bind(syncWidget);
this.widgets.push(syncWidget);
searchParametersFromUrl = syncWidget.searchParametersFromUrl;
} else {
this._createURL = defaultCreateURL;
this._createAbsoluteURL = defaultCreateURL;
this._onHistoryChange = function () {};
}
this.searchParameters = this.widgets.reduce(enhanceConfiguration(searchParametersFromUrl), this.searchParameters);
var helper = (0, _algoliasearchHelper2.default)(this.client, this.searchParameters.index || this.indexName, this.searchParameters);
if (this._searchFunction) {
this._originalHelperSearch = helper.search.bind(helper);
helper.search = this._wrappedSearch.bind(this);
}
this.helper = helper;
this._init(helper.state, helper);
helper.on('result', this._render.bind(this, helper));
helper.search();
}
}, {
key: '_wrappedSearch',
value: function _wrappedSearch() {
var helper = (0, _clone2.default)(this.helper);
helper.search = this._originalHelperSearch;
this._searchFunction(helper);
return;
}
}, {
key: 'createURL',
value: function createURL(params) {
if (!this._createURL) {
throw new Error('You need to call start() before calling createURL()');
}
return this._createURL(this.helper.state.setQueryParameters(params));
}
}, {
key: '_render',
value: function _render(helper, results, state) {
var _this3 = this;
(0, _forEach2.default)(this.widgets, function (widget) {
if (!widget.render) {
return;
}
widget.render({
templatesConfig: _this3.templatesConfig,
results: results,
state: state,
helper: helper,
createURL: _this3._createAbsoluteURL
});
});
this.emit('render');
}
}, {
key: '_init',
value: function _init(state, helper) {
var _this4 = this;
(0, _forEach2.default)(this.widgets, function (widget) {
if (widget.init) {
widget.init({
state: state,
helper: helper,
templatesConfig: _this4.templatesConfig,
createURL: _this4._createAbsoluteURL,
onHistoryChange: _this4._onHistoryChange
});
}
});
}
}]);
return InstantSearch;
}(_events.EventEmitter);
function enhanceConfiguration(searchParametersFromUrl) {
return function (configuration, widgetDefinition) {
if (!widgetDefinition.getConfiguration) return configuration;
// Get the relevant partial configuration asked by the widget
var partialConfiguration = widgetDefinition.getConfiguration(configuration, searchParametersFromUrl);
var customizer = function customizer(a, b) {
// always create a unified array for facets refinements
if (Array.isArray(a)) {
return (0, _union2.default)(a, b);
}
// avoid mutating objects
if ((0, _isPlainObject2.default)(a)) {
return (0, _mergeWith2.default)({}, a, b, customizer);
}
return undefined;
};
return (0, _mergeWith2.default)({}, configuration, partialConfiguration, customizer);
};
}
exports.default = InstantSearch;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var AlgoliaSearchCore = __webpack_require__(7);
var createAlgoliasearch = __webpack_require__(21);
module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) ');
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
module.exports = AlgoliaSearchCore;
var errors = __webpack_require__(8);
var exitPromise = __webpack_require__(11);
var IndexCore = __webpack_require__(12);
// We will always put the API KEY in the JSON body in case of too long API KEY
var MAX_API_KEY_LENGTH = 500;
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = __webpack_require__(17)('algoliasearch');
var clone = __webpack_require__(20);
var isArray = __webpack_require__(15);
var map = __webpack_require__(16);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
var defaultHosts = shuffle([
this.applicationID + '-1.algolianet.com',
this.applicationID + '-2.algolianet.com',
this.applicationID + '-3.algolianet.com'
]);
this.hosts = {
read: [],
write: []
};
this.hostIndex = {
read: 0,
write: 0
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
var timeout = opts.timeout === undefined ? 2000 : opts.timeout;
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
// no hosts given, add defaults
if (!opts.hosts) {
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.requestTimeout = timeout;
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
this._ua += ';' + algoliaAgent;
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
var requestDebug = __webpack_require__(17)('algoliasearch:' + initialOpts.url);
var body;
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(false);
} else {
headers = this._computeRequestHeaders();
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to support@algolia.com to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders();
reqOpts.timeout = client.requestTimeout * (tries + 1);
client.hostIndex[initialOpts.hostType] = 0;
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client.hosts[initialOpts.hostType][client.hostIndex[initialOpts.hostType]];
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeout: reqOpts.timeout,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeout: %d',
options.method, url, options.headers, options.timeout);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeout: reqOpts.timeout,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeout: reqOpts.timeout,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client.hostIndex[initialOpts.hostType] = (client.hostIndex[initialOpts.hostType] + 1) % client.hosts[initialOpts.hostType].length;
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client.hostIndex[initialOpts.hostType] = (client.hostIndex[initialOpts.hostType] + 1) % client.hosts[initialOpts.hostType].length;
reqOpts.timeout = client.requestTimeout * (tries + 1);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeout: client.requestTimeout * (tries + 1)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(withAPIKey) {
var forEach = __webpack_require__(10);
var requestHeaders = {
'x-algolia-agent': this._ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = __webpack_require__(15);
var map = __webpack_require__(16);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
*
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this.requestTimeout = parseInt(milliseconds, 10);
}
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = __webpack_require__(9);
function AlgoliaSearchError(message, extraProperties) {
var forEach = __webpack_require__(10);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
/***/ },
/* 9 */
/***/ function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ },
/* 10 */
/***/ function(module, exports) {
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
/***/ },
/* 11 */
/***/ function(module, exports) {
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var buildSearchMethod = __webpack_require__(13);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the full text query
* @param args (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param callback the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the similar query
* @param args (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = __webpack_require__(14);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse?' + params,
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse?cursor=' + encodeURIComponent(cursor),
hostType: 'read',
callback: callback
});
};
IndexCore.prototype._search = function(params, url, callback) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = __webpack_require__(15);
var map = __webpack_require__(16);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
module.exports = buildSearchMethod;
var errors = __webpack_require__(8);
function buildSearchMethod(queryParam, url) {
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
if (arguments.length === 0 || typeof query === 'function') {
// .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// .search(args), careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
if (args !== undefined) {
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback);
};
}
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var foreach = __webpack_require__(10);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
/***/ },
/* 15 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
var foreach = __webpack_require__(10);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = __webpack_require__(18);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = __webpack_require__(19);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
/***/ },
/* 19 */
/***/ function(module, exports) {
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
// long, short were "future reserved words in js", YUI compressor fail on them
// https://github.com/algolia/algoliasearch-client-js/issues/113#issuecomment-111978606
// https://github.com/yui/yuicompressor/issues/47
// https://github.com/rauchg/ms.js/pull/40
return options['long']
? _long(val)
: _short(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = '' + str;
if (str.length > 10000) return;
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
if (!match) return;
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function _short(ms) {
if (ms >= d) return Math.round(ms / d) + 'd';
if (ms >= h) return Math.round(ms / h) + 'h';
if (ms >= m) return Math.round(ms / m) + 'm';
if (ms >= s) return Math.round(ms / s) + 's';
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function _long(ms) {
return plural(ms, d, 'day')
|| plural(ms, h, 'hour')
|| plural(ms, m, 'minute')
|| plural(ms, s, 'second')
|| ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) return;
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
return Math.ceil(ms / n) + ' ' + name + 's';
}
/***/ },
/* 20 */
/***/ function(module, exports) {
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(22);
var Promise = global.Promise || __webpack_require__(23).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = __webpack_require__(9);
var errors = __webpack_require__(8);
var inlineHeaders = __webpack_require__(26);
var jsonpRequest = __webpack_require__(28);
var places = __webpack_require__(29);
uaSuffix = uaSuffix || '';
if (false) {
require('debug').enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = __webpack_require__(20);
var getDocumentProtocol = __webpack_require__(30);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = __webpack_require__(31);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: __webpack_require__(17),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
support.timeout = 'timeout' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var ontimeout;
var timedOut;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = function noop() {};
req.onload = load;
req.onerror = error;
if (support.timeout) {
// .timeout supported by both XHR and XDR,
// we do receive timeout event, tested
req.timeout = opts.timeout;
req.ontimeout = timeout;
} else {
ontimeout = setTimeout(timeout, opts.timeout);
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function load(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
if (!support.timeout) {
clearTimeout(ontimeout);
}
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function error(event) {
if (timedOut) {
return;
}
if (!support.timeout) {
clearTimeout(ontimeout);
}
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function timeout() {
if (!support.timeout) {
timedOut = true;
req.abort();
}
reject(new errors.RequestTimeout());
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
/***/ },
/* 22 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(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 = {};
}
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var require;/* WEBPACK VAR INJECTION */(function(process, global) {/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 3.3.1
*/
(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
return typeof x === 'function' || typeof x === 'object' && x !== null;
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (!Array.isArray) {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
_isArray = Array.isArray;
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
return function () {
vertxNext(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = require;
var vertx = __webpack_require__(25);
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && "function" === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
_resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
_reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
_reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
_reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return _resolve(promise, value);
}, function (reason) {
return _reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$) {
if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$ === GET_THEN_ERROR) {
_reject(promise, GET_THEN_ERROR.error);
} else if (then$$ === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$)) {
handleForeignThenable(promise, maybeThenable, then$$);
} else {
fulfill(promise, maybeThenable);
}
}
}
function _resolve(promise, value) {
if (promise === value) {
_reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function _reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
_reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
_resolve(promise, value);
} else if (failed) {
_reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
_reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
_resolve(promise, value);
}, function rejectPromise(reason) {
_reject(promise, reason);
});
} catch (e) {
_reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
_reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function () {
var length = this.length;
var _input = this._input;
for (var i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$ = c.resolve;
if (resolve$$ === resolve) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$) {
return resolve$$(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$(entry), i);
}
};
Enumerator.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
_reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
Promise.prototype = {
constructor: Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
function polyfill() {
var local = undefined;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise;
}
polyfill();
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
return Promise;
})));
//# sourceMappingURL=es6-promise.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24), (function() { return this; }())))
/***/ },
/* 24 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(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;
runClearTimeout(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) {
runTimeout(drainQueue);
}
};
// 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; };
/***/ },
/* 25 */
/***/ function(module, exports) {
/* (ignored) */
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = inlineHeaders;
var encode = __webpack_require__(27);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
/***/ },
/* 27 */
/***/ 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.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = jsonpRequest;
var errors = __webpack_require__(8);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeout);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
module.exports = createPlacesClient;
var buildSearchMethod = __webpack_require__(13);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = __webpack_require__(20);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
/***/ },
/* 30 */
/***/ function(module, exports) {
'use strict';
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
/***/ },
/* 31 */
/***/ function(module, exports) {
'use strict';
module.exports = '3.18.1';
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var AlgoliaSearchHelper = __webpack_require__(33);
var SearchParameters = __webpack_require__(34);
var SearchResults = __webpack_require__(239);
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new AlgoliaSearchHelper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = __webpack_require__(309);
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = __webpack_require__(296);
module.exports = algoliasearchHelper;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var SearchParameters = __webpack_require__(34);
var SearchResults = __webpack_require__(239);
var requestBuilder = __webpack_require__(290);
var util = __webpack_require__(291);
var events = __webpack_require__(294);
var forEach = __webpack_require__(164);
var bind = __webpack_require__(295);
var isEmpty = __webpack_require__(201);
var url = __webpack_require__(296);
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when the search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
this.client = client;
var opts = options || {};
opts.index = index;
this.state = SearchParameters.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
}
util.inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occcurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search();
return this;
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occured it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder._getQueries(tempState.index, tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
cb(err, new SearchResults(tempState, content), tempState);
});
}
return this.client.search(queries).then(
function(content) {
return {
content: new SearchResults(tempState, content),
state: tempState,
_originalResponse: content
};
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a facetted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optionnals, triggering different behaviors:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a facetted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a facetted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = new SearchParameters(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optionnal filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optionnal parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific facetted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for facetting
* @param {string} [value] optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get a parameter of the search by its name. It is possible that a parameter is directly
* defined in the index dashboard, but it will be undefined using this method.
*
* The complete list of parameters is
* available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters have their own API)
* @param {string} parameterName the parameter name
* @return {any} the parameter value
* @example
* var hitsPerPage = helper.getQueryParameter('hitsPerPage');
*/
AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
return this.state.getQueryParameter(parameterName);
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for facetting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
forEach(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var queries = requestBuilder._getQueries(state.index, state);
this.emit('search', state, this.lastResults);
this.client.search(queries,
bind(this._handleResponse,
this,
state,
this._queryId++));
};
/**
* Transform the response as sent by the server and transform it into a user
* usable objet that merge the results of all the batch requests.
* @private
* @param {SearchParameters} state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._handleResponse = function(state, queryId, err, content) {
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
return;
}
var formattedResponse = this.lastResults = new SearchResults(state, content);
this.emit('result', formattedResponse, state);
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the facetting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
module.exports = AlgoliaSearchHelper;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var keys = __webpack_require__(35);
var intersection = __webpack_require__(60);
var forOwn = __webpack_require__(114);
var forEach = __webpack_require__(164);
var filter = __webpack_require__(168);
var map = __webpack_require__(171);
var reduce = __webpack_require__(173);
var omit = __webpack_require__(176);
var indexOf = __webpack_require__(195);
var isNaN = __webpack_require__(199);
var isArray = __webpack_require__(41);
var isEmpty = __webpack_require__(201);
var isEqual = __webpack_require__(202);
var isUndefined = __webpack_require__(203);
var isString = __webpack_require__(204);
var isFunction = __webpack_require__(58);
var find = __webpack_require__(205);
var trim = __webpack_require__(208);
var defaults = __webpack_require__(217);
var merge = __webpack_require__(224);
var valToNumber = __webpack_require__(236);
var filterState = __webpack_require__(237);
var RefinementList = __webpack_require__(238);
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find(array, function(currentValue) {
return isEqual(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* seperated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFiters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
/**
* Contains the numeric filters in the raw format of the Algolia API. Setting
* this parameter is not compatible with the usage of numeric filters methods.
* @see https://www.algolia.com/doc/javascript#numericFilters
* @member {string}
*/
this.numericFilters = params.numericFilters;
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
* parameter is not compatible with the of the add/remove/toggle methods of the
* tag api.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.tagFilters = params.tagFilters;
/**
* Contains the optional tag filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalTagFilters = params.optionalTagFilters;
/**
* Contains the optional facet filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalFacetFilters = params.optionalFacetFilters;
// Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc/rest#param-hitsPerPage
*/
this.hitsPerPage = params.hitsPerPage;
/**
* Number of values for each facetted attribute
* @member {number}
* @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet
*/
this.maxValuesPerFacet = params.maxValuesPerFacet;
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc/rest#param-page
*/
this.page = params.page || 0;
/**
* How the query should be treated by the search engine.
* Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc/rest#param-queryType
* @member {string}
*/
this.queryType = params.queryType;
/**
* How the typo tolerance behave in the search engine.
* Possible values: true, false, min, strict
* @see https://www.algolia.com/doc/rest#param-typoTolerance
* @member {string}
*/
this.typoTolerance = params.typoTolerance;
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo
* @member {number}
*/
this.minWordSizefor1Typo = params.minWordSizefor1Typo;
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos
* @member {number}
*/
this.minWordSizefor2Typos = params.minWordSizefor2Typos;
/**
* Configure the precision of the proximity ranking criterion
* @see https://www.algolia.com/doc/rest#param-minProximity
*/
this.minProximity = params.minProximity;
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens
* @member {boolean}
*/
this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc/rest#param-ignorePlurals
* @member {boolean}
*/
this.ignorePlurals = params.ignorePlurals;
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes
* @member {string}
*/
this.restrictSearchableAttributes = params.restrictSearchableAttributes;
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc/rest#param-advancedSyntax
* @member {boolean}
*/
this.advancedSyntax = params.advancedSyntax;
/**
* Enable the analytics
* @see https://www.algolia.com/doc/rest#param-analytics
* @member {boolean}
*/
this.analytics = params.analytics;
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc/rest#param-analyticsTags
* @member {string}
*/
this.analyticsTags = params.analyticsTags;
/**
* Enable the synonyms
* @see https://www.algolia.com/doc/rest#param-synonyms
* @member {boolean}
*/
this.synonyms = params.synonyms;
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight
* @member {boolean}
*/
this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc/rest#param-optionalWords
* @member {string}
*/
this.optionalWords = params.optionalWords;
/**
* Possible values are "lastWords" "firstWords" "allOptional" "none" (default)
* @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults
* @member {string}
*/
this.removeWordsIfNoResults = params.removeWordsIfNoResults;
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc/rest#param-attributesToRetrieve
* @member {string}
*/
this.attributesToRetrieve = params.attributesToRetrieve;
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc/rest#param-attributesToHighlight
* @member {string}
*/
this.attributesToHighlight = params.attributesToHighlight;
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPreTag
* @member {string}
*/
this.highlightPreTag = params.highlightPreTag;
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPostTag
* @member {string}
*/
this.highlightPostTag = params.highlightPostTag;
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc/rest#param-attributesToSnippet
* @member {string}
*/
this.attributesToSnippet = params.attributesToSnippet;
/**
* Enable the ranking informations in the response, set to 1 to activate
* @see https://www.algolia.com/doc/rest#param-getRankingInfo
* @member {number}
*/
this.getRankingInfo = params.getRankingInfo;
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc/rest#param-distinct
* @member {boolean|number}
*/
this.distinct = params.distinct;
/**
* Center of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundLatLng
* @member {string}
*/
this.aroundLatLng = params.aroundLatLng;
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP
* @member {boolean}
*/
this.aroundLatLngViaIP = params.aroundLatLngViaIP;
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundRadius
* @member {number}
*/
this.aroundRadius = params.aroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundPrecision
* @member {number}
*/
this.minimumAroundRadius = params.minimumAroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-minimumAroundRadius
* @member {number}
*/
this.aroundPrecision = params.aroundPrecision;
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc/rest#param-insideBoundingBox
* @member {string}
*/
this.insideBoundingBox = params.insideBoundingBox;
/**
* Geo search inside a polygon.
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.insidePolygon = params.insidePolygon;
/**
* Allows to specify an ellipsis character for the snippet when we truncate the text
* (added before and after if truncated).
* The default value is an empty string and we recommend to set it to "…"
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.snippetEllipsisText = params.snippetEllipsisText;
/**
* Allows to specify some attributes name on which exact won't be applied.
* Attributes are separated with a comma (for example "name,address" ), you can also use a
* JSON string array encoding (for example encodeURIComponent('["name","address"]') ).
* By default the list is empty.
* @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes
* @member {string|string[]}
*/
this.disableExactOnAttributes = params.disableExactOnAttributes;
/**
* Applies 'exact' on single word queries if the word contains at least 3 characters
* and is not a stop word.
* Can take two values: true or false.
* By default, its set to false.
* @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery
* @member {boolean}
*/
this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery;
// Undocumented parameters, still needed otherwise we fail
this.offset = params.offset;
this.length = params.length;
var self = this;
forOwn(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach(numberKeys, function(k) {
var value = partialState[k];
if (isString(value)) {
var parsedValue = parseFloat(value);
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach(operators, function(values, operator) {
var parsedValues = map(values, function(v) {
if (isArray(v)) {
return map(v, function(vPrime) {
if (isString(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optionnal string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) facetting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge({}, this.numericRefinements);
mod[attribute] = merge({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
throw new Error(
facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration'
);
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
var paramValueAsNumber = valToNumber(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for facetting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optionnal string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(this.numericRefinements, attribute);
} else if (isFunction(attribute)) {
return reduce(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach(operators, function(values, operator) {
var outValues = [];
forEach(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the facetting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the facetting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: filter(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the facetted attribute.
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for facetting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; })
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleRefinement: function toggleRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value, optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} [value] optionnal value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value optionnal, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for facetting
* @param {string} value optionnal, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return indexOf(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined(value) && isUndefined(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined(this.numericRefinements[attribute][operator]);
if (isUndefined(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber(value);
var isAttributeValueDefined = !isUndefined(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection(
keys(this.numericRefinements),
this.disjunctiveFacets
);
return keys(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for facetting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map(this.hierarchicalFacets, 'name'),
keys(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter(this.disjunctiveFacets, function(f) {
return indexOf(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn(this, function(paramValue, paramName) {
if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys(params);
forEach(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map(path, trim);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
module.exports = SearchParameters;
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(36),
baseKeys = __webpack_require__(53),
isArrayLike = __webpack_require__(57);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(37),
isArguments = __webpack_require__(38),
isArray = __webpack_require__(41),
isBuffer = __webpack_require__(42),
isIndex = __webpack_require__(47),
isTypedArray = __webpack_require__(48);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ },
/* 37 */
/***/ function(module, exports) {
/**
* 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;
}
module.exports = baseTimes;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(39),
isObjectLike = __webpack_require__(40);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
var isObjectLike = __webpack_require__(40);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && objectToString.call(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ },
/* 40 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 41 */
/***/ function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(44),
stubFalse = __webpack_require__(46);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(43)(module)))
/***/ },
/* 43 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(45);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ },
/* 45 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 46 */
/***/ function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ },
/* 47 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(49),
baseUnary = __webpack_require__(51),
nodeUtil = __webpack_require__(52);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var isLength = __webpack_require__(50),
isObjectLike = __webpack_require__(40);
/** `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]',
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 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[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
}
module.exports = baseIsTypedArray;
/***/ },
/* 50 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ },
/* 51 */
/***/ function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(45);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(43)(module)))
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(54),
nativeKeys = __webpack_require__(55);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ },
/* 54 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(56);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ },
/* 56 */
/***/ function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(58),
isLength = __webpack_require__(50);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(59);
/** `Object#toString` result references. */
var funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ },
/* 59 */
/***/ function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(61),
baseIntersection = __webpack_require__(62),
baseRest = __webpack_require__(103),
castArrayLikeObject = __webpack_require__(112);
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
module.exports = intersection;
/***/ },
/* 61 */
/***/ function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array ? array.length : 0,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(63),
arrayIncludes = __webpack_require__(96),
arrayIncludesWith = __webpack_require__(101),
arrayMap = __webpack_require__(61),
baseUnary = __webpack_require__(51),
cacheHas = __webpack_require__(102);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseIntersection;
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(64),
setCacheAdd = __webpack_require__(94),
setCacheHas = __webpack_require__(95);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values ? values.length : 0;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(65),
mapCacheDelete = __webpack_require__(88),
mapCacheGet = __webpack_require__(91),
mapCacheHas = __webpack_require__(92),
mapCacheSet = __webpack_require__(93);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(66),
ListCache = __webpack_require__(79),
Map = __webpack_require__(87);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(67),
hashDelete = __webpack_require__(75),
hashGet = __webpack_require__(76),
hashHas = __webpack_require__(77),
hashSet = __webpack_require__(78);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(68);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(70),
getValue = __webpack_require__(74);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(58),
isMasked = __webpack_require__(71),
isObject = __webpack_require__(59),
toSource = __webpack_require__(73);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(72);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(44);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ },
/* 73 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to 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 '';
}
module.exports = toSource;
/***/ },
/* 74 */
/***/ function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ },
/* 75 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(68);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(68);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(68);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(80),
listCacheDelete = __webpack_require__(81),
listCacheGet = __webpack_require__(84),
listCacheHas = __webpack_require__(85),
listCacheSet = __webpack_require__(86);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ },
/* 80 */
/***/ function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(82);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(83);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ },
/* 83 */
/***/ function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(82);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(82);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(82);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69),
root = __webpack_require__(44);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(89);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(90);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ },
/* 90 */
/***/ function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(89);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(89);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(89);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ },
/* 94 */
/***/ function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ },
/* 95 */
/***/ function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(97);
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array ? array.length : 0;
return !!length && baseIndexOf(array, value, 0) > -1;
}
module.exports = arrayIncludes;
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(98),
baseIsNaN = __webpack_require__(99),
strictIndexOf = __webpack_require__(100);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ },
/* 98 */
/***/ function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ },
/* 99 */
/***/ function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ },
/* 100 */
/***/ function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ },
/* 101 */
/***/ function(module, exports) {
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array ? array.length : 0;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
module.exports = arrayIncludesWith;
/***/ },
/* 102 */
/***/ function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ },
/* 103 */
/***/ function(module, exports, __webpack_require__) {
var identity = __webpack_require__(104),
overRest = __webpack_require__(105),
setToString = __webpack_require__(107);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
/***/ },
/* 104 */
/***/ function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
var apply = __webpack_require__(106);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ },
/* 106 */
/***/ function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(108),
shortOut = __webpack_require__(111);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
var constant = __webpack_require__(109),
defineProperty = __webpack_require__(110),
identity = __webpack_require__(104);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ },
/* 109 */
/***/ function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ },
/* 111 */
/***/ function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 500,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
var isArrayLikeObject = __webpack_require__(113);
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
module.exports = castArrayLikeObject;
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(57),
isObjectLike = __webpack_require__(40);
/**
* 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);
}
module.exports = isArrayLikeObject;
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(115),
baseIteratee = __webpack_require__(118);
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, baseIteratee(iteratee, 3));
}
module.exports = forOwn;
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(116),
keys = __webpack_require__(35);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(117);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
/***/ },
/* 117 */
/***/ function(module, exports) {
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
var baseMatches = __webpack_require__(119),
baseMatchesProperty = __webpack_require__(146),
identity = __webpack_require__(104),
isArray = __webpack_require__(41),
property = __webpack_require__(161);
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
var baseIsMatch = __webpack_require__(120),
getMatchData = __webpack_require__(143),
matchesStrictComparable = __webpack_require__(145);
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
module.exports = baseMatches;
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(121),
baseIsEqual = __webpack_require__(127);
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(79),
stackClear = __webpack_require__(122),
stackDelete = __webpack_require__(123),
stackGet = __webpack_require__(124),
stackHas = __webpack_require__(125),
stackSet = __webpack_require__(126);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(79);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ },
/* 123 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ },
/* 124 */
/***/ function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ },
/* 125 */
/***/ function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(79),
Map = __webpack_require__(87),
MapCache = __webpack_require__(64);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(128),
isObject = __webpack_require__(59),
isObjectLike = __webpack_require__(40);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @param {boolean} [bitmask] The bitmask of comparison flags.
* The bitmask may be composed of the following flags:
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, bitmask, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
}
module.exports = baseIsEqual;
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(121),
equalArrays = __webpack_require__(129),
equalByTag = __webpack_require__(131),
equalObjects = __webpack_require__(136),
getTag = __webpack_require__(137),
isArray = __webpack_require__(41),
isBuffer = __webpack_require__(42),
isTypedArray = __webpack_require__(48);
/** Used to compose bitmasks for comparison styles. */
var PARTIAL_COMPARE_FLAG = 2;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparisons.
* @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag(object);
objTag = objTag == argsTag ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag(other);
othTag = othTag == argsTag ? objectTag : othTag;
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
: equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
}
if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
}
module.exports = baseIsEqualDeep;
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(63),
arraySome = __webpack_require__(130),
cacheHas = __webpack_require__(102);
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ },
/* 130 */
/***/ function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array ? array.length : 0;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(132),
Uint8Array = __webpack_require__(133),
eq = __webpack_require__(83),
equalArrays = __webpack_require__(129),
mapToArray = __webpack_require__(134),
setToArray = __webpack_require__(135);
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= UNORDERED_COMPARE_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(44);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(44);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ },
/* 134 */
/***/ function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ },
/* 135 */
/***/ function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ },
/* 136 */
/***/ function(module, exports, __webpack_require__) {
var keys = __webpack_require__(35);
/** Used to compose bitmasks for comparison styles. */
var PARTIAL_COMPARE_FLAG = 2;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(138),
Map = __webpack_require__(87),
Promise = __webpack_require__(139),
Set = __webpack_require__(140),
WeakMap = __webpack_require__(141),
baseGetTag = __webpack_require__(142),
toSource = __webpack_require__(73);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(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;
};
}
module.exports = getTag;
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69),
root = __webpack_require__(44);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69),
root = __webpack_require__(44);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69),
root = __webpack_require__(44);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(69),
root = __webpack_require__(44);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ },
/* 142 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* The base implementation of `getTag`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
return objectToString.call(value);
}
module.exports = baseGetTag;
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
var isStrictComparable = __webpack_require__(144),
keys = __webpack_require__(35);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(59);
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
/***/ },
/* 145 */
/***/ function(module, exports) {
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(127),
get = __webpack_require__(147),
hasIn = __webpack_require__(158),
isKey = __webpack_require__(156),
isStrictComparable = __webpack_require__(144),
matchesStrictComparable = __webpack_require__(145),
toKey = __webpack_require__(157);
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
};
}
module.exports = baseMatchesProperty;
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(148);
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(149),
isKey = __webpack_require__(156),
toKey = __webpack_require__(157);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = isKey(path, object) ? [path] : castPath(path);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(41),
stringToPath = __webpack_require__(150);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value) {
return isArray(value) ? value : stringToPath(value);
}
module.exports = castPath;
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(151),
toString = __webpack_require__(153);
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
string = toString(string);
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(152);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(64);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(154);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(132),
arrayMap = __webpack_require__(61),
isArray = __webpack_require__(41),
isSymbol = __webpack_require__(155);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
var isObjectLike = __webpack_require__(40);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
module.exports = isSymbol;
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(41),
isSymbol = __webpack_require__(155);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(155);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(159),
hasPath = __webpack_require__(160);
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
module.exports = hasIn;
/***/ },
/* 159 */
/***/ function(module, exports) {
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(149),
isArguments = __webpack_require__(38),
isArray = __webpack_require__(41),
isIndex = __webpack_require__(47),
isKey = __webpack_require__(156),
isLength = __webpack_require__(50),
toKey = __webpack_require__(157);
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = isKey(path, object) ? [path] : castPath(path);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object ? object.length : 0;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(162),
basePropertyDeep = __webpack_require__(163),
isKey = __webpack_require__(156),
toKey = __webpack_require__(157);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
/***/ },
/* 162 */
/***/ function(module, exports) {
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(148);
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(165),
baseEach = __webpack_require__(166),
baseIteratee = __webpack_require__(118),
isArray = __webpack_require__(41);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = forEach;
/***/ },
/* 165 */
/***/ function(module, exports) {
/**
* 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 ? array.length : 0;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(115),
createBaseEach = __webpack_require__(167);
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(57);
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(169),
baseFilter = __webpack_require__(170),
baseIteratee = __webpack_require__(118),
isArray = __webpack_require__(41);
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity]
* The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, baseIteratee(predicate, 3));
}
module.exports = filter;
/***/ },
/* 169 */
/***/ function(module, exports) {
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array ? array.length : 0,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(166);
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
module.exports = baseFilter;
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(61),
baseIteratee = __webpack_require__(118),
baseMap = __webpack_require__(172),
isArray = __webpack_require__(41);
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(166),
isArrayLike = __webpack_require__(57);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
var arrayReduce = __webpack_require__(174),
baseEach = __webpack_require__(166),
baseIteratee = __webpack_require__(118),
baseReduce = __webpack_require__(175),
isArray = __webpack_require__(41);
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
module.exports = reduce;
/***/ },
/* 174 */
/***/ function(module, exports) {
/**
* 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 ? array.length : 0;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
/***/ },
/* 175 */
/***/ function(module, exports) {
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
module.exports = baseReduce;
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(61),
baseDifference = __webpack_require__(177),
basePick = __webpack_require__(178),
flatRest = __webpack_require__(181),
getAllKeysIn = __webpack_require__(186),
toKey = __webpack_require__(157);
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable string keyed properties of `object` that are
* not omitted.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [props] The property identifiers to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, props) {
if (object == null) {
return {};
}
props = arrayMap(props, toKey);
return basePick(object, baseDifference(getAllKeysIn(object), props));
});
module.exports = omit;
/***/ },
/* 177 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(63),
arrayIncludes = __webpack_require__(96),
arrayIncludesWith = __webpack_require__(101),
arrayMap = __webpack_require__(61),
baseUnary = __webpack_require__(51),
cacheHas = __webpack_require__(102);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
var basePickBy = __webpack_require__(179);
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} props The property identifiers to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, props) {
object = Object(object);
return basePickBy(object, props, function(value, key) {
return key in object;
});
}
module.exports = basePick;
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(180);
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} props The property identifiers to pick from.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, props, predicate) {
var index = -1,
length = props.length,
result = {};
while (++index < length) {
var key = props[index],
value = object[key];
if (predicate(value, key)) {
baseAssignValue(result, key, value);
}
}
return result;
}
module.exports = basePickBy;
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(110);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ },
/* 181 */
/***/ function(module, exports, __webpack_require__) {
var flatten = __webpack_require__(182),
overRest = __webpack_require__(105),
setToString = __webpack_require__(107);
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
module.exports = flatRest;
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(183);
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(184),
isFlattenable = __webpack_require__(185);
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
module.exports = baseFlatten;
/***/ },
/* 184 */
/***/ function(module, exports) {
/**
* 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;
}
module.exports = arrayPush;
/***/ },
/* 185 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(132),
isArguments = __webpack_require__(38),
isArray = __webpack_require__(41);
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(187),
getSymbolsIn = __webpack_require__(188),
keysIn = __webpack_require__(192);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(184),
isArray = __webpack_require__(41);
/**
* 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));
}
module.exports = baseGetAllKeys;
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(184),
getPrototype = __webpack_require__(189),
getSymbols = __webpack_require__(190),
stubArray = __webpack_require__(191);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbol properties
* of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ },
/* 189 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(56);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(56),
stubArray = __webpack_require__(191);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbol properties of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
module.exports = getSymbols;
/***/ },
/* 191 */
/***/ function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ },
/* 192 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(36),
baseKeysIn = __webpack_require__(193),
isArrayLike = __webpack_require__(57);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ },
/* 193 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(59),
isPrototype = __webpack_require__(54),
nativeKeysIn = __webpack_require__(194);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ },
/* 194 */
/***/ function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(97),
toInteger = __webpack_require__(196);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(197);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ },
/* 197 */
/***/ function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(198);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(59),
isSymbol = __webpack_require__(155);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
var isNumber = __webpack_require__(200);
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
module.exports = isNaN;
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
var isObjectLike = __webpack_require__(40);
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && objectToString.call(value) == numberTag);
}
module.exports = isNumber;
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
var baseKeys = __webpack_require__(53),
getTag = __webpack_require__(137),
isArguments = __webpack_require__(38),
isArray = __webpack_require__(41),
isArrayLike = __webpack_require__(57),
isBuffer = __webpack_require__(42),
isPrototype = __webpack_require__(54),
isTypedArray = __webpack_require__(48);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
/***/ },
/* 202 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(127);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are **not** supported.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ },
/* 203 */
/***/ function(module, exports) {
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(41),
isObjectLike = __webpack_require__(40);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* 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 a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
module.exports = isString;
/***/ },
/* 205 */
/***/ function(module, exports, __webpack_require__) {
var createFind = __webpack_require__(206),
findIndex = __webpack_require__(207);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity]
* The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
module.exports = find;
/***/ },
/* 206 */
/***/ function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(118),
isArrayLike = __webpack_require__(57),
keys = __webpack_require__(35);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
/***/ },
/* 207 */
/***/ function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(98),
baseIteratee = __webpack_require__(118),
toInteger = __webpack_require__(196);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity]
* The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
module.exports = findIndex;
/***/ },
/* 208 */
/***/ function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(154),
castSlice = __webpack_require__(209),
charsEndIndex = __webpack_require__(211),
charsStartIndex = __webpack_require__(212),
stringToArray = __webpack_require__(213),
toString = __webpack_require__(153);
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
module.exports = trim;
/***/ },
/* 209 */
/***/ function(module, exports, __webpack_require__) {
var baseSlice = __webpack_require__(210);
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
/***/ },
/* 210 */
/***/ function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ },
/* 211 */
/***/ function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(97);
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
/***/ },
/* 212 */
/***/ function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(97);
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsStartIndex;
/***/ },
/* 213 */
/***/ function(module, exports, __webpack_require__) {
var asciiToArray = __webpack_require__(214),
hasUnicode = __webpack_require__(215),
unicodeToArray = __webpack_require__(216);
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
module.exports = stringToArray;
/***/ },
/* 214 */
/***/ function(module, exports) {
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
/***/ },
/* 215 */
/***/ function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
rsComboSymbolsRange = '\\u20d0-\\u20f0',
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
/***/ },
/* 216 */
/***/ function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
rsComboSymbolsRange = '\\u20d0-\\u20f0',
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
/***/ },
/* 217 */
/***/ function(module, exports, __webpack_require__) {
var apply = __webpack_require__(106),
assignInDefaults = __webpack_require__(218),
assignInWith = __webpack_require__(219),
baseRest = __webpack_require__(103);
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(args) {
args.push(undefined, assignInDefaults);
return apply(assignInWith, undefined, args);
});
module.exports = defaults;
/***/ },
/* 218 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(83);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function assignInDefaults(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
module.exports = assignInDefaults;
/***/ },
/* 219 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(220),
createAssigner = __webpack_require__(222),
keysIn = __webpack_require__(192);
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
module.exports = assignInWith;
/***/ },
/* 220 */
/***/ function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(221),
baseAssignValue = __webpack_require__(180);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ },
/* 221 */
/***/ function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(180),
eq = __webpack_require__(83);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ },
/* 222 */
/***/ function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(103),
isIterateeCall = __webpack_require__(223);
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ },
/* 223 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(83),
isArrayLike = __webpack_require__(57),
isIndex = __webpack_require__(47),
isObject = __webpack_require__(59);
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
/***/ },
/* 224 */
/***/ function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(225),
createAssigner = __webpack_require__(222);
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
/***/ },
/* 225 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(121),
assignMergeValue = __webpack_require__(226),
baseFor = __webpack_require__(116),
baseMergeDeep = __webpack_require__(227),
isObject = __webpack_require__(59),
keysIn = __webpack_require__(192);
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
if (isObject(srcValue)) {
stack || (stack = new Stack);
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
/***/ },
/* 226 */
/***/ function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(180),
eq = __webpack_require__(83);
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @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 assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
/***/ },
/* 227 */
/***/ function(module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(226),
cloneBuffer = __webpack_require__(228),
cloneTypedArray = __webpack_require__(229),
copyArray = __webpack_require__(231),
initCloneObject = __webpack_require__(232),
isArguments = __webpack_require__(38),
isArray = __webpack_require__(41),
isArrayLikeObject = __webpack_require__(113),
isBuffer = __webpack_require__(42),
isFunction = __webpack_require__(58),
isObject = __webpack_require__(59),
isPlainObject = __webpack_require__(234),
isTypedArray = __webpack_require__(48),
toPlainObject = __webpack_require__(235);
/**
* 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 {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
/***/ },
/* 228 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(44);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(43)(module)))
/***/ },
/* 229 */
/***/ function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(230);
/**
* 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);
}
module.exports = cloneTypedArray;
/***/ },
/* 230 */
/***/ function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(133);
/**
* 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;
}
module.exports = cloneArrayBuffer;
/***/ },
/* 231 */
/***/ function(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 copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ },
/* 232 */
/***/ function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(233),
getPrototype = __webpack_require__(189),
isPrototype = __webpack_require__(54);
/**
* 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))
: {};
}
module.exports = initCloneObject;
/***/ },
/* 233 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(59);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ },
/* 234 */
/***/ function(module, exports, __webpack_require__) {
var getPrototype = __webpack_require__(189),
isObjectLike = __webpack_require__(40);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = 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`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || objectToString.call(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
module.exports = isPlainObject;
/***/ },
/* 235 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(220),
keysIn = __webpack_require__(192);
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @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 copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ },
/* 236 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var map = __webpack_require__(171);
var isArray = __webpack_require__(41);
var isNumber = __webpack_require__(200);
var isString = __webpack_require__(204);
function valToNumber(v) {
if (isNumber(v)) {
return v;
} else if (isString(v)) {
return parseFloat(v);
} else if (isArray(v)) {
return map(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
module.exports = valToNumber;
/***/ },
/* 237 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var forEach = __webpack_require__(164);
var filter = __webpack_require__(168);
var map = __webpack_require__(171);
var isEmpty = __webpack_require__(201);
var indexOf = __webpack_require__(195);
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf(attributes, '*') === -1) {
forEach(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
module.exports = filterState;
/***/ },
/* 238 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var isUndefined = __webpack_require__(203);
var isString = __webpack_require__(204);
var isFunction = __webpack_require__(58);
var isEmpty = __webpack_require__(201);
var defaults = __webpack_require__(217);
var reduce = __webpack_require__(173);
var filter = __webpack_require__(168);
var omit = __webpack_require__(176);
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated prefinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaults({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* behaviors can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optionnal parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(refinementList, attribute);
} else if (isFunction(attribute)) {
return reduce(refinementList, function(memo, values, key) {
var facetList = filter(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = __webpack_require__(195);
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
module.exports = lib;
/***/ },
/* 239 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var forEach = __webpack_require__(164);
var compact = __webpack_require__(240);
var indexOf = __webpack_require__(195);
var findIndex = __webpack_require__(207);
var get = __webpack_require__(147);
var sumBy = __webpack_require__(241);
var find = __webpack_require__(205);
var includes = __webpack_require__(243);
var map = __webpack_require__(171);
var orderBy = __webpack_require__(246);
var defaults = __webpack_require__(217);
var merge = __webpack_require__(224);
var isArray = __webpack_require__(41);
var isFunction = __webpack_require__(58);
var partial = __webpack_require__(251);
var partialRight = __webpack_require__(283);
var formatSort = __webpack_require__(284);
var generateHierarchicalTree = __webpack_require__(287);
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the facetting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objets matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} value the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric fitlers.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
function getIndices(obj) {
var indices = {};
forEach(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {object} algoliaResponse the response from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, algoliaResponse) {
var mainSubResponse = algoliaResponse.results[0];
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy(algoliaResponse.results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach(disjunctiveFacets, function(disjunctiveFacet) {
var result = algoliaResponse.results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = algoliaResponse.results[nextDisjunctiveResult];
forEach(result.facets, function(facetResults, dfacet) {
var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state));
this.facets = compact(this.facets);
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the attribute facetted
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find(this.facets, predicate) ||
find(this.disjunctiveFacets, predicate) ||
find(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the facetted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find(results.facets, predicate);
if (!facet) return [];
return map(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map(node.data, partial(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name asending
* (alphabetical order). The sort formula can overriden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']);
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray(facetValues)) {
return orderBy(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight(orderBy, order[0], order[1]), facetValues);
} else if (isFunction(options.sortBy)) {
if (isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the facetted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`');
};
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach(state.facetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach(state.facetsExcludes, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach(state.numericRefinements, function(operators, attributeName) {
forEach(operators, function(values, operator) {
forEach(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var count = get(facet, 'data[' + name + ']');
var exhaustive = get(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find(facet.data, {name: splitted[i]});
}
var count = get(facet, 'count');
var exhaustive = get(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
module.exports = SearchResults;
/***/ },
/* 240 */
/***/ function(module, exports) {
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array ? array.length : 0,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
/***/ },
/* 241 */
/***/ function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(118),
baseSum = __webpack_require__(242);
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, baseIteratee(iteratee, 2))
: 0;
}
module.exports = sumBy;
/***/ },
/* 242 */
/***/ function(module, exports) {
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
module.exports = baseSum;
/***/ },
/* 243 */
/***/ function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(97),
isArrayLike = __webpack_require__(57),
isString = __webpack_require__(204),
toInteger = __webpack_require__(196),
values = __webpack_require__(244);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
/***/ },
/* 244 */
/***/ function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(245),
keys = __webpack_require__(35);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object ? baseValues(object, keys(object)) : [];
}
module.exports = values;
/***/ },
/* 245 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(61);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ },
/* 246 */
/***/ function(module, exports, __webpack_require__) {
var baseOrderBy = __webpack_require__(247),
isArray = __webpack_require__(41);
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
module.exports = orderBy;
/***/ },
/* 247 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(61),
baseIteratee = __webpack_require__(118),
baseMap = __webpack_require__(172),
baseSortBy = __webpack_require__(248),
baseUnary = __webpack_require__(51),
compareMultiple = __webpack_require__(249),
identity = __webpack_require__(104);
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
module.exports = baseOrderBy;
/***/ },
/* 248 */
/***/ function(module, exports) {
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
/***/ },
/* 249 */
/***/ function(module, exports, __webpack_require__) {
var compareAscending = __webpack_require__(250);
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
module.exports = compareMultiple;
/***/ },
/* 250 */
/***/ function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(155);
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
module.exports = compareAscending;
/***/ },
/* 251 */
/***/ function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(103),
createWrap = __webpack_require__(252),
getHolder = __webpack_require__(278),
replaceHolders = __webpack_require__(280);
/** Used to compose bitmasks for function metadata. */
var PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, PARTIAL_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
module.exports = partial;
/***/ },
/* 252 */
/***/ function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(253),
createBind = __webpack_require__(255),
createCurry = __webpack_require__(257),
createHybrid = __webpack_require__(258),
createPartial = __webpack_require__(281),
getData = __webpack_require__(266),
mergeData = __webpack_require__(282),
setData = __webpack_require__(273),
setWrapToString = __webpack_require__(274),
toInteger = __webpack_require__(196);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_FLAG = 8,
CURRY_RIGHT_FLAG = 16,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] == null
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) {
bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
/***/ },
/* 253 */
/***/ function(module, exports, __webpack_require__) {
var identity = __webpack_require__(104),
metaMap = __webpack_require__(254);
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
/***/ },
/* 254 */
/***/ function(module, exports, __webpack_require__) {
var WeakMap = __webpack_require__(141);
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
/***/ },
/* 255 */
/***/ function(module, exports, __webpack_require__) {
var createCtor = __webpack_require__(256),
root = __webpack_require__(44);
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
module.exports = createBind;
/***/ },
/* 256 */
/***/ function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(233),
isObject = __webpack_require__(59);
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtor;
/***/ },
/* 257 */
/***/ function(module, exports, __webpack_require__) {
var apply = __webpack_require__(106),
createCtor = __webpack_require__(256),
createHybrid = __webpack_require__(258),
createRecurry = __webpack_require__(262),
getHolder = __webpack_require__(278),
replaceHolders = __webpack_require__(280),
root = __webpack_require__(44);
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
module.exports = createCurry;
/***/ },
/* 258 */
/***/ function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(259),
composeArgsRight = __webpack_require__(260),
countHolders = __webpack_require__(261),
createCtor = __webpack_require__(256),
createRecurry = __webpack_require__(262),
getHolder = __webpack_require__(278),
reorder = __webpack_require__(279),
replaceHolders = __webpack_require__(280),
root = __webpack_require__(44);
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_FLAG = 8,
CURRY_RIGHT_FLAG = 16,
ARY_FLAG = 128,
FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & ARY_FLAG,
isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG),
isFlip = bitmask & FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
module.exports = createHybrid;
/***/ },
/* 259 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
/***/ },
/* 260 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
module.exports = composeArgsRight;
/***/ },
/* 261 */
/***/ function(module, exports) {
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
module.exports = countHolders;
/***/ },
/* 262 */
/***/ function(module, exports, __webpack_require__) {
var isLaziable = __webpack_require__(263),
setData = __webpack_require__(273),
setWrapToString = __webpack_require__(274);
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_BOUND_FLAG = 4,
CURRY_FLAG = 8,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
if (!(bitmask & CURRY_BOUND_FLAG)) {
bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
module.exports = createRecurry;
/***/ },
/* 263 */
/***/ function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(264),
getData = __webpack_require__(266),
getFuncName = __webpack_require__(268),
lodash = __webpack_require__(270);
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
module.exports = isLaziable;
/***/ },
/* 264 */
/***/ function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(233),
baseLodash = __webpack_require__(265);
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
module.exports = LazyWrapper;
/***/ },
/* 265 */
/***/ function(module, exports) {
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
module.exports = baseLodash;
/***/ },
/* 266 */
/***/ function(module, exports, __webpack_require__) {
var metaMap = __webpack_require__(254),
noop = __webpack_require__(267);
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
module.exports = getData;
/***/ },
/* 267 */
/***/ function(module, exports) {
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;
/***/ },
/* 268 */
/***/ function(module, exports, __webpack_require__) {
var realNames = __webpack_require__(269);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
module.exports = getFuncName;
/***/ },
/* 269 */
/***/ function(module, exports) {
/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;
/***/ },
/* 270 */
/***/ function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(264),
LodashWrapper = __webpack_require__(271),
baseLodash = __webpack_require__(265),
isArray = __webpack_require__(41),
isObjectLike = __webpack_require__(40),
wrapperClone = __webpack_require__(272);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array of at least `200` elements
* and any iteratees accept only one argument. The heuristic for whether a
* section qualifies for shortcut fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
/***/ },
/* 271 */
/***/ function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(233),
baseLodash = __webpack_require__(265);
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
/***/ },
/* 272 */
/***/ function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(264),
LodashWrapper = __webpack_require__(271),
copyArray = __webpack_require__(231);
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
/***/ },
/* 273 */
/***/ function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(253),
shortOut = __webpack_require__(111);
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
module.exports = setData;
/***/ },
/* 274 */
/***/ function(module, exports, __webpack_require__) {
var getWrapDetails = __webpack_require__(275),
insertWrapDetails = __webpack_require__(276),
setToString = __webpack_require__(107),
updateWrapDetails = __webpack_require__(277);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
module.exports = setWrapToString;
/***/ },
/* 275 */
/***/ function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
module.exports = getWrapDetails;
/***/ },
/* 276 */
/***/ function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
module.exports = insertWrapDetails;
/***/ },
/* 277 */
/***/ function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(165),
arrayIncludes = __webpack_require__(96);
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_FLAG = 8,
CURRY_RIGHT_FLAG = 16,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64,
ARY_FLAG = 128,
REARG_FLAG = 256,
FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', ARY_FLAG],
['bind', BIND_FLAG],
['bindKey', BIND_KEY_FLAG],
['curry', CURRY_FLAG],
['curryRight', CURRY_RIGHT_FLAG],
['flip', FLIP_FLAG],
['partial', PARTIAL_FLAG],
['partialRight', PARTIAL_RIGHT_FLAG],
['rearg', REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
module.exports = updateWrapDetails;
/***/ },
/* 278 */
/***/ function(module, exports) {
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
module.exports = getHolder;
/***/ },
/* 279 */
/***/ function(module, exports, __webpack_require__) {
var copyArray = __webpack_require__(231),
isIndex = __webpack_require__(47);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
module.exports = reorder;
/***/ },
/* 280 */
/***/ function(module, exports) {
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;
/***/ },
/* 281 */
/***/ function(module, exports, __webpack_require__) {
var apply = __webpack_require__(106),
createCtor = __webpack_require__(256),
root = __webpack_require__(44);
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
/***/ },
/* 282 */
/***/ function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(259),
composeArgsRight = __webpack_require__(260),
replaceHolders = __webpack_require__(280);
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_BOUND_FLAG = 4,
CURRY_FLAG = 8,
ARY_FLAG = 128,
REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG);
var isCombo =
((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) ||
((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
module.exports = mergeData;
/***/ },
/* 283 */
/***/ function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(103),
createWrap = __webpack_require__(252),
getHolder = __webpack_require__(278),
replaceHolders = __webpack_require__(280);
/** Used to compose bitmasks for function metadata. */
var PARTIAL_RIGHT_FLAG = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
module.exports = partialRight;
/***/ },
/* 284 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var reduce = __webpack_require__(173);
var find = __webpack_require__(205);
var startsWith = __webpack_require__(285);
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
module.exports = function formatSort(sortBy, defaults) {
return reduce(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find(defaults, function(predicate) {
return startsWith(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/***/ },
/* 285 */
/***/ function(module, exports, __webpack_require__) {
var baseClamp = __webpack_require__(286),
baseToString = __webpack_require__(154),
toInteger = __webpack_require__(196),
toString = __webpack_require__(153);
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
module.exports = startsWith;
/***/ },
/* 286 */
/***/ function(module, exports) {
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
module.exports = baseClamp;
/***/ },
/* 287 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = generateTrees;
var last = __webpack_require__(288);
var map = __webpack_require__(171);
var reduce = __webpack_require__(173);
var orderBy = __webpack_require__(246);
var trim = __webpack_require__(208);
var find = __webpack_require__(205);
var pickBy = __webpack_require__(289);
var prepareHierarchicalFacetSortBy = __webpack_require__(284);
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy(
map(
pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim(last(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/***/ },
/* 288 */
/***/ function(module, exports) {
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array ? array.length : 0;
return length ? array[length - 1] : undefined;
}
module.exports = last;
/***/ },
/* 289 */
/***/ function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(118),
basePickBy = __webpack_require__(179),
getAllKeysIn = __webpack_require__(186);
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
return object == null ? {} : basePickBy(object, getAllKeysIn(object), baseIteratee(predicate));
}
module.exports = pickBy;
/***/ },
/* 290 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var forEach = __webpack_require__(164);
var map = __webpack_require__(171);
var reduce = __webpack_require__(173);
var merge = __webpack_require__(224);
var isArray = __webpack_require__(41);
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach(state.numericRefinements, function(operators, attribute) {
forEach(operators, function(values, operator) {
if (facetName !== attribute) {
forEach(values, function(value) {
if (isArray(value)) {
var vs = map(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach(state.facetsRefinements, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach(state.facetsExcludes, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
}
};
module.exports = requestBuilder;
/***/ },
/* 291 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// 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 formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = ({"NODE_ENV":"production"}).NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(292);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(293);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(24)))
/***/ },
/* 292 */
/***/ function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ },
/* 293 */
/***/ function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ },
/* 294 */
/***/ 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
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
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;
}
/***/ },
/* 295 */
/***/ function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(103),
createWrap = __webpack_require__(252),
getHolder = __webpack_require__(278),
replaceHolders = __webpack_require__(280);
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
module.exports = bind;
/***/ },
/* 296 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var shortener = __webpack_require__(297);
var SearchParameters = __webpack_require__(34);
var qs = __webpack_require__(301);
var bind = __webpack_require__(295);
var forEach = __webpack_require__(164);
var pick = __webpack_require__(306);
var map = __webpack_require__(171);
var mapKeys = __webpack_require__(307);
var mapValues = __webpack_require__(308);
var isString = __webpack_require__(204);
var isPlainObject = __webpack_require__(234);
var isArray = __webpack_require__(41);
var invert = __webpack_require__(298);
var encode = __webpack_require__(303).encode;
function recursiveEncode(input) {
if (isPlainObject(input)) {
return mapValues(input, recursiveEncode);
}
if (isArray(input)) {
return map(input, recursiveEncode);
}
if (isString(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
exports.getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var partialStateWithPrefix = qs.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState);
return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
exports.getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var foreignConfig = {};
var config = qs.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
exports.getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (moreAttributes) {
var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = qs.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return qs.stringify(encodedState, {encode: safe, sort: sort});
};
/***/ },
/* 297 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var invert = __webpack_require__(298);
var keys = __webpack_require__(35);
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert(keys2Short);
module.exports = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
/***/ },
/* 298 */
/***/ function(module, exports, __webpack_require__) {
var constant = __webpack_require__(109),
createInverter = __webpack_require__(299),
identity = __webpack_require__(104);
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
result[value] = key;
}, constant(identity));
module.exports = invert;
/***/ },
/* 299 */
/***/ function(module, exports, __webpack_require__) {
var baseInverter = __webpack_require__(300);
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
module.exports = createInverter;
/***/ },
/* 300 */
/***/ function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(115);
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
module.exports = baseInverter;
/***/ },
/* 301 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var stringify = __webpack_require__(302);
var parse = __webpack_require__(305);
var formats = __webpack_require__(304);
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
/***/ },
/* 302 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(303);
var formats = __webpack_require__(304);
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults = {
delimiter: '&',
encode: true,
encoder: utils.encode,
serializeDate: function serializeDate(date) {
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder ? encoder(prefix) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(
obj[key],
generateArrayPrefix(prefix, key),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
} else {
values = values.concat(stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts || {};
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
if (typeof options.format === 'undefined') {
options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(
obj[key],
key,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter
));
}
return keys.join(delimiter);
};
/***/ },
/* 303 */
/***/ function(module, exports) {
'use strict';
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
target[source] = true;
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
(c >= 0x30 && c <= 0x39) || // 0-9
(c >= 0x41 && c <= 0x5A) || // a-z
(c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
/***/ },
/* 304 */
/***/ function(module, exports) {
'use strict';
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
module.exports = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
/***/ },
/* 305 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(303);
var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function parseValues(str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObject(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index) &&
root !== cleanRoot &&
String(index) === cleanRoot &&
index >= 0 &&
(options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey;
// The regex chunks
var parent = /^([^\[\]]*)/;
var child = /(\[[^\[\]]*\])/g;
// Get the parent
var segment = parent.exec(key);
// Stash the parent if it exists
var keys = [];
if (segment[1]) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, segment[1])) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) {
if (!options.allowPrototypes) {
continue;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
/***/ },
/* 306 */
/***/ function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(61),
basePick = __webpack_require__(178),
flatRest = __webpack_require__(181),
toKey = __webpack_require__(157);
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [props] The property identifiers to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, props) {
return object == null ? {} : basePick(object, arrayMap(props, toKey));
});
module.exports = pick;
/***/ },
/* 307 */
/***/ function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(180),
baseForOwn = __webpack_require__(115),
baseIteratee = __webpack_require__(118);
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
module.exports = mapKeys;
/***/ },
/* 308 */
/***/ function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(180),
baseForOwn = __webpack_require__(115),
baseIteratee = __webpack_require__(118);
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
module.exports = mapValues;
/***/ },
/* 309 */
/***/ function(module, exports) {
'use strict';
module.exports = '2.14.0';
/***/ },
/* 310 */
/***/ function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(225),
createAssigner = __webpack_require__(222);
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is 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 invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
});
module.exports = mergeWith;
/***/ },
/* 311 */
/***/ function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(183),
baseRest = __webpack_require__(103),
baseUniq = __webpack_require__(312),
isArrayLikeObject = __webpack_require__(113);
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/
var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
module.exports = union;
/***/ },
/* 312 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(63),
arrayIncludes = __webpack_require__(96),
arrayIncludesWith = __webpack_require__(101),
cacheHas = __webpack_require__(102),
createSet = __webpack_require__(313),
setToArray = __webpack_require__(135);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseUniq;
/***/ },
/* 313 */
/***/ function(module, exports, __webpack_require__) {
var Set = __webpack_require__(140),
noop = __webpack_require__(267),
setToArray = __webpack_require__(135);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
module.exports = createSet;
/***/ },
/* 314 */
/***/ function(module, exports, __webpack_require__) {
var baseClone = __webpack_require__(315);
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, false, true);
}
module.exports = clone;
/***/ },
/* 315 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(121),
arrayEach = __webpack_require__(165),
assignValue = __webpack_require__(221),
baseAssign = __webpack_require__(316),
cloneBuffer = __webpack_require__(228),
copyArray = __webpack_require__(231),
copySymbols = __webpack_require__(317),
getAllKeys = __webpack_require__(318),
getTag = __webpack_require__(137),
initCloneArray = __webpack_require__(319),
initCloneByTag = __webpack_require__(320),
initCloneObject = __webpack_require__(232),
isArray = __webpack_require__(41),
isBuffer = __webpack_require__(42),
isObject = __webpack_require__(59),
keys = __webpack_require__(35);
/** `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]',
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 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;
/**
* 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)) {
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);
var props = isArr ? undefined : (isFull ? getAllKeys : keys)(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ },
/* 316 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(220),
keys = __webpack_require__(35);
/**
* 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);
}
module.exports = baseAssign;
/***/ },
/* 317 */
/***/ function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(220),
getSymbols = __webpack_require__(190);
/**
* 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);
}
module.exports = copySymbols;
/***/ },
/* 318 */
/***/ function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(187),
getSymbols = __webpack_require__(190),
keys = __webpack_require__(35);
/**
* 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);
}
module.exports = getAllKeys;
/***/ },
/* 319 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = 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;
}
module.exports = initCloneArray;
/***/ },
/* 320 */
/***/ function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(230),
cloneDataView = __webpack_require__(321),
cloneMap = __webpack_require__(322),
cloneRegExp = __webpack_require__(324),
cloneSet = __webpack_require__(325),
cloneSymbol = __webpack_require__(327),
cloneTypedArray = __webpack_require__(229);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
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]';
/**
* 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);
}
}
module.exports = initCloneByTag;
/***/ },
/* 321 */
/***/ function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(230);
/**
* 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);
}
module.exports = cloneDataView;
/***/ },
/* 322 */
/***/ function(module, exports, __webpack_require__) {
var addMapEntry = __webpack_require__(323),
arrayReduce = __webpack_require__(174),
mapToArray = __webpack_require__(134);
/**
* 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);
}
module.exports = cloneMap;
/***/ },
/* 323 */
/***/ function(module, exports) {
/**
* 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's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
module.exports = addMapEntry;
/***/ },
/* 324 */
/***/ function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ },
/* 325 */
/***/ function(module, exports, __webpack_require__) {
var addSetEntry = __webpack_require__(326),
arrayReduce = __webpack_require__(174),
setToArray = __webpack_require__(135);
/**
* 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);
}
module.exports = cloneSet;
/***/ },
/* 326 */
/***/ function(module, exports) {
/**
* 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) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
module.exports = addSetEntry;
/***/ },
/* 327 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(132);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ },
/* 328 */
/***/ 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 _algoliasearchHelper = __webpack_require__(32);
var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper);
var _version = __webpack_require__(329);
var _version2 = _interopRequireDefault(_version);
var _url = __webpack_require__(296);
var _url2 = _interopRequireDefault(_url);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
var _assign = __webpack_require__(330);
var _assign2 = _interopRequireDefault(_assign);
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 AlgoliaSearchHelper = _algoliasearchHelper2.default.AlgoliaSearchHelper;
var majorVersionNumber = _version2.default.split('.')[0];
var firstRender = true;
function timerMaker(t0) {
var t = t0;
return function timer() {
var now = Date.now();
var delta = now - t;
t = now;
return delta;
};
}
/**
* @typedef {object} UrlUtil
* @property {string} character the character used in the url
* @property {function} onpopstate add an event listener for the URL change
* @property {function} pushState creates a new entry in the browser history
* @property {function} replaceState update the current entry of the browser history
* @property {function} readUrl reads the query string of the parameters
*/
/**
* Handles the legacy browsers
* @type {UrlUtil}
*/
var hashUrlUtils = {
character: '#',
onpopstate: function onpopstate(cb) {
window.addEventListener('hashchange', cb);
},
pushState: function pushState(qs) {
window.location.assign(getFullURL(this.createURL(qs)));
},
replaceState: function replaceState(qs) {
window.location.replace(getFullURL(this.createURL(qs)));
},
createURL: function createURL(qs) {
return window.location.search + this.character + qs;
},
readUrl: function readUrl() {
return window.location.hash.slice(1);
}
};
/**
* Handles the modern API
* @type {UrlUtil}
*/
var modernUrlUtils = {
character: '?',
onpopstate: function onpopstate(cb) {
window.addEventListener('popstate', cb);
},
pushState: function pushState(qs, _ref) {
var getHistoryState = _ref.getHistoryState;
window.history.pushState(getHistoryState(), '', getFullURL(this.createURL(qs)));
},
replaceState: function replaceState(qs, _ref2) {
var getHistoryState = _ref2.getHistoryState;
window.history.replaceState(getHistoryState(), '', getFullURL(this.createURL(qs)));
},
createURL: function createURL(qs) {
return this.character + qs + document.location.hash;
},
readUrl: function readUrl() {
return window.location.search.slice(1);
}
};
// we always push the full url to the url bar. Not a relative one.
// So that we handle cases like using a <base href>, see
// https://github.com/algolia/instantsearch.js/issues/790 for the original issue
function getFullURL(relative) {
return getLocationOrigin() + window.location.pathname + relative;
}
// IE <= 11 has no location.origin or buggy
function getLocationOrigin() {
// eslint-disable-next-line max-len
return window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
// see InstantSearch.js file for urlSync options
var URLSync = function () {
function URLSync(urlUtils, options) {
_classCallCheck(this, URLSync);
this.urlUtils = urlUtils;
this.originalConfig = null;
this.timer = timerMaker(Date.now());
this.mapping = options.mapping || {};
this.getHistoryState = options.getHistoryState || function () {
return null;
};
this.threshold = options.threshold || 700;
this.trackedParameters = options.trackedParameters || ['query', 'attribute:*', 'index', 'page', 'hitsPerPage'];
this.searchParametersFromUrl = AlgoliaSearchHelper.getConfigurationFromQueryString(this.urlUtils.readUrl(), { mapping: this.mapping });
}
_createClass(URLSync, [{
key: 'getConfiguration',
value: function getConfiguration(currentConfiguration) {
// we need to create a REAL helper to then get its state. Because some parameters
// like hierarchicalFacet.rootPath are then triggering a default refinement that would
// be not present if it was not going trough the SearchParameters constructor
this.originalConfig = (0, _algoliasearchHelper2.default)({}, currentConfiguration.index, currentConfiguration).state;
return this.searchParametersFromUrl;
}
}, {
key: 'render',
value: function render(_ref3) {
var _this = this;
var helper = _ref3.helper;
if (firstRender) {
firstRender = false;
this.onHistoryChange(this.onPopState.bind(this, helper));
helper.on('change', function (state) {
return _this.renderURLFromState(state);
});
}
}
}, {
key: 'onPopState',
value: function onPopState(helper, fullState) {
// compare with helper.state
var partialHelperState = helper.getState(this.trackedParameters);
var fullHelperState = (0, _assign2.default)({}, this.originalConfig, partialHelperState);
if ((0, _isEqual2.default)(fullHelperState, fullState)) return;
helper.overrideStateWithoutTriggeringChangeEvent(fullState).search();
}
}, {
key: 'renderURLFromState',
value: function renderURLFromState(state) {
var currentQueryString = this.urlUtils.readUrl();
var foreignConfig = AlgoliaSearchHelper.getForeignConfigurationInQueryString(currentQueryString, { mapping: this.mapping });
// eslint-disable-next-line camelcase
foreignConfig.is_v = majorVersionNumber;
var qs = _url2.default.getQueryStringFromState(state.filter(this.trackedParameters), {
moreAttributes: foreignConfig,
mapping: this.mapping,
safe: true
});
if (this.timer() < this.threshold) {
this.urlUtils.replaceState(qs, { getHistoryState: this.getHistoryState });
} else {
this.urlUtils.pushState(qs, { getHistoryState: this.getHistoryState });
}
}
// External API's
}, {
key: 'createURL',
value: function createURL(state, _ref4) {
var absolute = _ref4.absolute;
var currentQueryString = this.urlUtils.readUrl();
var filteredState = state.filter(this.trackedParameters);
var foreignConfig = _algoliasearchHelper2.default.url.getUnrecognizedParametersInQueryString(currentQueryString, { mapping: this.mapping });
// Add instantsearch version to reconciliate old url with newer versions
// eslint-disable-next-line camelcase
foreignConfig.is_v = majorVersionNumber;
var relative = this.urlUtils.createURL(_algoliasearchHelper2.default.url.getQueryStringFromState(filteredState, { mapping: this.mapping }));
return absolute ? getFullURL(relative) : relative;
}
}, {
key: 'onHistoryChange',
value: function onHistoryChange(fn) {
var _this2 = this;
this.urlUtils.onpopstate(function () {
var qs = _this2.urlUtils.readUrl();
var partialState = AlgoliaSearchHelper.getConfigurationFromQueryString(qs, { mapping: _this2.mapping });
var fullState = (0, _assign2.default)({}, _this2.originalConfig, partialState);
fn(fullState);
});
}
}]);
return URLSync;
}();
/**
* Instanciate a url sync widget. This widget let you synchronize the search
* parameters with the URL. It can operate with legacy API and hash or it can use
* the modern history API. By default, it will use the modern API, but if you are
* looking for compatibility with IE8 and IE9, then you should set 'useHash' to
* true.
* @param {object} options all the parameters to configure the URL synchronization. It
* may contain the following keys :
* - threshold:number time in ms after which a new state is created in the browser
* history. The default value is 700.
* - trackedParameters:string[] parameters that will be synchronized in the
* URL. By default, it will track the query, all the refinable attribute (facets and numeric
* filters), the index and the page.
* - useHash:boolean if set to true, the url will be hash based. Otherwise,
* it'll use the query parameters using the modern history API.
* @return {object} the widget instance
*/
function urlSync() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var useHash = options.useHash || false;
var urlUtils = useHash ? hashUrlUtils : modernUrlUtils;
return new URLSync(urlUtils, options);
}
exports.default = urlSync;
/***/ },
/* 329 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = '1.8.12';
/***/ },
/* 330 */
/***/ function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(221),
copyObject = __webpack_require__(220),
createAssigner = __webpack_require__(222),
isArrayLike = __webpack_require__(57),
isPrototype = __webpack_require__(54),
keys = __webpack_require__(35);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
module.exports = assign;
/***/ },
/* 331 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (_ref) {
var numberLocale = _ref.numberLocale;
return {
formatNumber: function formatNumber(number, render) {
return Number(render(number)).toLocaleString(numberLocale);
}
};
};
/***/ },
/* 332 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _defaultTemplates = __webpack_require__(347);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _ClearAll = __webpack_require__(348);
var _ClearAll2 = _interopRequireDefault(_ClearAll);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-clear-all');
/**
* Allows to clear all refinements at once
* @function clearAll
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string[]} [options.excludeAttributes] List of attributes names to exclude from clear actions
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template
* @param {string|Function} [options.templates.link] Link template
* @param {string|Function} [options.templates.footer] Footer template
* @param {boolean} [options.autoHideContainer=true] Hide the container when there's no refinement to clear
* @param {Object} [options.cssClasses] CSS classes to be added
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.link] CSS class to add to the link element
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\nclearAll({\n container,\n [ cssClasses.{root,header,body,footer,link}={} ],\n [ templates.{header,link,footer}={link: \'Clear all\'} ],\n [ autoHideContainer=true ],\n [ collapsible=false ],\n [ excludeAttributes=[] ]\n})';
function clearAll() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$excludeAttribute = _ref.excludeAttributes;
var excludeAttributes = _ref$excludeAttribute === undefined ? [] : _ref$excludeAttribute;
if (!container) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var ClearAll = (0, _headerFooter2.default)(_ClearAll2.default);
if (autoHideContainer === true) {
ClearAll = (0, _autoHideContainer2.default)(ClearAll);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link)
};
return {
init: function init(_ref2) {
var helper = _ref2.helper;
var templatesConfig = _ref2.templatesConfig;
this.clearAll = this.clearAll.bind(this, helper);
this._templateProps = (0, _utils.prepareTemplateProps)({ defaultTemplates: _defaultTemplates2.default, templatesConfig: templatesConfig, templates: templates });
},
render: function render(_ref3) {
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
this.clearAttributes = (0, _utils.getRefinements)(results, state).map(function (one) {
return one.attributeName;
}).filter(function (one) {
return excludeAttributes.indexOf(one) === -1;
});
var hasRefinements = this.clearAttributes.length !== 0;
var url = createURL((0, _utils.clearRefinementsFromState)(state));
_reactDom2.default.render(_react2.default.createElement(ClearAll, {
clearAll: this.clearAll,
collapsible: collapsible,
cssClasses: cssClasses,
hasRefinements: hasRefinements,
shouldAutoHideContainer: !hasRefinements,
templateProps: this._templateProps,
url: url
}), containerNode);
},
clearAll: function clearAll(helper) {
if (this.clearAttributes.length > 0) {
(0, _utils.clearRefinementsAndSearch)(helper, this.clearAttributes);
}
}
};
}
exports.default = clearAll;
/***/ },
/* 333 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {(function (global, factory) {
true ? module.exports = factory(__webpack_require__(334), __webpack_require__(335)) :
typeof define === 'function' && define.amd ? define(['proptypes', 'preact'], factory) :
(global.preactCompat = factory(global.PropTypes,global.preact));
}(this, (function (PropTypes,preact) {
PropTypes = 'default' in PropTypes ? PropTypes['default'] : PropTypes;
var version = '15.1.0'; // trick libraries to think we are react
var ELEMENTS = 'a abbr address area article aside audio b base bdi bdo big blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li link main map mark menu menuitem meta meter nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track u ul var video wbr circle clipPath defs ellipse g image line linearGradient mask path pattern polygon polyline radialGradient rect stop svg text tspan'.split(' ');
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7;
// don't autobind these methods since they already have guaranteed context.
var AUTOBIND_BLACKLIST = {
constructor: 1,
render: 1,
shouldComponentUpdate: 1,
componentWillReceiveProps: 1,
componentWillUpdate: 1,
componentDidUpdate: 1,
componentWillMount: 1,
componentDidMount: 1,
componentWillUnmount: 1,
componentDidUnmount: 1
};
var CAMEL_PROPS = /^(?:accent|alignment|arabic|baseline|cap|clip|color|fill|flood|font|glyph|horiz|marker|overline|paint|stop|strikethrough|stroke|text|underline|unicode|units|v|vert|word|writing|x)[A-Z]/;
var BYPASS_HOOK = {};
/*global process*/
var DEV = typeof process!=='undefined' && ({"NODE_ENV":"production"}) && ("production")!=='production';
// a component that renders nothing. Used to replace components for unmountComponentAtNode.
var EmptyComponent = function () { return null; };
// make react think we're react.
var VNode = preact.h('').constructor;
VNode.prototype.$$typeof = REACT_ELEMENT_TYPE;
VNode.prototype.preactCompatUpgraded = false;
VNode.prototype.preactCompatNormalized = false;
Object.defineProperty(VNode.prototype, 'type', {
get: function get() { return this.nodeName; },
set: function set(v) { this.nodeName = v; },
configurable:true
});
Object.defineProperty(VNode.prototype, 'props', {
get: function get$1() { return this.attributes; },
set: function set$1(v) { this.attributes = v; },
configurable:true
});
var oldVnodeHook = preact.options.vnode;
preact.options.vnode = function (vnode) {
if (!vnode.preactCompatUpgraded) {
vnode.preactCompatUpgraded = true;
var tag = vnode.nodeName,
attrs = vnode.attributes;
if (!attrs) attrs = vnode.attributes = {};
if (typeof tag==='function') {
if (tag[COMPONENT_WRAPPER_KEY]===true || (tag.prototype && 'isReactComponent' in tag.prototype)) {
if (!vnode.preactCompatNormalized) {
normalizeVNode(vnode);
}
handleComponentVNode(vnode);
}
}
else if (attrs) {
handleElementVNode(vnode, attrs);
}
}
if (oldVnodeHook) oldVnodeHook(vnode);
};
function handleComponentVNode(vnode) {
var tag = vnode.nodeName,
a = vnode.attributes;
vnode.attributes = {};
if (tag.defaultProps) extend(vnode.attributes, tag.defaultProps);
if (a) extend(vnode.attributes, a);
a = vnode.attributes;
if (vnode.children && !vnode.children.length) vnode.children = undefined;
if (vnode.children) a.children = vnode.children;
}
function handleElementVNode(vnode, a) {
var shouldSanitize, attrs, i;
if (a) {
for (i in a) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
if (shouldSanitize) {
attrs = vnode.attributes = {};
for (i in a) {
if (a.hasOwnProperty(i)) {
attrs[ CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i ] = a[i];
}
}
}
}
}
// proxy render() since React returns a Component reference.
function render$1$1(vnode, parent, callback) {
var prev = parent._preactCompatRendered;
// ignore impossible previous renders
if (prev && prev.parentNode!==parent) prev = null;
// default to first Element child
if (!prev) prev = parent.children[0];
// remove unaffected siblings
for (var i=parent.childNodes.length; i--; ) {
if (parent.childNodes[i]!==prev) {
parent.removeChild(parent.childNodes[i]);
}
}
var out = preact.render(vnode, parent, prev);
parent._preactCompatRendered = out;
if (typeof callback==='function') callback();
return out && out._component || out.base;
}
var ContextProvider = function ContextProvider () {};
ContextProvider.prototype.getChildContext = function getChildContext () {
return this.props.context;
};
ContextProvider.prototype.render = function render$1 (props) {
return props.children[0];
};
function renderSubtreeIntoContainer(parentComponent, vnode, container, callback) {
var wrap = preact.h(ContextProvider, { context: parentComponent.context }, vnode);
var c = render$1$1(wrap, container);
if (callback) callback(c);
return c;
}
function unmountComponentAtNode(container) {
var existing = container._preactCompatRendered;
if (existing && existing.parentNode===container) {
preact.render(preact.h(EmptyComponent), container, existing);
return true;
}
return false;
}
var ARR = [];
// This API is completely unnecessary for Preact, so it's basically passthrough.
var Children = {
map: function map(children, fn, ctx) {
children = Children.toArray(children);
if (ctx && ctx!==children) fn = fn.bind(ctx);
return children.map(fn);
},
forEach: function forEach(children, fn, ctx) {
children = Children.toArray(children);
if (ctx && ctx!==children) fn = fn.bind(ctx);
children.forEach(fn);
},
count: function count(children) {
children = Children.toArray(children);
return children.length;
},
only: function only(children) {
children = Children.toArray(children);
if (children.length!==1) throw new Error('Children.only() expects only one child.');
return children[0];
},
toArray: function toArray(children) {
return Array.isArray && Array.isArray(children) ? children : ARR.concat(children);
}
};
/** Track current render() component for ref assignment */
var currentComponent;
function createFactory(type) {
return createElement.bind(null, type);
}
var DOM = {};
for (var i=ELEMENTS.length; i--; ) {
DOM[ELEMENTS[i]] = createFactory(ELEMENTS[i]);
}
function upgradeToVNodes(arr, offset) {
for (var i=offset || 0; i<arr.length; i++) {
var obj = arr[i];
if (Array.isArray(obj)) {
upgradeToVNodes(obj);
}
else if (obj && typeof obj==='object' && !isValidElement(obj) && ((obj.props && obj.type) || (obj.attributes && obj.nodeName) || obj.children)) {
arr[i] = createElement(obj.type || obj.nodeName, obj.props || obj.attributes, obj.children);
}
}
}
function isStatelessComponent(c) {
return typeof c==='function' && !(c.prototype && c.prototype.render);
}
var COMPONENT_WRAPPER_KEY = typeof Symbol!=='undefined' ? Symbol.for('__preactCompatWrapper') : '__preactCompatWrapper';
// wraps stateless functional components in a PropTypes validator
function wrapStatelessComponent(WrappedComponent) {
return createClass({
displayName: WrappedComponent.displayName || WrappedComponent.name,
render: function render$1$1(props, state, context) {
return WrappedComponent(props, context);
}
});
}
function statelessComponentHook(Ctor) {
var Wrapped = Ctor[COMPONENT_WRAPPER_KEY];
if (Wrapped) return Wrapped===true ? Ctor : Wrapped;
Wrapped = wrapStatelessComponent(Ctor);
Object.defineProperty(Wrapped, COMPONENT_WRAPPER_KEY, { configurable:true, value:true });
Wrapped.displayName = Ctor.displayName;
Wrapped.propTypes = Ctor.propTypes;
Wrapped.defaultProps = Ctor.defaultProps;
Object.defineProperty(Ctor, COMPONENT_WRAPPER_KEY, { configurable:true, value:Wrapped });
return Wrapped;
}
function createElement() {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
upgradeToVNodes(args, 2);
return normalizeVNode(preact.h.apply(void 0, args));
}
function normalizeVNode(vnode) {
vnode.preactCompatNormalized = true;
applyClassName(vnode);
if (isStatelessComponent(vnode.nodeName)) {
vnode.nodeName = statelessComponentHook(vnode.nodeName);
}
var ref = vnode.attributes.ref,
type = ref && typeof ref;
if (currentComponent && (type==='string' || type==='number')) {
vnode.attributes.ref = createStringRefProxy(ref, currentComponent);
}
applyEventNormalization(vnode);
return vnode;
}
function cloneElement$1(element, props) {
var children = [], len = arguments.length - 2;
while ( len-- > 0 ) children[ len ] = arguments[ len + 2 ];
if (!isValidElement(element)) return element;
var elementProps = element.attributes || element.props;
var node = preact.h(
element.nodeName || element.type,
elementProps,
element.children || elementProps && elementProps.children
);
return normalizeVNode(preact.cloneElement.apply(void 0, [ node, props ].concat( children )));
}
function isValidElement(element) {
return element && ((element instanceof VNode) || element.$$typeof===REACT_ELEMENT_TYPE);
}
function createStringRefProxy(name, component) {
return component._refProxies[name] || (component._refProxies[name] = function (resolved) {
if (component && component.refs) {
component.refs[name] = resolved;
if (resolved===null) {
delete component._refProxies[name];
component = null;
}
}
});
}
function applyEventNormalization(ref) {
var nodeName = ref.nodeName;
var attributes = ref.attributes;
if (!attributes || typeof nodeName!=='string') return;
var props = {};
for (var i in attributes) {
props[i.toLowerCase()] = i;
}
if (props.onchange) {
nodeName = nodeName.toLowerCase();
var attr = nodeName==='input' && String(attributes.type).toLowerCase()==='checkbox' ? 'onclick' : 'oninput',
normalized = props[attr] || attr;
if (!attributes[normalized]) {
attributes[normalized] = multihook([attributes[props[attr]], attributes[props.onchange]]);
}
}
}
function applyClassName(ref) {
var attributes = ref.attributes;
if (!attributes) return;
var cl = attributes.className || attributes.class;
if (cl) attributes.className = cl;
}
function extend(base, props) {
for (var key in props) {
if (props.hasOwnProperty(key)) {
base[key] = props[key];
}
}
return base;
}
function shallowDiffers(a, b) {
for (var i in a) if (!(i in b)) return true;
for (var i$1 in b) if (a[i$1]!==b[i$1]) return true;
return false;
}
var findDOMNode = function (component) { return component && component.base || component; };
function F(){}
function createClass(obj) {
var mixins = obj.mixins && collateMixins(obj.mixins);
function cl(props, context) {
extend(this, obj);
if (mixins) applyMixins(this, mixins);
Component$1.call(this, props, context, BYPASS_HOOK);
bindAll(this);
newComponentHook.call(this, props, context);
}
if (obj.statics) {
extend(cl, obj.statics);
}
if (obj.propTypes) {
cl.propTypes = obj.propTypes;
}
if (obj.defaultProps) {
cl.defaultProps = obj.defaultProps;
}
if (obj.getDefaultProps) {
cl.defaultProps = obj.getDefaultProps();
}
F.prototype = Component$1.prototype;
cl.prototype = new F();
cl.prototype.constructor = cl;
cl.displayName = obj.displayName || 'Component';
return cl;
}
// Flatten an Array of mixins to a map of method name to mixin implementations
function collateMixins(mixins) {
var keyed = {};
for (var i=0; i<mixins.length; i++) {
var mixin = mixins[i];
for (var key in mixin) {
if (mixin.hasOwnProperty(key) && typeof mixin[key]==='function') {
(keyed[key] || (keyed[key]=[])).push(mixin[key]);
}
}
}
return keyed;
}
// apply a mapping of Arrays of mixin methods to a component instance
function applyMixins(inst, mixins) {
for (var key in mixins) if (mixins.hasOwnProperty(key)) {
inst[key] = multihook(mixins[key].concat(inst[key] || key));
}
}
function bindAll(ctx) {
for (var i in ctx) {
var v = ctx[i];
if (typeof v==='function' && !v.__bound && !AUTOBIND_BLACKLIST.hasOwnProperty(i)) {
(ctx[i] = v.bind(ctx)).__bound = true;
}
}
}
function callMethod(ctx, m, args) {
if (typeof m==='string') {
m = ctx.constructor.prototype[m];
}
if (typeof m==='function') {
return m.apply(ctx, args);
}
}
function multihook(hooks) {
return function() {
var arguments$1 = arguments;
var this$1 = this;
var ret;
for (var i=0; i<hooks.length; i++) {
var r = callMethod(this$1, hooks[i], arguments$1);
if (typeof r!=='undefined') ret = r;
}
return ret;
};
}
function newComponentHook(props, context) {
propsHook.call(this, props, context);
this.componentWillReceiveProps = multihook([propsHook, this.componentWillReceiveProps || 'componentWillReceiveProps']);
this.render = multihook([propsHook, beforeRender, this.render || 'render', afterRender]);
}
function propsHook(props, context) {
var this$1 = this;
if (!props) return;
// React annoyingly special-cases single children, and some react components are ridiculously strict about this.
var c = props.children;
if (c && Array.isArray(c) && c.length===1) {
props.children = c[0];
// but its totally still going to be an Array.
if (props.children && typeof props.children==='object') {
props.children.length = 1;
props.children[0] = props.children;
}
}
// add proptype checking
if (DEV) {
var ctor = typeof this==='function' ? this : this.constructor,
propTypes = this.propTypes || ctor.propTypes;
if (propTypes) {
for (var prop in propTypes) {
if (propTypes.hasOwnProperty(prop) && typeof propTypes[prop]==='function') {
var displayName = this$1.displayName || ctor.name;
var err = propTypes[prop](props, prop, displayName, 'prop');
if (err) console.error(new Error(err.message || err));
}
}
}
}
}
function beforeRender(props) {
currentComponent = this;
}
function afterRender() {
if (currentComponent===this) {
currentComponent = null;
}
}
function Component$1(props, context, opts) {
preact.Component.call(this, props, context);
if (this.getInitialState) this.state = this.getInitialState();
this.refs = {};
this._refProxies = {};
if (opts!==BYPASS_HOOK) {
newComponentHook.call(this, props, context);
}
}
Component$1.prototype = new preact.Component();
extend(Component$1.prototype, {
constructor: Component$1,
isReactComponent: {},
getDOMNode: function getDOMNode() {
return this.base;
},
isMounted: function isMounted() {
return !!this.base;
}
});
function PureComponent(props, context) {
Component$1.call(this, props, context);
}
PureComponent.prototype = new Component$1({}, {}, BYPASS_HOOK);
PureComponent.prototype.shouldComponentUpdate = function(props, state) {
return shallowDiffers(this.props, props) || shallowDiffers(this.state, state);
};
var index = {
version: version,
DOM: DOM,
PropTypes: PropTypes,
Children: Children,
render: render$1$1,
createClass: createClass,
createFactory: createFactory,
createElement: createElement,
cloneElement: cloneElement$1,
isValidElement: isValidElement,
findDOMNode: findDOMNode,
unmountComponentAtNode: unmountComponentAtNode,
Component: Component$1,
PureComponent: PureComponent,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
return index;
})));
//# sourceMappingURL=preact-compat.js.map
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24)))
/***/ },
/* 334 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports, module], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module);
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod);
global.PropTypes = mod.exports;
}
})(this, function (exports, module) {
'use strict';
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
var ReactElement = {};
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
var ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
var emptyFunction = {
thatReturns: function thatReturns(what) {
return function () {
return what;
};
}
};
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
var preciseType = getPreciseType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']');
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
return 'object';
}
return propType;
}
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
});
//# sourceMappingURL=index.js.map
/***/ },
/* 335 */
/***/ function(module, exports, __webpack_require__) {
!function(global, factory) {
true ? factory(exports) : 'function' == typeof define && define.amd ? define([ 'exports' ], factory) : factory(global.preact = global.preact || {});
}(this, function(exports) {
function VNode(nodeName, attributes, children) {
this.nodeName = nodeName;
this.attributes = attributes;
this.children = children;
this.key = attributes && attributes.key;
}
function h(nodeName, attributes) {
var lastSimple, child, simple, i, children = [];
for (i = arguments.length; i-- > 2; ) stack.push(arguments[i]);
if (attributes && attributes.children) {
if (!stack.length) stack.push(attributes.children);
delete attributes.children;
}
while (stack.length) if ((child = stack.pop()) instanceof Array) for (i = child.length; i--; ) stack.push(child[i]); else if (null != child && child !== !1) {
if ('number' == typeof child || child === !0) child = String(child);
simple = 'string' == typeof child;
if (simple && lastSimple) children[children.length - 1] += child; else {
children.push(child);
lastSimple = simple;
}
}
var p = new VNode(nodeName, attributes || void 0, children);
if (options.vnode) options.vnode(p);
return p;
}
function extend(obj, props) {
if (props) for (var i in props) obj[i] = props[i];
return obj;
}
function clone(obj) {
return extend({}, obj);
}
function delve(obj, key) {
for (var p = key.split('.'), i = 0; i < p.length && obj; i++) obj = obj[p[i]];
return obj;
}
function isFunction(obj) {
return 'function' == typeof obj;
}
function isString(obj) {
return 'string' == typeof obj;
}
function hashToClassName(c) {
var str = '';
for (var prop in c) if (c[prop]) {
if (str) str += ' ';
str += prop;
}
return str;
}
function cloneElement(vnode, props) {
return h(vnode.nodeName, extend(clone(vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children);
}
function createLinkedState(component, key, eventPath) {
var path = key.split('.'), p0 = path[0];
return function(e) {
var _component$setState;
var i, t = e && e.currentTarget || this, s = component.state, obj = s, v = isString(eventPath) ? delve(e, eventPath) : t.nodeName ? (t.nodeName + t.type).match(/^input(che|rad)/i) ? t.checked : t.value : e;
if (path.length > 1) {
for (i = 0; i < path.length - 1; i++) obj = obj[path[i]] || (obj[path[i]] = {});
obj[path[i]] = v;
v = s[p0];
}
component.setState((_component$setState = {}, _component$setState[p0] = v, _component$setState));
};
}
function enqueueRender(component) {
if (!component._dirty && (component._dirty = !0) && 1 == items.push(component)) (options.debounceRendering || defer)(rerender);
}
function rerender() {
var p, list = items;
items = [];
while (p = list.pop()) if (p._dirty) renderComponent(p);
}
function isFunctionalComponent(vnode) {
var nodeName = vnode && vnode.nodeName;
return nodeName && isFunction(nodeName) && !(nodeName.prototype && nodeName.prototype.render);
}
function buildFunctionalComponent(vnode, context) {
return vnode.nodeName(getNodeProps(vnode), context || EMPTY);
}
function isSameNodeType(node, vnode) {
if (isString(vnode)) return node instanceof Text;
if (isString(vnode.nodeName)) return isNamedNode(node, vnode.nodeName);
if (isFunction(vnode.nodeName)) return node._componentConstructor === vnode.nodeName || isFunctionalComponent(vnode); else ;
}
function isNamedNode(node, nodeName) {
return node.normalizedNodeName === nodeName || toLowerCase(node.nodeName) === toLowerCase(nodeName);
}
function getNodeProps(vnode) {
var props = clone(vnode.attributes);
props.children = vnode.children;
var defaultProps = vnode.nodeName.defaultProps;
if (defaultProps) for (var i in defaultProps) if (void 0 === props[i]) props[i] = defaultProps[i];
return props;
}
function removeNode(node) {
var p = node.parentNode;
if (p) p.removeChild(node);
}
function setAccessor(node, name, old, value, isSvg) {
if ('className' === name) name = 'class';
if ('class' === name && value && 'object' == typeof value) value = hashToClassName(value);
if ('key' === name) ; else if ('class' === name && !isSvg) node.className = value || ''; else if ('style' === name) {
if (!value || isString(value) || isString(old)) node.style.cssText = value || '';
if (value && 'object' == typeof value) {
if (!isString(old)) for (var i in old) if (!(i in value)) node.style[i] = '';
for (var i in value) node.style[i] = 'number' == typeof value[i] && !NON_DIMENSION_PROPS[i] ? value[i] + 'px' : value[i];
}
} else if ('dangerouslySetInnerHTML' === name) {
if (value) node.innerHTML = value.__html;
} else if ('o' == name[0] && 'n' == name[1]) {
var l = node._listeners || (node._listeners = {});
name = toLowerCase(name.substring(2));
if (value) {
if (!l[name]) node.addEventListener(name, eventProxy, !!NON_BUBBLING_EVENTS[name]);
} else if (l[name]) node.removeEventListener(name, eventProxy, !!NON_BUBBLING_EVENTS[name]);
l[name] = value;
} else if ('list' !== name && 'type' !== name && !isSvg && name in node) {
setProperty(node, name, null == value ? '' : value);
if (null == value || value === !1) node.removeAttribute(name);
} else {
var ns = isSvg && name.match(/^xlink\:?(.+)/);
if (null == value || value === !1) if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', toLowerCase(ns[1])); else node.removeAttribute(name); else if ('object' != typeof value && !isFunction(value)) if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', toLowerCase(ns[1]), value); else node.setAttribute(name, value);
}
}
function setProperty(node, name, value) {
try {
node[name] = value;
} catch (e) {}
}
function eventProxy(e) {
return this._listeners[e.type](options.event && options.event(e) || e);
}
function collectNode(node) {
removeNode(node);
if (node instanceof Element) {
node._component = node._componentConstructor = null;
var _name = node.normalizedNodeName || toLowerCase(node.nodeName);
(nodes[_name] || (nodes[_name] = [])).push(node);
}
}
function createNode(nodeName, isSvg) {
var name = toLowerCase(nodeName), node = nodes[name] && nodes[name].pop() || (isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName));
node.normalizedNodeName = name;
return node;
}
function flushMounts() {
var c;
while (c = mounts.pop()) if (c.componentDidMount) c.componentDidMount();
}
function diff(dom, vnode, context, mountAll, parent, componentRoot) {
if (!diffLevel++) isSvgMode = parent instanceof SVGElement;
var ret = idiff(dom, vnode, context, mountAll);
if (parent && ret.parentNode !== parent) parent.appendChild(ret);
if (!--diffLevel && !componentRoot) flushMounts();
return ret;
}
function idiff(dom, vnode, context, mountAll) {
var originalAttributes = vnode && vnode.attributes;
while (isFunctionalComponent(vnode)) vnode = buildFunctionalComponent(vnode, context);
if (null == vnode) vnode = '';
if (isString(vnode)) {
if (dom) {
if (dom instanceof Text && dom.parentNode) {
dom.nodeValue = vnode;
return dom;
}
recollectNodeTree(dom);
}
return document.createTextNode(vnode);
}
if (isFunction(vnode.nodeName)) return buildComponentFromVNode(dom, vnode, context, mountAll);
var out = dom, nodeName = vnode.nodeName, prevSvgMode = isSvgMode;
if (!isString(nodeName)) nodeName = String(nodeName);
isSvgMode = 'svg' === nodeName ? !0 : 'foreignObject' === nodeName ? !1 : isSvgMode;
if (!dom) out = createNode(nodeName, isSvgMode); else if (!isNamedNode(dom, nodeName)) {
out = createNode(nodeName, isSvgMode);
while (dom.firstChild) out.appendChild(dom.firstChild);
recollectNodeTree(dom);
}
if (vnode.children && 1 === vnode.children.length && 'string' == typeof vnode.children[0] && 1 === out.childNodes.length && out.firstChild instanceof Text) out.firstChild.nodeValue = vnode.children[0]; else if (vnode.children && vnode.children.length || out.firstChild) innerDiffNode(out, vnode.children, context, mountAll);
var props = out[ATTR_KEY];
if (!props) {
out[ATTR_KEY] = props = {};
for (var a = out.attributes, i = a.length; i--; ) props[a[i].name] = a[i].value;
}
diffAttributes(out, vnode.attributes, props);
if (originalAttributes && 'function' == typeof originalAttributes.ref) (props.ref = originalAttributes.ref)(out);
isSvgMode = prevSvgMode;
return out;
}
function innerDiffNode(dom, vchildren, context, mountAll) {
var j, c, vchild, child, originalChildren = dom.childNodes, children = [], keyed = {}, keyedLen = 0, min = 0, len = originalChildren.length, childrenLen = 0, vlen = vchildren && vchildren.length;
if (len) for (var i = 0; i < len; i++) {
var _child = originalChildren[i], key = vlen ? (c = _child._component) ? c.__key : (c = _child[ATTR_KEY]) ? c.key : null : null;
if (key || 0 === key) {
keyedLen++;
keyed[key] = _child;
} else children[childrenLen++] = _child;
}
if (vlen) for (var i = 0; i < vlen; i++) {
vchild = vchildren[i];
child = null;
var key = vchild.key;
if (null != key) {
if (keyedLen && key in keyed) {
child = keyed[key];
keyed[key] = void 0;
keyedLen--;
}
} else if (!child && min < childrenLen) {
for (j = min; j < childrenLen; j++) {
c = children[j];
if (c && isSameNodeType(c, vchild)) {
child = c;
children[j] = void 0;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
}
if (!child && min < childrenLen && isFunction(vchild.nodeName) && mountAll) {
child = children[min];
children[min++] = void 0;
}
}
child = idiff(child, vchild, context, mountAll);
if (child && child !== dom && child !== originalChildren[i]) dom.insertBefore(child, originalChildren[i] || null);
}
if (keyedLen) for (var i in keyed) if (keyed[i]) recollectNodeTree(keyed[i]);
if (min < childrenLen) removeOrphanedChildren(children);
}
function removeOrphanedChildren(children, unmountOnly) {
for (var i = children.length; i--; ) if (children[i]) recollectNodeTree(children[i], unmountOnly);
}
function recollectNodeTree(node, unmountOnly) {
var component = node._component;
if (component) unmountComponent(component, !unmountOnly); else {
if (node[ATTR_KEY] && node[ATTR_KEY].ref) node[ATTR_KEY].ref(null);
if (!unmountOnly) collectNode(node);
if (node.childNodes && node.childNodes.length) removeOrphanedChildren(node.childNodes, unmountOnly);
}
}
function diffAttributes(dom, attrs, old) {
for (var _name in old) if (!(attrs && _name in attrs) && null != old[_name]) setAccessor(dom, _name, old[_name], old[_name] = void 0, isSvgMode);
if (attrs) for (var _name2 in attrs) if (!('children' === _name2 || 'innerHTML' === _name2 || _name2 in old && attrs[_name2] === ('value' === _name2 || 'checked' === _name2 ? dom[_name2] : old[_name2]))) setAccessor(dom, _name2, old[_name2], old[_name2] = attrs[_name2], isSvgMode);
}
function collectComponent(component) {
var name = component.constructor.name, list = components[name];
if (list) list.push(component); else components[name] = [ component ];
}
function createComponent(Ctor, props, context) {
var inst = new Ctor(props, context), list = components[Ctor.name];
Component.call(inst, props, context);
if (list) for (var i = list.length; i--; ) if (list[i].constructor === Ctor) {
inst.nextBase = list[i].nextBase;
list.splice(i, 1);
break;
}
return inst;
}
function setComponentProps(component, props, opts, context, mountAll) {
if (!component._disable) {
component._disable = !0;
if (component.__ref = props.ref) delete props.ref;
if (component.__key = props.key) delete props.key;
if (!component.base || mountAll) {
if (component.componentWillMount) component.componentWillMount();
} else if (component.componentWillReceiveProps) component.componentWillReceiveProps(props, context);
if (context && context !== component.context) {
if (!component.prevContext) component.prevContext = component.context;
component.context = context;
}
if (!component.prevProps) component.prevProps = component.props;
component.props = props;
component._disable = !1;
if (0 !== opts) if (1 === opts || options.syncComponentUpdates !== !1 || !component.base) renderComponent(component, 1, mountAll); else enqueueRender(component);
if (component.__ref) component.__ref(component);
}
}
function renderComponent(component, opts, mountAll, isChild) {
if (!component._disable) {
var skip, rendered, inst, cbase, props = component.props, state = component.state, context = component.context, previousProps = component.prevProps || props, previousState = component.prevState || state, previousContext = component.prevContext || context, isUpdate = component.base, nextBase = component.nextBase, initialBase = isUpdate || nextBase, initialChildComponent = component._component;
if (isUpdate) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
if (2 !== opts && component.shouldComponentUpdate && component.shouldComponentUpdate(props, state, context) === !1) skip = !0; else if (component.componentWillUpdate) component.componentWillUpdate(props, state, context);
component.props = props;
component.state = state;
component.context = context;
}
component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
component._dirty = !1;
if (!skip) {
if (component.render) rendered = component.render(props, state, context);
if (component.getChildContext) context = extend(clone(context), component.getChildContext());
while (isFunctionalComponent(rendered)) rendered = buildFunctionalComponent(rendered, context);
var toUnmount, base, childComponent = rendered && rendered.nodeName;
if (isFunction(childComponent)) {
inst = initialChildComponent;
var childProps = getNodeProps(rendered);
if (inst && inst.constructor === childComponent) setComponentProps(inst, childProps, 1, context); else {
toUnmount = inst;
inst = createComponent(childComponent, childProps, context);
inst.nextBase = inst.nextBase || nextBase;
inst._parentComponent = component;
component._component = inst;
setComponentProps(inst, childProps, 0, context);
renderComponent(inst, 1, mountAll, !0);
}
base = inst.base;
} else {
cbase = initialBase;
toUnmount = initialChildComponent;
if (toUnmount) cbase = component._component = null;
if (initialBase || 1 === opts) {
if (cbase) cbase._component = null;
base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, !0);
}
}
if (initialBase && base !== initialBase && inst !== initialChildComponent) {
var baseParent = initialBase.parentNode;
if (baseParent && base !== baseParent) baseParent.replaceChild(base, initialBase);
if (!cbase && !toUnmount && component._parentComponent) {
initialBase._component = null;
recollectNodeTree(initialBase);
}
}
if (toUnmount) unmountComponent(toUnmount, base !== initialBase);
component.base = base;
if (base && !isChild) {
var componentRef = component, t = component;
while (t = t._parentComponent) componentRef = t;
base._component = componentRef;
base._componentConstructor = componentRef.constructor;
}
}
if (!isUpdate || mountAll) mounts.unshift(component); else if (!skip && component.componentDidUpdate) component.componentDidUpdate(previousProps, previousState, previousContext);
var fn, cb = component._renderCallbacks;
if (cb) while (fn = cb.pop()) fn.call(component);
if (!diffLevel && !isChild) flushMounts();
}
}
function buildComponentFromVNode(dom, vnode, context, mountAll) {
var c = dom && dom._component, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode);
while (c && !isOwner && (c = c._parentComponent)) isOwner = c.constructor === vnode.nodeName;
if (c && isOwner && (!mountAll || c._component)) {
setComponentProps(c, props, 3, context, mountAll);
dom = c.base;
} else {
if (c && !isDirectOwner) {
unmountComponent(c, !0);
dom = oldDom = null;
}
c = createComponent(vnode.nodeName, props, context);
if (dom && !c.nextBase) c.nextBase = dom;
setComponentProps(c, props, 1, context, mountAll);
dom = c.base;
if (oldDom && dom !== oldDom) {
oldDom._component = null;
recollectNodeTree(oldDom);
}
}
return dom;
}
function unmountComponent(component, remove) {
var base = component.base;
component._disable = !0;
if (component.componentWillUnmount) component.componentWillUnmount();
component.base = null;
var inner = component._component;
if (inner) unmountComponent(inner, remove); else if (base) {
if (base[ATTR_KEY] && base[ATTR_KEY].ref) base[ATTR_KEY].ref(null);
component.nextBase = base;
if (remove) {
removeNode(base);
collectComponent(component);
}
removeOrphanedChildren(base.childNodes, !remove);
}
if (component.__ref) component.__ref(null);
if (component.componentDidUnmount) component.componentDidUnmount();
}
function Component(props, context) {
this._dirty = !0;
this.context = context;
this.props = props;
if (!this.state) this.state = {};
}
function render(vnode, parent, merge) {
return diff(merge, vnode, {}, !1, parent);
}
var options = {};
var stack = [];
var lcCache = {};
var toLowerCase = function(s) {
return lcCache[s] || (lcCache[s] = s.toLowerCase());
};
var resolved = 'undefined' != typeof Promise && Promise.resolve();
var defer = resolved ? function(f) {
resolved.then(f);
} : setTimeout;
var EMPTY = {};
var ATTR_KEY = 'undefined' != typeof Symbol ? Symbol.for('preactattr') : '__preactattr_';
var NON_DIMENSION_PROPS = {
boxFlex: 1,
boxFlexGroup: 1,
columnCount: 1,
fillOpacity: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
fontWeight: 1,
lineClamp: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
strokeOpacity: 1,
widows: 1,
zIndex: 1,
zoom: 1
};
var NON_BUBBLING_EVENTS = {
blur: 1,
error: 1,
focus: 1,
load: 1,
resize: 1,
scroll: 1
};
var items = [];
var nodes = {};
var mounts = [];
var diffLevel = 0;
var isSvgMode = !1;
var components = {};
extend(Component.prototype, {
linkState: function(key, eventPath) {
var c = this._linkedStates || (this._linkedStates = {});
return c[key + eventPath] || (c[key + eventPath] = createLinkedState(this, key, eventPath));
},
setState: function(state, callback) {
var s = this.state;
if (!this.prevState) this.prevState = clone(s);
extend(s, isFunction(state) ? state(s, this.props) : state);
if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback);
enqueueRender(this);
},
forceUpdate: function() {
renderComponent(this, 2);
},
render: function() {}
});
exports.h = h;
exports.cloneElement = cloneElement;
exports.Component = Component;
exports.render = render;
exports.rerender = rerender;
exports.options = options;
});
//# sourceMappingURL=preact.js.map
/***/ },
/* 336 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.prefixKeys = exports.clearRefinementsAndSearch = exports.clearRefinementsFromState = exports.getRefinements = exports.isDomElement = exports.isSpecialClick = exports.prepareTemplateProps = exports.bemHelper = exports.getContainerNode = undefined;
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 _reduce = __webpack_require__(173);
var _reduce2 = _interopRequireDefault(_reduce);
var _forEach = __webpack_require__(164);
var _forEach2 = _interopRequireDefault(_forEach);
var _find = __webpack_require__(205);
var _find2 = _interopRequireDefault(_find);
var _get = __webpack_require__(147);
var _get2 = _interopRequireDefault(_get);
var _isEmpty = __webpack_require__(201);
var _isEmpty2 = _interopRequireDefault(_isEmpty);
var _keys = __webpack_require__(35);
var _keys2 = _interopRequireDefault(_keys);
var _uniq = __webpack_require__(337);
var _uniq2 = _interopRequireDefault(_uniq);
var _mapKeys = __webpack_require__(307);
var _mapKeys2 = _interopRequireDefault(_mapKeys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
exports.getContainerNode = getContainerNode;
exports.bemHelper = bemHelper;
exports.prepareTemplateProps = prepareTemplateProps;
exports.isSpecialClick = isSpecialClick;
exports.isDomElement = isDomElement;
exports.getRefinements = getRefinements;
exports.clearRefinementsFromState = clearRefinementsFromState;
exports.clearRefinementsAndSearch = clearRefinementsAndSearch;
exports.prefixKeys = prefixKeys;
/**
* Return the container. If it's a string, it is considered a
* css selector and retrieves the first matching element. Otherwise
* test if it validates that it's a correct DOMElement.
* @param {string|DOMElement} selectorOrHTMLElement a selector or a node
* @return {DOMElement} The resolved DOMElement
* @throws Error when the type is not correct
*/
function getContainerNode(selectorOrHTMLElement) {
var isFromString = typeof selectorOrHTMLElement === 'string';
var domElement = void 0;
if (isFromString) {
domElement = document.querySelector(selectorOrHTMLElement);
} else {
domElement = selectorOrHTMLElement;
}
if (!isDomElement(domElement)) {
var errorMessage = 'Container must be `string` or `HTMLElement`.';
if (isFromString) {
errorMessage += ' Unable to find ' + selectorOrHTMLElement;
}
throw new Error(errorMessage);
}
return domElement;
}
/**
* Returns true if the parameter is a DOMElement.
* @param {any} o the value to test
* @return {boolean} true if o is a DOMElement
*/
function isDomElement(o) {
return o instanceof window.HTMLElement || Boolean(o) && o.nodeType > 0;
}
function isSpecialClick(event) {
var isMiddleClick = event.button === 1;
return isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
}
/**
* Creates BEM class name according the vanilla BEM style.
* @param {string} block the main block
* @return {function} function that takes up to 2 parameters
* that determine the element and the modifier of the BEM class.
*/
function bemHelper(block) {
return function (element, modifier) {
// block--element
if (element && !modifier) {
return block + '--' + element;
}
// block--element__modifier
if (element && modifier) {
return block + '--' + element + '__' + modifier;
}
// block__modifier
if (!element && modifier) {
return block + '__' + modifier;
}
return block;
};
}
/**
* Prepares an object to be passed to the Template widget
* @param {object} unknownBecauseES6 an object with the following attributes:
* - transformData
* - defaultTemplate
* - templates
* - templatesConfig
* @return {object} the configuration with the attributes:
* - transformData
* - defaultTemplate
* - templates
* - useCustomCompileOptions
*/
function prepareTemplateProps(_ref) {
var transformData = _ref.transformData;
var defaultTemplates = _ref.defaultTemplates;
var templates = _ref.templates;
var templatesConfig = _ref.templatesConfig;
var preparedTemplates = prepareTemplates(defaultTemplates, templates);
return _extends({
transformData: transformData,
templatesConfig: templatesConfig
}, preparedTemplates);
}
function prepareTemplates() {
var defaultTemplates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var templates = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var allKeys = (0, _uniq2.default)([].concat(_toConsumableArray((0, _keys2.default)(defaultTemplates)), _toConsumableArray((0, _keys2.default)(templates))));
return (0, _reduce2.default)(allKeys, function (config, key) {
var defaultTemplate = defaultTemplates[key];
var customTemplate = templates[key];
var isCustomTemplate = customTemplate !== undefined && customTemplate !== defaultTemplate;
config.templates[key] = isCustomTemplate ? customTemplate : defaultTemplate;
config.useCustomCompileOptions[key] = isCustomTemplate;
return config;
}, { templates: {}, useCustomCompileOptions: {} });
}
function getRefinement(state, type, attributeName, name, resultsFacets) {
var res = { type: type, attributeName: attributeName, name: name };
var facet = (0, _find2.default)(resultsFacets, { name: attributeName });
var count = void 0;
if (type === 'hierarchical') {
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
res.name = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = (0, _find2.default)(facet.data, { name: splitted[i] });
}
count = (0, _get2.default)(facet, 'count');
} else {
count = (0, _get2.default)(facet, 'data["' + res.name + '"]');
}
var exhaustive = (0, _get2.default)(facet, 'exhaustive');
if (count !== undefined) {
res.count = count;
}
if (exhaustive !== undefined) {
res.exhaustive = exhaustive;
}
return res;
}
function getRefinements(results, state) {
var res = [];
(0, _forEach2.default)(state.facetsRefinements, function (refinements, attributeName) {
(0, _forEach2.default)(refinements, function (name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
(0, _forEach2.default)(state.facetsExcludes, function (refinements, attributeName) {
(0, _forEach2.default)(refinements, function (name) {
res.push({ type: 'exclude', attributeName: attributeName, name: name, exclude: true });
});
});
(0, _forEach2.default)(state.disjunctiveFacetsRefinements, function (refinements, attributeName) {
(0, _forEach2.default)(refinements, function (name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
(0, _forEach2.default)(state.hierarchicalFacetsRefinements, function (refinements, attributeName) {
(0, _forEach2.default)(refinements, function (name) {
res.push(getRefinement(state, 'hierarchical', attributeName, name, results.hierarchicalFacets));
});
});
(0, _forEach2.default)(state.numericRefinements, function (operators, attributeName) {
(0, _forEach2.default)(operators, function (values, operator) {
(0, _forEach2.default)(values, function (value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: '' + value,
numericValue: value,
operator: operator
});
});
});
});
(0, _forEach2.default)(state.tagRefinements, function (name) {
res.push({ type: 'tag', attributeName: '_tags', name: name });
});
return res;
}
function clearRefinementsFromState(inputState, attributeNames) {
var state = inputState;
if ((0, _isEmpty2.default)(attributeNames)) {
state = state.clearTags();
state = state.clearRefinements();
return state;
}
(0, _forEach2.default)(attributeNames, function (attributeName) {
if (attributeName === '_tags') {
state = state.clearTags();
} else {
state = state.clearRefinements(attributeName);
}
});
return state;
}
function clearRefinementsAndSearch(helper, attributeNames) {
helper.setState(clearRefinementsFromState(helper.state, attributeNames)).search();
}
function prefixKeys(prefix, obj) {
if (obj) {
return (0, _mapKeys2.default)(obj, function (v, k) {
return prefix + k;
});
}
return undefined;
}
/***/ },
/* 337 */
/***/ function(module, exports, __webpack_require__) {
var baseUniq = __webpack_require__(312);
/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/
function uniq(array) {
return (array && array.length)
? baseUniq(array)
: [];
}
module.exports = uniq;
/***/ },
/* 338 */
/***/ 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;
}
}());
/***/ },
/* 339 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
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 _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; } /* eslint-disable react/no-find-dom-node */
function autoHideContainer(ComposedComponent) {
var AutoHide = function (_React$Component) {
_inherits(AutoHide, _React$Component);
function AutoHide() {
_classCallCheck(this, AutoHide);
return _possibleConstructorReturn(this, (AutoHide.__proto__ || Object.getPrototypeOf(AutoHide)).apply(this, arguments));
}
_createClass(AutoHide, [{
key: 'componentDidMount',
value: function componentDidMount() {
this._hideOrShowContainer(this.props);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.props.shouldAutoHideContainer === nextProps.shouldAutoHideContainer) {
return;
}
this._hideOrShowContainer(nextProps);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return nextProps.shouldAutoHideContainer === false;
}
}, {
key: '_hideOrShowContainer',
value: function _hideOrShowContainer(props) {
var container = _reactDom2.default.findDOMNode(this).parentNode;
container.style.display = props.shouldAutoHideContainer === true ? 'none' : '';
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(ComposedComponent, this.props);
}
}]);
return AutoHide;
}(_react2.default.Component);
// precise displayName for ease of debugging (react dev tool, react warnings)
AutoHide.displayName = ComposedComponent.name + '-AutoHide';
return AutoHide;
}
exports.default = autoHideContainer;
/***/ },
/* 340 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _get = __webpack_require__(147);
var _get2 = _interopRequireDefault(_get);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
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 _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; } // Issue with eslint + high-order components like decorators
/* eslint react/prop-types: 0 */
function headerFooter(ComposedComponent) {
var HeaderFooter = function (_React$Component) {
_inherits(HeaderFooter, _React$Component);
function HeaderFooter(props) {
_classCallCheck(this, HeaderFooter);
var _this = _possibleConstructorReturn(this, (HeaderFooter.__proto__ || Object.getPrototypeOf(HeaderFooter)).call(this, props));
_this.handleHeaderClick = _this.handleHeaderClick.bind(_this);
_this.state = {
collapsed: props.collapsible && props.collapsible.collapsed
};
_this._cssClasses = {
root: (0, _classnames2.default)('ais-root', _this.props.cssClasses.root),
body: (0, _classnames2.default)('ais-body', _this.props.cssClasses.body)
};
_this._footerElement = _this._getElement({ type: 'footer' });
return _this;
}
_createClass(HeaderFooter, [{
key: '_getElement',
value: function _getElement(_ref) {
var type = _ref.type;
var _ref$handleClick = _ref.handleClick;
var handleClick = _ref$handleClick === undefined ? null : _ref$handleClick;
var templates = this.props.templateProps.templates;
if (!templates || !templates[type]) {
return null;
}
var className = (0, _classnames2.default)(this.props.cssClasses[type], 'ais-' + type);
var templateData = (0, _get2.default)(this.props, 'headerFooterData.' + type);
return _react2.default.createElement(_Template2.default, _extends({}, this.props.templateProps, {
data: templateData,
rootProps: { className: className, onClick: handleClick },
templateKey: type,
transformData: null
}));
}
}, {
key: 'handleHeaderClick',
value: function handleHeaderClick() {
this.setState({
collapsed: !this.state.collapsed
});
}
}, {
key: 'render',
value: function render() {
var rootCssClasses = [this._cssClasses.root];
if (this.props.collapsible) {
rootCssClasses.push('ais-root__collapsible');
}
if (this.state.collapsed) {
rootCssClasses.push('ais-root__collapsed');
}
var cssClasses = _extends({}, this._cssClasses, {
root: (0, _classnames2.default)(rootCssClasses)
});
var headerElement = this._getElement({
type: 'header',
handleClick: this.props.collapsible ? this.handleHeaderClick : null
});
return _react2.default.createElement(
'div',
{ className: cssClasses.root },
headerElement,
_react2.default.createElement(
'div',
{
className: cssClasses.body
},
_react2.default.createElement(ComposedComponent, this.props)
),
this._footerElement
);
}
}]);
return HeaderFooter;
}(_react2.default.Component);
HeaderFooter.defaultProps = {
cssClasses: {},
collapsible: false
};
// precise displayName for ease of debugging (react dev tool, react warnings)
HeaderFooter.displayName = ComposedComponent.name + '-HeaderFooter';
return HeaderFooter;
}
exports.default = headerFooter;
/***/ },
/* 341 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _curry = __webpack_require__(342);
var _curry2 = _interopRequireDefault(_curry);
var _cloneDeep = __webpack_require__(343);
var _cloneDeep2 = _interopRequireDefault(_cloneDeep);
var _mapValues = __webpack_require__(308);
var _mapValues2 = _interopRequireDefault(_mapValues);
var _hogan = __webpack_require__(344);
var _hogan2 = _interopRequireDefault(_hogan);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 _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 Template = function (_React$Component) {
_inherits(Template, _React$Component);
function Template() {
_classCallCheck(this, Template);
return _possibleConstructorReturn(this, (Template.__proto__ || Object.getPrototypeOf(Template)).apply(this, arguments));
}
_createClass(Template, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return !(0, _isEqual2.default)(this.props.data, nextProps.data) || this.props.templateKey !== nextProps.templateKey;
}
}, {
key: 'render',
value: function render() {
var useCustomCompileOptions = this.props.useCustomCompileOptions[this.props.templateKey];
var compileOptions = useCustomCompileOptions ? this.props.templatesConfig.compileOptions : {};
var content = renderTemplate({
templates: this.props.templates,
templateKey: this.props.templateKey,
compileOptions: compileOptions,
helpers: this.props.templatesConfig.helpers,
data: transformData(this.props.transformData, this.props.templateKey, this.props.data)
});
if (content === null) {
// Adds a noscript to the DOM but virtual DOM is null
// See http://facebook.github.io/react/docs/component-specs.html#render
return null;
}
if (_react2.default.isValidElement(content)) {
return _react2.default.createElement(
'div',
this.props.rootProps,
content
);
}
return _react2.default.createElement('div', _extends({}, this.props.rootProps, { dangerouslySetInnerHTML: { __html: content } }));
}
}]);
return Template;
}(_react2.default.Component);
Template.defaultProps = {
data: {},
useCustomCompileOptions: {},
templates: {},
templatesConfig: {}
};
function transformData(fn, templateKey, originalData) {
if (!fn) {
return originalData;
}
var clonedData = (0, _cloneDeep2.default)(originalData);
var data = void 0;
var typeFn = typeof fn === 'undefined' ? 'undefined' : _typeof(fn);
if (typeFn === 'function') {
data = fn(clonedData);
} else if (typeFn === 'object') {
// ex: transformData: {hit, empty}
if (fn[templateKey]) {
data = fn[templateKey](clonedData);
} else {
// if the templateKey doesn't exist, just use the
// original data
data = originalData;
}
} else {
throw new Error('transformData must be a function or an object, was ' + typeFn + ' (key : ' + templateKey + ')');
}
var dataType = typeof data === 'undefined' ? 'undefined' : _typeof(data);
var expectedType = typeof originalData === 'undefined' ? 'undefined' : _typeof(originalData);
if (dataType !== expectedType) {
throw new Error('`transformData` must return a `' + expectedType + '`, got `' + dataType + '`.');
}
return data;
}
function renderTemplate(_ref) {
var templates = _ref.templates;
var templateKey = _ref.templateKey;
var compileOptions = _ref.compileOptions;
var helpers = _ref.helpers;
var data = _ref.data;
var template = templates[templateKey];
var templateType = typeof template === 'undefined' ? 'undefined' : _typeof(template);
var isTemplateString = templateType === 'string';
var isTemplateFunction = templateType === 'function';
if (!isTemplateString && !isTemplateFunction) {
throw new Error('Template must be \'string\' or \'function\', was \'' + templateType + '\' (key: ' + templateKey + ')');
} else if (isTemplateFunction) {
return template(data);
} else {
var transformedHelpers = transformHelpersToHogan(helpers, compileOptions, data);
var preparedData = _extends({}, data, { helpers: transformedHelpers });
return _hogan2.default.compile(template, compileOptions).render(preparedData);
}
}
// We add all our template helper methods to the template as lambdas. Note
// that lambdas in Mustache are supposed to accept a second argument of
// `render` to get the rendered value, not the literal `{{value}}`. But
// this is currently broken (see
// https://github.com/twitter/hogan.js/issues/222).
function transformHelpersToHogan(helpers, compileOptions, data) {
return (0, _mapValues2.default)(helpers, function (method) {
return (0, _curry2.default)(function (text) {
var _this2 = this;
var render = function render(value) {
return _hogan2.default.compile(value, compileOptions).render(_this2);
};
return method.call(data, text, render);
});
});
}
exports.default = Template;
/***/ },
/* 342 */
/***/ function(module, exports, __webpack_require__) {
var createWrap = __webpack_require__(252);
/** Used to compose bitmasks for function metadata. */
var CURRY_FLAG = 8;
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
// Assign default placeholders.
curry.placeholder = {};
module.exports = curry;
/***/ },
/* 343 */
/***/ function(module, exports, __webpack_require__) {
var baseClone = __webpack_require__(315);
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, true, true);
}
module.exports = cloneDeep;
/***/ },
/* 344 */
/***/ function(module, exports, __webpack_require__) {
/*
* Copyright 2011 Twitter, Inc.
* 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.
*/
// This file is for use with Node.js. See dist/ for browser files.
var Hogan = __webpack_require__(345);
Hogan.Template = __webpack_require__(346).Template;
Hogan.template = Hogan.Template;
module.exports = Hogan;
/***/ },
/* 345 */
/***/ function(module, exports, __webpack_require__) {
/*
* Copyright 2011 Twitter, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function (Hogan) {
// Setup regex assignments
// remove whitespace according to Mustache spec
var rIsWhitespace = /\S/,
rQuot = /\"/g,
rNewline = /\n/g,
rCr = /\r/g,
rSlash = /\\/g,
rLineSep = /\u2028/,
rParagraphSep = /\u2029/;
Hogan.tags = {
'#': 1, '^': 2, '<': 3, '$': 4,
'/': 5, '!': 6, '>': 7, '=': 8, '_v': 9,
'{': 10, '&': 11, '_t': 12
};
Hogan.scan = function scan(text, delimiters) {
var len = text.length,
IN_TEXT = 0,
IN_TAG_TYPE = 1,
IN_TAG = 2,
state = IN_TEXT,
tagType = null,
tag = null,
buf = '',
tokens = [],
seenTag = false,
i = 0,
lineStart = 0,
otag = '{{',
ctag = '}}';
function addBuf() {
if (buf.length > 0) {
tokens.push({tag: '_t', text: new String(buf)});
buf = '';
}
}
function lineIsWhitespace() {
var isAllWhitespace = true;
for (var j = lineStart; j < tokens.length; j++) {
isAllWhitespace =
(Hogan.tags[tokens[j].tag] < Hogan.tags['_v']) ||
(tokens[j].tag == '_t' && tokens[j].text.match(rIsWhitespace) === null);
if (!isAllWhitespace) {
return false;
}
}
return isAllWhitespace;
}
function filterLine(haveSeenTag, noNewLine) {
addBuf();
if (haveSeenTag && lineIsWhitespace()) {
for (var j = lineStart, next; j < tokens.length; j++) {
if (tokens[j].text) {
if ((next = tokens[j+1]) && next.tag == '>') {
// set indent to token value
next.indent = tokens[j].text.toString()
}
tokens.splice(j, 1);
}
}
} else if (!noNewLine) {
tokens.push({tag:'\n'});
}
seenTag = false;
lineStart = tokens.length;
}
function changeDelimiters(text, index) {
var close = '=' + ctag,
closeIndex = text.indexOf(close, index),
delimiters = trim(
text.substring(text.indexOf('=', index) + 1, closeIndex)
).split(' ');
otag = delimiters[0];
ctag = delimiters[delimiters.length - 1];
return closeIndex + close.length - 1;
}
if (delimiters) {
delimiters = delimiters.split(' ');
otag = delimiters[0];
ctag = delimiters[1];
}
for (i = 0; i < len; i++) {
if (state == IN_TEXT) {
if (tagChange(otag, text, i)) {
--i;
addBuf();
state = IN_TAG_TYPE;
} else {
if (text.charAt(i) == '\n') {
filterLine(seenTag);
} else {
buf += text.charAt(i);
}
}
} else if (state == IN_TAG_TYPE) {
i += otag.length - 1;
tag = Hogan.tags[text.charAt(i + 1)];
tagType = tag ? text.charAt(i + 1) : '_v';
if (tagType == '=') {
i = changeDelimiters(text, i);
state = IN_TEXT;
} else {
if (tag) {
i++;
}
state = IN_TAG;
}
seenTag = i;
} else {
if (tagChange(ctag, text, i)) {
tokens.push({tag: tagType, n: trim(buf), otag: otag, ctag: ctag,
i: (tagType == '/') ? seenTag - otag.length : i + ctag.length});
buf = '';
i += ctag.length - 1;
state = IN_TEXT;
if (tagType == '{') {
if (ctag == '}}') {
i++;
} else {
cleanTripleStache(tokens[tokens.length - 1]);
}
}
} else {
buf += text.charAt(i);
}
}
}
filterLine(seenTag, true);
return tokens;
}
function cleanTripleStache(token) {
if (token.n.substr(token.n.length - 1) === '}') {
token.n = token.n.substring(0, token.n.length - 1);
}
}
function trim(s) {
if (s.trim) {
return s.trim();
}
return s.replace(/^\s*|\s*$/g, '');
}
function tagChange(tag, text, index) {
if (text.charAt(index) != tag.charAt(0)) {
return false;
}
for (var i = 1, l = tag.length; i < l; i++) {
if (text.charAt(index + i) != tag.charAt(i)) {
return false;
}
}
return true;
}
// the tags allowed inside super templates
var allowedInSuper = {'_t': true, '\n': true, '$': true, '/': true};
function buildTree(tokens, kind, stack, customTags) {
var instructions = [],
opener = null,
tail = null,
token = null;
tail = stack[stack.length - 1];
while (tokens.length > 0) {
token = tokens.shift();
if (tail && tail.tag == '<' && !(token.tag in allowedInSuper)) {
throw new Error('Illegal content in < super tag.');
}
if (Hogan.tags[token.tag] <= Hogan.tags['$'] || isOpener(token, customTags)) {
stack.push(token);
token.nodes = buildTree(tokens, token.tag, stack, customTags);
} else if (token.tag == '/') {
if (stack.length === 0) {
throw new Error('Closing tag without opener: /' + token.n);
}
opener = stack.pop();
if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) {
throw new Error('Nesting error: ' + opener.n + ' vs. ' + token.n);
}
opener.end = token.i;
return instructions;
} else if (token.tag == '\n') {
token.last = (tokens.length == 0) || (tokens[0].tag == '\n');
}
instructions.push(token);
}
if (stack.length > 0) {
throw new Error('missing closing tag: ' + stack.pop().n);
}
return instructions;
}
function isOpener(token, tags) {
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].o == token.n) {
token.tag = '#';
return true;
}
}
}
function isCloser(close, open, tags) {
for (var i = 0, l = tags.length; i < l; i++) {
if (tags[i].c == close && tags[i].o == open) {
return true;
}
}
}
function stringifySubstitutions(obj) {
var items = [];
for (var key in obj) {
items.push('"' + esc(key) + '": function(c,p,t,i) {' + obj[key] + '}');
}
return "{ " + items.join(",") + " }";
}
function stringifyPartials(codeObj) {
var partials = [];
for (var key in codeObj.partials) {
partials.push('"' + esc(key) + '":{name:"' + esc(codeObj.partials[key].name) + '", ' + stringifyPartials(codeObj.partials[key]) + "}");
}
return "partials: {" + partials.join(",") + "}, subs: " + stringifySubstitutions(codeObj.subs);
}
Hogan.stringify = function(codeObj, text, options) {
return "{code: function (c,p,i) { " + Hogan.wrapMain(codeObj.code) + " }," + stringifyPartials(codeObj) + "}";
}
var serialNo = 0;
Hogan.generate = function(tree, text, options) {
serialNo = 0;
var context = { code: '', subs: {}, partials: {} };
Hogan.walk(tree, context);
if (options.asString) {
return this.stringify(context, text, options);
}
return this.makeTemplate(context, text, options);
}
Hogan.wrapMain = function(code) {
return 'var t=this;t.b(i=i||"");' + code + 'return t.fl();';
}
Hogan.template = Hogan.Template;
Hogan.makeTemplate = function(codeObj, text, options) {
var template = this.makePartials(codeObj);
template.code = new Function('c', 'p', 'i', this.wrapMain(codeObj.code));
return new this.template(template, text, this, options);
}
Hogan.makePartials = function(codeObj) {
var key, template = {subs: {}, partials: codeObj.partials, name: codeObj.name};
for (key in template.partials) {
template.partials[key] = this.makePartials(template.partials[key]);
}
for (key in codeObj.subs) {
template.subs[key] = new Function('c', 'p', 't', 'i', codeObj.subs[key]);
}
return template;
}
function esc(s) {
return s.replace(rSlash, '\\\\')
.replace(rQuot, '\\\"')
.replace(rNewline, '\\n')
.replace(rCr, '\\r')
.replace(rLineSep, '\\u2028')
.replace(rParagraphSep, '\\u2029');
}
function chooseMethod(s) {
return (~s.indexOf('.')) ? 'd' : 'f';
}
function createPartial(node, context) {
var prefix = "<" + (context.prefix || "");
var sym = prefix + node.n + serialNo++;
context.partials[sym] = {name: node.n, partials: {}};
context.code += 't.b(t.rp("' + esc(sym) + '",c,p,"' + (node.indent || '') + '"));';
return sym;
}
Hogan.codegen = {
'#': function(node, context) {
context.code += 'if(t.s(t.' + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,1),' +
'c,p,0,' + node.i + ',' + node.end + ',"' + node.otag + " " + node.ctag + '")){' +
't.rs(c,p,' + 'function(c,p,t){';
Hogan.walk(node.nodes, context);
context.code += '});c.pop();}';
},
'^': function(node, context) {
context.code += 'if(!t.s(t.' + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,1),c,p,1,0,0,"")){';
Hogan.walk(node.nodes, context);
context.code += '};';
},
'>': createPartial,
'<': function(node, context) {
var ctx = {partials: {}, code: '', subs: {}, inPartial: true};
Hogan.walk(node.nodes, ctx);
var template = context.partials[createPartial(node, context)];
template.subs = ctx.subs;
template.partials = ctx.partials;
},
'$': function(node, context) {
var ctx = {subs: {}, code: '', partials: context.partials, prefix: node.n};
Hogan.walk(node.nodes, ctx);
context.subs[node.n] = ctx.code;
if (!context.inPartial) {
context.code += 't.sub("' + esc(node.n) + '",c,p,i);';
}
},
'\n': function(node, context) {
context.code += write('"\\n"' + (node.last ? '' : ' + i'));
},
'_v': function(node, context) {
context.code += 't.b(t.v(t.' + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,0)));';
},
'_t': function(node, context) {
context.code += write('"' + esc(node.text) + '"');
},
'{': tripleStache,
'&': tripleStache
}
function tripleStache(node, context) {
context.code += 't.b(t.t(t.' + chooseMethod(node.n) + '("' + esc(node.n) + '",c,p,0)));';
}
function write(s) {
return 't.b(' + s + ');';
}
Hogan.walk = function(nodelist, context) {
var func;
for (var i = 0, l = nodelist.length; i < l; i++) {
func = Hogan.codegen[nodelist[i].tag];
func && func(nodelist[i], context);
}
return context;
}
Hogan.parse = function(tokens, text, options) {
options = options || {};
return buildTree(tokens, '', [], options.sectionTags || []);
}
Hogan.cache = {};
Hogan.cacheKey = function(text, options) {
return [text, !!options.asString, !!options.disableLambda, options.delimiters, !!options.modelGet].join('||');
}
Hogan.compile = function(text, options) {
options = options || {};
var key = Hogan.cacheKey(text, options);
var template = this.cache[key];
if (template) {
var partials = template.partials;
for (var name in partials) {
delete partials[name].instance;
}
return template;
}
template = this.generate(this.parse(this.scan(text, options.delimiters), text, options), text, options);
return this.cache[key] = template;
}
})( true ? exports : Hogan);
/***/ },
/* 346 */
/***/ function(module, exports, __webpack_require__) {
/*
* Copyright 2011 Twitter, Inc.
* 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.
*/
var Hogan = {};
(function (Hogan) {
Hogan.Template = function (codeObj, text, compiler, options) {
codeObj = codeObj || {};
this.r = codeObj.code || this.r;
this.c = compiler;
this.options = options || {};
this.text = text || '';
this.partials = codeObj.partials || {};
this.subs = codeObj.subs || {};
this.buf = '';
}
Hogan.Template.prototype = {
// render: replaced by generated code.
r: function (context, partials, indent) { return ''; },
// variable escaping
v: hoganEscape,
// triple stache
t: coerceToString,
render: function render(context, partials, indent) {
return this.ri([context], partials || {}, indent);
},
// render internal -- a hook for overrides that catches partials too
ri: function (context, partials, indent) {
return this.r(context, partials, indent);
},
// ensurePartial
ep: function(symbol, partials) {
var partial = this.partials[symbol];
// check to see that if we've instantiated this partial before
var template = partials[partial.name];
if (partial.instance && partial.base == template) {
return partial.instance;
}
if (typeof template == 'string') {
if (!this.c) {
throw new Error("No compiler available.");
}
template = this.c.compile(template, this.options);
}
if (!template) {
return null;
}
// We use this to check whether the partials dictionary has changed
this.partials[symbol].base = template;
if (partial.subs) {
// Make sure we consider parent template now
if (!partials.stackText) partials.stackText = {};
for (key in partial.subs) {
if (!partials.stackText[key]) {
partials.stackText[key] = (this.activeSub !== undefined && partials.stackText[this.activeSub]) ? partials.stackText[this.activeSub] : this.text;
}
}
template = createSpecializedPartial(template, partial.subs, partial.partials,
this.stackSubs, this.stackPartials, partials.stackText);
}
this.partials[symbol].instance = template;
return template;
},
// tries to find a partial in the current scope and render it
rp: function(symbol, context, partials, indent) {
var partial = this.ep(symbol, partials);
if (!partial) {
return '';
}
return partial.ri(context, partials, indent);
},
// render a section
rs: function(context, partials, section) {
var tail = context[context.length - 1];
if (!isArray(tail)) {
section(context, partials, this);
return;
}
for (var i = 0; i < tail.length; i++) {
context.push(tail[i]);
section(context, partials, this);
context.pop();
}
},
// maybe start a section
s: function(val, ctx, partials, inverted, start, end, tags) {
var pass;
if (isArray(val) && val.length === 0) {
return false;
}
if (typeof val == 'function') {
val = this.ms(val, ctx, partials, inverted, start, end, tags);
}
pass = !!val;
if (!inverted && pass && ctx) {
ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]);
}
return pass;
},
// find values with dotted names
d: function(key, ctx, partials, returnFound) {
var found,
names = key.split('.'),
val = this.f(names[0], ctx, partials, returnFound),
doModelGet = this.options.modelGet,
cx = null;
if (key === '.' && isArray(ctx[ctx.length - 2])) {
val = ctx[ctx.length - 1];
} else {
for (var i = 1; i < names.length; i++) {
found = findInScope(names[i], val, doModelGet);
if (found !== undefined) {
cx = val;
val = found;
} else {
val = '';
}
}
}
if (returnFound && !val) {
return false;
}
if (!returnFound && typeof val == 'function') {
ctx.push(cx);
val = this.mv(val, ctx, partials);
ctx.pop();
}
return val;
},
// find values with normal names
f: function(key, ctx, partials, returnFound) {
var val = false,
v = null,
found = false,
doModelGet = this.options.modelGet;
for (var i = ctx.length - 1; i >= 0; i--) {
v = ctx[i];
val = findInScope(key, v, doModelGet);
if (val !== undefined) {
found = true;
break;
}
}
if (!found) {
return (returnFound) ? false : "";
}
if (!returnFound && typeof val == 'function') {
val = this.mv(val, ctx, partials);
}
return val;
},
// higher order templates
ls: function(func, cx, partials, text, tags) {
var oldTags = this.options.delimiters;
this.options.delimiters = tags;
this.b(this.ct(coerceToString(func.call(cx, text)), cx, partials));
this.options.delimiters = oldTags;
return false;
},
// compile text
ct: function(text, cx, partials) {
if (this.options.disableLambda) {
throw new Error('Lambda features disabled.');
}
return this.c.compile(text, this.options).render(cx, partials);
},
// template result buffering
b: function(s) { this.buf += s; },
fl: function() { var r = this.buf; this.buf = ''; return r; },
// method replace section
ms: function(func, ctx, partials, inverted, start, end, tags) {
var textSource,
cx = ctx[ctx.length - 1],
result = func.call(cx);
if (typeof result == 'function') {
if (inverted) {
return true;
} else {
textSource = (this.activeSub && this.subsText && this.subsText[this.activeSub]) ? this.subsText[this.activeSub] : this.text;
return this.ls(result, cx, partials, textSource.substring(start, end), tags);
}
}
return result;
},
// method replace variable
mv: function(func, ctx, partials) {
var cx = ctx[ctx.length - 1];
var result = func.call(cx);
if (typeof result == 'function') {
return this.ct(coerceToString(result.call(cx)), cx, partials);
}
return result;
},
sub: function(name, context, partials, indent) {
var f = this.subs[name];
if (f) {
this.activeSub = name;
f(context, partials, this, indent);
this.activeSub = false;
}
}
};
//Find a key in an object
function findInScope(key, scope, doModelGet) {
var val;
if (scope && typeof scope == 'object') {
if (scope[key] !== undefined) {
val = scope[key];
// try lookup with get for backbone or similar model data
} else if (doModelGet && scope.get && typeof scope.get == 'function') {
val = scope.get(key);
}
}
return val;
}
function createSpecializedPartial(instance, subs, partials, stackSubs, stackPartials, stackText) {
function PartialTemplate() {};
PartialTemplate.prototype = instance;
function Substitutions() {};
Substitutions.prototype = instance.subs;
var key;
var partial = new PartialTemplate();
partial.subs = new Substitutions();
partial.subsText = {}; //hehe. substext.
partial.buf = '';
stackSubs = stackSubs || {};
partial.stackSubs = stackSubs;
partial.subsText = stackText;
for (key in subs) {
if (!stackSubs[key]) stackSubs[key] = subs[key];
}
for (key in stackSubs) {
partial.subs[key] = stackSubs[key];
}
stackPartials = stackPartials || {};
partial.stackPartials = stackPartials;
for (key in partials) {
if (!stackPartials[key]) stackPartials[key] = partials[key];
}
for (key in stackPartials) {
partial.partials[key] = stackPartials[key];
}
return partial;
}
var rAmp = /&/g,
rLt = /</g,
rGt = />/g,
rApos = /\'/g,
rQuot = /\"/g,
hChars = /[&<>\"\']/;
function coerceToString(val) {
return String((val === null || val === undefined) ? '' : val);
}
function hoganEscape(str) {
str = coerceToString(str);
return hChars.test(str) ?
str
.replace(rAmp, '&')
.replace(rLt, '<')
.replace(rGt, '>')
.replace(rApos, ''')
.replace(rQuot, '"') :
str;
}
var isArray = Array.isArray || function(a) {
return Object.prototype.toString.call(a) === '[object Array]';
};
})( true ? exports : Hogan);
/***/ },
/* 347 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
header: '',
link: 'Clear all',
footer: ''
};
/***/ },
/* 348 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
var _utils = __webpack_require__(336);
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 _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 ClearAll = function (_React$Component) {
_inherits(ClearAll, _React$Component);
function ClearAll() {
_classCallCheck(this, ClearAll);
return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments));
}
_createClass(ClearAll, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.handleClick = this.handleClick.bind(this);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.url !== nextProps.url || this.props.hasRefinements !== nextProps.hasRefinements;
}
}, {
key: 'handleClick',
value: function handleClick(e) {
if ((0, _utils.isSpecialClick)(e)) {
// do not alter the default browser behavior
// if one special key is down
return;
}
e.preventDefault();
this.props.clearAll();
}
}, {
key: 'render',
value: function render() {
var data = {
hasRefinements: this.props.hasRefinements
};
return _react2.default.createElement(
'a',
{
className: this.props.cssClasses.link,
href: this.props.url,
onClick: this.handleClick
},
_react2.default.createElement(_Template2.default, _extends({
data: data,
templateKey: 'link'
}, this.props.templateProps))
);
}
}]);
return ClearAll;
}(_react2.default.Component);
exports.default = ClearAll;
/***/ },
/* 349 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _isUndefined = __webpack_require__(203);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isBoolean = __webpack_require__(350);
var _isBoolean2 = _interopRequireDefault(_isBoolean);
var _isString = __webpack_require__(204);
var _isString2 = _interopRequireDefault(_isString);
var _isArray = __webpack_require__(41);
var _isArray2 = _interopRequireDefault(_isArray);
var _isPlainObject = __webpack_require__(234);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _isFunction = __webpack_require__(58);
var _isFunction2 = _interopRequireDefault(_isFunction);
var _isEmpty = __webpack_require__(201);
var _isEmpty2 = _interopRequireDefault(_isEmpty);
var _map = __webpack_require__(171);
var _map2 = _interopRequireDefault(_map);
var _reduce = __webpack_require__(173);
var _reduce2 = _interopRequireDefault(_reduce);
var _filter = __webpack_require__(168);
var _filter2 = _interopRequireDefault(_filter);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _defaultTemplates = __webpack_require__(351);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _CurrentRefinedValues = __webpack_require__(352);
var _CurrentRefinedValues2 = _interopRequireDefault(_CurrentRefinedValues);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-current-refined-values');
/**
* Instantiate a list of current refinements with the possibility to clear them
* @function currentRefinedValues
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {Array} [option.attributes] Attributes configuration
* @param {string} [option.attributes[].name] Required attribute name
* @param {string} [option.attributes[].label] Attribute label (passed to the item template)
* @param {string|Function} [option.attributes[].template] Attribute specific template
* @param {Function} [option.attributes[].transformData] Attribute specific transformData
* @param {boolean|string} [option.clearAll='before'] Clear all position (one of ('before', 'after', false))
* @param {boolean} [options.onlyListedAttributes=false] Only use declared attributes
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template
* @param {string|Function} [options.templates.item] Item template
* @param {string|Function} [options.templates.clearAll] Clear all template
* @param {string|Function} [options.templates.footer] Footer template
* @param {Function} [options.transformData.item] Function to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when no current refinements
* @param {Object} [options.cssClasses] CSS classes to be added
* @param {string} [options.cssClasses.root] CSS classes added to the root element
* @param {string} [options.cssClasses.header] CSS classes added to the header element
* @param {string} [options.cssClasses.body] CSS classes added to the body element
* @param {string} [options.cssClasses.clearAll] CSS classes added to the clearAll element
* @param {string} [options.cssClasses.list] CSS classes added to the list element
* @param {string} [options.cssClasses.item] CSS classes added to the item element
* @param {string} [options.cssClasses.link] CSS classes added to the link element
* @param {string} [options.cssClasses.count] CSS classes added to the count element
* @param {string} [options.cssClasses.footer] CSS classes added to the footer element
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\ncurrentRefinedValues({\n container,\n [ attributes: [{name[, label, template, transformData]}] ],\n [ onlyListedAttributes = false ],\n [ clearAll = \'before\' ] // One of [\'before\', \'after\', false]\n [ templates.{header,item,clearAll,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer = true ],\n [ cssClasses.{root, header, body, clearAll, list, item, link, count, footer} = {} ],\n [ collapsible=false ]\n})';
function currentRefinedValues(_ref) {
var container = _ref.container;
var _ref$attributes = _ref.attributes;
var attributes = _ref$attributes === undefined ? [] : _ref$attributes;
var _ref$onlyListedAttrib = _ref.onlyListedAttributes;
var onlyListedAttributes = _ref$onlyListedAttrib === undefined ? false : _ref$onlyListedAttrib;
var _ref$clearAll = _ref.clearAll;
var clearAll = _ref$clearAll === undefined ? 'before' : _ref$clearAll;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var attributesOK = (0, _isArray2.default)(attributes) && (0, _reduce2.default)(attributes, function (res, val) {
return res && (0, _isPlainObject2.default)(val) && (0, _isString2.default)(val.name) && ((0, _isUndefined2.default)(val.label) || (0, _isString2.default)(val.label)) && ((0, _isUndefined2.default)(val.template) || (0, _isString2.default)(val.template) || (0, _isFunction2.default)(val.template)) && ((0, _isUndefined2.default)(val.transformData) || (0, _isFunction2.default)(val.transformData));
}, true);
var templatesKeys = ['header', 'item', 'clearAll', 'footer'];
var templatesOK = (0, _isPlainObject2.default)(templates) && (0, _reduce2.default)(templates, function (res, val, key) {
return res && templatesKeys.indexOf(key) !== -1 && ((0, _isString2.default)(val) || (0, _isFunction2.default)(val));
}, true);
var userCssClassesKeys = ['root', 'header', 'body', 'clearAll', 'list', 'item', 'link', 'count', 'footer'];
var userCssClassesOK = (0, _isPlainObject2.default)(userCssClasses) && (0, _reduce2.default)(userCssClasses, function (res, val, key) {
return res && userCssClassesKeys.indexOf(key) !== -1 && (0, _isString2.default)(val) || (0, _isArray2.default)(val);
}, true);
var transformDataOK = (0, _isUndefined2.default)(transformData) || (0, _isFunction2.default)(transformData) || (0, _isPlainObject2.default)(transformData) && (0, _isFunction2.default)(transformData.item);
var showUsage = false || !((0, _isString2.default)(container) || (0, _utils.isDomElement)(container)) || !(0, _isArray2.default)(attributes) || !attributesOK || !(0, _isBoolean2.default)(onlyListedAttributes) || [false, 'before', 'after'].indexOf(clearAll) === -1 || !(0, _isPlainObject2.default)(templates) || !templatesOK || !transformDataOK || !(0, _isBoolean2.default)(autoHideContainer) || !userCssClassesOK;
if (showUsage) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var CurrentRefinedValues = (0, _headerFooter2.default)(_CurrentRefinedValues2.default);
if (autoHideContainer === true) {
CurrentRefinedValues = (0, _autoHideContainer2.default)(CurrentRefinedValues);
}
var attributeNames = (0, _map2.default)(attributes, function (attribute) {
return attribute.name;
});
var restrictedTo = onlyListedAttributes ? attributeNames : [];
var attributesObj = (0, _reduce2.default)(attributes, function (res, attribute) {
res[attribute.name] = attribute;
return res;
}, {});
return {
init: function init(_ref2) {
var helper = _ref2.helper;
this._clearRefinementsAndSearch = _utils.clearRefinementsAndSearch.bind(null, helper, restrictedTo);
},
render: function render(_ref3) {
var results = _ref3.results;
var helper = _ref3.helper;
var state = _ref3.state;
var templatesConfig = _ref3.templatesConfig;
var createURL = _ref3.createURL;
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
clearAll: (0, _classnames2.default)(bem('clear-all'), userCssClasses.clearAll),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link),
count: (0, _classnames2.default)(bem('count'), userCssClasses.count),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer)
};
var templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
var clearAllURL = createURL((0, _utils.clearRefinementsFromState)(state, restrictedTo));
var refinements = getFilteredRefinements(results, state, attributeNames, onlyListedAttributes);
var clearRefinementURLs = refinements.map(function (refinement) {
return createURL(clearRefinementFromState(state, refinement));
});
var clearRefinementClicks = refinements.map(function (refinement) {
return clearRefinement.bind(null, helper, refinement);
});
var shouldAutoHideContainer = refinements.length === 0;
_reactDom2.default.render(_react2.default.createElement(CurrentRefinedValues, {
attributes: attributesObj,
clearAllClick: this._clearRefinementsAndSearch,
clearAllPosition: clearAll,
clearAllURL: clearAllURL,
clearRefinementClicks: clearRefinementClicks,
clearRefinementURLs: clearRefinementURLs,
collapsible: collapsible,
cssClasses: cssClasses,
refinements: refinements,
shouldAutoHideContainer: shouldAutoHideContainer,
templateProps: templateProps
}), containerNode);
}
};
}
function getRestrictedIndexForSort(attributeNames, otherAttributeNames, attributeName) {
var idx = attributeNames.indexOf(attributeName);
if (idx !== -1) {
return idx;
}
return attributeNames.length + otherAttributeNames.indexOf(attributeName);
}
function compareRefinements(attributeNames, otherAttributeNames, a, b) {
var idxa = getRestrictedIndexForSort(attributeNames, otherAttributeNames, a.attributeName);
var idxb = getRestrictedIndexForSort(attributeNames, otherAttributeNames, b.attributeName);
if (idxa === idxb) {
if (a.name === b.name) {
return 0;
}
return a.name < b.name ? -1 : 1;
}
return idxa < idxb ? -1 : 1;
}
function getFilteredRefinements(results, state, attributeNames, onlyListedAttributes) {
var refinements = (0, _utils.getRefinements)(results, state);
var otherAttributeNames = (0, _reduce2.default)(refinements, function (res, refinement) {
if (attributeNames.indexOf(refinement.attributeName) === -1 && res.indexOf(refinement.attributeName === -1)) {
res.push(refinement.attributeName);
}
return res;
}, []);
refinements = refinements.sort(compareRefinements.bind(null, attributeNames, otherAttributeNames));
if (onlyListedAttributes && !(0, _isEmpty2.default)(attributeNames)) {
refinements = (0, _filter2.default)(refinements, function (refinement) {
return attributeNames.indexOf(refinement.attributeName) !== -1;
});
}
return refinements;
}
function clearRefinementFromState(state, refinement) {
switch (refinement.type) {
case 'facet':
return state.removeFacetRefinement(refinement.attributeName, refinement.name);
case 'disjunctive':
return state.removeDisjunctiveFacetRefinement(refinement.attributeName, refinement.name);
case 'hierarchical':
return state.clearRefinements(refinement.attributeName);
case 'exclude':
return state.removeExcludeRefinement(refinement.attributeName, refinement.name);
case 'numeric':
return state.removeNumericRefinement(refinement.attributeName, refinement.operator, refinement.numericValue);
case 'tag':
return state.removeTagRefinement(refinement.name);
default:
throw new Error('clearRefinement: type ' + refinement.type + ' is not handled');
}
}
function clearRefinement(helper, refinement) {
helper.setState(clearRefinementFromState(helper.state, refinement)).search();
}
exports.default = currentRefinedValues;
/***/ },
/* 350 */
/***/ function(module, exports, __webpack_require__) {
var isObjectLike = __webpack_require__(40);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && objectToString.call(value) == boolTag);
}
module.exports = isBoolean;
/***/ },
/* 351 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
header: '',
item: '' + '{{#label}}' + '{{label}}' + '{{^operator}}:{{/operator}}' + ' ' + '{{/label}}' + '{{#operator}}{{{displayOperator}}} {{/operator}}' + '{{#exclude}}-{{/exclude}}' + '{{name}} <span class="{{cssClasses.count}}">{{count}}</span>',
clearAll: 'Clear all',
footer: ''
};
/***/ },
/* 352 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
var _utils = __webpack_require__(336);
var _map = __webpack_require__(171);
var _map2 = _interopRequireDefault(_map);
var _cloneDeep = __webpack_require__(343);
var _cloneDeep2 = _interopRequireDefault(_cloneDeep);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 _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 CurrentRefinedValues = function (_React$Component) {
_inherits(CurrentRefinedValues, _React$Component);
function CurrentRefinedValues() {
_classCallCheck(this, CurrentRefinedValues);
return _possibleConstructorReturn(this, (CurrentRefinedValues.__proto__ || Object.getPrototypeOf(CurrentRefinedValues)).apply(this, arguments));
}
_createClass(CurrentRefinedValues, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return !(0, _isEqual2.default)(this.props.refinements, nextProps.refinements);
}
}, {
key: '_clearAllElement',
value: function _clearAllElement(position, requestedPosition) {
if (requestedPosition !== position) {
return undefined;
}
return _react2.default.createElement(
'a',
{
className: this.props.cssClasses.clearAll,
href: this.props.clearAllURL,
onClick: handleClick(this.props.clearAllClick)
},
_react2.default.createElement(_Template2.default, _extends({ templateKey: 'clearAll' }, this.props.templateProps))
);
}
}, {
key: '_refinementElement',
value: function _refinementElement(refinement, i) {
var attribute = this.props.attributes[refinement.attributeName] || {};
var templateData = getTemplateData(attribute, refinement, this.props.cssClasses);
var customTemplateProps = getCustomTemplateProps(attribute);
var key = refinement.attributeName + (refinement.operator ? refinement.operator : ':') + (refinement.exclude ? refinement.exclude : '') + refinement.name;
return _react2.default.createElement(
'div',
{
className: this.props.cssClasses.item,
key: key
},
_react2.default.createElement(
'a',
{
className: this.props.cssClasses.link,
href: this.props.clearRefinementURLs[i],
onClick: handleClick(this.props.clearRefinementClicks[i])
},
_react2.default.createElement(_Template2.default, _extends({ data: templateData, templateKey: 'item' }, this.props.templateProps, customTemplateProps))
)
);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
null,
this._clearAllElement('before', this.props.clearAllPosition),
_react2.default.createElement(
'div',
{ className: this.props.cssClasses.list },
(0, _map2.default)(this.props.refinements, this._refinementElement.bind(this))
),
this._clearAllElement('after', this.props.clearAllPosition)
);
}
}]);
return CurrentRefinedValues;
}(_react2.default.Component);
function getCustomTemplateProps(attribute) {
var customTemplateProps = {};
if (attribute.template !== undefined) {
customTemplateProps.templates = {
item: attribute.template
};
}
if (attribute.transformData !== undefined) {
customTemplateProps.transformData = attribute.transformData;
}
return customTemplateProps;
}
function getTemplateData(attribute, _refinement, cssClasses) {
var templateData = (0, _cloneDeep2.default)(_refinement);
templateData.cssClasses = cssClasses;
if (attribute.label !== undefined) {
templateData.label = attribute.label;
}
if (templateData.operator !== undefined) {
templateData.displayOperator = templateData.operator;
if (templateData.operator === '>=') {
templateData.displayOperator = '≥';
}
if (templateData.operator === '<=') {
templateData.displayOperator = '≤';
}
}
return templateData;
}
function handleClick(cb) {
return function (e) {
if ((0, _utils.isSpecialClick)(e)) {
// do not alter the default browser behavior
// if one special key is down
return;
}
e.preventDefault();
cb();
};
}
exports.default = CurrentRefinedValues;
/***/ },
/* 353 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _defaultTemplates = __webpack_require__(354);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _RefinementList = __webpack_require__(355);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-hierarchical-menu');
/**
* Create a hierarchical menu using multiple attributes
* @function hierarchicalMenu
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string[]} options.attributes Array of attributes to use to generate the hierarchy of the menu.
* See the example for the convention to follow.
* @param {string} [options.separator=' > '] Separator used in the attributes to separate level values.
* @param {string} [options.rootPath] Prefix path to use if the first level is not the root level.
* @param {string} [options.showParentLevel=false] Show the parent level of the current refined value
* @param {number} [options.limit=10] How much facet values to get
* @param {string[]|Function} [options.sortBy=['name:asc']] How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header=''] Header template (root level only)
* @param {string|Function} [options.templates.item] Item template, provided with `name`, `count`, `isRefined`, `url` data properties
* @param {string|Function} [options.templates.footer=''] Footer template (root level only)
* @param {Function} [options.transformData.item] Method to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when there are no items in the menu
* @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.depth] CSS class to add to each item element to denote its depth. The actual level will be appended to the given class name (ie. if `depth` is given, the widget will add `depth0`, `depth1`, ... according to the level of each item).
* @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element
* @param {string|string[]} [options.cssClasses.link] CSS class to add to each link (when using the default template)
* @param {string|string[]} [options.cssClasses.count] CSS class to add to each count element (when using the default template)
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\nhierarchicalMenu({\n container,\n attributes,\n [ separator=\' > \' ],\n [ rootPath ],\n [ showParentLevel=true ],\n [ limit=10 ],\n [ sortBy=[\'name:asc\'] ],\n [ cssClasses.{root , header, body, footer, list, depth, item, active, link}={} ],\n [ templates.{header, item, footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})';
function hierarchicalMenu() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var attributes = _ref.attributes;
var _ref$separator = _ref.separator;
var separator = _ref$separator === undefined ? ' > ' : _ref$separator;
var _ref$rootPath = _ref.rootPath;
var rootPath = _ref$rootPath === undefined ? null : _ref$rootPath;
var _ref$showParentLevel = _ref.showParentLevel;
var showParentLevel = _ref$showParentLevel === undefined ? true : _ref$showParentLevel;
var _ref$limit = _ref.limit;
var limit = _ref$limit === undefined ? 10 : _ref$limit;
var _ref$sortBy = _ref.sortBy;
var sortBy = _ref$sortBy === undefined ? ['name:asc'] : _ref$sortBy;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
if (!container || !attributes || !attributes.length) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var RefinementList = (0, _headerFooter2.default)(_RefinementList2.default);
if (autoHideContainer === true) {
RefinementList = (0, _autoHideContainer2.default)(RefinementList);
}
// we need to provide a hierarchicalFacet name for the search state
// so that we can always map $hierarchicalFacetName => real attributes
// we use the first attribute name
var hierarchicalFacetName = attributes[0];
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
depth: bem('list', 'lvl'),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link),
count: (0, _classnames2.default)(bem('count'), userCssClasses.count)
};
return {
getConfiguration: function getConfiguration(currentConfiguration) {
return {
hierarchicalFacets: [{
name: hierarchicalFacetName,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}],
maxValuesPerFacet: currentConfiguration.maxValuesPerFacet !== undefined ? Math.max(currentConfiguration.maxValuesPerFacet, limit) : limit
};
},
init: function init(_ref2) {
var helper = _ref2.helper;
var templatesConfig = _ref2.templatesConfig;
this._toggleRefinement = function (facetValue) {
return helper.toggleRefinement(hierarchicalFacetName, facetValue).search();
};
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
},
_prepareFacetValues: function _prepareFacetValues(facetValues, state) {
var _this = this;
return facetValues.slice(0, limit).map(function (subValue) {
if (Array.isArray(subValue.data)) {
subValue.data = _this._prepareFacetValues(subValue.data, state);
}
return subValue;
});
},
render: function render(_ref3) {
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var facetValues = results.getFacetValues(hierarchicalFacetName, { sortBy: sortBy }).data || [];
facetValues = this._prepareFacetValues(facetValues, state);
// Bind createURL to this specific attribute
function _createURL(facetValue) {
return createURL(state.toggleRefinement(hierarchicalFacetName, facetValue));
}
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
attributeNameKey: 'path',
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: facetValues,
shouldAutoHideContainer: facetValues.length === 0,
templateProps: this._templateProps,
toggleRefinement: this._toggleRefinement
}), containerNode);
}
};
}
exports.default = hierarchicalMenu;
/***/ },
/* 354 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint-disable max-len */
exports.default = {
header: '',
item: '<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span></a>',
footer: ''
};
/***/ },
/* 355 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _utils = __webpack_require__(336);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
var _RefinementListItem = __webpack_require__(356);
var _RefinementListItem2 = _interopRequireDefault(_RefinementListItem);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 RefinementList = function (_React$Component) {
_inherits(RefinementList, _React$Component);
function RefinementList(props) {
_classCallCheck(this, RefinementList);
var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props));
_this.state = {
isShowMoreOpen: false
};
_this.handleItemClick = _this.handleItemClick.bind(_this);
_this.handleClickShowMore = _this.handleClickShowMore.bind(_this);
return _this;
}
_createClass(RefinementList, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var isStateDifferent = nextState !== this.state;
var isFacetValuesDifferent = !(0, _isEqual2.default)(this.props.facetValues, nextProps.facetValues);
var shouldUpdate = isStateDifferent || isFacetValuesDifferent;
return shouldUpdate;
}
}, {
key: 'refine',
value: function refine(facetValueToRefine, isRefined) {
this.props.toggleRefinement(facetValueToRefine, isRefined);
}
}, {
key: '_generateFacetItem',
value: function _generateFacetItem(facetValue) {
var subItems = void 0;
var hasChildren = facetValue.data && facetValue.data.length > 0;
if (hasChildren) {
subItems = _react2.default.createElement(RefinementList, _extends({}, this.props, {
depth: this.props.depth + 1,
facetValues: facetValue.data
}));
}
var url = this.props.createURL(facetValue[this.props.attributeNameKey]);
var templateData = _extends({}, facetValue, { url: url, cssClasses: this.props.cssClasses });
var cssClassItem = (0, _classnames2.default)(this.props.cssClasses.item, _defineProperty({}, this.props.cssClasses.active, facetValue.isRefined));
var key = facetValue[this.props.attributeNameKey];
if (facetValue.isRefined !== undefined) {
key += '/' + facetValue.isRefined;
}
if (facetValue.count !== undefined) {
key += '/' + facetValue.count;
}
return _react2.default.createElement(_RefinementListItem2.default, {
facetValueToRefine: facetValue[this.props.attributeNameKey],
handleClick: this.handleItemClick,
isRefined: facetValue.isRefined,
itemClassName: cssClassItem,
key: key,
subItems: subItems,
templateData: templateData,
templateKey: 'item',
templateProps: this.props.templateProps
});
}
// Click events on DOM tree like LABEL > INPUT will result in two click events
// instead of one.
// No matter the framework, see https://www.google.com/search?q=click+label+twice
//
// Thus making it hard to distinguish activation from deactivation because both click events
// are very close. Debounce is a solution but hacky.
//
// So the code here checks if the click was done on or in a LABEL. If this LABEL
// has a checkbox inside, we ignore the first click event because we will get another one.
//
// We also check if the click was done inside a link and then e.preventDefault() because we already
// handle the url
//
// Finally, we always stop propagation of the event to avoid multiple levels RefinementLists to fail: click
// on child would click on parent also
}, {
key: 'handleItemClick',
value: function handleItemClick(_ref) {
var facetValueToRefine = _ref.facetValueToRefine;
var originalEvent = _ref.originalEvent;
var isRefined = _ref.isRefined;
if ((0, _utils.isSpecialClick)(originalEvent)) {
// do not alter the default browser behavior
// if one special key is down
return;
}
if (originalEvent.target.tagName === 'INPUT') {
this.refine(facetValueToRefine, isRefined);
return;
}
var parent = originalEvent.target;
while (parent !== originalEvent.currentTarget) {
if (parent.tagName === 'LABEL' && (parent.querySelector('input[type="checkbox"]') || parent.querySelector('input[type="radio"]'))) {
return;
}
if (parent.tagName === 'A' && parent.href) {
originalEvent.preventDefault();
}
parent = parent.parentNode;
}
originalEvent.stopPropagation();
this.refine(facetValueToRefine, isRefined);
}
}, {
key: 'handleClickShowMore',
value: function handleClickShowMore() {
var isShowMoreOpen = !this.state.isShowMoreOpen;
this.setState({ isShowMoreOpen: isShowMoreOpen });
}
}, {
key: 'render',
value: function render() {
// Adding `-lvl0` classes
var cssClassList = [this.props.cssClasses.list];
if (this.props.cssClasses.depth) {
cssClassList.push('' + this.props.cssClasses.depth + this.props.depth);
}
var limit = this.state.isShowMoreOpen ? this.props.limitMax : this.props.limitMin;
var displayedFacetValues = this.props.facetValues.slice(0, limit);
var displayShowMore = this.props.showMore === true &&
// "Show more"
this.props.facetValues.length > displayedFacetValues.length ||
// "Show less", but hide it if the result set changed
this.state.isShowMoreOpen && displayedFacetValues.length > this.props.limitMin;
var showMoreBtn = displayShowMore ? _react2.default.createElement(_Template2.default, _extends({
rootProps: { onClick: this.handleClickShowMore },
templateKey: 'show-more-' + (this.state.isShowMoreOpen ? 'active' : 'inactive')
}, this.props.templateProps)) : undefined;
return _react2.default.createElement(
'div',
{ className: (0, _classnames2.default)(cssClassList) },
displayedFacetValues.map(this._generateFacetItem, this),
showMoreBtn
);
}
}]);
return RefinementList;
}(_react2.default.Component);
RefinementList.defaultProps = {
cssClasses: {},
depth: 0,
attributeNameKey: 'name'
};
exports.default = RefinementList;
/***/ },
/* 356 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 _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 RefinementListItem = function (_React$Component) {
_inherits(RefinementListItem, _React$Component);
function RefinementListItem() {
_classCallCheck(this, RefinementListItem);
return _possibleConstructorReturn(this, (RefinementListItem.__proto__ || Object.getPrototypeOf(RefinementListItem)).apply(this, arguments));
}
_createClass(RefinementListItem, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.handleClick = this.handleClick.bind(this);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return !(0, _isEqual2.default)(this.props, nextProps);
}
}, {
key: 'handleClick',
value: function handleClick(originalEvent) {
this.props.handleClick({
facetValueToRefine: this.props.facetValueToRefine,
isRefined: this.props.isRefined,
originalEvent: originalEvent
});
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{
className: this.props.itemClassName,
onClick: this.handleClick
},
_react2.default.createElement(_Template2.default, _extends({
data: this.props.templateData,
templateKey: this.props.templateKey
}, this.props.templateProps)),
this.props.subItems
);
}
}]);
return RefinementListItem;
}(_react2.default.Component);
exports.default = RefinementListItem;
/***/ },
/* 357 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _Hits = __webpack_require__(358);
var _Hits2 = _interopRequireDefault(_Hits);
var _defaultTemplates = __webpack_require__(361);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-hits');
/**
* Display the list of results (hits) from the current search
* @function hits
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.empty=''] Template to use when there are no results.
* @param {string|Function} [options.templates.item=''] Template to use for each result. This template will receive an object containing a single record.
* @param {string|Function} [options.templates.allItems=''] Template to use for the list of all results. (Can't be used with `item` template). This template will receive a complete SearchResults result object, this object contains the key hits that contains all the records retrieved.
* @param {Object} [options.transformData] Method to change the object passed to the templates
* @param {Function} [options.transformData.empty] Method used to change the object passed to the `empty` template
* @param {Function} [options.transformData.item] Method used to change the object passed to the `item` template
* @param {Function} [options.transformData.allItems] Method used to change the object passed to the `allItems` template
* @param {number} [hitsPerPage=20] The number of hits to display per page
* @param {Object} [options.cssClasses] CSS classes to add
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the wrapping element
* @param {string|string[]} [options.cssClasses.empty] CSS class to add to the wrapping element when no results
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each result
* @return {Object}
*/
var usage = '\nUsage:\nhits({\n container,\n [ cssClasses.{root,empty,item}={} ],\n [ templates.{empty,item} | templates.{empty, allItems} ],\n [ transformData.{empty,item} | transformData.{empty, allItems} ],\n [ hitsPerPage=20 ]\n})';
function hits() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var transformData = _ref.transformData;
var _ref$hitsPerPage = _ref.hitsPerPage;
var hitsPerPage = _ref$hitsPerPage === undefined ? 20 : _ref$hitsPerPage;
if (!container) {
throw new Error('Must provide a container.' + usage);
}
if (templates.item && templates.allItems) {
throw new Error('Must contain only allItems OR item template.' + usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
empty: (0, _classnames2.default)(bem(null, 'empty'), userCssClasses.empty)
};
return {
getConfiguration: function getConfiguration() {
return { hitsPerPage: hitsPerPage };
},
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
},
render: function render(_ref3) {
var results = _ref3.results;
_reactDom2.default.render(_react2.default.createElement(_Hits2.default, {
cssClasses: cssClasses,
hits: results.hits,
results: results,
templateProps: this._templateProps
}), containerNode);
}
};
}
exports.default = hits;
/***/ },
/* 358 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _map = __webpack_require__(171);
var _map2 = _interopRequireDefault(_map);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
var _has = __webpack_require__(359);
var _has2 = _interopRequireDefault(_has);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
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 _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 Hits = function (_React$Component) {
_inherits(Hits, _React$Component);
function Hits() {
_classCallCheck(this, Hits);
return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments));
}
_createClass(Hits, [{
key: 'renderWithResults',
value: function renderWithResults() {
var _this2 = this;
var renderedHits = (0, _map2.default)(this.props.results.hits, function (hit, position) {
var data = _extends({}, hit, {
__hitIndex: position
});
return _react2.default.createElement(_Template2.default, _extends({
data: data,
key: data.objectID,
rootProps: { className: _this2.props.cssClasses.item },
templateKey: 'item'
}, _this2.props.templateProps));
});
return _react2.default.createElement(
'div',
{ className: this.props.cssClasses.root },
renderedHits
);
}
}, {
key: 'renderAllResults',
value: function renderAllResults() {
var className = (0, _classnames2.default)(this.props.cssClasses.root, this.props.cssClasses.allItems);
return _react2.default.createElement(_Template2.default, _extends({
data: this.props.results,
rootProps: { className: className },
templateKey: 'allItems'
}, this.props.templateProps));
}
}, {
key: 'renderNoResults',
value: function renderNoResults() {
var className = (0, _classnames2.default)(this.props.cssClasses.root, this.props.cssClasses.empty);
return _react2.default.createElement(_Template2.default, _extends({
data: this.props.results,
rootProps: { className: className },
templateKey: 'empty'
}, this.props.templateProps));
}
}, {
key: 'render',
value: function render() {
var hasResults = this.props.results.hits.length > 0;
var hasAllItemsTemplate = (0, _has2.default)(this.props, 'templateProps.templates.allItems');
if (!hasResults) {
return this.renderNoResults();
}
// If a allItems template is defined, it takes precedence over our looping
// through hits
if (hasAllItemsTemplate) {
return this.renderAllResults();
}
return this.renderWithResults();
}
}]);
return Hits;
}(_react2.default.Component);
Hits.defaultProps = {
results: { hits: [] }
};
exports.default = Hits;
/***/ },
/* 359 */
/***/ function(module, exports, __webpack_require__) {
var baseHas = __webpack_require__(360),
hasPath = __webpack_require__(160);
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
module.exports = has;
/***/ },
/* 360 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* 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) {
return object != null && hasOwnProperty.call(object, key);
}
module.exports = baseHas;
/***/ },
/* 361 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
empty: 'No results',
item: function item(data) {
return JSON.stringify(data, null, 2);
}
};
/***/ },
/* 362 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _some = __webpack_require__(363);
var _some2 = _interopRequireDefault(_some);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _Selector = __webpack_require__(365);
var _Selector2 = _interopRequireDefault(_Selector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-hits-per-page-selector');
/**
* Instantiate a dropdown element to choose the number of hits to display per page
* @function hitsPerPageSelector
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {Array} options.options Array of objects defining the different values and labels
* @param {number} options.options[0].value number of hits to display per page
* @param {string} options.options[0].label Label to display in the option
* @param {boolean} [options.autoHideContainer=false] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to be added
* @param {string|string[]} [options.cssClasses.root] CSS classes added to the parent `<select>`
* @param {string|string[]} [options.cssClasses.item] CSS classes added to each `<option>`
* @return {Object}
*/
var usage = 'Usage:\nhitsPerPageSelector({\n container,\n options,\n [ cssClasses.{root,item}={} ],\n [ autoHideContainer=false ]\n})';
function hitsPerPageSelector() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var userOptions = _ref.options;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? false : _ref$autoHideContaine;
var options = userOptions;
if (!container || !options) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var Selector = _Selector2.default;
if (autoHideContainer === true) {
Selector = (0, _autoHideContainer2.default)(Selector);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item)
};
return {
init: function init(_ref2) {
var helper = _ref2.helper;
var state = _ref2.state;
var isCurrentInOptions = (0, _some2.default)(options, function (option) {
return Number(state.hitsPerPage) === Number(option.value);
});
if (!isCurrentInOptions) {
if (state.hitsPerPage === undefined) {
if (window.console) {
window.console.log('[Warning][hitsPerPageSelector] hitsPerPage not defined.\nYou should probably use a `hits` widget or set the value `hitsPerPage`\nusing the searchParameters attribute of the instantsearch constructor.');
}
} else if (window.console) {
window.console.log('[Warning][hitsPerPageSelector] No option in `options`\nwith `value: hitsPerPage` (hitsPerPage: ' + state.hitsPerPage + ')');
}
options = [{ value: undefined, label: '' }].concat(options);
}
this.setHitsPerPage = function (value) {
return helper.setQueryParameter('hitsPerPage', Number(value)).search();
};
},
render: function render(_ref3) {
var state = _ref3.state;
var results = _ref3.results;
var currentValue = state.hitsPerPage;
var hasNoResults = results.nbHits === 0;
_reactDom2.default.render(_react2.default.createElement(Selector, {
cssClasses: cssClasses,
currentValue: currentValue,
options: options,
setValue: this.setHitsPerPage,
shouldAutoHideContainer: hasNoResults
}), containerNode);
}
};
}
exports.default = hitsPerPageSelector;
/***/ },
/* 363 */
/***/ function(module, exports, __webpack_require__) {
var arraySome = __webpack_require__(130),
baseIteratee = __webpack_require__(118),
baseSome = __webpack_require__(364),
isArray = __webpack_require__(41),
isIterateeCall = __webpack_require__(223);
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, baseIteratee(predicate, 3));
}
module.exports = some;
/***/ },
/* 364 */
/***/ function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(166);
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
module.exports = baseSome;
/***/ },
/* 365 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
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 _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 Selector = function (_React$Component) {
_inherits(Selector, _React$Component);
function Selector() {
_classCallCheck(this, Selector);
return _possibleConstructorReturn(this, (Selector.__proto__ || Object.getPrototypeOf(Selector)).apply(this, arguments));
}
_createClass(Selector, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.handleChange = this.handleChange.bind(this);
}
}, {
key: 'handleChange',
value: function handleChange(event) {
this.props.setValue(event.target.value);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var currentValue = _props.currentValue;
var options = _props.options;
return _react2.default.createElement(
'select',
{
className: this.props.cssClasses.root,
onChange: this.handleChange,
value: currentValue
},
options.map(function (option) {
return _react2.default.createElement(
'option',
{
className: _this2.props.cssClasses.item,
key: option.value,
value: option.value },
option.label
);
})
);
}
}]);
return Selector;
}(_react2.default.Component);
exports.default = Selector;
/***/ },
/* 366 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _getShowMoreConfig = __webpack_require__(367);
var _getShowMoreConfig2 = _interopRequireDefault(_getShowMoreConfig);
var _defaultTemplates = __webpack_require__(369);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _RefinementList = __webpack_require__(355);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-menu');
/**
* Create a menu out of a facet
* @function menu
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the attribute for faceting
* @param {string[]|Function} [options.sortBy=['count:desc', 'name:asc']] How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`
* @param {string} [options.limit=10] How many facets values to retrieve
* @param {object|boolean} [options.showMore=false] Limit the number of results and display a showMore button
* @param {object} [options.showMore.templates] Templates to use for showMore
* @param {object} [options.showMore.templates.active] Template used when showMore was clicked
* @param {object} [options.showMore.templates.inactive] Template used when showMore not clicked
* @param {object} [options.showMore.limit] Max number of facets values to display when showMore is clicked
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template
* @param {string|Function} [options.templates.item] Item template, provided with `name`, `count`, `isRefined`, `url` data properties
* @param {string|Function} [options.templates.footer] Footer template
* @param {Function} [options.transformData.item] Method to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when there are no items in the menu
* @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element
* @param {string|string[]} [options.cssClasses.link] CSS class to add to each link (when using the default template)
* @param {string|string[]} [options.cssClasses.count] CSS class to add to each count element (when using the default template)
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\nmenu({\n container,\n attributeName,\n [ sortBy=[\'count:desc\', \'name:asc\'] ],\n [ limit=10 ],\n [ cssClasses.{root,list,item} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer ],\n [ showMore.{templates: {active, inactive}, limit} ],\n [ collapsible=false ]\n})';
function menu() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var attributeName = _ref.attributeName;
var _ref$sortBy = _ref.sortBy;
var sortBy = _ref$sortBy === undefined ? ['count:desc', 'name:asc'] : _ref$sortBy;
var _ref$limit = _ref.limit;
var limit = _ref$limit === undefined ? 10 : _ref$limit;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$showMore = _ref.showMore;
var showMore = _ref$showMore === undefined ? false : _ref$showMore;
var showMoreConfig = (0, _getShowMoreConfig2.default)(showMore);
if (showMoreConfig && showMoreConfig.limit < limit) {
throw new Error('showMore.limit configuration should be > than the limit in the main configuration'); // eslint-disable-line
}
var widgetMaxValuesPerFacet = showMoreConfig && showMoreConfig.limit || limit;
if (!container || !attributeName) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var RefinementList = (0, _headerFooter2.default)(_RefinementList2.default);
if (autoHideContainer === true) {
RefinementList = (0, _autoHideContainer2.default)(RefinementList);
}
// we use a hierarchicalFacet for the menu because that's one of the use cases
// of hierarchicalFacet: a flat menu
var hierarchicalFacetName = attributeName;
var showMoreTemplates = showMoreConfig && (0, _utils.prefixKeys)('show-more-', showMoreConfig.templates);
var allTemplates = showMoreTemplates ? _extends({}, templates, showMoreTemplates) : templates;
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link),
count: (0, _classnames2.default)(bem('count'), userCssClasses.count)
};
return {
getConfiguration: function getConfiguration(configuration) {
var widgetConfiguration = {
hierarchicalFacets: [{
name: hierarchicalFacetName,
attributes: [attributeName]
}]
};
var currentMaxValuesPerFacet = configuration.maxValuesPerFacet || 0;
widgetConfiguration.maxValuesPerFacet = Math.max(currentMaxValuesPerFacet, widgetMaxValuesPerFacet);
return widgetConfiguration;
},
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
var helper = _ref2.helper;
var createURL = _ref2.createURL;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: allTemplates
});
this._createURL = function (state, facetValue) {
return createURL(state.toggleRefinement(hierarchicalFacetName, facetValue));
};
this._toggleRefinement = function (facetValue) {
return helper.toggleRefinement(hierarchicalFacetName, facetValue).search();
};
},
_prepareFacetValues: function _prepareFacetValues(facetValues, state) {
var _this = this;
return facetValues.map(function (facetValue) {
facetValue.url = _this._createURL(state, facetValue);
return facetValue;
});
},
render: function render(_ref3) {
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var facetValues = results.getFacetValues(hierarchicalFacetName, { sortBy: sortBy }).data || [];
facetValues = this._prepareFacetValues(facetValues, state);
// Bind createURL to this specific attribute
function _createURL(facetValue) {
return createURL(state.toggleRefinement(attributeName, facetValue));
}
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: facetValues,
limitMax: widgetMaxValuesPerFacet,
limitMin: limit,
shouldAutoHideContainer: facetValues.length === 0,
showMore: showMoreConfig !== null,
templateProps: this._templateProps,
toggleRefinement: this._toggleRefinement
}), containerNode);
}
};
}
exports.default = menu;
/***/ },
/* 367 */
/***/ 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; };
exports.default = getShowMoreConfig;
var _defaultShowMoreTemplates = __webpack_require__(368);
var _defaultShowMoreTemplates2 = _interopRequireDefault(_defaultShowMoreTemplates);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaultShowMoreConfig = {
templates: _defaultShowMoreTemplates2.default,
limit: 100
};
function getShowMoreConfig(showMoreOptions) {
if (!showMoreOptions) return null;
if (showMoreOptions === true) {
return defaultShowMoreConfig;
}
var config = _extends({}, showMoreOptions);
if (!showMoreOptions.templates) {
config.templates = defaultShowMoreConfig.templates;
}
if (!showMoreOptions.limit) {
config.limit = defaultShowMoreConfig.limit;
}
return config;
}
/***/ },
/* 368 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
active: '<a class="ais-show-more ais-show-more__active">Show less</a>',
inactive: '<a class="ais-show-more ais-show-more__inactive">Show more</a>'
};
/***/ },
/* 369 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint-disable max-len */
exports.default = {
header: '',
item: '<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span></a>',
footer: ''
};
/***/ },
/* 370 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _filter = __webpack_require__(168);
var _filter2 = _interopRequireDefault(_filter);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _getShowMoreConfig = __webpack_require__(367);
var _getShowMoreConfig2 = _interopRequireDefault(_getShowMoreConfig);
var _defaultTemplates = __webpack_require__(371);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _RefinementList = __webpack_require__(355);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
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; }
var bem = (0, _utils.bemHelper)('ais-refinement-list');
/**
* Instantiate a list of refinements based on a facet
* @function refinementList
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the attribute for faceting
* @param {string} [options.operator='or'] How to apply refinements. Possible values: `or`, `and`
* @param {string[]|Function} [options.sortBy=['count:desc', 'name:asc']] How to sort refinements. Possible values: `count:asc|count:desc|name:asc|name:desc|isRefined`
* @param {string} [options.limit=10] How much facet values to get. When the show more feature is activated this is the minimum number of facets requested (the show more button is not in active state).
* @param {object|boolean} [options.showMore=false] Limit the number of results and display a showMore button
* @param {object} [options.showMore.templates] Templates to use for showMore
* @param {object} [options.showMore.templates.active] Template used when showMore was clicked
* @param {object} [options.showMore.templates.inactive] Template used when showMore not clicked
* @param {object} [options.showMore.limit] Max number of facets values to display when showMore is clicked
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template, provided with `refinedFacetsCount` data property
* @param {string|Function} [options.templates.item] Item template, provided with `name`, `count`, `isRefined`, `url` data properties
* @param {string|Function} [options.templates.footer] Footer template
* @param {Function} [options.transformData.item] Function to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when no items in the refinement list
* @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element
* @param {string|string[]} [options.cssClasses.label] CSS class to add to each label element (when using the default template)
* @param {string|string[]} [options.cssClasses.checkbox] CSS class to add to each checkbox element (when using the default template)
* @param {string|string[]} [options.cssClasses.count] CSS class to add to each count element (when using the default template)
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\nrefinementList({\n container,\n attributeName,\n [ operator=\'or\' ],\n [ sortBy=[\'count:desc\', \'name:asc\'] ],\n [ limit=10 ],\n [ cssClasses.{root, header, body, footer, list, item, active, label, checkbox, count}],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ],\n [ showMore.{templates: {active, inactive}, limit} ],\n [ collapsible=false ]\n})';
function refinementList(_ref) {
var container = _ref.container;
var attributeName = _ref.attributeName;
var _ref$operator = _ref.operator;
var operator = _ref$operator === undefined ? 'or' : _ref$operator;
var _ref$sortBy = _ref.sortBy;
var sortBy = _ref$sortBy === undefined ? ['count:desc', 'name:asc'] : _ref$sortBy;
var _ref$limit = _ref.limit;
var limit = _ref$limit === undefined ? 10 : _ref$limit;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$showMore = _ref.showMore;
var showMore = _ref$showMore === undefined ? false : _ref$showMore;
var showMoreConfig = (0, _getShowMoreConfig2.default)(showMore);
if (showMoreConfig && showMoreConfig.limit < limit) {
throw new Error('showMore.limit configuration should be > than the limit in the main configuration'); // eslint-disable-line
}
var widgetMaxValuesPerFacet = showMoreConfig && showMoreConfig.limit || limit;
var RefinementList = _RefinementList2.default;
if (!container || !attributeName) {
throw new Error(usage);
}
RefinementList = (0, _headerFooter2.default)(RefinementList);
if (autoHideContainer === true) {
RefinementList = (0, _autoHideContainer2.default)(RefinementList);
}
var containerNode = (0, _utils.getContainerNode)(container);
if (operator) {
operator = operator.toLowerCase();
if (operator !== 'and' && operator !== 'or') {
throw new Error(usage);
}
}
var showMoreTemplates = showMoreConfig && (0, _utils.prefixKeys)('show-more-', showMoreConfig.templates);
var allTemplates = showMoreTemplates ? _extends({}, templates, showMoreTemplates) : templates;
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active),
label: (0, _classnames2.default)(bem('label'), userCssClasses.label),
checkbox: (0, _classnames2.default)(bem('checkbox'), userCssClasses.checkbox),
count: (0, _classnames2.default)(bem('count'), userCssClasses.count)
};
return {
getConfiguration: function getConfiguration(configuration) {
var widgetConfiguration = _defineProperty({}, operator === 'and' ? 'facets' : 'disjunctiveFacets', [attributeName]);
var currentMaxValuesPerFacet = configuration.maxValuesPerFacet || 0;
widgetConfiguration.maxValuesPerFacet = Math.max(currentMaxValuesPerFacet, widgetMaxValuesPerFacet);
return widgetConfiguration;
},
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
var helper = _ref2.helper;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: allTemplates
});
this.toggleRefinement = function (facetValue) {
return helper.toggleRefinement(attributeName, facetValue).search();
};
},
render: function render(_ref3) {
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var facetValues = results.getFacetValues(attributeName, { sortBy: sortBy });
// Bind createURL to this specific attribute
function _createURL(facetValue) {
return createURL(state.toggleRefinement(attributeName, facetValue));
}
// Pass count of currently selected items to the header template
var refinedFacetsCount = (0, _filter2.default)(facetValues, { isRefined: true }).length;
var headerFooterData = {
header: { refinedFacetsCount: refinedFacetsCount }
};
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: facetValues,
headerFooterData: headerFooterData,
limitMax: widgetMaxValuesPerFacet,
limitMin: limit,
shouldAutoHideContainer: facetValues.length === 0,
showMore: showMoreConfig !== null,
templateProps: this._templateProps,
toggleRefinement: this.toggleRefinement
}), containerNode);
}
};
}
exports.default = refinementList;
/***/ },
/* 371 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
header: '',
item: '<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>\n</label>',
footer: ''
};
/***/ },
/* 372 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _find = __webpack_require__(205);
var _find2 = _interopRequireDefault(_find);
var _includes = __webpack_require__(243);
var _includes2 = _interopRequireDefault(_includes);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _defaultTemplates = __webpack_require__(373);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _RefinementList = __webpack_require__(355);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-refinement-list');
/**
* Instantiate a list of refinements based on a facet
* @function numericRefinementList
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the attribute for filtering
* @param {Object[]} options.options List of all the options
* @param {string} options.options[].name Name of the option
* @param {number} [options.options[].start] Low bound of the option (>=)
* @param {number} [options.options[].end] High bound of the option (<=)
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template
* @param {string|Function} [options.templates.item] Item template, provided with `name`, `isRefined`, `url` data properties
* @param {string|Function} [options.templates.footer] Footer template
* @param {Function} [options.transformData.item] Function to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element
* @param {string|string[]} [options.cssClasses.label] CSS class to add to each link element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.radio] CSS class to add to each radio element (when using the default template)
* @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\nnumericRefinementList({\n container,\n attributeName,\n options,\n [ cssClasses.{root,header,body,footer,list,item,active,label,radio,count} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer ],\n [ collapsible=false ]\n})';
function numericRefinementList(_ref) {
var container = _ref.container;
var attributeName = _ref.attributeName;
var options = _ref.options;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
if (!container || !attributeName || !options) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var RefinementList = (0, _headerFooter2.default)(_RefinementList2.default);
if (autoHideContainer === true) {
RefinementList = (0, _autoHideContainer2.default)(RefinementList);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
label: (0, _classnames2.default)(bem('label'), userCssClasses.label),
radio: (0, _classnames2.default)(bem('radio'), userCssClasses.radio),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active)
};
return {
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
var helper = _ref2.helper;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
this._toggleRefinement = function (facetValue) {
var refinedState = refine(helper.state, attributeName, options, facetValue);
helper.setState(refinedState).search();
};
},
render: function render(_ref3) {
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var facetValues = options.map(function (facetValue) {
return _extends({}, facetValue, {
isRefined: isRefined(state, attributeName, facetValue),
attributeName: attributeName
});
});
// Bind createURL to this specific attribute
function _createURL(facetValue) {
return createURL(refine(state, attributeName, options, facetValue));
}
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: facetValues,
shouldAutoHideContainer: results.nbHits === 0,
templateProps: this._templateProps,
toggleRefinement: this._toggleRefinement
}), containerNode);
}
};
}
function isRefined(state, attributeName, option) {
var currentRefinements = state.getNumericRefinements(attributeName);
if (option.start !== undefined && option.end !== undefined) {
if (option.start === option.end) {
return hasNumericRefinement(currentRefinements, '=', option.start);
}
}
if (option.start !== undefined) {
return hasNumericRefinement(currentRefinements, '>=', option.start);
}
if (option.end !== undefined) {
return hasNumericRefinement(currentRefinements, '<=', option.end);
}
if (option.start === undefined && option.end === undefined) {
return Object.keys(currentRefinements).length === 0;
}
return undefined;
}
function refine(state, attributeName, options, facetValue) {
var resolvedState = state;
var refinedOption = (0, _find2.default)(options, { name: facetValue });
var currentRefinements = resolvedState.getNumericRefinements(attributeName);
if (refinedOption.start === undefined && refinedOption.end === undefined) {
return resolvedState.clearRefinements(attributeName);
}
if (!isRefined(resolvedState, attributeName, refinedOption)) {
resolvedState = resolvedState.clearRefinements(attributeName);
}
if (refinedOption.start !== undefined && refinedOption.end !== undefined) {
if (refinedOption.start > refinedOption.end) {
throw new Error('option.start should be > to option.end');
}
if (refinedOption.start === refinedOption.end) {
if (hasNumericRefinement(currentRefinements, '=', refinedOption.start)) {
resolvedState = resolvedState.removeNumericRefinement(attributeName, '=', refinedOption.start);
} else {
resolvedState = resolvedState.addNumericRefinement(attributeName, '=', refinedOption.start);
}
return resolvedState;
}
}
if (refinedOption.start !== undefined) {
if (hasNumericRefinement(currentRefinements, '>=', refinedOption.start)) {
resolvedState = resolvedState.removeNumericRefinement(attributeName, '>=', refinedOption.start);
} else {
resolvedState = resolvedState.addNumericRefinement(attributeName, '>=', refinedOption.start);
}
}
if (refinedOption.end !== undefined) {
if (hasNumericRefinement(currentRefinements, '<=', refinedOption.end)) {
resolvedState = resolvedState.removeNumericRefinement(attributeName, '<=', refinedOption.end);
} else {
resolvedState = resolvedState.addNumericRefinement(attributeName, '<=', refinedOption.end);
}
}
return resolvedState;
}
function hasNumericRefinement(currentRefinements, operator, value) {
var hasOperatorRefinements = currentRefinements[operator] !== undefined;
var includesValue = (0, _includes2.default)(currentRefinements[operator], value);
return hasOperatorRefinements && includesValue;
}
exports.default = numericRefinementList;
/***/ },
/* 373 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint-disable max-len */
exports.default = {
header: '',
item: '<label class="{{cssClasses.label}}">\n <input type="radio" class="{{cssClasses.radio}}" name="{{attributeName}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n</label>',
footer: ''
};
/***/ },
/* 374 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _Selector = __webpack_require__(365);
var _Selector2 = _interopRequireDefault(_Selector);
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; }
var bem = (0, _utils.bemHelper)('ais-numeric-selector');
/**
* Instantiate a dropdown element to choose the number of hits to display per page
* @function numericSelector
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the numeric attribute to use
* @param {Array} options.options Array of objects defining the different values and labels
* @param {number} options.options[i].value The numerical value to refine with
* @param {string} options.options[i].label Label to display in the option
* @param {string} [options.operator] The operator to use to refine
* @param {boolean} [options.autoHideContainer=false] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to be added
* @param {string|string[]} [options.cssClasses.root] CSS classes added to the parent `<select>`
* @param {string|string[]} [options.cssClasses.item] CSS classes added to each `<option>`
* @return {Object}
*/
function numericSelector(_ref) {
var container = _ref.container;
var _ref$operator = _ref.operator;
var operator = _ref$operator === undefined ? '=' : _ref$operator;
var attributeName = _ref.attributeName;
var options = _ref.options;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? false : _ref$autoHideContaine;
var containerNode = (0, _utils.getContainerNode)(container);
var usage = 'Usage: numericSelector({\n container,\n attributeName,\n options,\n cssClasses.{root,item},\n autoHideContainer\n })';
var Selector = _Selector2.default;
if (autoHideContainer === true) {
Selector = (0, _autoHideContainer2.default)(Selector);
}
if (!container || !options || options.length === 0 || !attributeName) {
throw new Error(usage);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item)
};
return {
getConfiguration: function getConfiguration(currentSearchParameters, searchParametersFromUrl) {
return {
numericRefinements: _defineProperty({}, attributeName, _defineProperty({}, operator, [this._getRefinedValue(searchParametersFromUrl)]))
};
},
init: function init(_ref2) {
var helper = _ref2.helper;
this._refine = function (value) {
helper.clearRefinements(attributeName);
if (value !== undefined) {
helper.addNumericRefinement(attributeName, operator, value);
}
helper.search();
};
},
render: function render(_ref3) {
var helper = _ref3.helper;
var results = _ref3.results;
_reactDom2.default.render(_react2.default.createElement(Selector, {
cssClasses: cssClasses,
currentValue: this._getRefinedValue(helper.state),
options: options,
setValue: this._refine,
shouldAutoHideContainer: results.nbHits === 0
}), containerNode);
},
_getRefinedValue: function _getRefinedValue(state) {
// This is reimplementing state.getNumericRefinement
// But searchParametersFromUrl is not an actual SearchParameters object
// It's only the object structure without the methods, because getStateFromQueryString
// is not sending a SearchParameters. There's no way given how web built the helper
// to initialize a true partial state where only the refinements are present
return state && state.numericRefinements && state.numericRefinements[attributeName] !== undefined && state.numericRefinements[attributeName][operator] !== undefined && state.numericRefinements[attributeName][operator][0] !== undefined ? // could be 0
state.numericRefinements[attributeName][operator][0] : options[0].value;
}
};
}
exports.default = numericSelector;
/***/ },
/* 375 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _defaults = __webpack_require__(217);
var _defaults2 = _interopRequireDefault(_defaults);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _utils = __webpack_require__(336);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _Pagination = __webpack_require__(376);
var _Pagination2 = _interopRequireDefault(_Pagination);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaultLabels = {
previous: '‹',
next: '›',
first: '«',
last: '»'
};
var bem = (0, _utils.bemHelper)('ais-pagination');
/**
* Add a pagination menu to navigate through the results
* @function pagination
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {Object} [options.labels] Text to display in the various links (prev, next, first, last)
* @param {string} [options.labels.previous] Label for the Previous link
* @param {string} [options.labels.next] Label for the Next link
* @param {string} [options.labels.first] Label for the First link
* @param {string} [options.labels.last] Label for the Last link
* @param {number} [options.maxPages] The max number of pages to browse
* @param {number} [options.padding=3] The number of pages to display on each side of the current page
* @param {string|DOMElement|boolean} [options.scrollTo='body'] Where to scroll after a click, set to `false` to disable
* @param {boolean} [options.showFirstLast=true] Define if the First and Last links should be displayed
* @param {boolean} [options.autoHideContainer=true] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to be added
* @param {string|string[]} [options.cssClasses.root] CSS classes added to the parent `<ul>`
* @param {string|string[]} [options.cssClasses.item] CSS classes added to each `<li>`
* @param {string|string[]} [options.cssClasses.link] CSS classes added to each link
* @param {string|string[]} [options.cssClasses.page] CSS classes added to page `<li>`
* @param {string|string[]} [options.cssClasses.previous] CSS classes added to the previous `<li>`
* @param {string|string[]} [options.cssClasses.next] CSS classes added to the next `<li>`
* @param {string|string[]} [options.cssClasses.first] CSS classes added to the first `<li>`
* @param {string|string[]} [options.cssClasses.last] CSS classes added to the last `<li>`
* @param {string|string[]} [options.cssClasses.active] CSS classes added to the active `<li>`
* @param {string|string[]} [options.cssClasses.disabled] CSS classes added to the disabled `<li>`
* @return {Object}
*/
var usage = 'Usage:\npagination({\n container,\n [ cssClasses.{root,item,page,previous,next,first,last,active,disabled}={} ],\n [ labels.{previous,next,first,last} ],\n [ maxPages ],\n [ padding=3 ],\n [ showFirstLast=true ],\n [ autoHideContainer=true ],\n [ scrollTo=\'body\' ]\n})';
function pagination() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$labels = _ref.labels;
var userLabels = _ref$labels === undefined ? {} : _ref$labels;
var maxPages = _ref.maxPages;
var _ref$padding = _ref.padding;
var padding = _ref$padding === undefined ? 3 : _ref$padding;
var _ref$showFirstLast = _ref.showFirstLast;
var showFirstLast = _ref$showFirstLast === undefined ? true : _ref$showFirstLast;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$scrollTo = _ref.scrollTo;
var userScrollTo = _ref$scrollTo === undefined ? 'body' : _ref$scrollTo;
var scrollTo = userScrollTo;
if (!container) {
throw new Error(usage);
}
if (scrollTo === true) {
scrollTo = 'body';
}
var containerNode = (0, _utils.getContainerNode)(container);
var scrollToNode = scrollTo !== false ? (0, _utils.getContainerNode)(scrollTo) : false;
var Pagination = _Pagination2.default;
if (autoHideContainer === true) {
Pagination = (0, _autoHideContainer2.default)(Pagination);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link),
page: (0, _classnames2.default)(bem('item', 'page'), userCssClasses.page),
previous: (0, _classnames2.default)(bem('item', 'previous'), userCssClasses.previous),
next: (0, _classnames2.default)(bem('item', 'next'), userCssClasses.next),
first: (0, _classnames2.default)(bem('item', 'first'), userCssClasses.first),
last: (0, _classnames2.default)(bem('item', 'last'), userCssClasses.last),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active),
disabled: (0, _classnames2.default)(bem('item', 'disabled'), userCssClasses.disabled)
};
var labels = (0, _defaults2.default)(userLabels, defaultLabels);
return {
init: function init(_ref2) {
var helper = _ref2.helper;
this.setCurrentPage = function (page) {
helper.setCurrentPage(page);
if (scrollToNode !== false) {
scrollToNode.scrollIntoView();
}
helper.search();
};
},
getMaxPage: function getMaxPage(results) {
if (maxPages !== undefined) {
return Math.min(maxPages, results.nbPages);
}
return results.nbPages;
},
render: function render(_ref3) {
var results = _ref3.results;
var state = _ref3.state;
var _createURL = _ref3.createURL;
_reactDom2.default.render(_react2.default.createElement(Pagination, {
createURL: function createURL(page) {
return _createURL(state.setPage(page));
},
cssClasses: cssClasses,
currentPage: results.page,
labels: labels,
nbHits: results.nbHits,
nbPages: this.getMaxPage(results),
padding: padding,
setCurrentPage: this.setCurrentPage,
shouldAutoHideContainer: results.nbHits === 0,
showFirstLast: showFirstLast
}), containerNode);
}
};
}
exports.default = pagination;
/***/ },
/* 376 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _forEach = __webpack_require__(164);
var _forEach2 = _interopRequireDefault(_forEach);
var _defaultsDeep = __webpack_require__(377);
var _defaultsDeep2 = _interopRequireDefault(_defaultsDeep);
var _utils = __webpack_require__(336);
var _Paginator = __webpack_require__(379);
var _Paginator2 = _interopRequireDefault(_Paginator);
var _PaginationLink = __webpack_require__(383);
var _PaginationLink2 = _interopRequireDefault(_PaginationLink);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
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 _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 Pagination = function (_React$Component) {
_inherits(Pagination, _React$Component);
function Pagination(props) {
_classCallCheck(this, Pagination);
var _this = _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).call(this, (0, _defaultsDeep2.default)(props, Pagination.defaultProps)));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
_createClass(Pagination, [{
key: 'pageLink',
value: function pageLink(_ref) {
var label = _ref.label;
var ariaLabel = _ref.ariaLabel;
var pageNumber = _ref.pageNumber;
var _ref$additionalClassN = _ref.additionalClassName;
var additionalClassName = _ref$additionalClassN === undefined ? null : _ref$additionalClassN;
var _ref$isDisabled = _ref.isDisabled;
var isDisabled = _ref$isDisabled === undefined ? false : _ref$isDisabled;
var _ref$isActive = _ref.isActive;
var isActive = _ref$isActive === undefined ? false : _ref$isActive;
var createURL = _ref.createURL;
var cssClasses = {
item: (0, _classnames2.default)(this.props.cssClasses.item, additionalClassName),
link: (0, _classnames2.default)(this.props.cssClasses.link)
};
if (isDisabled) {
cssClasses.item = (0, _classnames2.default)(cssClasses.item, this.props.cssClasses.disabled);
} else if (isActive) {
cssClasses.item = (0, _classnames2.default)(cssClasses.item, this.props.cssClasses.active);
}
var url = createURL && !isDisabled ? createURL(pageNumber) : '#';
return _react2.default.createElement(_PaginationLink2.default, {
ariaLabel: ariaLabel,
cssClasses: cssClasses,
handleClick: this.handleClick,
isDisabled: isDisabled,
key: label + pageNumber,
label: label,
pageNumber: pageNumber,
url: url
});
}
}, {
key: 'previousPageLink',
value: function previousPageLink(pager, createURL) {
return this.pageLink({
ariaLabel: 'Previous',
additionalClassName: this.props.cssClasses.previous,
isDisabled: pager.isFirstPage(),
label: this.props.labels.previous,
pageNumber: pager.currentPage - 1,
createURL: createURL
});
}
}, {
key: 'nextPageLink',
value: function nextPageLink(pager, createURL) {
return this.pageLink({
ariaLabel: 'Next',
additionalClassName: this.props.cssClasses.next,
isDisabled: pager.isLastPage(),
label: this.props.labels.next,
pageNumber: pager.currentPage + 1,
createURL: createURL
});
}
}, {
key: 'firstPageLink',
value: function firstPageLink(pager, createURL) {
return this.pageLink({
ariaLabel: 'First',
additionalClassName: this.props.cssClasses.first,
isDisabled: pager.isFirstPage(),
label: this.props.labels.first,
pageNumber: 0,
createURL: createURL
});
}
}, {
key: 'lastPageLink',
value: function lastPageLink(pager, createURL) {
return this.pageLink({
ariaLabel: 'Last',
additionalClassName: this.props.cssClasses.last,
isDisabled: pager.isLastPage(),
label: this.props.labels.last,
pageNumber: pager.total - 1,
createURL: createURL
});
}
}, {
key: 'pages',
value: function pages(pager, createURL) {
var _this2 = this;
var pages = [];
(0, _forEach2.default)(pager.pages(), function (pageNumber) {
var isActive = pageNumber === pager.currentPage;
pages.push(_this2.pageLink({
ariaLabel: pageNumber + 1,
additionalClassName: _this2.props.cssClasses.page,
isActive: isActive,
label: pageNumber + 1,
pageNumber: pageNumber,
createURL: createURL
}));
});
return pages;
}
}, {
key: 'handleClick',
value: function handleClick(pageNumber, event) {
if ((0, _utils.isSpecialClick)(event)) {
// do not alter the default browser behavior
// if one special key is down
return;
}
event.preventDefault();
this.props.setCurrentPage(pageNumber);
}
}, {
key: 'render',
value: function render() {
var pager = new _Paginator2.default({
currentPage: this.props.currentPage,
total: this.props.nbPages,
padding: this.props.padding
});
var createURL = this.props.createURL;
return _react2.default.createElement(
'ul',
{ className: this.props.cssClasses.root },
this.props.showFirstLast ? this.firstPageLink(pager, createURL) : null,
this.previousPageLink(pager, createURL),
this.pages(pager, createURL),
this.nextPageLink(pager, createURL),
this.props.showFirstLast ? this.lastPageLink(pager, createURL) : null
);
}
}]);
return Pagination;
}(_react2.default.Component);
Pagination.defaultProps = {
nbHits: 0,
currentPage: 0,
nbPages: 0
};
exports.default = Pagination;
/***/ },
/* 377 */
/***/ function(module, exports, __webpack_require__) {
var apply = __webpack_require__(106),
baseRest = __webpack_require__(103),
mergeDefaults = __webpack_require__(378),
mergeWith = __webpack_require__(310);
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, mergeDefaults);
return apply(mergeWith, undefined, args);
});
module.exports = defaultsDeep;
/***/ },
/* 378 */
/***/ function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(225),
isObject = __webpack_require__(59);
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/
function mergeDefaults(objValue, srcValue, key, object, source, stack) {
if (isObject(objValue) && isObject(srcValue)) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue);
baseMerge(objValue, srcValue, undefined, mergeDefaults, stack);
stack['delete'](srcValue);
}
return objValue;
}
module.exports = mergeDefaults;
/***/ },
/* 379 */
/***/ 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 _range = __webpack_require__(380);
var _range2 = _interopRequireDefault(_range);
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 Paginator = function () {
function Paginator(params) {
_classCallCheck(this, Paginator);
this.currentPage = params.currentPage;
this.total = params.total;
this.padding = params.padding;
}
_createClass(Paginator, [{
key: 'pages',
value: function pages() {
var total = this.total;
var currentPage = this.currentPage;
var padding = this.padding;
var totalDisplayedPages = this.nbPagesDisplayed(padding, total);
if (totalDisplayedPages === total) return (0, _range2.default)(0, total);
var paddingLeft = this.calculatePaddingLeft(currentPage, padding, total, totalDisplayedPages);
var paddingRight = totalDisplayedPages - paddingLeft;
var first = currentPage - paddingLeft;
var last = currentPage + paddingRight;
return (0, _range2.default)(first, last);
}
}, {
key: 'nbPagesDisplayed',
value: function nbPagesDisplayed(padding, total) {
return Math.min(2 * padding + 1, total);
}
}, {
key: 'calculatePaddingLeft',
value: function calculatePaddingLeft(current, padding, total, totalDisplayedPages) {
if (current <= padding) {
return current;
}
if (current >= total - padding) {
return totalDisplayedPages - (total - current);
}
return padding;
}
}, {
key: 'isLastPage',
value: function isLastPage() {
return this.currentPage === this.total - 1;
}
}, {
key: 'isFirstPage',
value: function isFirstPage() {
return this.currentPage === 0;
}
}]);
return Paginator;
}();
exports.default = Paginator;
/***/ },
/* 380 */
/***/ function(module, exports, __webpack_require__) {
var createRange = __webpack_require__(381);
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
module.exports = range;
/***/ },
/* 381 */
/***/ function(module, exports, __webpack_require__) {
var baseRange = __webpack_require__(382),
isIterateeCall = __webpack_require__(223),
toFinite = __webpack_require__(197);
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
module.exports = createRange;
/***/ },
/* 382 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeMax = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
module.exports = baseRange;
/***/ },
/* 383 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 _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 PaginationLink = function (_React$Component) {
_inherits(PaginationLink, _React$Component);
function PaginationLink() {
_classCallCheck(this, PaginationLink);
return _possibleConstructorReturn(this, (PaginationLink.__proto__ || Object.getPrototypeOf(PaginationLink)).apply(this, arguments));
}
_createClass(PaginationLink, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.handleClick = this.handleClick.bind(this);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return !(0, _isEqual2.default)(this.props, nextProps);
}
}, {
key: 'handleClick',
value: function handleClick(e) {
this.props.handleClick(this.props.pageNumber, e);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var cssClasses = _props.cssClasses;
var label = _props.label;
var ariaLabel = _props.ariaLabel;
var url = _props.url;
var isDisabled = _props.isDisabled;
var tagName = 'span';
var attributes = {
className: cssClasses.link,
dangerouslySetInnerHTML: {
__html: label
}
};
// "Enable" the element, by making it a link
if (!isDisabled) {
tagName = 'a';
attributes = _extends({}, attributes, {
'aria-label': ariaLabel,
'href': url,
'onClick': this.handleClick
});
}
var element = _react2.default.createElement(tagName, attributes);
return _react2.default.createElement(
'li',
{ className: cssClasses.item },
element
);
}
}]);
return PaginationLink;
}(_react2.default.Component);
exports.default = PaginationLink;
/***/ },
/* 384 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _generateRanges2 = __webpack_require__(385);
var _generateRanges3 = _interopRequireDefault(_generateRanges2);
var _defaultTemplates = __webpack_require__(386);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _PriceRanges = __webpack_require__(387);
var _PriceRanges2 = _interopRequireDefault(_PriceRanges);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-price-ranges');
/**
* Instantiate a price ranges on a numerical facet
* @function priceRanges
* @param {string|DOMElement} options.container Valid CSS Selector as a string or DOMElement
* @param {string} options.attributeName Name of the attribute for faceting
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.item] Item template. Template data: `from`, `to` and `currency`
* @param {string} [options.currency='$'] The currency to display
* @param {Object} [options.labels] Labels to use for the widget
* @param {string|Function} [options.labels.separator] Separator label, between min and max
* @param {string|Function} [options.labels.button] Button label
* @param {boolean} [options.autoHideContainer=true] Hide the container when no refinements available
* @param {Object} [options.cssClasses] CSS classes to add
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the wrapping list element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.active] CSS class to add to the active item element
* @param {string|string[]} [options.cssClasses.link] CSS class to add to each link element
* @param {string|string[]} [options.cssClasses.form] CSS class to add to the form element
* @param {string|string[]} [options.cssClasses.label] CSS class to add to each wrapping label of the form
* @param {string|string[]} [options.cssClasses.input] CSS class to add to each input of the form
* @param {string|string[]} [options.cssClasses.currency] CSS class to add to each currency element of the form
* @param {string|string[]} [options.cssClasses.separator] CSS class to add to the separator of the form
* @param {string|string[]} [options.cssClasses.button] CSS class to add to the submit button of the form
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\npriceRanges({\n container,\n attributeName,\n [ currency=$ ],\n [ cssClasses.{root,header,body,list,item,active,link,form,label,input,currency,separator,button,footer} ],\n [ templates.{header,item,footer} ],\n [ labels.{currency,separator,button} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})';
function priceRanges() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var attributeName = _ref.attributeName;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var _ref$labels = _ref.labels;
var userLabels = _ref$labels === undefined ? {} : _ref$labels;
var _ref$currency = _ref.currency;
var userCurrency = _ref$currency === undefined ? '$' : _ref$currency;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var currency = userCurrency;
if (!container || !attributeName) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var PriceRanges = (0, _headerFooter2.default)(_PriceRanges2.default);
if (autoHideContainer === true) {
PriceRanges = (0, _autoHideContainer2.default)(PriceRanges);
}
var labels = _extends({
button: 'Go',
separator: 'to'
}, userLabels);
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active),
form: (0, _classnames2.default)(bem('form'), userCssClasses.form),
label: (0, _classnames2.default)(bem('label'), userCssClasses.label),
input: (0, _classnames2.default)(bem('input'), userCssClasses.input),
currency: (0, _classnames2.default)(bem('currency'), userCssClasses.currency),
button: (0, _classnames2.default)(bem('button'), userCssClasses.button),
separator: (0, _classnames2.default)(bem('separator'), userCssClasses.separator),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer)
};
// before we had opts.currency, you had to pass labels.currency
if (userLabels.currency !== undefined && userLabels.currency !== currency) currency = userLabels.currency;
return {
getConfiguration: function getConfiguration() {
return {
facets: [attributeName]
};
},
_generateRanges: function _generateRanges(results) {
var stats = results.getFacetStats(attributeName);
return (0, _generateRanges3.default)(stats);
},
_extractRefinedRange: function _extractRefinedRange(helper) {
var refinements = helper.getRefinements(attributeName);
var from = void 0;
var to = void 0;
if (refinements.length === 0) {
return [];
}
refinements.forEach(function (v) {
if (v.operator.indexOf('>') !== -1) {
from = Math.floor(v.value[0]);
} else if (v.operator.indexOf('<') !== -1) {
to = Math.ceil(v.value[0]);
}
});
return [{ from: from, to: to, isRefined: true }];
},
_refine: function _refine(helper, from, to) {
var facetValues = this._extractRefinedRange(helper);
helper.clearRefinements(attributeName);
if (facetValues.length === 0 || facetValues[0].from !== from || facetValues[0].to !== to) {
if (typeof from !== 'undefined') {
helper.addNumericRefinement(attributeName, '>=', Math.floor(from));
}
if (typeof to !== 'undefined') {
helper.addNumericRefinement(attributeName, '<=', Math.ceil(to));
}
}
helper.search();
},
init: function init(_ref2) {
var helper = _ref2.helper;
var templatesConfig = _ref2.templatesConfig;
this._refine = this._refine.bind(this, helper);
this._templateProps = (0, _utils.prepareTemplateProps)({
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
},
render: function render(_ref3) {
var results = _ref3.results;
var helper = _ref3.helper;
var state = _ref3.state;
var createURL = _ref3.createURL;
var facetValues = void 0;
if (results.hits.length > 0) {
facetValues = this._extractRefinedRange(helper);
if (facetValues.length === 0) {
facetValues = this._generateRanges(results);
}
} else {
facetValues = [];
}
facetValues.map(function (facetValue) {
var newState = state.clearRefinements(attributeName);
if (!facetValue.isRefined) {
if (facetValue.from !== undefined) {
newState = newState.addNumericRefinement(attributeName, '>=', Math.floor(facetValue.from));
}
if (facetValue.to !== undefined) {
newState = newState.addNumericRefinement(attributeName, '<=', Math.ceil(facetValue.to));
}
}
facetValue.url = createURL(newState);
return facetValue;
});
_reactDom2.default.render(_react2.default.createElement(PriceRanges, {
collapsible: collapsible,
cssClasses: cssClasses,
currency: currency,
facetValues: facetValues,
labels: labels,
refine: this._refine,
shouldAutoHideContainer: facetValues.length === 0,
templateProps: this._templateProps
}), containerNode);
}
};
}
exports.default = priceRanges;
/***/ },
/* 385 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function round(v, precision) {
var res = Math.round(v / precision) * precision;
if (res < 1) {
res = 1;
}
return res;
}
function generateRanges(stats) {
var precision = void 0;
if (stats.avg < 100) {
precision = 1;
} else if (stats.avg < 1000) {
precision = 10;
} else {
precision = 100;
}
var avg = round(Math.round(stats.avg), precision);
var min = Math.ceil(stats.min);
var max = round(Math.floor(stats.max), precision);
while (max > stats.max) {
max -= precision;
}
var next = void 0;
var from = void 0;
var facetValues = [];
if (min !== max) {
next = min;
facetValues.push({
to: next
});
while (next < avg) {
from = facetValues[facetValues.length - 1].to;
next = round(from + (avg - min) / 3, precision);
if (next <= from) {
next = from + 1;
}
facetValues.push({
from: from,
to: next
});
}
while (next < max) {
from = facetValues[facetValues.length - 1].to;
next = round(from + (max - avg) / 3, precision);
if (next <= from) {
next = from + 1;
}
facetValues.push({
from: from,
to: next
});
}
if (facetValues.length === 1) {
if (next !== avg) {
facetValues.push({
from: next,
to: avg
});
next = avg;
}
}
if (facetValues.length === 1) {
facetValues[0].from = stats.min;
facetValues[0].to = stats.max;
} else {
delete facetValues[facetValues.length - 1].to;
}
}
return facetValues;
}
exports.default = generateRanges;
/***/ },
/* 386 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
header: '',
item: '\n {{#from}}\n {{^to}}\n ≥\n {{/to}}\n {{currency}}{{from}}\n {{/from}}\n {{#to}}\n {{#from}}\n -\n {{/from}}\n {{^from}}\n ≤\n {{/from}}\n {{to}}\n {{/to}}\n ',
footer: ''
};
/***/ },
/* 387 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
var _PriceRangesForm = __webpack_require__(388);
var _PriceRangesForm2 = _interopRequireDefault(_PriceRangesForm);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 PriceRanges = function (_React$Component) {
_inherits(PriceRanges, _React$Component);
function PriceRanges() {
_classCallCheck(this, PriceRanges);
return _possibleConstructorReturn(this, (PriceRanges.__proto__ || Object.getPrototypeOf(PriceRanges)).apply(this, arguments));
}
_createClass(PriceRanges, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.refine = this.refine.bind(this);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return !(0, _isEqual2.default)(this.props.facetValues, nextProps.facetValues);
}
}, {
key: 'getForm',
value: function getForm() {
var labels = _extends({
currency: this.props.currency
}, this.props.labels);
var currentRefinement = void 0;
if (this.props.facetValues.length === 1) {
currentRefinement = {
from: this.props.facetValues[0].from !== undefined ? this.props.facetValues[0].from : '',
to: this.props.facetValues[0].to !== undefined ? this.props.facetValues[0].to : ''
};
} else {
currentRefinement = { from: '', to: '' };
}
return _react2.default.createElement(_PriceRangesForm2.default, {
cssClasses: this.props.cssClasses,
currentRefinement: currentRefinement,
labels: labels,
refine: this.refine
});
}
}, {
key: 'getItemFromFacetValue',
value: function getItemFromFacetValue(facetValue) {
var cssClassItem = (0, _classnames2.default)(this.props.cssClasses.item, _defineProperty({}, this.props.cssClasses.active, facetValue.isRefined));
var key = facetValue.from + '_' + facetValue.to;
var handleClick = this.refine.bind(this, facetValue.from, facetValue.to);
var data = _extends({
currency: this.props.currency
}, facetValue);
return _react2.default.createElement(
'div',
{ className: cssClassItem, key: key },
_react2.default.createElement(
'a',
{
className: this.props.cssClasses.link,
href: facetValue.url,
onClick: handleClick
},
_react2.default.createElement(_Template2.default, _extends({ data: data, templateKey: 'item' }, this.props.templateProps))
)
);
}
}, {
key: 'refine',
value: function refine(from, to, event) {
event.preventDefault();
this.props.refine(from, to);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(
'div',
{ className: this.props.cssClasses.list },
this.props.facetValues.map(function (facetValue) {
return _this2.getItemFromFacetValue(facetValue);
})
),
this.getForm()
);
}
}]);
return PriceRanges;
}(_react2.default.Component);
PriceRanges.defaultProps = {
cssClasses: {}
};
exports.default = PriceRanges;
/***/ },
/* 388 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
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 PriceRangesForm = function (_React$Component) {
_inherits(PriceRangesForm, _React$Component);
function PriceRangesForm(props) {
_classCallCheck(this, PriceRangesForm);
var _this = _possibleConstructorReturn(this, (PriceRangesForm.__proto__ || Object.getPrototypeOf(PriceRangesForm)).call(this, props));
_this.state = {
from: props.currentRefinement.from,
to: props.currentRefinement.to
};
return _this;
}
_createClass(PriceRangesForm, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.handleSubmit = this.handleSubmit.bind(this);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
this.setState({
from: props.currentRefinement.from,
to: props.currentRefinement.to
});
}
}, {
key: 'getInput',
value: function getInput(type) {
var _this2 = this;
return _react2.default.createElement(
'label',
{ className: this.props.cssClasses.label },
_react2.default.createElement(
'span',
{ className: this.props.cssClasses.currency },
this.props.labels.currency,
' '
),
_react2.default.createElement('input', {
className: this.props.cssClasses.input,
onChange: function onChange(e) {
return _this2.setState(_defineProperty({}, type, e.target.value));
},
ref: type,
type: 'number',
value: this.state[type]
})
);
}
}, {
key: 'handleSubmit',
value: function handleSubmit(event) {
var from = this.refs.from.value !== '' ? parseInt(this.refs.from.value, 10) : undefined;
var to = this.refs.to.value !== '' ? parseInt(this.refs.to.value, 10) : undefined;
this.props.refine(from, to, event);
}
}, {
key: 'render',
value: function render() {
var fromInput = this.getInput('from');
var toInput = this.getInput('to');
var onSubmit = this.handleSubmit;
return _react2.default.createElement(
'form',
{ className: this.props.cssClasses.form, onSubmit: onSubmit, ref: 'form' },
fromInput,
_react2.default.createElement(
'span',
{ className: this.props.cssClasses.separator },
' ',
this.props.labels.separator,
' '
),
toInput,
_react2.default.createElement(
'button',
{ className: this.props.cssClasses.button, type: 'submit' },
this.props.labels.button
)
);
}
}]);
return PriceRangesForm;
}(_react2.default.Component);
PriceRangesForm.defaultProps = {
cssClasses: {},
labels: {}
};
exports.default = PriceRangesForm;
/***/ },
/* 389 */
/***/ 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 _utils = __webpack_require__(336);
var _forEach = __webpack_require__(164);
var _forEach2 = _interopRequireDefault(_forEach);
var _isString = __webpack_require__(204);
var _isString2 = _interopRequireDefault(_isString);
var _isFunction = __webpack_require__(58);
var _isFunction2 = _interopRequireDefault(_isFunction);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _hogan = __webpack_require__(344);
var _hogan2 = _interopRequireDefault(_hogan);
var _defaultTemplates = __webpack_require__(390);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-search-box');
var KEY_ENTER = 13;
var KEY_SUPPRESS = 8;
/**
* Instantiate a searchbox
* @function searchBox
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} [options.placeholder] Input's placeholder
* @param {boolean|Object} [options.poweredBy=false] Define if a "powered by Algolia" link should be added near the input
* @param {function|string} [options.poweredBy.template] Template used for displaying the link. Can accept a function or a Hogan string.
* @param {number} [options.poweredBy.cssClasses] CSS classes to add
* @param {string|string[]} [options.poweredBy.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.poweredBy.cssClasses.link] CSS class to add to the link element
* @param {boolean} [options.wrapInput=true] Wrap the input in a `div.ais-search-box`
* @param {boolean|string} [autofocus='auto'] autofocus on the input
* @param {boolean} [options.searchOnEnterKeyPressOnly=false] If set, trigger the search
* once `<Enter>` is pressed only
* @param {Object} [options.cssClasses] CSS classes to add
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the
* wrapping div (if `wrapInput` set to `true`)
* @param {string|string[]} [options.cssClasses.input] CSS class to add to the input
* @param {function} [options.queryHook] A function that will be called every time a new search would be done. You
* will get the query as first parameter and a search(query) function to call as the second parameter.
* This queryHook can be used to debounce the number of searches done from the searchBox.
* @return {Object}
*/
var usage = 'Usage:\nsearchBox({\n container,\n [ placeholder ],\n [ cssClasses.{input,poweredBy} ],\n [ poweredBy=false || poweredBy.{template, cssClasses.{root,link}} ],\n [ wrapInput ],\n [ autofocus ],\n [ searchOnEnterKeyPressOnly ],\n [ queryHook ]\n})';
function searchBox(_ref) {
var container = _ref.container;
var _ref$placeholder = _ref.placeholder;
var placeholder = _ref$placeholder === undefined ? '' : _ref$placeholder;
var _ref$cssClasses = _ref.cssClasses;
var cssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$poweredBy = _ref.poweredBy;
var poweredBy = _ref$poweredBy === undefined ? false : _ref$poweredBy;
var _ref$wrapInput = _ref.wrapInput;
var wrapInput = _ref$wrapInput === undefined ? true : _ref$wrapInput;
var _ref$autofocus = _ref.autofocus;
var autofocus = _ref$autofocus === undefined ? 'auto' : _ref$autofocus;
var _ref$searchOnEnterKey = _ref.searchOnEnterKeyPressOnly;
var searchOnEnterKeyPressOnly = _ref$searchOnEnterKey === undefined ? false : _ref$searchOnEnterKey;
var queryHook = _ref.queryHook;
// the 'input' event is triggered when the input value changes
// in any case: typing, copy pasting with mouse..
// 'onpropertychange' is the IE8 alternative until we support IE8
// but it's flawed: http://help.dottoro.com/ljhxklln.php
var INPUT_EVENT = window.addEventListener ? 'input' : 'propertychange';
if (!container) {
throw new Error(usage);
}
container = (0, _utils.getContainerNode)(container);
// Only possible values are 'auto', true and false
if (typeof autofocus !== 'boolean') {
autofocus = 'auto';
}
// Convert to object if only set to true
if (poweredBy === true) {
poweredBy = {};
}
return {
getInput: function getInput() {
// Returns reference to targeted input if present, or create a new one
if (container.tagName === 'INPUT') {
return container;
}
return document.createElement('input');
},
wrapInput: function wrapInput(input) {
// Wrap input in a .ais-search-box div
var wrapper = document.createElement('div');
var CSSClassesToAdd = (0, _classnames2.default)(bem(null), cssClasses.root).split(' ');
CSSClassesToAdd.forEach(function (cssClass) {
return wrapper.classList.add(cssClass);
});
wrapper.appendChild(input);
return wrapper;
},
addDefaultAttributesToInput: function addDefaultAttributesToInput(input, query) {
var defaultAttributes = {
autocapitalize: 'off',
autocomplete: 'off',
autocorrect: 'off',
placeholder: placeholder,
role: 'textbox',
spellcheck: 'false',
type: 'text',
value: query
};
// Overrides attributes if not already set
(0, _forEach2.default)(defaultAttributes, function (value, key) {
if (input.hasAttribute(key)) {
return;
}
input.setAttribute(key, value);
});
// Add classes
var CSSClassesToAdd = (0, _classnames2.default)(bem('input'), cssClasses.input).split(' ');
CSSClassesToAdd.forEach(function (cssClass) {
return input.classList.add(cssClass);
});
},
addPoweredBy: function addPoweredBy(input) {
// Default values
poweredBy = _extends({
cssClasses: {},
template: _defaultTemplates2.default.poweredBy
}, poweredBy);
var poweredByCSSClasses = {
root: (0, _classnames2.default)(bem('powered-by'), poweredBy.cssClasses.root),
link: (0, _classnames2.default)(bem('powered-by-link'), poweredBy.cssClasses.link)
};
var url = 'https://www.algolia.com/?' + 'utm_source=instantsearch.js&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby';
var templateData = {
cssClasses: poweredByCSSClasses,
url: url
};
var template = poweredBy.template;
var stringNode = void 0;
if ((0, _isString2.default)(template)) {
stringNode = _hogan2.default.compile(template).render(templateData);
}
if ((0, _isFunction2.default)(template)) {
stringNode = template(templateData);
}
// Crossbrowser way to create a DOM node from a string. We wrap in
// a `span` to make sure we have one and only one node.
var tmpNode = document.createElement('div');
tmpNode.innerHTML = '<span>' + stringNode.trim() + '</span>';
var htmlNode = tmpNode.firstChild;
input.parentNode.insertBefore(htmlNode, input.nextSibling);
},
init: function init(_ref2) {
var state = _ref2.state;
var helper = _ref2.helper;
var onHistoryChange = _ref2.onHistoryChange;
var isInputTargeted = container.tagName === 'INPUT';
var input = this._input = this.getInput();
var previousQuery = void 0;
// Add all the needed attributes and listeners to the input
this.addDefaultAttributesToInput(input, state.query);
// always set the query every keystrokes when there's no queryHook
if (!queryHook) {
addListener(input, INPUT_EVENT, getInputValueAndCall(setQuery));
}
// search on enter
if (searchOnEnterKeyPressOnly) {
addListener(input, 'keyup', ifKey(KEY_ENTER, getInputValueAndCall(maybeSearch)));
} else {
addListener(input, INPUT_EVENT, getInputValueAndCall(maybeSearch));
// handle IE8 weirdness where BACKSPACE key will not trigger an input change..
// can be removed as soon as we remove support for it
if (INPUT_EVENT === 'propertychange' || window.attachEvent) {
addListener(input, 'keyup', ifKey(KEY_SUPPRESS, getInputValueAndCall(setQuery)));
addListener(input, 'keyup', ifKey(KEY_SUPPRESS, getInputValueAndCall(maybeSearch)));
}
}
function maybeSearch(query) {
if (queryHook) {
queryHook(query, setQueryAndSearch);
return;
}
search(query);
}
function setQuery(query) {
if (query !== helper.state.query) {
previousQuery = helper.state.query;
helper.setQuery(query);
}
}
function search(query) {
if (previousQuery !== undefined && previousQuery !== query) helper.search();
}
function setQueryAndSearch(query) {
setQuery(query);
search(query);
}
if (isInputTargeted) {
// To replace the node, we need to create an intermediate node
var placeholderNode = document.createElement('div');
input.parentNode.insertBefore(placeholderNode, input);
var parentNode = input.parentNode;
var wrappedInput = wrapInput ? this.wrapInput(input) : input;
parentNode.replaceChild(wrappedInput, placeholderNode);
} else {
var _wrappedInput = wrapInput ? this.wrapInput(input) : input;
container.appendChild(_wrappedInput);
}
// Optional "powered by Algolia" widget
if (poweredBy) {
this.addPoweredBy(input);
}
// Update value when query change outside of the input
onHistoryChange(function (fullState) {
input.value = fullState.query || '';
});
// When the page is coming from BFCache
// (https://developer.mozilla.org/en-US/docs/Working_with_BFCache)
// then we force the input value to be the current query
// Otherwise, this happens:
// - <input> autocomplete = off (default)
// - search $query
// - navigate away
// - use back button
// - input query is empty (because <input> autocomplete = off)
window.addEventListener('pageshow', function () {
input.value = helper.state.query;
});
if (autofocus === true || autofocus === 'auto' && helper.state.query === '') {
input.focus();
input.setSelectionRange(helper.state.query.length, helper.state.query.length);
}
},
render: function render(_ref3) {
var helper = _ref3.helper;
// updating the query from the outside using the helper
// will fall in this case
// If the input is focused, we do not update it.
if (document.activeElement === this._input) {
return;
}
if (helper.state.query !== this._input.value) {
this._input.value = helper.state.query;
}
}
};
}
function addListener(el, type, fn) {
if (el.addEventListener) {
el.addEventListener(type, fn);
} else {
el.attachEvent('on' + type, fn);
}
}
function getValue(e) {
return (e.currentTarget ? e.currentTarget : e.srcElement).value;
}
function ifKey(expectedKeyCode, func) {
return function (actualEvent) {
return actualEvent.keyCode === expectedKeyCode && func(actualEvent);
};
}
function getInputValueAndCall(func) {
return function (actualEvent) {
return func(getValue(actualEvent));
};
}
exports.default = searchBox;
/***/ },
/* 390 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
poweredBy: "\n<div class=\"{{cssClasses.root}}\">\n Search by\n <a class=\"{{cssClasses.link}}\" href=\"{{url}}\" target=\"_blank\">Algolia</a>\n</div>"
};
/***/ },
/* 391 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _find = __webpack_require__(205);
var _find2 = _interopRequireDefault(_find);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _Slider = __webpack_require__(392);
var _Slider2 = _interopRequireDefault(_Slider);
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; }
var bem = (0, _utils.bemHelper)('ais-range-slider');
var defaultTemplates = {
header: '',
footer: ''
};
/**
* Instantiate a slider based on a numeric attribute.
* This is a wrapper around [noUiSlider](http://refreshless.com/nouislider/)
* @function rangeSlider
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the attribute for faceting
* @param {boolean|Object} [options.tooltips=true] Should we show tooltips or not.
* The default tooltip will show the raw value.
* You can also provide
* `tooltips: {format: function(rawValue) {return '$' + Math.round(rawValue).toLocaleString()}}`
* So that you can format the tooltip display value as you want
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header=''] Header template
* @param {string|Function} [options.templates.footer=''] Footer template
* @param {boolean} [options.autoHideContainer=true] Hide the container when no refinements available
* @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {boolean|object} [options.pips=true] Show slider pips.
* @param {boolean|object} [options.step=1] Every handle move will jump that number of steps.
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @param {number} [options.min] Minimal slider value, default to automatically computed from the result set
* @param {number} [options.max] Maximal slider value, defaults to automatically computed from the result set
* @return {Object}
*/
var usage = 'Usage:\nrangeSlider({\n container,\n attributeName,\n [ tooltips=true ],\n [ templates.{header, footer} ],\n [ cssClasses.{root, header, body, footer} ],\n [ step=1 ],\n [ pips=true ],\n [ autoHideContainer=true ],\n [ collapsible=false ],\n [ min ],\n [ max ]\n});\n';
function rangeSlider() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var attributeName = _ref.attributeName;
var _ref$tooltips = _ref.tooltips;
var tooltips = _ref$tooltips === undefined ? true : _ref$tooltips;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? defaultTemplates : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$step = _ref.step;
var step = _ref$step === undefined ? 1 : _ref$step;
var _ref$pips = _ref.pips;
var pips = _ref$pips === undefined ? true : _ref$pips;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var userMin = _ref.min;
var userMax = _ref.max;
var _ref$precision = _ref.precision;
var precision = _ref$precision === undefined ? 2 : _ref$precision;
if (!container || !attributeName) {
throw new Error(usage);
}
var formatToNumber = function formatToNumber(v) {
return Number(Number(v).toFixed(precision));
};
var sliderFormatter = {
from: function from(v) {
return v;
},
to: function to(v) {
return formatToNumber(v).toLocaleString();
}
};
var containerNode = (0, _utils.getContainerNode)(container);
var Slider = (0, _headerFooter2.default)(_Slider2.default);
if (autoHideContainer === true) {
Slider = (0, _autoHideContainer2.default)(Slider);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer)
};
return {
getConfiguration: function getConfiguration(originalConf) {
var conf = {
disjunctiveFacets: [attributeName]
};
if ((userMin !== undefined || userMax !== undefined) && (!originalConf || originalConf.numericRefinements && originalConf.numericRefinements[attributeName] === undefined)) {
conf.numericRefinements = _defineProperty({}, attributeName, {});
if (userMin !== undefined) {
conf.numericRefinements[attributeName]['>='] = [userMin];
}
if (userMax !== undefined) {
conf.numericRefinements[attributeName]['<='] = [userMax];
}
}
return conf;
},
_getCurrentRefinement: function _getCurrentRefinement(helper) {
var min = helper.state.getNumericRefinement(attributeName, '>=');
var max = helper.state.getNumericRefinement(attributeName, '<=');
if (min && min.length) {
min = min[0];
} else {
min = -Infinity;
}
if (max && max.length) {
max = max[0];
} else {
max = Infinity;
}
return {
min: min,
max: max
};
},
_refine: function _refine(helper, oldValues, newValues) {
helper.clearRefinements(attributeName);
if (newValues[0] > oldValues.min) {
helper.addNumericRefinement(attributeName, '>=', formatToNumber(newValues[0]));
}
if (newValues[1] < oldValues.max) {
helper.addNumericRefinement(attributeName, '<=', formatToNumber(newValues[1]));
}
helper.search();
},
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
this._templateProps = (0, _utils.prepareTemplateProps)({
defaultTemplates: defaultTemplates,
templatesConfig: templatesConfig,
templates: templates
});
},
render: function render(_ref3) {
var results = _ref3.results;
var helper = _ref3.helper;
var facet = (0, _find2.default)(results.disjunctiveFacets, { name: attributeName });
var stats = facet !== undefined && facet.stats !== undefined ? facet.stats : {
min: null,
max: null
};
if (userMin !== undefined) stats.min = userMin;
if (userMax !== undefined) stats.max = userMax;
var currentRefinement = this._getCurrentRefinement(helper);
if (tooltips.format !== undefined) {
tooltips = [{ to: tooltips.format }, { to: tooltips.format }];
}
_reactDom2.default.render(_react2.default.createElement(Slider, {
collapsible: collapsible,
cssClasses: cssClasses,
onChange: this._refine.bind(this, helper, stats),
pips: pips,
range: { min: Math.floor(stats.min), max: Math.ceil(stats.max) },
shouldAutoHideContainer: stats.min === stats.max,
start: [currentRefinement.min, currentRefinement.max],
step: step,
templateProps: this._templateProps,
tooltips: tooltips,
format: sliderFormatter
}), containerNode);
}
};
}
exports.default = rangeSlider;
/***/ },
/* 392 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _omit = __webpack_require__(176);
var _omit2 = _interopRequireDefault(_omit);
var _reactNouislider = __webpack_require__(393);
var _reactNouislider2 = _interopRequireDefault(_reactNouislider);
var _isEqual = __webpack_require__(202);
var _isEqual2 = _interopRequireDefault(_isEqual);
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 _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 cssPrefix = 'ais-range-slider--';
var Slider = function (_React$Component) {
_inherits(Slider, _React$Component);
function Slider() {
_classCallCheck(this, Slider);
return _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).apply(this, arguments));
}
_createClass(Slider, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.handleChange = this.handleChange.bind(this);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return !(0, _isEqual2.default)(this.props.range, nextProps.range) || !(0, _isEqual2.default)(this.props.start, nextProps.start);
}
// we are only interested in rawValues
}, {
key: 'handleChange',
value: function handleChange(formattedValues, handleId, rawValues) {
this.props.onChange(rawValues);
}
}, {
key: 'render',
value: function render() {
if (this.props.range.min === this.props.range.max) {
// There's no need to try to render the Slider, it will not be usable
// and will throw
return null;
}
// setup pips
var pips = void 0;
if (this.props.pips === false) {
pips = undefined;
} else if (this.props.pips === true || typeof this.props.pips === 'undefined') {
pips = {
mode: 'positions',
density: 3,
values: [0, 50, 100],
stepped: true
};
} else {
pips = this.props.pips;
}
return _react2.default.createElement(_reactNouislider2.default
// NoUiSlider also accepts a cssClasses prop, but we don't want to
// provide one.
, _extends({}, (0, _omit2.default)(this.props, ['cssClasses']), {
animate: false,
behaviour: 'snap',
connect: true,
cssPrefix: cssPrefix,
onChange: this.handleChange,
pips: pips
}));
}
}]);
return Slider;
}(_react2.default.Component);
exports.default = Slider;
/***/ },
/* 393 */
/***/ 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; }; })();
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__(333);
var _react2 = _interopRequireDefault(_react);
var _nouislider = __webpack_require__(394);
var _nouislider2 = _interopRequireDefault(_nouislider);
var Nouislider = (function (_React$Component) {
_inherits(Nouislider, _React$Component);
function Nouislider() {
_classCallCheck(this, Nouislider);
_get(Object.getPrototypeOf(Nouislider.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Nouislider, [{
key: 'componentDidMount',
value: function componentDidMount() {
if (this.props.disabled) this.sliderContainer.setAttribute('disabled', true);else this.sliderContainer.removeAttribute('disabled');
this.createSlider();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if (this.props.disabled) this.sliderContainer.setAttribute('disabled', true);else this.sliderContainer.removeAttribute('disabled');
this.slider.destroy();
this.createSlider();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.slider.destroy();
}
}, {
key: 'createSlider',
value: function createSlider() {
var slider = this.slider = _nouislider2['default'].create(this.sliderContainer, _extends({}, this.props));
if (this.props.onUpdate) {
slider.on('update', this.props.onUpdate);
}
if (this.props.onChange) {
slider.on('change', this.props.onChange);
}
if (this.props.onSlide) {
slider.on('slide', this.props.onSlide);
}
if (this.props.onStart) {
slider.on('start', this.props.onStart);
}
if (this.props.onEnd) {
slider.on('end', this.props.onEnd);
}
if (this.props.onSet) {
slider.on('set', this.props.onSet);
}
}
}, {
key: 'render',
value: function render() {
var _this = this;
return _react2['default'].createElement('div', { ref: function (slider) {
_this.sliderContainer = slider;
} });
}
}]);
return Nouislider;
})(_react2['default'].Component);
Nouislider.propTypes = {
// http://refreshless.com/nouislider/slider-options/#section-animate
animate: _react2['default'].PropTypes.bool,
// http://refreshless.com/nouislider/behaviour-option/
behaviour: _react2['default'].PropTypes.string,
// http://refreshless.com/nouislider/slider-options/#section-Connect
connect: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.oneOf(['lower', 'upper']), _react2['default'].PropTypes.bool]),
// http://refreshless.com/nouislider/slider-options/#section-cssPrefix
cssPrefix: _react2['default'].PropTypes.string,
// http://refreshless.com/nouislider/slider-options/#section-orientation
direction: _react2['default'].PropTypes.oneOf(['ltr', 'rtl']),
// http://refreshless.com/nouislider/more/#section-disable
disabled: _react2['default'].PropTypes.bool,
// http://refreshless.com/nouislider/slider-options/#section-limit
limit: _react2['default'].PropTypes.number,
// http://refreshless.com/nouislider/slider-options/#section-margin
margin: _react2['default'].PropTypes.number,
// http://refreshless.com/nouislider/events-callbacks/#section-change
onChange: _react2['default'].PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/
onEnd: _react2['default'].PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/#section-set
onSet: _react2['default'].PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/#section-slide
onSlide: _react2['default'].PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/
onStart: _react2['default'].PropTypes.func,
// http://refreshless.com/nouislider/events-callbacks/#section-update
onUpdate: _react2['default'].PropTypes.func,
// http://refreshless.com/nouislider/slider-options/#section-orientation
orientation: _react2['default'].PropTypes.oneOf(['horizontal', 'vertical']),
// http://refreshless.com/nouislider/pips/
pips: _react2['default'].PropTypes.object,
// http://refreshless.com/nouislider/slider-values/#section-range
range: _react2['default'].PropTypes.object.isRequired,
// http://refreshless.com/nouislider/slider-options/#section-start
start: _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.number).isRequired,
// http://refreshless.com/nouislider/slider-options/#section-step
step: _react2['default'].PropTypes.number,
// http://refreshless.com/nouislider/slider-options/#section-tooltips
tooltips: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.shape({
to: _react2['default'].PropTypes.func
}))])
};
module.exports = Nouislider;
/***/ },
/* 394 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! nouislider - 8.5.1 - 2016-04-24 16:00:29 */
(function (factory) {
if ( true ) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if ( typeof exports === 'object' ) {
// Node/CommonJS
module.exports = factory();
} else {
// Browser globals
window.noUiSlider = factory();
}
}(function( ){
'use strict';
// Removes duplicates from an array.
function unique(array) {
return array.filter(function(a){
return !this[a] ? this[a] = true : false;
}, {});
}
// Round a value to the closest 'to'.
function closest ( value, to ) {
return Math.round(value / to) * to;
}
// Current position of an element relative to the document.
function offset ( elem ) {
var rect = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
docElem = doc.documentElement,
pageOffset = getPageOffset();
// getBoundingClientRect contains left scroll in Chrome on Android.
// I haven't found a feature detection that proves this. Worst case
// scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
if ( /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) ) {
pageOffset.x = 0;
}
return {
top: rect.top + pageOffset.y - docElem.clientTop,
left: rect.left + pageOffset.x - docElem.clientLeft
};
}
// Checks whether a value is numerical.
function isNumeric ( a ) {
return typeof a === 'number' && !isNaN( a ) && isFinite( a );
}
// Sets a class and removes it after [duration] ms.
function addClassFor ( element, className, duration ) {
addClass(element, className);
setTimeout(function(){
removeClass(element, className);
}, duration);
}
// Limits a value to 0 - 100
function limit ( a ) {
return Math.max(Math.min(a, 100), 0);
}
// Wraps a variable as an array, if it isn't one yet.
function asArray ( a ) {
return Array.isArray(a) ? a : [a];
}
// Counts decimals
function countDecimals ( numStr ) {
var pieces = numStr.split(".");
return pieces.length > 1 ? pieces[1].length : 0;
}
// http://youmightnotneedjquery.com/#add_class
function addClass ( el, className ) {
if ( el.classList ) {
el.classList.add(className);
} else {
el.className += ' ' + className;
}
}
// http://youmightnotneedjquery.com/#remove_class
function removeClass ( el, className ) {
if ( el.classList ) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
// https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/
function hasClass ( el, className ) {
return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className);
}
// https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes
function getPageOffset ( ) {
var supportPageOffset = window.pageXOffset !== undefined,
isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"),
x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft,
y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
return {
x: x,
y: y
};
}
// we provide a function to compute constants instead
// of accessing window.* as soon as the module needs it
// so that we do not compute anything if not needed
function getActions ( ) {
// Determine the events to bind. IE11 implements pointerEvents without
// a prefix, which breaks compatibility with the IE10 implementation.
return window.navigator.pointerEnabled ? {
start: 'pointerdown',
move: 'pointermove',
end: 'pointerup'
} : window.navigator.msPointerEnabled ? {
start: 'MSPointerDown',
move: 'MSPointerMove',
end: 'MSPointerUp'
} : {
start: 'mousedown touchstart',
move: 'mousemove touchmove',
end: 'mouseup touchend'
};
}
// Value calculation
// Determine the size of a sub-range in relation to a full range.
function subRangeRatio ( pa, pb ) {
return (100 / (pb - pa));
}
// (percentage) How many percent is this value of this range?
function fromPercentage ( range, value ) {
return (value * 100) / ( range[1] - range[0] );
}
// (percentage) Where is this value on this range?
function toPercentage ( range, value ) {
return fromPercentage( range, range[0] < 0 ?
value + Math.abs(range[0]) :
value - range[0] );
}
// (value) How much is this percentage on this range?
function isPercentage ( range, value ) {
return ((value * ( range[1] - range[0] )) / 100) + range[0];
}
// Range conversion
function getJ ( value, arr ) {
var j = 1;
while ( value >= arr[j] ){
j += 1;
}
return j;
}
// (percentage) Input a value, find where, on a scale of 0-100, it applies.
function toStepping ( xVal, xPct, value ) {
if ( value >= xVal.slice(-1)[0] ){
return 100;
}
var j = getJ( value, xVal ), va, vb, pa, pb;
va = xVal[j-1];
vb = xVal[j];
pa = xPct[j-1];
pb = xPct[j];
return pa + (toPercentage([va, vb], value) / subRangeRatio (pa, pb));
}
// (value) Input a percentage, find where it is on the specified range.
function fromStepping ( xVal, xPct, value ) {
// There is no range group that fits 100
if ( value >= 100 ){
return xVal.slice(-1)[0];
}
var j = getJ( value, xPct ), va, vb, pa, pb;
va = xVal[j-1];
vb = xVal[j];
pa = xPct[j-1];
pb = xPct[j];
return isPercentage([va, vb], (value - pa) * subRangeRatio (pa, pb));
}
// (percentage) Get the step that applies at a certain value.
function getStep ( xPct, xSteps, snap, value ) {
if ( value === 100 ) {
return value;
}
var j = getJ( value, xPct ), a, b;
// If 'snap' is set, steps are used as fixed points on the slider.
if ( snap ) {
a = xPct[j-1];
b = xPct[j];
// Find the closest position, a or b.
if ((value - a) > ((b-a)/2)){
return b;
}
return a;
}
if ( !xSteps[j-1] ){
return value;
}
return xPct[j-1] + closest(
value - xPct[j-1],
xSteps[j-1]
);
}
// Entry parsing
function handleEntryPoint ( index, value, that ) {
var percentage;
// Wrap numerical input in an array.
if ( typeof value === "number" ) {
value = [value];
}
// Reject any invalid input, by testing whether value is an array.
if ( Object.prototype.toString.call( value ) !== '[object Array]' ){
throw new Error("noUiSlider: 'range' contains invalid value.");
}
// Covert min/max syntax to 0 and 100.
if ( index === 'min' ) {
percentage = 0;
} else if ( index === 'max' ) {
percentage = 100;
} else {
percentage = parseFloat( index );
}
// Check for correct input.
if ( !isNumeric( percentage ) || !isNumeric( value[0] ) ) {
throw new Error("noUiSlider: 'range' value isn't numeric.");
}
// Store values.
that.xPct.push( percentage );
that.xVal.push( value[0] );
// NaN will evaluate to false too, but to keep
// logging clear, set step explicitly. Make sure
// not to override the 'step' setting with false.
if ( !percentage ) {
if ( !isNaN( value[1] ) ) {
that.xSteps[0] = value[1];
}
} else {
that.xSteps.push( isNaN(value[1]) ? false : value[1] );
}
}
function handleStepPoint ( i, n, that ) {
// Ignore 'false' stepping.
if ( !n ) {
return true;
}
// Factor to range ratio
that.xSteps[i] = fromPercentage([
that.xVal[i]
,that.xVal[i+1]
], n) / subRangeRatio (
that.xPct[i],
that.xPct[i+1] );
}
// Interface
// The interface to Spectrum handles all direction-based
// conversions, so the above values are unaware.
function Spectrum ( entry, snap, direction, singleStep ) {
this.xPct = [];
this.xVal = [];
this.xSteps = [ singleStep || false ];
this.xNumSteps = [ false ];
this.snap = snap;
this.direction = direction;
var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ];
// Map the object keys to an array.
for ( index in entry ) {
if ( entry.hasOwnProperty(index) ) {
ordered.push([entry[index], index]);
}
}
// Sort all entries by value (numeric sort).
if ( ordered.length && typeof ordered[0][0] === "object" ) {
ordered.sort(function(a, b) { return a[0][0] - b[0][0]; });
} else {
ordered.sort(function(a, b) { return a[0] - b[0]; });
}
// Convert all entries to subranges.
for ( index = 0; index < ordered.length; index++ ) {
handleEntryPoint(ordered[index][1], ordered[index][0], this);
}
// Store the actual step values.
// xSteps is sorted in the same order as xPct and xVal.
this.xNumSteps = this.xSteps.slice(0);
// Convert all numeric steps to the percentage of the subrange they represent.
for ( index = 0; index < this.xNumSteps.length; index++ ) {
handleStepPoint(index, this.xNumSteps[index], this);
}
}
Spectrum.prototype.getMargin = function ( value ) {
return this.xPct.length === 2 ? fromPercentage(this.xVal, value) : false;
};
Spectrum.prototype.toStepping = function ( value ) {
value = toStepping( this.xVal, this.xPct, value );
// Invert the value if this is a right-to-left slider.
if ( this.direction ) {
value = 100 - value;
}
return value;
};
Spectrum.prototype.fromStepping = function ( value ) {
// Invert the value if this is a right-to-left slider.
if ( this.direction ) {
value = 100 - value;
}
return fromStepping( this.xVal, this.xPct, value );
};
Spectrum.prototype.getStep = function ( value ) {
// Find the proper step for rtl sliders by search in inverse direction.
// Fixes issue #262.
if ( this.direction ) {
value = 100 - value;
}
value = getStep(this.xPct, this.xSteps, this.snap, value );
if ( this.direction ) {
value = 100 - value;
}
return value;
};
Spectrum.prototype.getApplicableStep = function ( value ) {
// If the value is 100%, return the negative step twice.
var j = getJ(value, this.xPct), offset = value === 100 ? 2 : 1;
return [this.xNumSteps[j-2], this.xVal[j-offset], this.xNumSteps[j-offset]];
};
// Outside testing
Spectrum.prototype.convert = function ( value ) {
return this.getStep(this.toStepping(value));
};
/* Every input option is tested and parsed. This'll prevent
endless validation in internal methods. These tests are
structured with an item for every option available. An
option can be marked as required by setting the 'r' flag.
The testing function is provided with three arguments:
- The provided value for the option;
- A reference to the options object;
- The name for the option;
The testing function returns false when an error is detected,
or true when everything is OK. It can also modify the option
object, to make sure all values can be correctly looped elsewhere. */
var defaultFormatter = { 'to': function( value ){
return value !== undefined && value.toFixed(2);
}, 'from': Number };
function testStep ( parsed, entry ) {
if ( !isNumeric( entry ) ) {
throw new Error("noUiSlider: 'step' is not numeric.");
}
// The step option can still be used to set stepping
// for linear sliders. Overwritten if set in 'range'.
parsed.singleStep = entry;
}
function testRange ( parsed, entry ) {
// Filter incorrect input.
if ( typeof entry !== 'object' || Array.isArray(entry) ) {
throw new Error("noUiSlider: 'range' is not an object.");
}
// Catch missing start or end.
if ( entry.min === undefined || entry.max === undefined ) {
throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
}
// Catch equal start or end.
if ( entry.min === entry.max ) {
throw new Error("noUiSlider: 'range' 'min' and 'max' cannot be equal.");
}
parsed.spectrum = new Spectrum(entry, parsed.snap, parsed.dir, parsed.singleStep);
}
function testStart ( parsed, entry ) {
entry = asArray(entry);
// Validate input. Values aren't tested, as the public .val method
// will always provide a valid location.
if ( !Array.isArray( entry ) || !entry.length || entry.length > 2 ) {
throw new Error("noUiSlider: 'start' option is incorrect.");
}
// Store the number of handles.
parsed.handles = entry.length;
// When the slider is initialized, the .val method will
// be called with the start options.
parsed.start = entry;
}
function testSnap ( parsed, entry ) {
// Enforce 100% stepping within subranges.
parsed.snap = entry;
if ( typeof entry !== 'boolean' ){
throw new Error("noUiSlider: 'snap' option must be a boolean.");
}
}
function testAnimate ( parsed, entry ) {
// Enforce 100% stepping within subranges.
parsed.animate = entry;
if ( typeof entry !== 'boolean' ){
throw new Error("noUiSlider: 'animate' option must be a boolean.");
}
}
function testAnimationDuration ( parsed, entry ) {
parsed.animationDuration = entry;
if ( typeof entry !== 'number' ){
throw new Error("noUiSlider: 'animationDuration' option must be a number.");
}
}
function testConnect ( parsed, entry ) {
if ( entry === 'lower' && parsed.handles === 1 ) {
parsed.connect = 1;
} else if ( entry === 'upper' && parsed.handles === 1 ) {
parsed.connect = 2;
} else if ( entry === true && parsed.handles === 2 ) {
parsed.connect = 3;
} else if ( entry === false ) {
parsed.connect = 0;
} else {
throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
}
}
function testOrientation ( parsed, entry ) {
// Set orientation to an a numerical value for easy
// array selection.
switch ( entry ){
case 'horizontal':
parsed.ort = 0;
break;
case 'vertical':
parsed.ort = 1;
break;
default:
throw new Error("noUiSlider: 'orientation' option is invalid.");
}
}
function testMargin ( parsed, entry ) {
if ( !isNumeric(entry) ){
throw new Error("noUiSlider: 'margin' option must be numeric.");
}
// Issue #582
if ( entry === 0 ) {
return;
}
parsed.margin = parsed.spectrum.getMargin(entry);
if ( !parsed.margin ) {
throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.");
}
}
function testLimit ( parsed, entry ) {
if ( !isNumeric(entry) ){
throw new Error("noUiSlider: 'limit' option must be numeric.");
}
parsed.limit = parsed.spectrum.getMargin(entry);
if ( !parsed.limit ) {
throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.");
}
}
function testDirection ( parsed, entry ) {
// Set direction as a numerical value for easy parsing.
// Invert connection for RTL sliders, so that the proper
// handles get the connect/background classes.
switch ( entry ) {
case 'ltr':
parsed.dir = 0;
break;
case 'rtl':
parsed.dir = 1;
parsed.connect = [0,2,1,3][parsed.connect];
break;
default:
throw new Error("noUiSlider: 'direction' option was not recognized.");
}
}
function testBehaviour ( parsed, entry ) {
// Make sure the input is a string.
if ( typeof entry !== 'string' ) {
throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
}
// Check if the string contains any keywords.
// None are required.
var tap = entry.indexOf('tap') >= 0,
drag = entry.indexOf('drag') >= 0,
fixed = entry.indexOf('fixed') >= 0,
snap = entry.indexOf('snap') >= 0,
hover = entry.indexOf('hover') >= 0;
// Fix #472
if ( drag && !parsed.connect ) {
throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");
}
parsed.events = {
tap: tap || snap,
drag: drag,
fixed: fixed,
snap: snap,
hover: hover
};
}
function testTooltips ( parsed, entry ) {
var i;
if ( entry === false ) {
return;
} else if ( entry === true ) {
parsed.tooltips = [];
for ( i = 0; i < parsed.handles; i++ ) {
parsed.tooltips.push(true);
}
} else {
parsed.tooltips = asArray(entry);
if ( parsed.tooltips.length !== parsed.handles ) {
throw new Error("noUiSlider: must pass a formatter for all handles.");
}
parsed.tooltips.forEach(function(formatter){
if ( typeof formatter !== 'boolean' && (typeof formatter !== 'object' || typeof formatter.to !== 'function') ) {
throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.");
}
});
}
}
function testFormat ( parsed, entry ) {
parsed.format = entry;
// Any object with a to and from method is supported.
if ( typeof entry.to === 'function' && typeof entry.from === 'function' ) {
return true;
}
throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");
}
function testCssPrefix ( parsed, entry ) {
if ( entry !== undefined && typeof entry !== 'string' && entry !== false ) {
throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");
}
parsed.cssPrefix = entry;
}
function testCssClasses ( parsed, entry ) {
if ( entry !== undefined && typeof entry !== 'object' ) {
throw new Error("noUiSlider: 'cssClasses' must be an object.");
}
if ( typeof parsed.cssPrefix === 'string' ) {
parsed.cssClasses = {};
for ( var key in entry ) {
if ( !entry.hasOwnProperty(key) ) { continue; }
parsed.cssClasses[key] = parsed.cssPrefix + entry[key];
}
} else {
parsed.cssClasses = entry;
}
}
// Test all developer settings and parse to assumption-safe values.
function testOptions ( options ) {
// To prove a fix for #537, freeze options here.
// If the object is modified, an error will be thrown.
// Object.freeze(options);
var parsed = {
margin: 0,
limit: 0,
animate: true,
animationDuration: 300,
format: defaultFormatter
}, tests;
// Tests are executed in the order they are presented here.
tests = {
'step': { r: false, t: testStep },
'start': { r: true, t: testStart },
'connect': { r: true, t: testConnect },
'direction': { r: true, t: testDirection },
'snap': { r: false, t: testSnap },
'animate': { r: false, t: testAnimate },
'animationDuration': { r: false, t: testAnimationDuration },
'range': { r: true, t: testRange },
'orientation': { r: false, t: testOrientation },
'margin': { r: false, t: testMargin },
'limit': { r: false, t: testLimit },
'behaviour': { r: true, t: testBehaviour },
'format': { r: false, t: testFormat },
'tooltips': { r: false, t: testTooltips },
'cssPrefix': { r: false, t: testCssPrefix },
'cssClasses': { r: false, t: testCssClasses }
};
var defaults = {
'connect': false,
'direction': 'ltr',
'behaviour': 'tap',
'orientation': 'horizontal',
'cssPrefix' : 'noUi-',
'cssClasses': {
target: 'target',
base: 'base',
origin: 'origin',
handle: 'handle',
handleLower: 'handle-lower',
handleUpper: 'handle-upper',
horizontal: 'horizontal',
vertical: 'vertical',
background: 'background',
connect: 'connect',
ltr: 'ltr',
rtl: 'rtl',
draggable: 'draggable',
drag: 'state-drag',
tap: 'state-tap',
active: 'active',
stacking: 'stacking',
tooltip: 'tooltip',
pips: 'pips',
pipsHorizontal: 'pips-horizontal',
pipsVertical: 'pips-vertical',
marker: 'marker',
markerHorizontal: 'marker-horizontal',
markerVertical: 'marker-vertical',
markerNormal: 'marker-normal',
markerLarge: 'marker-large',
markerSub: 'marker-sub',
value: 'value',
valueHorizontal: 'value-horizontal',
valueVertical: 'value-vertical',
valueNormal: 'value-normal',
valueLarge: 'value-large',
valueSub: 'value-sub'
}
};
// Run all options through a testing mechanism to ensure correct
// input. It should be noted that options might get modified to
// be handled properly. E.g. wrapping integers in arrays.
Object.keys(tests).forEach(function( name ){
// If the option isn't set, but it is required, throw an error.
if ( options[name] === undefined && defaults[name] === undefined ) {
if ( tests[name].r ) {
throw new Error("noUiSlider: '" + name + "' is required.");
}
return true;
}
tests[name].t( parsed, options[name] === undefined ? defaults[name] : options[name] );
});
// Forward pips options
parsed.pips = options.pips;
// Pre-define the styles.
parsed.style = parsed.ort ? 'top' : 'left';
return parsed;
}
function closure ( target, options, originalOptions ){
var
actions = getActions( ),
// All variables local to 'closure' are prefixed with 'scope_'
scope_Target = target,
scope_Locations = [-1, -1],
scope_Base,
scope_Handles,
scope_Spectrum = options.spectrum,
scope_Values = [],
scope_Events = {},
scope_Self;
// Delimit proposed values for handle positions.
function getPositions ( a, b, delimit ) {
// Add movement to current position.
var c = a + b[0], d = a + b[1];
// Only alter the other position on drag,
// not on standard sliding.
if ( delimit ) {
if ( c < 0 ) {
d += Math.abs(c);
}
if ( d > 100 ) {
c -= ( d - 100 );
}
// Limit values to 0 and 100.
return [limit(c), limit(d)];
}
return [c,d];
}
// Provide a clean event with standardized offset values.
function fixEvent ( e, pageOffset ) {
// Prevent scrolling and panning on touch events, while
// attempting to slide. The tap event also depends on this.
e.preventDefault();
// Filter the event to register the type, which can be
// touch, mouse or pointer. Offset changes need to be
// made on an event specific basis.
var touch = e.type.indexOf('touch') === 0,
mouse = e.type.indexOf('mouse') === 0,
pointer = e.type.indexOf('pointer') === 0,
x,y, event = e;
// IE10 implemented pointer events with a prefix;
if ( e.type.indexOf('MSPointer') === 0 ) {
pointer = true;
}
if ( touch ) {
// noUiSlider supports one movement at a time,
// so we can select the first 'changedTouch'.
x = e.changedTouches[0].pageX;
y = e.changedTouches[0].pageY;
}
pageOffset = pageOffset || getPageOffset();
if ( mouse || pointer ) {
x = e.clientX + pageOffset.x;
y = e.clientY + pageOffset.y;
}
event.pageOffset = pageOffset;
event.points = [x, y];
event.cursor = mouse || pointer; // Fix #435
return event;
}
// Append a handle to the base.
function addHandle ( direction, index ) {
var origin = document.createElement('div'),
handle = document.createElement('div'),
classModifier = [options.cssClasses.handleLower, options.cssClasses.handleUpper];
if ( direction ) {
classModifier.reverse();
}
addClass(handle, options.cssClasses.handle);
addClass(handle, classModifier[index]);
addClass(origin, options.cssClasses.origin);
origin.appendChild(handle);
return origin;
}
// Add the proper connection classes.
function addConnection ( connect, target, handles ) {
// Apply the required connection classes to the elements
// that need them. Some classes are made up for several
// segments listed in the class list, to allow easy
// renaming and provide a minor compression benefit.
switch ( connect ) {
case 1: addClass(target, options.cssClasses.connect);
addClass(handles[0], options.cssClasses.background);
break;
case 3: addClass(handles[1], options.cssClasses.background);
/* falls through */
case 2: addClass(handles[0], options.cssClasses.connect);
/* falls through */
case 0: addClass(target, options.cssClasses.background);
break;
}
}
// Add handles to the slider base.
function addHandles ( nrHandles, direction, base ) {
var index, handles = [];
// Append handles.
for ( index = 0; index < nrHandles; index += 1 ) {
// Keep a list of all added handles.
handles.push( base.appendChild(addHandle( direction, index )) );
}
return handles;
}
// Initialize a single slider.
function addSlider ( direction, orientation, target ) {
// Apply classes and data to the target.
addClass(target, options.cssClasses.target);
if ( direction === 0 ) {
addClass(target, options.cssClasses.ltr);
} else {
addClass(target, options.cssClasses.rtl);
}
if ( orientation === 0 ) {
addClass(target, options.cssClasses.horizontal);
} else {
addClass(target, options.cssClasses.vertical);
}
var div = document.createElement('div');
addClass(div, options.cssClasses.base);
target.appendChild(div);
return div;
}
function addTooltip ( handle, index ) {
if ( !options.tooltips[index] ) {
return false;
}
var element = document.createElement('div');
element.className = options.cssClasses.tooltip;
return handle.firstChild.appendChild(element);
}
// The tooltips option is a shorthand for using the 'update' event.
function tooltips ( ) {
if ( options.dir ) {
options.tooltips.reverse();
}
// Tooltips are added with options.tooltips in original order.
var tips = scope_Handles.map(addTooltip);
if ( options.dir ) {
tips.reverse();
options.tooltips.reverse();
}
bindEvent('update', function(f, o, r) {
if ( tips[o] ) {
tips[o].innerHTML = options.tooltips[o] === true ? f[o] : options.tooltips[o].to(r[o]);
}
});
}
function getGroup ( mode, values, stepped ) {
// Use the range.
if ( mode === 'range' || mode === 'steps' ) {
return scope_Spectrum.xVal;
}
if ( mode === 'count' ) {
// Divide 0 - 100 in 'count' parts.
var spread = ( 100 / (values-1) ), v, i = 0;
values = [];
// List these parts and have them handled as 'positions'.
while ((v=i++*spread) <= 100 ) {
values.push(v);
}
mode = 'positions';
}
if ( mode === 'positions' ) {
// Map all percentages to on-range values.
return values.map(function( value ){
return scope_Spectrum.fromStepping( stepped ? scope_Spectrum.getStep( value ) : value );
});
}
if ( mode === 'values' ) {
// If the value must be stepped, it needs to be converted to a percentage first.
if ( stepped ) {
return values.map(function( value ){
// Convert to percentage, apply step, return to value.
return scope_Spectrum.fromStepping( scope_Spectrum.getStep( scope_Spectrum.toStepping( value ) ) );
});
}
// Otherwise, we can simply use the values.
return values;
}
}
function generateSpread ( density, mode, group ) {
function safeIncrement(value, increment) {
// Avoid floating point variance by dropping the smallest decimal places.
return (value + increment).toFixed(7) / 1;
}
var originalSpectrumDirection = scope_Spectrum.direction,
indexes = {},
firstInRange = scope_Spectrum.xVal[0],
lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],
ignoreFirst = false,
ignoreLast = false,
prevPct = 0;
// This function loops the spectrum in an ltr linear fashion,
// while the toStepping method is direction aware. Trick it into
// believing it is ltr.
scope_Spectrum.direction = 0;
// Create a copy of the group, sort it and filter away all duplicates.
group = unique(group.slice().sort(function(a, b){ return a - b; }));
// Make sure the range starts with the first element.
if ( group[0] !== firstInRange ) {
group.unshift(firstInRange);
ignoreFirst = true;
}
// Likewise for the last one.
if ( group[group.length - 1] !== lastInRange ) {
group.push(lastInRange);
ignoreLast = true;
}
group.forEach(function ( current, index ) {
// Get the current step and the lower + upper positions.
var step, i, q,
low = current,
high = group[index+1],
newPct, pctDifference, pctPos, type,
steps, realSteps, stepsize;
// When using 'steps' mode, use the provided steps.
// Otherwise, we'll step on to the next subrange.
if ( mode === 'steps' ) {
step = scope_Spectrum.xNumSteps[ index ];
}
// Default to a 'full' step.
if ( !step ) {
step = high-low;
}
// Low can be 0, so test for false. If high is undefined,
// we are at the last subrange. Index 0 is already handled.
if ( low === false || high === undefined ) {
return;
}
// Find all steps in the subrange.
for ( i = low; i <= high; i = safeIncrement(i, step) ) {
// Get the percentage value for the current step,
// calculate the size for the subrange.
newPct = scope_Spectrum.toStepping( i );
pctDifference = newPct - prevPct;
steps = pctDifference / density;
realSteps = Math.round(steps);
// This ratio represents the ammount of percentage-space a point indicates.
// For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-devided.
// Round the percentage offset to an even number, then divide by two
// to spread the offset on both sides of the range.
stepsize = pctDifference/realSteps;
// Divide all points evenly, adding the correct number to this subrange.
// Run up to <= so that 100% gets a point, event if ignoreLast is set.
for ( q = 1; q <= realSteps; q += 1 ) {
// The ratio between the rounded value and the actual size might be ~1% off.
// Correct the percentage offset by the number of points
// per subrange. density = 1 will result in 100 points on the
// full range, 2 for 50, 4 for 25, etc.
pctPos = prevPct + ( q * stepsize );
indexes[pctPos.toFixed(5)] = ['x', 0];
}
// Determine the point type.
type = (group.indexOf(i) > -1) ? 1 : ( mode === 'steps' ? 2 : 0 );
// Enforce the 'ignoreFirst' option by overwriting the type for 0.
if ( !index && ignoreFirst ) {
type = 0;
}
if ( !(i === high && ignoreLast)) {
// Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
indexes[newPct.toFixed(5)] = [i, type];
}
// Update the percentage count.
prevPct = newPct;
}
});
// Reset the spectrum.
scope_Spectrum.direction = originalSpectrumDirection;
return indexes;
}
function addMarking ( spread, filterFunc, formatter ) {
var element = document.createElement('div'),
out = '',
valueSizeClasses = [
options.cssClasses.valueNormal,
options.cssClasses.valueLarge,
options.cssClasses.valueSub
],
markerSizeClasses = [
options.cssClasses.markerNormal,
options.cssClasses.markerLarge,
options.cssClasses.markerSub
],
valueOrientationClasses = [
options.cssClasses.valueHorizontal,
options.cssClasses.valueVertical
],
markerOrientationClasses = [
options.cssClasses.markerHorizontal,
options.cssClasses.markerVertical
];
addClass(element, options.cssClasses.pips);
addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);
function getClasses( type, source ){
var a = source === options.cssClasses.value,
orientationClasses = a ? valueOrientationClasses : markerOrientationClasses,
sizeClasses = a ? valueSizeClasses : markerSizeClasses;
return source + ' ' + orientationClasses[options.ort] + ' ' + sizeClasses[type];
}
function getTags( offset, source, values ) {
return 'class="' + getClasses(values[1], source) + '" style="' + options.style + ': ' + offset + '%"';
}
function addSpread ( offset, values ){
if ( scope_Spectrum.direction ) {
offset = 100 - offset;
}
// Apply the filter function, if it is set.
values[1] = (values[1] && filterFunc) ? filterFunc(values[0], values[1]) : values[1];
// Add a marker for every point
out += '<div ' + getTags(offset, options.cssClasses.marker, values) + '></div>';
// Values are only appended for points marked '1' or '2'.
if ( values[1] ) {
out += '<div ' + getTags(offset, options.cssClasses.value, values) + '>' + formatter.to(values[0]) + '</div>';
}
}
// Append all points.
Object.keys(spread).forEach(function(a){
addSpread(a, spread[a]);
});
element.innerHTML = out;
return element;
}
function pips ( grid ) {
var mode = grid.mode,
density = grid.density || 1,
filter = grid.filter || false,
values = grid.values || false,
stepped = grid.stepped || false,
group = getGroup( mode, values, stepped ),
spread = generateSpread( density, mode, group ),
format = grid.format || {
to: Math.round
};
return scope_Target.appendChild(addMarking(
spread,
filter,
format
));
}
// Shorthand for base dimensions.
function baseSize ( ) {
var rect = scope_Base.getBoundingClientRect(), alt = 'offset' + ['Width', 'Height'][options.ort];
return options.ort === 0 ? (rect.width||scope_Base[alt]) : (rect.height||scope_Base[alt]);
}
// External event handling
function fireEvent ( event, handleNumber, tap ) {
var i;
// During initialization, do not fire events.
for ( i = 0; i < options.handles; i++ ) {
if ( scope_Locations[i] === -1 ) {
return;
}
}
if ( handleNumber !== undefined && options.handles !== 1 ) {
handleNumber = Math.abs(handleNumber - options.dir);
}
Object.keys(scope_Events).forEach(function( targetEvent ) {
var eventType = targetEvent.split('.')[0];
if ( event === eventType ) {
scope_Events[targetEvent].forEach(function( callback ) {
callback.call(
// Use the slider public API as the scope ('this')
scope_Self,
// Return values as array, so arg_1[arg_2] is always valid.
asArray(valueGet()),
// Handle index, 0 or 1
handleNumber,
// Unformatted slider values
asArray(inSliderOrder(Array.prototype.slice.call(scope_Values))),
// Event is fired by tap, true or false
tap || false,
// Left offset of the handle, in relation to the slider
scope_Locations
);
});
}
});
}
// Returns the input array, respecting the slider direction configuration.
function inSliderOrder ( values ) {
// If only one handle is used, return a single value.
if ( values.length === 1 ){
return values[0];
}
if ( options.dir ) {
return values.reverse();
}
return values;
}
// Handler for attaching events trough a proxy.
function attach ( events, element, callback, data ) {
// This function can be used to 'filter' events to the slider.
// element is a node, not a nodeList
var method = function ( e ){
if ( scope_Target.hasAttribute('disabled') ) {
return false;
}
// Stop if an active 'tap' transition is taking place.
if ( hasClass(scope_Target, options.cssClasses.tap) ) {
return false;
}
e = fixEvent(e, data.pageOffset);
// Ignore right or middle clicks on start #454
if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
return false;
}
// Ignore right or middle clicks on start #454
if ( data.hover && e.buttons ) {
return false;
}
e.calcPoint = e.points[ options.ort ];
// Call the event handler with the event [ and additional data ].
callback ( e, data );
}, methods = [];
// Bind a closure on the target for every event type.
events.split(' ').forEach(function( eventName ){
element.addEventListener(eventName, method, false);
methods.push([eventName, method]);
});
return methods;
}
// Handle movement on document for handle and range drag.
function move ( event, data ) {
// Fix #498
// Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
// https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
// IE9 has .buttons and .which zero on mousemove.
// Firefox breaks the spec MDN defines.
if ( navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0 ) {
return end(event, data);
}
var handles = data.handles || scope_Handles, positions, state = false,
proposal = ((event.calcPoint - data.start) * 100) / data.baseSize,
handleNumber = handles[0] === scope_Handles[0] ? 0 : 1, i;
// Calculate relative positions for the handles.
positions = getPositions( proposal, data.positions, handles.length > 1);
state = setHandle ( handles[0], positions[handleNumber], handles.length === 1 );
if ( handles.length > 1 ) {
state = setHandle ( handles[1], positions[handleNumber?0:1], false ) || state;
if ( state ) {
// fire for both handles
for ( i = 0; i < data.handles.length; i++ ) {
fireEvent('slide', i);
}
}
} else if ( state ) {
// Fire for a single handle
fireEvent('slide', handleNumber);
}
}
// Unbind move events on document, call callbacks.
function end ( event, data ) {
// The handle is no longer active, so remove the class.
var active = scope_Base.querySelector( '.' + options.cssClasses.active ),
handleNumber = data.handles[0] === scope_Handles[0] ? 0 : 1;
if ( active !== null ) {
removeClass(active, options.cssClasses.active);
}
// Remove cursor styles and text-selection events bound to the body.
if ( event.cursor ) {
document.body.style.cursor = '';
document.body.removeEventListener('selectstart', document.body.noUiListener);
}
var d = document.documentElement;
// Unbind the move and end events, which are added on 'start'.
d.noUiListeners.forEach(function( c ) {
d.removeEventListener(c[0], c[1]);
});
// Remove dragging class.
removeClass(scope_Target, options.cssClasses.drag);
// Fire the change and set events.
fireEvent('set', handleNumber);
fireEvent('change', handleNumber);
// If this is a standard handle movement, fire the end event.
if ( data.handleNumber !== undefined ) {
fireEvent('end', data.handleNumber);
}
}
// Fire 'end' when a mouse or pen leaves the document.
function documentLeave ( event, data ) {
if ( event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null ){
end ( event, data );
}
}
// Bind move events on document.
function start ( event, data ) {
var d = document.documentElement;
// Mark the handle as 'active' so it can be styled.
if ( data.handles.length === 1 ) {
// Support 'disabled' handles
if ( data.handles[0].hasAttribute('disabled') ) {
return false;
}
addClass(data.handles[0].children[0], options.cssClasses.active);
}
// Fix #551, where a handle gets selected instead of dragged.
event.preventDefault();
// A drag should never propagate up to the 'tap' event.
event.stopPropagation();
// Attach the move and end events.
var moveEvent = attach(actions.move, d, move, {
start: event.calcPoint,
baseSize: baseSize(),
pageOffset: event.pageOffset,
handles: data.handles,
handleNumber: data.handleNumber,
buttonsProperty: event.buttons,
positions: [
scope_Locations[0],
scope_Locations[scope_Handles.length - 1]
]
}), endEvent = attach(actions.end, d, end, {
handles: data.handles,
handleNumber: data.handleNumber
});
var outEvent = attach("mouseout", d, documentLeave, {
handles: data.handles,
handleNumber: data.handleNumber
});
d.noUiListeners = moveEvent.concat(endEvent, outEvent);
// Text selection isn't an issue on touch devices,
// so adding cursor styles can be skipped.
if ( event.cursor ) {
// Prevent the 'I' cursor and extend the range-drag cursor.
document.body.style.cursor = getComputedStyle(event.target).cursor;
// Mark the target with a dragging state.
if ( scope_Handles.length > 1 ) {
addClass(scope_Target, options.cssClasses.drag);
}
var f = function(){
return false;
};
document.body.noUiListener = f;
// Prevent text selection when dragging the handles.
document.body.addEventListener('selectstart', f, false);
}
if ( data.handleNumber !== undefined ) {
fireEvent('start', data.handleNumber);
}
}
// Move closest handle to tapped location.
function tap ( event ) {
var location = event.calcPoint, total = 0, handleNumber, to;
// The tap event shouldn't propagate up and cause 'edge' to run.
event.stopPropagation();
// Add up the handle offsets.
scope_Handles.forEach(function(a){
total += offset(a)[ options.style ];
});
// Find the handle closest to the tapped position.
handleNumber = ( location < total/2 || scope_Handles.length === 1 ) ? 0 : 1;
// Check if handler is not disablet if yes set number to the next handler
if (scope_Handles[handleNumber].hasAttribute('disabled')) {
handleNumber = handleNumber ? 0 : 1;
}
location -= offset(scope_Base)[ options.style ];
// Calculate the new position.
to = ( location * 100 ) / baseSize();
if ( !options.events.snap ) {
// Flag the slider as it is now in a transitional state.
// Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.
addClassFor( scope_Target, options.cssClasses.tap, options.animationDuration );
}
// Support 'disabled' handles
if ( scope_Handles[handleNumber].hasAttribute('disabled') ) {
return false;
}
// Find the closest handle and calculate the tapped point.
// The set handle to the new position.
setHandle( scope_Handles[handleNumber], to );
fireEvent('slide', handleNumber, true);
fireEvent('set', handleNumber, true);
fireEvent('change', handleNumber, true);
if ( options.events.snap ) {
start(event, { handles: [scope_Handles[handleNumber]] });
}
}
// Fires a 'hover' event for a hovered mouse/pen position.
function hover ( event ) {
var location = event.calcPoint - offset(scope_Base)[ options.style ],
to = scope_Spectrum.getStep(( location * 100 ) / baseSize()),
value = scope_Spectrum.fromStepping( to );
Object.keys(scope_Events).forEach(function( targetEvent ) {
if ( 'hover' === targetEvent.split('.')[0] ) {
scope_Events[targetEvent].forEach(function( callback ) {
callback.call( scope_Self, value );
});
}
});
}
// Attach events to several slider parts.
function events ( behaviour ) {
// Attach the standard drag event to the handles.
if ( !behaviour.fixed ) {
scope_Handles.forEach(function( handle, index ){
// These events are only bound to the visual handle
// element, not the 'real' origin element.
attach ( actions.start, handle.children[0], start, {
handles: [ handle ],
handleNumber: index
});
});
}
// Attach the tap event to the slider base.
if ( behaviour.tap ) {
attach ( actions.start, scope_Base, tap, {
handles: scope_Handles
});
}
// Fire hover events
if ( behaviour.hover ) {
attach ( actions.move, scope_Base, hover, { hover: true } );
}
// Make the range draggable.
if ( behaviour.drag ){
var drag = [scope_Base.querySelector( '.' + options.cssClasses.connect )];
addClass(drag[0], options.cssClasses.draggable);
// When the range is fixed, the entire range can
// be dragged by the handles. The handle in the first
// origin will propagate the start event upward,
// but it needs to be bound manually on the other.
if ( behaviour.fixed ) {
drag.push(scope_Handles[(drag[0] === scope_Handles[0] ? 1 : 0)].children[0]);
}
drag.forEach(function( element ) {
attach ( actions.start, element, start, {
handles: scope_Handles
});
});
}
}
// Test suggested values and apply margin, step.
function setHandle ( handle, to, noLimitOption ) {
var trigger = handle !== scope_Handles[0] ? 1 : 0,
lowerMargin = scope_Locations[0] + options.margin,
upperMargin = scope_Locations[1] - options.margin,
lowerLimit = scope_Locations[0] + options.limit,
upperLimit = scope_Locations[1] - options.limit;
// For sliders with multiple handles,
// limit movement to the other handle.
// Apply the margin option by adding it to the handle positions.
if ( scope_Handles.length > 1 ) {
to = trigger ? Math.max( to, lowerMargin ) : Math.min( to, upperMargin );
}
// The limit option has the opposite effect, limiting handles to a
// maximum distance from another. Limit must be > 0, as otherwise
// handles would be unmoveable. 'noLimitOption' is set to 'false'
// for the .val() method, except for pass 4/4.
if ( noLimitOption !== false && options.limit && scope_Handles.length > 1 ) {
to = trigger ? Math.min ( to, lowerLimit ) : Math.max( to, upperLimit );
}
// Handle the step option.
to = scope_Spectrum.getStep( to );
// Limit percentage to the 0 - 100 range
to = limit(to);
// Return false if handle can't move
if ( to === scope_Locations[trigger] ) {
return false;
}
// Set the handle to the new position.
// Use requestAnimationFrame for efficient painting.
// No significant effect in Chrome, Edge sees dramatic
// performace improvements.
if ( window.requestAnimationFrame ) {
window.requestAnimationFrame(function(){
handle.style[options.style] = to + '%';
});
} else {
handle.style[options.style] = to + '%';
}
// Force proper handle stacking
if ( !handle.previousSibling ) {
removeClass(handle, options.cssClasses.stacking);
if ( to > 50 ) {
addClass(handle, options.cssClasses.stacking);
}
}
// Update locations.
scope_Locations[trigger] = to;
// Convert the value to the slider stepping/range.
scope_Values[trigger] = scope_Spectrum.fromStepping( to );
fireEvent('update', trigger);
return true;
}
// Loop values from value method and apply them.
function setValues ( count, values ) {
var i, trigger, to;
// With the limit option, we'll need another limiting pass.
if ( options.limit ) {
count += 1;
}
// If there are multiple handles to be set run the setting
// mechanism twice for the first handle, to make sure it
// can be bounced of the second one properly.
for ( i = 0; i < count; i += 1 ) {
trigger = i%2;
// Get the current argument from the array.
to = values[trigger];
// Setting with null indicates an 'ignore'.
// Inputting 'false' is invalid.
if ( to !== null && to !== false ) {
// If a formatted number was passed, attemt to decode it.
if ( typeof to === 'number' ) {
to = String(to);
}
to = options.format.from( to );
// Request an update for all links if the value was invalid.
// Do so too if setting the handle fails.
if ( to === false || isNaN(to) || setHandle( scope_Handles[trigger], scope_Spectrum.toStepping( to ), i === (3 - options.dir) ) === false ) {
fireEvent('update', trigger);
}
}
}
}
// Set the slider value.
function valueSet ( input, fireSetEvent ) {
var count, values = asArray( input ), i;
// Event fires by default
fireSetEvent = (fireSetEvent === undefined ? true : !!fireSetEvent);
// The RTL settings is implemented by reversing the front-end,
// internal mechanisms are the same.
if ( options.dir && options.handles > 1 ) {
values.reverse();
}
// Animation is optional.
// Make sure the initial values where set before using animated placement.
if ( options.animate && scope_Locations[0] !== -1 ) {
addClassFor( scope_Target, options.cssClasses.tap, options.animationDuration );
}
// Determine how often to set the handles.
count = scope_Handles.length > 1 ? 3 : 1;
if ( values.length === 1 ) {
count = 1;
}
setValues ( count, values );
// Fire the 'set' event for both handles.
for ( i = 0; i < scope_Handles.length; i++ ) {
// Fire the event only for handles that received a new value, as per #579
if ( values[i] !== null && fireSetEvent ) {
fireEvent('set', i);
}
}
}
// Get the slider value.
function valueGet ( ) {
var i, retour = [];
// Get the value from all handles.
for ( i = 0; i < options.handles; i += 1 ){
retour[i] = options.format.to( scope_Values[i] );
}
return inSliderOrder( retour );
}
// Removes classes from the root and empties it.
function destroy ( ) {
for ( var key in options.cssClasses ) {
if ( !options.cssClasses.hasOwnProperty(key) ) { continue; }
removeClass(scope_Target, options.cssClasses[key]);
}
while (scope_Target.firstChild) {
scope_Target.removeChild(scope_Target.firstChild);
}
delete scope_Target.noUiSlider;
}
// Get the current step size for the slider.
function getCurrentStep ( ) {
// Check all locations, map them to their stepping point.
// Get the step point, then find it in the input list.
var retour = scope_Locations.map(function( location, index ){
var step = scope_Spectrum.getApplicableStep( location ),
// As per #391, the comparison for the decrement step can have some rounding issues.
// Round the value to the precision used in the step.
stepDecimals = countDecimals(String(step[2])),
// Get the current numeric value
value = scope_Values[index],
// To move the slider 'one step up', the current step value needs to be added.
// Use null if we are at the maximum slider value.
increment = location === 100 ? null : step[2],
// Going 'one step down' might put the slider in a different sub-range, so we
// need to switch between the current or the previous step.
prev = Number((value - step[2]).toFixed(stepDecimals)),
// If the value fits the step, return the current step value. Otherwise, use the
// previous step. Return null if the slider is at its minimum value.
decrement = location === 0 ? null : (prev >= step[1]) ? step[2] : (step[0] || false);
return [decrement, increment];
});
// Return values in the proper order.
return inSliderOrder( retour );
}
// Attach an event to this slider, possibly including a namespace
function bindEvent ( namespacedEvent, callback ) {
scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
scope_Events[namespacedEvent].push(callback);
// If the event bound is 'update,' fire it immediately for all handles.
if ( namespacedEvent.split('.')[0] === 'update' ) {
scope_Handles.forEach(function(a, index){
fireEvent('update', index);
});
}
}
// Undo attachment of event
function removeEvent ( namespacedEvent ) {
var event = namespacedEvent && namespacedEvent.split('.')[0],
namespace = event && namespacedEvent.substring(event.length);
Object.keys(scope_Events).forEach(function( bind ){
var tEvent = bind.split('.')[0],
tNamespace = bind.substring(tEvent.length);
if ( (!event || event === tEvent) && (!namespace || namespace === tNamespace) ) {
delete scope_Events[bind];
}
});
}
// Updateable: margin, limit, step, range, animate, snap
function updateOptions ( optionsToUpdate, fireSetEvent ) {
// Spectrum is created using the range, snap, direction and step options.
// 'snap' and 'step' can be updated, 'direction' cannot, due to event binding.
// If 'snap' and 'step' are not passed, they should remain unchanged.
var v = valueGet(), newOptions = testOptions({
start: [0, 0],
margin: optionsToUpdate.margin,
limit: optionsToUpdate.limit,
step: optionsToUpdate.step === undefined ? options.singleStep : optionsToUpdate.step,
range: optionsToUpdate.range,
animate: optionsToUpdate.animate,
snap: optionsToUpdate.snap === undefined ? options.snap : optionsToUpdate.snap
});
['margin', 'limit', 'range', 'animate'].forEach(function(name){
// Only change options that we're actually passed to update.
if ( optionsToUpdate[name] !== undefined ) {
options[name] = optionsToUpdate[name];
}
});
// Save current spectrum direction as testOptions in testRange call
// doesn't rely on current direction
newOptions.spectrum.direction = scope_Spectrum.direction;
scope_Spectrum = newOptions.spectrum;
// Invalidate the current positioning so valueSet forces an update.
scope_Locations = [-1, -1];
valueSet(optionsToUpdate.start || v, fireSetEvent);
}
// Throw an error if the slider was already initialized.
if ( scope_Target.noUiSlider ) {
throw new Error('Slider was already initialized.');
}
// Create the base element, initialise HTML and set classes.
// Add handles and links.
scope_Base = addSlider( options.dir, options.ort, scope_Target );
scope_Handles = addHandles( options.handles, options.dir, scope_Base );
// Set the connect classes.
addConnection ( options.connect, scope_Target, scope_Handles );
if ( options.pips ) {
pips(options.pips);
}
if ( options.tooltips ) {
tooltips();
}
scope_Self = {
destroy: destroy,
steps: getCurrentStep,
on: bindEvent,
off: removeEvent,
get: valueGet,
set: valueSet,
updateOptions: updateOptions,
options: originalOptions, // Issue #600
target: scope_Target, // Issue #597
pips: pips // Issue #594
};
// Attach user events.
events( options.events );
return scope_Self;
}
// Run the standard initializer
function initialize ( target, originalOptions ) {
if ( !target.nodeName ) {
throw new Error('noUiSlider.create requires a single element.');
}
// Test the options and create the slider environment;
var options = testOptions( originalOptions, target ),
slider = closure( target, options, originalOptions );
// Use the public value method to set the start values.
slider.set(options.start);
target.noUiSlider = slider;
return slider;
}
// Use an object instead of a function for future expansibility;
return {
create: initialize
};
}));
/***/ },
/* 395 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _findIndex = __webpack_require__(207);
var _findIndex2 = _interopRequireDefault(_findIndex);
var _map = __webpack_require__(171);
var _map2 = _interopRequireDefault(_map);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _Selector = __webpack_require__(365);
var _Selector2 = _interopRequireDefault(_Selector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-sort-by-selector');
/**
* Instantiate a dropdown element to choose the current targeted index
* @function sortBySelector
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {Array} options.indices Array of objects defining the different indices to choose from.
* @param {string} options.indices[0].name Name of the index to target
* @param {string} options.indices[0].label Label displayed in the dropdown
* @param {boolean} [options.autoHideContainer=false] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to be added
* @param {string|string[]} [options.cssClasses.root] CSS classes added to the parent <select>
* @param {string|string[]} [options.cssClasses.item] CSS classes added to each <option>
* @return {Object}
*/
var usage = 'Usage:\nsortBySelector({\n container,\n indices,\n [cssClasses.{root,item}={}],\n [autoHideContainer=false]\n})';
function sortBySelector() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var indices = _ref.indices;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? false : _ref$autoHideContaine;
if (!container || !indices) {
throw new Error(usage);
}
var containerNode = (0, _utils.getContainerNode)(container);
var Selector = _Selector2.default;
if (autoHideContainer === true) {
Selector = (0, _autoHideContainer2.default)(Selector);
}
var selectorOptions = (0, _map2.default)(indices, function (index) {
return { label: index.label, value: index.name };
});
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item)
};
return {
init: function init(_ref2) {
var helper = _ref2.helper;
var currentIndex = helper.getIndex();
var isIndexInList = (0, _findIndex2.default)(indices, { name: currentIndex }) !== -1;
if (!isIndexInList) {
throw new Error('[sortBySelector]: Index ' + currentIndex + ' not present in `indices`');
}
this.setIndex = function (indexName) {
return helper.setIndex(indexName).search();
};
},
render: function render(_ref3) {
var helper = _ref3.helper;
var results = _ref3.results;
_reactDom2.default.render(_react2.default.createElement(Selector, {
cssClasses: cssClasses,
currentValue: helper.getIndex(),
options: selectorOptions,
setValue: this.setIndex,
shouldAutoHideContainer: results.nbHits === 0
}), containerNode);
}
};
}
exports.default = sortBySelector;
/***/ },
/* 396 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _defaultTemplates = __webpack_require__(397);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _defaultLabels = __webpack_require__(398);
var _defaultLabels2 = _interopRequireDefault(_defaultLabels);
var _RefinementList = __webpack_require__(355);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-star-rating');
/**
* Instantiate a list of refinements based on a rating attribute
* The ratings must be integer values. You can still keep the precise float value in another attribute
* to be used in the custom ranking configuration. So that the actual hits ranking is precise.
* @function starRating
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the attribute for filtering
* @param {number} [options.max] The maximum rating value
* @param {Object} [options.labels] Labels used by the default template
* @param {string} [options.labels.andUp] The label suffixed after each line
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template
* @param {string|Function} [options.templates.item] Item template, provided with `name`, `count`, `isRefined`, `url` data properties
* @param {string|Function} [options.templates.footer] Footer template
* @param {Function} [options.transformData.item] Function to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to add to the wrapping elements
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.link] CSS class to add to each link element
* @param {string|string[]} [options.cssClasses.disabledLink] CSS class to add to each disabled link (when using the default template)
* @param {string|string[]} [options.cssClasses.star] CSS class to add to each star element (when using the default template)
* @param {string|string[]} [options.cssClasses.emptyStar] CSS class to add to each empty star element (when using the default template)
* @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\nstarRating({\n container,\n attributeName,\n [ max=5 ],\n [ cssClasses.{root,header,body,footer,list,item,active,link,disabledLink,star,emptyStar,count} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ labels.{andUp} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})';
function starRating(_ref) {
var container = _ref.container;
var attributeName = _ref.attributeName;
var _ref$max = _ref.max;
var max = _ref$max === undefined ? 5 : _ref$max;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$labels = _ref.labels;
var labels = _ref$labels === undefined ? _defaultLabels2.default : _ref$labels;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var containerNode = (0, _utils.getContainerNode)(container);
var RefinementList = (0, _headerFooter2.default)(_RefinementList2.default);
if (autoHideContainer === true) {
RefinementList = (0, _autoHideContainer2.default)(RefinementList);
}
if (!container || !attributeName) {
throw new Error(usage);
}
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
link: (0, _classnames2.default)(bem('link'), userCssClasses.link),
disabledLink: (0, _classnames2.default)(bem('link', 'disabled'), userCssClasses.disabledLink),
count: (0, _classnames2.default)(bem('count'), userCssClasses.count),
star: (0, _classnames2.default)(bem('star'), userCssClasses.star),
emptyStar: (0, _classnames2.default)(bem('star', 'empty'), userCssClasses.emptyStar),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active)
};
return {
getConfiguration: function getConfiguration() {
return { disjunctiveFacets: [attributeName] };
},
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
var helper = _ref2.helper;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
this._toggleRefinement = this._toggleRefinement.bind(this, helper);
},
render: function render(_ref3) {
var helper = _ref3.helper;
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var facetValues = [];
var allValues = {};
for (var v = max - 1; v >= 0; --v) {
allValues[v] = 0;
}
results.getFacetValues(attributeName).forEach(function (facet) {
var val = Math.round(facet.name);
if (!val || val > max - 1) {
return;
}
for (var _v = val; _v >= 1; --_v) {
allValues[_v] += facet.count;
}
});
var refinedStar = this._getRefinedStar(helper);
for (var star = max - 1; star >= 1; --star) {
var count = allValues[star];
if (refinedStar && star !== refinedStar && count === 0) {
// skip count==0 when at least 1 refinement is enabled
// eslint-disable-next-line no-continue
continue;
}
var stars = [];
for (var i = 1; i <= max; ++i) {
stars.push(i <= star);
}
facetValues.push({
stars: stars,
name: String(star),
count: count,
isRefined: refinedStar === star,
labels: labels
});
}
// Bind createURL to this specific attribute
function _createURL(facetValue) {
return createURL(state.toggleRefinement(attributeName, facetValue));
}
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: facetValues,
shouldAutoHideContainer: results.nbHits === 0,
templateProps: this._templateProps,
toggleRefinement: this._toggleRefinement
}), containerNode);
},
_toggleRefinement: function _toggleRefinement(helper, facetValue) {
var isRefined = this._getRefinedStar(helper) === Number(facetValue);
helper.clearRefinements(attributeName);
if (!isRefined) {
for (var val = Number(facetValue); val <= max; ++val) {
helper.addDisjunctiveFacetRefinement(attributeName, val);
}
}
helper.search();
},
_getRefinedStar: function _getRefinedStar(helper) {
var refinedStar = undefined;
var refinements = helper.getRefinements(attributeName);
refinements.forEach(function (r) {
if (!refinedStar || Number(r.value) < refinedStar) {
refinedStar = Number(r.value);
}
});
return refinedStar;
}
};
}
exports.default = starRating;
/***/ },
/* 397 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/* eslint-disable max-len */
exports.default = {
header: '',
item: '<a class="{{cssClasses.link}}{{^count}} {{cssClasses.disabledLink}}{{/count}}" {{#count}}href="{{href}}"{{/count}}>\n {{#stars}}<span class="{{#.}}{{cssClasses.star}}{{/.}}{{^.}}{{cssClasses.emptyStar}}{{/.}}"></span>{{/stars}}\n {{labels.andUp}}\n {{#count}}<span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>{{/count}}\n</a>',
footer: ''
};
/***/ },
/* 398 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
andUp: '& Up'
};
/***/ },
/* 399 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _utils = __webpack_require__(336);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _Stats = __webpack_require__(400);
var _Stats2 = _interopRequireDefault(_Stats);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _defaultTemplates = __webpack_require__(401);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-stats');
/**
* Display various stats about the current search state
* @function stats
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header=''] Header template
* @param {string|Function} [options.templates.body] Body template, provided with `hasManyResults`,
* `hasNoResults`, `hasOneResult`, `hitsPerPage`, `nbHits`, `nbPages`, `page`, `processingTimeMS`, `query`
* @param {string|Function} [options.templates.footer=''] Footer template
* @param {Function} [options.transformData.body] Function to change the object passed to the `body` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when no results match
* @param {Object} [options.cssClasses] CSS classes to add
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.time] CSS class to add to the element wrapping the time processingTimeMs
* @return {Object}
*/
var usage = 'Usage:\nstats({\n container,\n [ templates.{header,body,footer} ],\n [ transformData.{body} ],\n [ autoHideContainer]\n})';
function stats() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var transformData = _ref.transformData;
if (!container) throw new Error(usage);
var containerNode = (0, _utils.getContainerNode)(container);
var Stats = (0, _headerFooter2.default)(_Stats2.default);
if (autoHideContainer === true) {
Stats = (0, _autoHideContainer2.default)(Stats);
}
if (!containerNode) {
throw new Error(usage);
}
var cssClasses = {
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
time: (0, _classnames2.default)(bem('time'), userCssClasses.time)
};
return {
init: function init(_ref2) {
var templatesConfig = _ref2.templatesConfig;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
},
render: function render(_ref3) {
var results = _ref3.results;
_reactDom2.default.render(_react2.default.createElement(Stats, {
collapsible: collapsible,
cssClasses: cssClasses,
hitsPerPage: results.hitsPerPage,
nbHits: results.nbHits,
nbPages: results.nbPages,
page: results.page,
processingTimeMS: results.processingTimeMS,
query: results.query,
shouldAutoHideContainer: results.nbHits === 0,
templateProps: this._templateProps
}), containerNode);
}
};
}
exports.default = stats;
/***/ },
/* 400 */
/***/ 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 _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _Template = __webpack_require__(341);
var _Template2 = _interopRequireDefault(_Template);
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 _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 Stats = function (_React$Component) {
_inherits(Stats, _React$Component);
function Stats() {
_classCallCheck(this, Stats);
return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments));
}
_createClass(Stats, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return this.props.nbHits !== nextProps.hits || this.props.processingTimeMS !== nextProps.processingTimeMS;
}
}, {
key: 'render',
value: function render() {
var data = {
hasManyResults: this.props.nbHits > 1,
hasNoResults: this.props.nbHits === 0,
hasOneResult: this.props.nbHits === 1,
hitsPerPage: this.props.hitsPerPage,
nbHits: this.props.nbHits,
nbPages: this.props.nbPages,
page: this.props.page,
processingTimeMS: this.props.processingTimeMS,
query: this.props.query,
cssClasses: this.props.cssClasses
};
return _react2.default.createElement(_Template2.default, _extends({ data: data, templateKey: 'body' }, this.props.templateProps));
}
}]);
return Stats;
}(_react2.default.Component);
exports.default = Stats;
/***/ },
/* 401 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
header: '',
body: '{{#hasNoResults}}No results{{/hasNoResults}}\n {{#hasOneResult}}1 result{{/hasOneResult}}\n {{#hasManyResults}}{{#helpers.formatNumber}}{{nbHits}}{{/helpers.formatNumber}} results{{/hasManyResults}}\n <span class="{{cssClasses.time}}">found in {{processingTimeMS}}ms</span>',
footer: ''
};
/***/ },
/* 402 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(336);
var _defaultTemplates = __webpack_require__(403);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _classnames = __webpack_require__(338);
var _classnames2 = _interopRequireDefault(_classnames);
var _autoHideContainer = __webpack_require__(339);
var _autoHideContainer2 = _interopRequireDefault(_autoHideContainer);
var _headerFooter = __webpack_require__(340);
var _headerFooter2 = _interopRequireDefault(_headerFooter);
var _RefinementList = __webpack_require__(355);
var _RefinementList2 = _interopRequireDefault(_RefinementList);
var _currentToggle = __webpack_require__(404);
var _currentToggle2 = _interopRequireDefault(_currentToggle);
var _legacyToggle = __webpack_require__(405);
var _legacyToggle2 = _interopRequireDefault(_legacyToggle);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var bem = (0, _utils.bemHelper)('ais-toggle');
// we cannot use helper. because the facet is not yet declared in the helper
var hasFacetsRefinementsFor = function hasFacetsRefinementsFor(attributeName, searchParameters) {
return searchParameters && searchParameters.facetsRefinements && searchParameters.facetsRefinements[attributeName] !== undefined;
};
/**
* Instantiate the toggling of a boolean facet filter on and off.
* @function toggle
* @param {string|DOMElement} options.container CSS Selector or DOMElement to insert the widget
* @param {string} options.attributeName Name of the attribute for faceting (eg. "free_shipping")
* @param {string} options.label Human-readable name of the filter (eg. "Free Shipping")
* @param {Object} [options.values] Lets you define the values to filter on when toggling
* @param {string|number|boolean} [options.values.on=true] Value to filter on when checked
* @param {string|number|boolean} [options.values.off=undefined] Value to filter on when unchecked
* element (when using the default template). By default when switching to `off`, no refinement will be asked. So you
* will get both `true` and `false` results. If you set the off value to `false` then you will get only objects
* having `false` has a value for the selected attribute.
* @param {Object} [options.templates] Templates to use for the widget
* @param {string|Function} [options.templates.header] Header template
* @param {string|Function} [options.templates.item] Item template, provided with `name`, `count`, `isRefined`, `url` data properties
* count is always the number of hits that would be shown if you toggle the widget. We also provide
* `onFacetValue` and `offFacetValue` objects with according counts.
* @param {string|Function} [options.templates.footer] Footer template
* @param {Function} [options.transformData.item] Function to change the object passed to the `item` template
* @param {boolean} [options.autoHideContainer=true] Hide the container when there are no results
* @param {Object} [options.cssClasses] CSS classes to add
* @param {string|string[]} [options.cssClasses.root] CSS class to add to the root element
* @param {string|string[]} [options.cssClasses.header] CSS class to add to the header element
* @param {string|string[]} [options.cssClasses.body] CSS class to add to the body element
* @param {string|string[]} [options.cssClasses.footer] CSS class to add to the footer element
* @param {string|string[]} [options.cssClasses.list] CSS class to add to the list element
* @param {string|string[]} [options.cssClasses.item] CSS class to add to each item element
* @param {string|string[]} [options.cssClasses.active] CSS class to add to each active element
* @param {string|string[]} [options.cssClasses.label] CSS class to add to each
* label element (when using the default template)
* @param {string|string[]} [options.cssClasses.checkbox] CSS class to add to each
* checkbox element (when using the default template)
* @param {string|string[]} [options.cssClasses.count] CSS class to add to each count
* @param {object|boolean} [options.collapsible=false] Hide the widget body and footer when clicking on header
* @param {boolean} [options.collapsible.collapsed] Initial collapsed state of a collapsible widget
* @return {Object}
*/
var usage = 'Usage:\ntoggle({\n container,\n attributeName,\n label,\n [ values={on: true, off: undefined} ],\n [ cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})';
function toggle() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var container = _ref.container;
var attributeName = _ref.attributeName;
var label = _ref.label;
var _ref$values = _ref.values;
var userValues = _ref$values === undefined ? { on: true, off: undefined } : _ref$values;
var _ref$templates = _ref.templates;
var templates = _ref$templates === undefined ? _defaultTemplates2.default : _ref$templates;
var _ref$collapsible = _ref.collapsible;
var collapsible = _ref$collapsible === undefined ? false : _ref$collapsible;
var _ref$cssClasses = _ref.cssClasses;
var userCssClasses = _ref$cssClasses === undefined ? {} : _ref$cssClasses;
var transformData = _ref.transformData;
var _ref$autoHideContaine = _ref.autoHideContainer;
var autoHideContainer = _ref$autoHideContaine === undefined ? true : _ref$autoHideContaine;
var containerNode = (0, _utils.getContainerNode)(container);
if (!container || !attributeName || !label) {
throw new Error(usage);
}
var RefinementList = (0, _headerFooter2.default)(_RefinementList2.default);
if (autoHideContainer === true) {
RefinementList = (0, _autoHideContainer2.default)(RefinementList);
}
var hasAnOffValue = userValues.off !== undefined;
var cssClasses = {
root: (0, _classnames2.default)(bem(null), userCssClasses.root),
header: (0, _classnames2.default)(bem('header'), userCssClasses.header),
body: (0, _classnames2.default)(bem('body'), userCssClasses.body),
footer: (0, _classnames2.default)(bem('footer'), userCssClasses.footer),
list: (0, _classnames2.default)(bem('list'), userCssClasses.list),
item: (0, _classnames2.default)(bem('item'), userCssClasses.item),
active: (0, _classnames2.default)(bem('item', 'active'), userCssClasses.active),
label: (0, _classnames2.default)(bem('label'), userCssClasses.label),
checkbox: (0, _classnames2.default)(bem('checkbox'), userCssClasses.checkbox),
count: (0, _classnames2.default)(bem('count'), userCssClasses.count)
};
// store the computed options for usage in the two toggle implementations
var implemOptions = {
attributeName: attributeName,
label: label,
userValues: userValues,
templates: templates,
collapsible: collapsible,
transformData: transformData,
hasAnOffValue: hasAnOffValue,
containerNode: containerNode,
RefinementList: RefinementList,
cssClasses: cssClasses
};
return {
getConfiguration: function getConfiguration(currentSearchParameters, searchParametersFromUrl) {
var useLegacyToggle = hasFacetsRefinementsFor(attributeName, currentSearchParameters) || hasFacetsRefinementsFor(attributeName, searchParametersFromUrl);
var toggleImplementation = useLegacyToggle ? (0, _legacyToggle2.default)(implemOptions) : (0, _currentToggle2.default)(implemOptions);
this.init = toggleImplementation.init.bind(toggleImplementation);
this.render = toggleImplementation.render.bind(toggleImplementation);
return toggleImplementation.getConfiguration(currentSearchParameters, searchParametersFromUrl);
},
init: function init() {},
render: function render() {}
};
}
exports.default = toggle;
/***/ },
/* 403 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
header: '',
item: '<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>\n</label>',
footer: ''
};
/***/ },
/* 404 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _find = __webpack_require__(205);
var _find2 = _interopRequireDefault(_find);
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _defaultTemplates = __webpack_require__(403);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _utils = __webpack_require__(336);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// cannot use a function declaration because of
// https://github.com/speedskater/babel-plugin-rewire/issues/109#issuecomment-227917555
var currentToggle = function currentToggle() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var attributeName = _ref.attributeName;
var label = _ref.label;
var userValues = _ref.userValues;
var templates = _ref.templates;
var collapsible = _ref.collapsible;
var transformData = _ref.transformData;
var hasAnOffValue = _ref.hasAnOffValue;
var containerNode = _ref.containerNode;
var RefinementList = _ref.RefinementList;
var cssClasses = _ref.cssClasses;
return {
getConfiguration: function getConfiguration() {
return {
disjunctiveFacets: [attributeName]
};
},
toggleRefinement: function toggleRefinement(helper, facetValue, isRefined) {
var on = userValues.on;
var off = userValues.off;
// Checking
if (!isRefined) {
if (hasAnOffValue) {
helper.removeDisjunctiveFacetRefinement(attributeName, off);
}
helper.addDisjunctiveFacetRefinement(attributeName, on);
} else {
// Unchecking
helper.removeDisjunctiveFacetRefinement(attributeName, on);
if (hasAnOffValue) {
helper.addDisjunctiveFacetRefinement(attributeName, off);
}
}
helper.search();
},
init: function init(_ref2) {
var state = _ref2.state;
var helper = _ref2.helper;
var templatesConfig = _ref2.templatesConfig;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
this.toggleRefinement = this.toggleRefinement.bind(this, helper);
// no need to refine anything at init if no custom off values
if (!hasAnOffValue) {
return;
}
// Add filtering on the 'off' value if set
var isRefined = state.isDisjunctiveFacetRefined(attributeName, userValues.on);
if (!isRefined) {
helper.addDisjunctiveFacetRefinement(attributeName, userValues.off);
}
},
render: function render(_ref3) {
var helper = _ref3.helper;
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var isRefined = helper.state.isDisjunctiveFacetRefined(attributeName, userValues.on);
var onValue = userValues.on;
var offValue = userValues.off === undefined ? false : userValues.off;
var allFacetValues = results.getFacetValues(attributeName);
var onData = (0, _find2.default)(allFacetValues, { name: onValue.toString() });
var onFacetValue = {
name: label,
isRefined: onData !== undefined ? onData.isRefined : false,
count: onData === undefined ? null : onData.count
};
var offData = hasAnOffValue ? (0, _find2.default)(allFacetValues, { name: offValue.toString() }) : undefined;
var offFacetValue = {
name: label,
isRefined: offData !== undefined ? offData.isRefined : false,
count: offData === undefined ? results.nbHits : offData.count
};
// what will we show by default,
// if checkbox is not checked, show: [ ] free shipping (countWhenChecked)
// if checkbox is checked, show: [x] free shipping (countWhenNotChecked)
var nextRefinement = isRefined ? offFacetValue : onFacetValue;
var facetValue = {
name: label,
isRefined: isRefined,
count: nextRefinement === undefined ? null : nextRefinement.count,
onFacetValue: onFacetValue,
offFacetValue: offFacetValue
};
// Bind createURL to this specific attribute
function _createURL() {
return createURL(state.removeDisjunctiveFacetRefinement(attributeName, isRefined ? onValue : userValues.off).addDisjunctiveFacetRefinement(attributeName, isRefined ? userValues.off : onValue));
}
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: [facetValue],
shouldAutoHideContainer: facetValue.count === 0 || facetValue.count === null,
templateProps: this._templateProps,
toggleRefinement: this.toggleRefinement
}), containerNode);
}
};
};
exports.default = currentToggle;
/***/ },
/* 405 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = currentToggle;
var _find = __webpack_require__(205);
var _find2 = _interopRequireDefault(_find);
var _react = __webpack_require__(333);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(333);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _defaultTemplates = __webpack_require__(403);
var _defaultTemplates2 = _interopRequireDefault(_defaultTemplates);
var _utils = __webpack_require__(336);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function currentToggle() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var attributeName = _ref.attributeName;
var label = _ref.label;
var userValues = _ref.userValues;
var templates = _ref.templates;
var collapsible = _ref.collapsible;
var transformData = _ref.transformData;
var hasAnOffValue = _ref.hasAnOffValue;
var containerNode = _ref.containerNode;
var RefinementList = _ref.RefinementList;
var cssClasses = _ref.cssClasses;
return {
getConfiguration: function getConfiguration() {
return {
facets: [attributeName]
};
},
toggleRefinement: function toggleRefinement(helper, facetValue, isRefined) {
var on = userValues.on;
var off = userValues.off;
// Checking
if (!isRefined) {
if (hasAnOffValue) {
helper.removeFacetRefinement(attributeName, off);
}
helper.addFacetRefinement(attributeName, on);
} else {
// Unchecking
helper.removeFacetRefinement(attributeName, on);
if (hasAnOffValue) {
helper.addFacetRefinement(attributeName, off);
}
}
helper.search();
},
init: function init(_ref2) {
var state = _ref2.state;
var helper = _ref2.helper;
var templatesConfig = _ref2.templatesConfig;
this._templateProps = (0, _utils.prepareTemplateProps)({
transformData: transformData,
defaultTemplates: _defaultTemplates2.default,
templatesConfig: templatesConfig,
templates: templates
});
this.toggleRefinement = this.toggleRefinement.bind(this, helper);
// no need to refine anything at init if no custom off values
if (!hasAnOffValue) {
return;
}
// Add filtering on the 'off' value if set
var isRefined = state.isFacetRefined(attributeName, userValues.on);
if (!isRefined) {
helper.addFacetRefinement(attributeName, userValues.off);
}
},
render: function render(_ref3) {
var helper = _ref3.helper;
var results = _ref3.results;
var state = _ref3.state;
var createURL = _ref3.createURL;
var isRefined = helper.state.isFacetRefined(attributeName, userValues.on);
var currentRefinement = isRefined ? userValues.on : userValues.off;
var count = void 0;
if (typeof currentRefinement === 'number') {
count = results.getFacetStats(attributeName).sum;
} else {
var facetData = (0, _find2.default)(results.getFacetValues(attributeName), { name: isRefined.toString() });
count = facetData !== undefined ? facetData.count : null;
}
var facetValue = {
name: label,
isRefined: isRefined,
count: count
};
// Bind createURL to this specific attribute
function _createURL() {
return createURL(state.toggleRefinement(attributeName, isRefined));
}
_reactDom2.default.render(_react2.default.createElement(RefinementList, {
collapsible: collapsible,
createURL: _createURL,
cssClasses: cssClasses,
facetValues: [facetValue],
shouldAutoHideContainer: results.nbHits === 0,
templateProps: this._templateProps,
toggleRefinement: this.toggleRefinement
}), containerNode);
}
};
}
/***/ }
/******/ ])
});
;
//# sourceMappingURL=instantsearch-preact.js.map |
files/react/0.13.1/react.js | hubdotcom/jsdelivr | /**
* React v0.13.1
*/
(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.React = 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(_dereq_,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 React
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var EventPluginUtils = _dereq_(19);
var ReactChildren = _dereq_(32);
var ReactComponent = _dereq_(34);
var ReactClass = _dereq_(33);
var ReactContext = _dereq_(38);
var ReactCurrentOwner = _dereq_(39);
var ReactElement = _dereq_(57);
var ReactElementValidator = _dereq_(58);
var ReactDOM = _dereq_(40);
var ReactDOMTextComponent = _dereq_(51);
var ReactDefaultInjection = _dereq_(54);
var ReactInstanceHandles = _dereq_(66);
var ReactMount = _dereq_(70);
var ReactPerf = _dereq_(75);
var ReactPropTypes = _dereq_(78);
var ReactReconciler = _dereq_(81);
var ReactServerRendering = _dereq_(84);
var assign = _dereq_(27);
var findDOMNode = _dereq_(117);
var onlyChild = _dereq_(144);
ReactDefaultInjection.inject();
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if ("production" !== "development") {
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var render = ReactPerf.measure('React', 'render', ReactMount.render);
var React = {
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
only: onlyChild
},
Component: ReactComponent,
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
EventPluginUtils.useTouchEvents = shouldUseTouch;
},
createClass: ReactClass.createClass,
createElement: createElement,
cloneElement: cloneElement,
createFactory: createFactory,
createMixin: function(mixin) {
// Currently a noop. Will be used to validate and trace mixins.
return mixin;
},
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
findDOMNode: findDOMNode,
render: render,
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
isValidElement: ReactElement.isValidElement,
withContext: ReactContext.withContext,
// Hook for JSX spread, don't use this for anything else.
__spread: assign
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
CurrentOwner: ReactCurrentOwner,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
Reconciler: ReactReconciler,
TextComponent: ReactDOMTextComponent
});
}
if ("production" !== "development") {
var ExecutionEnvironment = _dereq_(21);
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// If we're in Chrome, look for the devtools marker and provide a download
// link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1) {
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
console.debug(
'Download the React DevTools for a better development experience: ' +
'http://fb.me/react-devtools'
);
}
}
var expectedFeatures = [
// shims
Array.isArray,
Array.prototype.every,
Array.prototype.forEach,
Array.prototype.indexOf,
Array.prototype.map,
Date.now,
Function.prototype.bind,
Object.keys,
String.prototype.split,
String.prototype.trim,
// shams
Object.create,
Object.freeze
];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
console.error(
'One or more ES5 shim/shams expected by React are not available: ' +
'http://fb.me/react-warning-polyfills'
);
break;
}
}
}
}
React.version = '0.13.1';
module.exports = React;
},{"117":117,"144":144,"19":19,"21":21,"27":27,"32":32,"33":33,"34":34,"38":38,"39":39,"40":40,"51":51,"54":54,"57":57,"58":58,"66":66,"70":70,"75":75,"78":78,"81":81,"84":84}],2:[function(_dereq_,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 AutoFocusMixin
* @typechecks static-only
*/
'use strict';
var focusNode = _dereq_(119);
var AutoFocusMixin = {
componentDidMount: function() {
if (this.props.autoFocus) {
focusNode(this.getDOMNode());
}
}
};
module.exports = AutoFocusMixin;
},{"119":119}],3:[function(_dereq_,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 BeforeInputEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(20);
var ExecutionEnvironment = _dereq_(21);
var FallbackCompositionState = _dereq_(22);
var SyntheticCompositionEvent = _dereq_(93);
var SyntheticInputEvent = _dereq_(97);
var keyOf = _dereq_(141);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = (
ExecutionEnvironment.canUseDOM &&
'CompositionEvent' in window
);
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = (
ExecutionEnvironment.canUseDOM &&
'TextEvent' in window &&
!documentMode &&
!isPresto()
);
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = (
ExecutionEnvironment.canUseDOM &&
(
(!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11)
)
);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return (
typeof opera === 'object' &&
typeof opera.version === 'function' &&
parseInt(opera.version(), 10) <= 12
);
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({onBeforeInput: null}),
captured: keyOf({onBeforeInputCapture: null})
},
dependencies: [
topLevelTypes.topCompositionEnd,
topLevelTypes.topKeyPress,
topLevelTypes.topTextInput,
topLevelTypes.topPaste
]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionEnd: null}),
captured: keyOf({onCompositionEndCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topCompositionEnd,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyPress,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown
]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionStart: null}),
captured: keyOf({onCompositionStartCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topCompositionStart,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyPress,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown
]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionUpdate: null}),
captured: keyOf({onCompositionUpdateCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topCompositionUpdate,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyPress,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown
]
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (
(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey)
);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return (
topLevelType === topLevelTypes.topKeyDown &&
nativeEvent.keyCode === START_KEYCODE
);
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1);
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return (nativeEvent.keyCode !== START_KEYCODE);
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(
eventType,
topLevelTargetID,
nativeEvent
);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (
topLevelType === topLevelTypes.topCompositionEnd ||
isFallbackCompositionEnd(topLevelType, nativeEvent)
) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(
eventTypes.beforeInput,
topLevelTargetID,
nativeEvent
);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
) {
return [
extractCompositionEvent(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
),
extractBeforeInputEvent(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
)
];
}
};
module.exports = BeforeInputEventPlugin;
},{"141":141,"15":15,"20":20,"21":21,"22":22,"93":93,"97":97}],4:[function(_dereq_,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 CSSProperty
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
boxFlex: true,
boxFlexGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
strokeOpacity: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function(prop) {
prefixes.forEach(function(prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundImage: true,
backgroundPosition: true,
backgroundRepeat: true,
backgroundColor: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],5:[function(_dereq_,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 CSSPropertyOperations
* @typechecks static-only
*/
'use strict';
var CSSProperty = _dereq_(4);
var ExecutionEnvironment = _dereq_(21);
var camelizeStyleName = _dereq_(108);
var dangerousStyleValue = _dereq_(113);
var hyphenateStyleName = _dereq_(133);
var memoizeStringOnly = _dereq_(143);
var warning = _dereq_(154);
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if ("production" !== "development") {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnHyphenatedStyleName = function(name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
("production" !== "development" ? warning(
false,
'Unsupported style property %s. Did you mean %s?',
name,
camelizeStyleName(name)
) : null);
};
var warnBadVendoredStyleName = function(name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
("production" !== "development" ? warning(
false,
'Unsupported vendor-prefixed style property %s. Did you mean %s?',
name,
name.charAt(0).toUpperCase() + name.slice(1)
) : null);
};
var warnStyleValueWithSemicolon = function(name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
("production" !== "development" ? warning(
false,
'Style property values shouldn\'t contain a semicolon. ' +
'Try "%s: %s" instead.',
name,
value.replace(badStyleValueWithSemicolonPattern, '')
) : null);
};
/**
* @param {string} name
* @param {*} value
*/
var warnValidStyle = function(name, value) {
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @return {?string}
*/
createMarkupForStyles: function(styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if ("production" !== "development") {
warnValidStyle(styleName, styleValue);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if ("production" !== "development") {
warnValidStyle(styleName, styles[styleName]);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleName === 'float') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
},{"108":108,"113":113,"133":133,"143":143,"154":154,"21":21,"4":4}],6:[function(_dereq_,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 CallbackQueue
*/
'use strict';
var PooledClass = _dereq_(28);
var assign = _dereq_(27);
var invariant = _dereq_(135);
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function(callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function() {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
("production" !== "development" ? invariant(
callbacks.length === contexts.length,
'Mismatched list of contexts in callback queue'
) : invariant(callbacks.length === contexts.length));
this._callbacks = null;
this._contexts = null;
for (var i = 0, l = callbacks.length; i < l; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function() {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
},{"135":135,"27":27,"28":28}],7:[function(_dereq_,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 ChangeEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(17);
var EventPropagators = _dereq_(20);
var ExecutionEnvironment = _dereq_(21);
var ReactUpdates = _dereq_(87);
var SyntheticEvent = _dereq_(95);
var isEventSupported = _dereq_(136);
var isTextInputElement = _dereq_(138);
var keyOf = _dereq_(141);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({onChange: null}),
captured: keyOf({onChangeCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topChange,
topLevelTypes.topClick,
topLevelTypes.topFocus,
topLevelTypes.topInput,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyUp,
topLevelTypes.topSelectionChange
]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
return (
elem.nodeName === 'SELECT' ||
(elem.nodeName === 'INPUT' && elem.type === 'file')
);
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (
(!('documentMode' in document) || document.documentMode > 8)
);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
activeElementID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue();
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events
isInputEventSupported = isEventSupported('input') && (
(!('documentMode' in document) || document.documentMode > 9)
);
}
/**
* (For old IE.) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function() {
return activeElementValueProp.get.call(this);
},
set: function(val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For old IE.) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(
target.constructor.prototype,
'value'
);
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetIDForInputEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topSelectionChange ||
topLevelType === topLevelTypes.topKeyUp ||
topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementID;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return (
elem.nodeName === 'INPUT' &&
(elem.type === 'checkbox' || elem.type === 'radio')
);
}
function getTargetIDForClickEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
if (targetID) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
targetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
}
}
};
module.exports = ChangeEventPlugin;
},{"136":136,"138":138,"141":141,"15":15,"17":17,"20":20,"21":21,"87":87,"95":95}],8:[function(_dereq_,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 ClientReactRootIndex
* @typechecks
*/
'use strict';
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function() {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
},{}],9:[function(_dereq_,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 DOMChildrenOperations
* @typechecks static-only
*/
'use strict';
var Danger = _dereq_(12);
var ReactMultiChildUpdateTypes = _dereq_(72);
var setTextContent = _dereq_(149);
var invariant = _dereq_(135);
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
// By exploiting arrays returning `undefined` for an undefined index, we can
// rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. However, using `undefined` is not allowed by all
// browsers so we must replace it with `null`.
parentNode.insertBefore(
childNode,
parentNode.childNodes[index] || null
);
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: setTextContent,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function(updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; i < updates.length; i++) {
update = updates[i];
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING ||
update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
("production" !== "development" ? invariant(
updatedChild,
'processUpdates(): Unable to find child %s of element. This ' +
'probably means the DOM was unexpectedly mutated (e.g., by the ' +
'browser), usually due to forgetting a <tbody> when using tables, ' +
'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' +
'in an <svg> parent. Try inspecting the child nodes of the element ' +
'with React ID `%s`.',
updatedIndex,
parentID
) : invariant(updatedChild));
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; k < updates.length; k++) {
update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(
update.parentNode,
renderedMarkup[update.markupIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(
update.parentNode,
initialChildren[update.parentID][update.fromIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(
update.parentNode,
update.textContent
);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
module.exports = DOMChildrenOperations;
},{"12":12,"135":135,"149":149,"72":72}],10:[function(_dereq_,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 DOMProperty
* @typechecks static-only
*/
/*jslint bitwise: true */
'use strict';
var invariant = _dereq_(135);
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_SIDE_EFFECTS: 0x4,
HAS_BOOLEAN_VALUE: 0x8,
HAS_NUMERIC_VALUE: 0x10,
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function(domPropertyConfig) {
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(
domPropertyConfig.isCustomAttribute
);
}
for (var propName in Properties) {
("production" !== "development" ? invariant(
!DOMProperty.isStandardName.hasOwnProperty(propName),
'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' +
'\'%s\' which has already been injected. You may be accidentally ' +
'injecting the same DOM property config twice, or you may be ' +
'injecting two configs that have conflicting property names.',
propName
) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName)));
DOMProperty.isStandardName[propName] = true;
var lowerCased = propName.toLowerCase();
DOMProperty.getPossibleStandardName[lowerCased] = propName;
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
DOMProperty.getPossibleStandardName[attributeName] = propName;
DOMProperty.getAttributeName[propName] = attributeName;
} else {
DOMProperty.getAttributeName[propName] = lowerCased;
}
DOMProperty.getPropertyName[propName] =
DOMPropertyNames.hasOwnProperty(propName) ?
DOMPropertyNames[propName] :
propName;
if (DOMMutationMethods.hasOwnProperty(propName)) {
DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName];
} else {
DOMProperty.getMutationMethod[propName] = null;
}
var propConfig = Properties[propName];
DOMProperty.mustUseAttribute[propName] =
checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE);
DOMProperty.mustUseProperty[propName] =
checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY);
DOMProperty.hasSideEffects[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS);
DOMProperty.hasBooleanValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE);
DOMProperty.hasNumericValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE);
DOMProperty.hasPositiveNumericValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE);
DOMProperty.hasOverloadedBooleanValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE);
("production" !== "development" ? invariant(
!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName],
'DOMProperty: Cannot require using both attribute and property: %s',
propName
) : invariant(!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName]));
("production" !== "development" ? invariant(
DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName],
'DOMProperty: Properties that have side effects must use property: %s',
propName
) : invariant(DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName]));
("production" !== "development" ? invariant(
!!DOMProperty.hasBooleanValue[propName] +
!!DOMProperty.hasNumericValue[propName] +
!!DOMProperty.hasOverloadedBooleanValue[propName] <= 1,
'DOMProperty: Value can be one of boolean, overloaded boolean, or ' +
'numeric value, but not a combination: %s',
propName
) : invariant(!!DOMProperty.hasBooleanValue[propName] +
!!DOMProperty.hasNumericValue[propName] +
!!DOMProperty.hasOverloadedBooleanValue[propName] <= 1));
}
}
};
var defaultValueCache = {};
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
/**
* Checks whether a property name is a standard property.
* @type {Object}
*/
isStandardName: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties.
* @type {Object}
*/
getPossibleStandardName: {},
/**
* Mapping from normalized names to attribute names that differ. Attribute
* names are used when rendering markup or with `*Attribute()`.
* @type {Object}
*/
getAttributeName: {},
/**
* Mapping from normalized names to properties on DOM node instances.
* (This includes properties that mutate due to external factors.)
* @type {Object}
*/
getPropertyName: {},
/**
* Mapping from normalized names to mutation methods. This will only exist if
* mutation cannot be set simply by the property or `setAttribute()`.
* @type {Object}
*/
getMutationMethod: {},
/**
* Whether the property must be accessed and mutated as an object property.
* @type {Object}
*/
mustUseAttribute: {},
/**
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* @type {Object}
*/
mustUseProperty: {},
/**
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. We must ensure that
* the value is only set if it has changed.
* @type {Object}
*/
hasSideEffects: {},
/**
* Whether the property should be removed when set to a falsey value.
* @type {Object}
*/
hasBooleanValue: {},
/**
* Whether the property must be numeric or parse as a
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasNumericValue: {},
/**
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasPositiveNumericValue: {},
/**
* Whether the property can be used as a flag as well as with a value. Removed
* when strictly equal to false; present without a value when strictly equal
* to true; present with a value otherwise.
* @type {Object}
*/
hasOverloadedBooleanValue: {},
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function(attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function(nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
},{"135":135}],11:[function(_dereq_,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 DOMPropertyOperations
* @typechecks static-only
*/
'use strict';
var DOMProperty = _dereq_(10);
var quoteAttributeValueForBrowser = _dereq_(147);
var warning = _dereq_(154);
function shouldIgnoreValue(name, value) {
return value == null ||
(DOMProperty.hasBooleanValue[name] && !value) ||
(DOMProperty.hasNumericValue[name] && isNaN(value)) ||
(DOMProperty.hasPositiveNumericValue[name] && (value < 1)) ||
(DOMProperty.hasOverloadedBooleanValue[name] && value === false);
}
if ("production" !== "development") {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function(name) {
if (reactProps.hasOwnProperty(name) && reactProps[name] ||
warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = (
DOMProperty.isCustomAttribute(lowerCasedName) ?
lowerCasedName :
DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ?
DOMProperty.getPossibleStandardName[lowerCasedName] :
null
);
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
("production" !== "development" ? warning(
standardName == null,
'Unknown DOM property %s. Did you mean %s?',
name,
standardName
) : null);
};
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function(id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' +
quoteAttributeValueForBrowser(id);
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function(name, value) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
if (shouldIgnoreValue(name, value)) {
return '';
}
var attributeName = DOMProperty.getAttributeName[name];
if (DOMProperty.hasBooleanValue[name] ||
(DOMProperty.hasOverloadedBooleanValue[name] && value === true)) {
return attributeName;
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
return null;
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function(node, name, value) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(name, value)) {
this.deleteValueForProperty(node, name);
} else if (DOMProperty.mustUseAttribute[name]) {
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
} else {
var propName = DOMProperty.getPropertyName[name];
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
if (!DOMProperty.hasSideEffects[name] ||
('' + node[propName]) !== ('' + value)) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function(node, name) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (DOMProperty.mustUseAttribute[name]) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
var propName = DOMProperty.getPropertyName[name];
var defaultValue = DOMProperty.getDefaultValueForProperty(
node.nodeName,
propName
);
if (!DOMProperty.hasSideEffects[name] ||
('' + node[propName]) !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
}
};
module.exports = DOMPropertyOperations;
},{"10":10,"147":147,"154":154}],12:[function(_dereq_,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 Danger
* @typechecks static-only
*/
/*jslint evil: true, sub: true */
'use strict';
var ExecutionEnvironment = _dereq_(21);
var createNodesFromMarkup = _dereq_(112);
var emptyFunction = _dereq_(114);
var getMarkupWrap = _dereq_(127);
var invariant = _dereq_(135);
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function(markupList) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' +
'thread. Make sure `window` and `document` are available globally ' +
'before requiring React when unit testing or use ' +
'React.renderToString for server rendering.'
) : invariant(ExecutionEnvironment.canUseDOM));
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
("production" !== "development" ? invariant(
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
) : invariant(markupList[i]));
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
var resultIndex;
for (resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(
OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '
);
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(
markupListByNodeName.join(''),
emptyFunction // Do nothing special with <script> tags.
);
for (var j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
if (renderNode.hasAttribute &&
renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
("production" !== "development" ? invariant(
!resultList.hasOwnProperty(resultIndex),
'Danger: Assigning to an already-occupied result index.'
) : invariant(!resultList.hasOwnProperty(resultIndex)));
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("production" !== "development") {
console.error(
'Danger: Discarding unexpected node:',
renderNode
);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
("production" !== "development" ? invariant(
resultListAssignmentCount === resultList.length,
'Danger: Did not assign to every index of resultList.'
) : invariant(resultListAssignmentCount === resultList.length));
("production" !== "development" ? invariant(
resultList.length === markupList.length,
'Danger: Expected markup to render %s nodes, but rendered %s.',
markupList.length,
resultList.length
) : invariant(resultList.length === markupList.length));
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' +
'worker thread. Make sure `window` and `document` are available ' +
'globally before requiring React when unit testing or use ' +
'React.renderToString for server rendering.'
) : invariant(ExecutionEnvironment.canUseDOM));
("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup));
("production" !== "development" ? invariant(
oldChild.tagName.toLowerCase() !== 'html',
'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' +
'<html> node. This is because browser quirks make this unreliable ' +
'and/or slow. If you want to render to the root you must use ' +
'server rendering. See React.renderToString().'
) : invariant(oldChild.tagName.toLowerCase() !== 'html'));
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"112":112,"114":114,"127":127,"135":135,"21":21}],13:[function(_dereq_,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 DefaultEventPluginOrder
*/
'use strict';
var keyOf = _dereq_(141);
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [
keyOf({ResponderEventPlugin: null}),
keyOf({SimpleEventPlugin: null}),
keyOf({TapEventPlugin: null}),
keyOf({EnterLeaveEventPlugin: null}),
keyOf({ChangeEventPlugin: null}),
keyOf({SelectEventPlugin: null}),
keyOf({BeforeInputEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null}),
keyOf({MobileSafariClickEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"141":141}],14:[function(_dereq_,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 EnterLeaveEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(20);
var SyntheticMouseEvent = _dereq_(99);
var ReactMount = _dereq_(70);
var keyOf = _dereq_(141);
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({onMouseEnter: null}),
dependencies: [
topLevelTypes.topMouseOut,
topLevelTypes.topMouseOver
]
},
mouseLeave: {
registrationName: keyOf({onMouseLeave: null}),
dependencies: [
topLevelTypes.topMouseOut,
topLevelTypes.topMouseOver
]
}
};
var extractedEvents = [null, null];
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topMouseOver &&
(nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut &&
topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (topLevelTarget.window === topLevelTarget) {
// `topLevelTarget` is probably a window object.
win = topLevelTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = topLevelTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from, to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
to =
getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
win;
} else {
from = win;
to = topLevelTarget;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromID = from ? ReactMount.getID(from) : '';
var toID = to ? ReactMount.getID(to) : '';
var leave = SyntheticMouseEvent.getPooled(
eventTypes.mouseLeave,
fromID,
nativeEvent
);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(
eventTypes.mouseEnter,
toID,
nativeEvent
);
enter.type = 'mouseenter';
enter.target = to;
enter.relatedTarget = from;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
},{"141":141,"15":15,"20":20,"70":70,"99":99}],15:[function(_dereq_,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 EventConstants
*/
'use strict';
var keyMirror = _dereq_(140);
var PropagationPhases = keyMirror({bubbled: null, captured: null});
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topBlur: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topError: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topReset: null,
topScroll: null,
topSelectionChange: null,
topSubmit: null,
topTextInput: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"140":140}],16:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
*
* 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.
*
* @providesModule EventListener
* @typechecks
*/
var emptyFunction = _dereq_(114);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function() {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function(target, eventType, callback) {
if (!target.addEventListener) {
if ("production" !== "development") {
console.error(
'Attempted to listen to events during the capture phase on a ' +
'browser that does not support the capture phase. Your application ' +
'will not receive some events.'
);
}
return {
remove: emptyFunction
};
} else {
target.addEventListener(eventType, callback, true);
return {
remove: function() {
target.removeEventListener(eventType, callback, true);
}
};
}
},
registerDefault: function() {}
};
module.exports = EventListener;
},{"114":114}],17:[function(_dereq_,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 EventPluginHub
*/
'use strict';
var EventPluginRegistry = _dereq_(18);
var EventPluginUtils = _dereq_(19);
var accumulateInto = _dereq_(105);
var forEachAccumulated = _dereq_(120);
var invariant = _dereq_(135);
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @private
*/
var executeDispatchesAndRelease = function(event) {
if (event) {
var executeDispatch = EventPluginUtils.executeDispatch;
// Plugins can provide custom behavior when dispatching events.
var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event);
if (PluginModule && PluginModule.executeDispatch) {
executeDispatch = PluginModule.executeDispatch;
}
EventPluginUtils.executeDispatchesInOrder(event, executeDispatch);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var InstanceHandle = null;
function validateInstanceHandle() {
var valid =
InstanceHandle &&
InstanceHandle.traverseTwoPhase &&
InstanceHandle.traverseEnterLeave;
("production" !== "development" ? invariant(
valid,
'InstanceHandle not injected before use!'
) : invariant(valid));
}
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {object} InjectedMount
* @public
*/
injectMount: EventPluginUtils.injection.injectMount,
/**
* @param {object} InjectedInstanceHandle
* @public
*/
injectInstanceHandle: function(InjectedInstanceHandle) {
InstanceHandle = InjectedInstanceHandle;
if ("production" !== "development") {
validateInstanceHandle();
}
},
getInstanceHandle: function() {
if ("production" !== "development") {
validateInstanceHandle();
}
return InstanceHandle;
},
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
registrationNameModules: EventPluginRegistry.registrationNameModules,
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function(id, registrationName, listener) {
("production" !== "development" ? invariant(
!listener || typeof listener === 'function',
'Expected %s listener to be a function, instead got type %s',
registrationName, typeof listener
) : invariant(!listener || typeof listener === 'function'));
var bankForRegistrationName =
listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function(id) {
for (var registrationName in listenerBank) {
delete listenerBank[registrationName][id];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0, l = plugins.length; i < l; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function(events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function() {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
forEachAccumulated(processingEventQueue, executeDispatchesAndRelease);
("production" !== "development" ? invariant(
!eventQueue,
'processEventQueue(): Additional events were enqueued while processing ' +
'an event queue. Support for this has not yet been implemented.'
) : invariant(!eventQueue));
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function() {
listenerBank = {};
},
__getListenerBank: function() {
return listenerBank;
}
};
module.exports = EventPluginHub;
},{"105":105,"120":120,"135":135,"18":18,"19":19}],18:[function(_dereq_,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 EventPluginRegistry
* @typechecks static-only
*/
'use strict';
var invariant = _dereq_(135);
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
("production" !== "development" ? invariant(
pluginIndex > -1,
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
'the plugin ordering, `%s`.',
pluginName
) : invariant(pluginIndex > -1));
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
("production" !== "development" ? invariant(
PluginModule.extractEvents,
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
'method, but `%s` does not.',
pluginName
) : invariant(PluginModule.extractEvents));
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
("production" !== "development" ? invariant(
publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
),
'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
eventName,
pluginName
) : invariant(publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
)));
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
("production" !== "development" ? invariant(
!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName),
'EventPluginHub: More than one plugin attempted to publish the same ' +
'event name, `%s`.',
eventName
) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName)));
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(
phasedRegistrationName,
PluginModule,
eventName
);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(
dispatchConfig.registrationName,
PluginModule,
eventName
);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
("production" !== "development" ? invariant(
!EventPluginRegistry.registrationNameModules[registrationName],
'EventPluginHub: More than one plugin attempted to publish the same ' +
'registration name, `%s`.',
registrationName
) : invariant(!EventPluginRegistry.registrationNameModules[registrationName]));
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] =
PluginModule.eventTypes[eventName].dependencies;
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function(InjectedEventPluginOrder) {
("production" !== "development" ? invariant(
!EventPluginOrder,
'EventPluginRegistry: Cannot inject event plugin ordering more than ' +
'once. You are likely trying to load more than one copy of React.'
) : invariant(!EventPluginOrder));
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function(injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) ||
namesToPlugins[pluginName] !== PluginModule) {
("production" !== "development" ? invariant(
!namesToPlugins[pluginName],
'EventPluginRegistry: Cannot inject two different event plugins ' +
'using the same name, `%s`.',
pluginName
) : invariant(!namesToPlugins[pluginName]));
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function(event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[
dispatchConfig.registrationName
] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[
dispatchConfig.phasedRegistrationNames[phase]
];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function() {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
}
};
module.exports = EventPluginRegistry;
},{"135":135}],19:[function(_dereq_,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 EventPluginUtils
*/
'use strict';
var EventConstants = _dereq_(15);
var invariant = _dereq_(135);
/**
* Injected dependencies:
*/
/**
* - `Mount`: [required] Module that can convert between React dom IDs and
* actual node references.
*/
var injection = {
Mount: null,
injectMount: function(InjectedMount) {
injection.Mount = InjectedMount;
if ("production" !== "development") {
("production" !== "development" ? invariant(
InjectedMount && InjectedMount.getNode,
'EventPluginUtils.injection.injectMount(...): Injected Mount module ' +
'is missing getNode.'
) : invariant(InjectedMount && InjectedMount.getNode));
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp ||
topLevelType === topLevelTypes.topTouchEnd ||
topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove ||
topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown ||
topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if ("production" !== "development") {
validateEventDispatches = function(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ?
dispatchListeners.length :
dispatchListeners ? 1 : 0;
("production" !== "development" ? invariant(
idsIsArr === listenersIsArr && IDsLen === listenersLen,
'EventPluginUtils: Invalid `event`.'
) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen));
};
}
/**
* Invokes `cb(event, listener, id)`. Avoids using call if no scope is
* provided. The `(listener,id)` pair effectively forms the "dispatch" but are
* kept separate to conserve memory.
*/
function forEachEventDispatch(event, cb) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
cb(event, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
cb(event, dispatchListeners, dispatchIDs);
}
}
/**
* Default implementation of PluginModule.executeDispatch().
* @param {SyntheticEvent} SyntheticEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, listener, domID) {
event.currentTarget = injection.Mount.getNode(domID);
var returnValue = listener(event, domID);
event.currentTarget = null;
return returnValue;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, cb) {
forEachEventDispatch(event, cb);
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return id of the first dispatch execution who's listener returns true, or
* null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchIDs = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if ("production" !== "development") {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
("production" !== "development" ? invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `event`.'
) : invariant(!Array.isArray(dispatchListener)));
var res = dispatchListener ?
dispatchListener(event, dispatchID) :
null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {bool} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatch: executeDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
injection: injection,
useTouchEvents: false
};
module.exports = EventPluginUtils;
},{"135":135,"15":15}],20:[function(_dereq_,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 EventPropagators
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(17);
var accumulateInto = _dereq_(105);
var forEachAccumulated = _dereq_(120);
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName =
event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if ("production" !== "development") {
if (!domID) {
throw new Error('Dispatching id must not be null');
}
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners =
accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We can not perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(
event.dispatchMarker,
accumulateDirectionalDispatches,
event
);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners =
accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(
fromID,
toID,
accumulateDispatches,
leave,
enter
);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
},{"105":105,"120":120,"15":15,"17":17}],21:[function(_dereq_,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
*/
/*jslint evil: true */
"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;
},{}],22:[function(_dereq_,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 FallbackCompositionState
* @typechecks static-only
*/
'use strict';
var PooledClass = _dereq_(28);
var assign = _dereq_(27);
var getTextContentAccessor = _dereq_(130);
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
assign(FallbackCompositionState.prototype, {
/**
* Get current text of input.
*
* @return {string}
*/
getText: function() {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function() {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
},{"130":130,"27":27,"28":28}],23:[function(_dereq_,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 HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
'use strict';
var DOMProperty = _dereq_(10);
var ExecutionEnvironment = _dereq_(21);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = (
implementation &&
implementation.hasFeature &&
implementation.hasFeature(
'http://www.w3.org/TR/SVG11/feature#BasicStructure',
'1.1'
)
);
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formAction: MUST_USE_ATTRIBUTE,
formEncType: MUST_USE_ATTRIBUTE,
formMethod: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
headers: null,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
manifest: MUST_USE_ATTRIBUTE,
marginHeight: null,
marginWidth: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
autoCorrect: null,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: MUST_USE_ATTRIBUTE,
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
itemType: MUST_USE_ATTRIBUTE,
// itemID and itemRef are for Microdata support as well but
// only specified in the the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: MUST_USE_ATTRIBUTE,
itemRef: MUST_USE_ATTRIBUTE,
// property is supported for OpenGraph in meta tags.
property: null
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
encType: 'encoding',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
},{"10":10,"21":21}],24:[function(_dereq_,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 LinkedValueUtils
* @typechecks static-only
*/
'use strict';
var ReactPropTypes = _dereq_(78);
var invariant = _dereq_(135);
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(input) {
("production" !== "development" ? invariant(
input.props.checkedLink == null || input.props.valueLink == null,
'Cannot provide a checkedLink and a valueLink. If you want to use ' +
'checkedLink, you probably don\'t want to use valueLink and vice versa.'
) : invariant(input.props.checkedLink == null || input.props.valueLink == null));
}
function _assertValueLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.value == null && input.props.onChange == null,
'Cannot provide a valueLink and a value or onChange event. If you want ' +
'to use value or onChange, you probably don\'t want to use valueLink.'
) : invariant(input.props.value == null && input.props.onChange == null));
}
function _assertCheckedLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.checked == null && input.props.onChange == null,
'Cannot provide a checkedLink and a checked property or onChange event. ' +
'If you want to use checked or onChange, you probably don\'t want to ' +
'use checkedLink'
) : invariant(input.props.checked == null && input.props.onChange == null));
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedValueChange(e) {
/*jshint validthis:true */
this.props.valueLink.requestChange(e.target.value);
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedCheckChange(e) {
/*jshint validthis:true */
this.props.checkedLink.requestChange(e.target.checked);
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
Mixin: {
propTypes: {
value: function(props, propName, componentName) {
if (!props[propName] ||
hasReadOnlyValue[props.type] ||
props.onChange ||
props.readOnly ||
props.disabled) {
return null;
}
return new Error(
'You provided a `value` prop to a form field without an ' +
'`onChange` handler. This will render a read-only field. If ' +
'the field should be mutable use `defaultValue`. Otherwise, ' +
'set either `onChange` or `readOnly`.'
);
},
checked: function(props, propName, componentName) {
if (!props[propName] ||
props.onChange ||
props.readOnly ||
props.disabled) {
return null;
}
return new Error(
'You provided a `checked` prop to a form field without an ' +
'`onChange` handler. This will render a read-only field. If ' +
'the field should be mutable use `defaultChecked`. Otherwise, ' +
'set either `onChange` or `readOnly`.'
);
},
onChange: ReactPropTypes.func
}
},
/**
* @param {ReactComponent} input Form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return input.props.valueLink.value;
}
return input.props.value;
},
/**
* @param {ReactComponent} input Form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function(input) {
if (input.props.checkedLink) {
_assertCheckedLink(input);
return input.props.checkedLink.value;
}
return input.props.checked;
},
/**
* @param {ReactComponent} input Form component
* @return {function} change callback either from onChange prop or link.
*/
getOnChange: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return _handleLinkedValueChange;
} else if (input.props.checkedLink) {
_assertCheckedLink(input);
return _handleLinkedCheckChange;
}
return input.props.onChange;
}
};
module.exports = LinkedValueUtils;
},{"135":135,"78":78}],25:[function(_dereq_,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 LocalEventTrapMixin
*/
'use strict';
var ReactBrowserEventEmitter = _dereq_(30);
var accumulateInto = _dereq_(105);
var forEachAccumulated = _dereq_(120);
var invariant = _dereq_(135);
function remove(event) {
event.remove();
}
var LocalEventTrapMixin = {
trapBubbledEvent:function(topLevelType, handlerBaseName) {
("production" !== "development" ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted()));
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
var node = this.getDOMNode();
("production" !== "development" ? invariant(
node,
'LocalEventTrapMixin.trapBubbledEvent(...): Requires node to be rendered.'
) : invariant(node));
var listener = ReactBrowserEventEmitter.trapBubbledEvent(
topLevelType,
handlerBaseName,
node
);
this._localEventListeners =
accumulateInto(this._localEventListeners, listener);
},
// trapCapturedEvent would look nearly identical. We don't implement that
// method because it isn't currently needed.
componentWillUnmount:function() {
if (this._localEventListeners) {
forEachAccumulated(this._localEventListeners, remove);
}
}
};
module.exports = LocalEventTrapMixin;
},{"105":105,"120":120,"135":135,"30":30}],26:[function(_dereq_,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 MobileSafariClickEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var emptyFunction = _dereq_(114);
var topLevelTypes = EventConstants.topLevelTypes;
/**
* Mobile Safari does not fire properly bubble click events on non-interactive
* elements, which means delegated click listeners do not fire. The workaround
* for this bug involves attaching an empty click listener on the target node.
*
* This particular plugin works around the bug by attaching an empty click
* listener on `touchstart` (which does fire on every element).
*/
var MobileSafariClickEventPlugin = {
eventTypes: null,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topTouchStart) {
var target = nativeEvent.target;
if (target && !target.onclick) {
target.onclick = emptyFunction;
}
}
}
};
module.exports = MobileSafariClickEventPlugin;
},{"114":114,"15":15}],27:[function(_dereq_,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;
},{}],28:[function(_dereq_,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 PooledClass
*/
'use strict';
var invariant = _dereq_(135);
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function(a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fiveArgumentPooler = function(a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function(instance) {
var Klass = this;
("production" !== "development" ? invariant(
instance instanceof Klass,
'Trying to release an instance into a pool of a different type.'
) : invariant(instance instanceof Klass));
if (instance.destructor) {
instance.destructor();
}
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"135":135}],29:[function(_dereq_,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 ReactBrowserComponentMixin
*/
'use strict';
var findDOMNode = _dereq_(117);
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
return findDOMNode(this);
}
};
module.exports = ReactBrowserComponentMixin;
},{"117":117}],30:[function(_dereq_,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 ReactBrowserEventEmitter
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(17);
var EventPluginRegistry = _dereq_(18);
var ReactEventEmitterMixin = _dereq_(61);
var ViewportMetrics = _dereq_(104);
var assign = _dereq_(27);
var isEventSupported = _dereq_(136);
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topBlur: 'blur',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topScroll: 'scroll',
topSelectionChange: 'selectionchange',
topTextInput: 'textInput',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function(ReactEventListener) {
ReactEventListener.setHandleTopLevel(
ReactBrowserEventEmitter.handleTopLevel
);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return !!(
(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled())
);
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function(registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.
registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0, l = dependencies.length; i < l; i++) {
var dependency = dependencies[i];
if (!(
(isListening.hasOwnProperty(dependency) && isListening[dependency])
)) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topWheel,
'wheel',
mountAt
);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topWheel,
'mousewheel',
mountAt
);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topWheel,
'DOMMouseScroll',
mountAt
);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelTypes.topScroll,
'scroll',
mountAt
);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topScroll,
'scroll',
ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE
);
}
} else if (dependency === topLevelTypes.topFocus ||
dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelTypes.topFocus,
'focus',
mountAt
);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelTypes.topBlur,
'blur',
mountAt
);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topFocus,
'focusin',
mountAt
);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topBlur,
'focusout',
mountAt
);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
dependency,
topEventMapping[dependency],
mountAt
);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function(topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelType,
handlerBaseName,
handle
);
},
trapCapturedEvent: function(topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelType,
handlerBaseName,
handle
);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function() {
if (!isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners
});
module.exports = ReactBrowserEventEmitter;
},{"104":104,"136":136,"15":15,"17":17,"18":18,"27":27,"61":61}],31:[function(_dereq_,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 ReactChildReconciler
* @typechecks static-only
*/
'use strict';
var ReactReconciler = _dereq_(81);
var flattenChildren = _dereq_(118);
var instantiateReactComponent = _dereq_(134);
var shouldUpdateReactComponent = _dereq_(151);
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function(nestedChildNodes, transaction, context) {
var children = flattenChildren(nestedChildNodes);
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
// The rendered children must be turned into instances as they're
// mounted.
var childInstance = instantiateReactComponent(child, null);
children[name] = childInstance;
}
}
return children;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextNestedChildNodes Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function(
prevChildren,
nextNestedChildNodes,
transaction,
context) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
var nextChildren = flattenChildren(nextNestedChildNodes);
if (!nextChildren && !prevChildren) {
return null;
}
var name;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(
prevChild, nextElement, transaction, context
);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
ReactReconciler.unmountComponent(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(
nextElement,
null
);
nextChildren[name] = nextChildInstance;
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren.hasOwnProperty(name))) {
ReactReconciler.unmountComponent(prevChildren[name]);
}
}
return nextChildren;
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function(renderedChildren) {
for (var name in renderedChildren) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild);
}
}
};
module.exports = ReactChildReconciler;
},{"118":118,"134":134,"151":151,"81":81}],32:[function(_dereq_,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 ReactChildren
*/
'use strict';
var PooledClass = _dereq_(28);
var ReactFragment = _dereq_(63);
var traverseAllChildren = _dereq_(153);
var warning = _dereq_(154);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var threeArgumentPooler = PooledClass.threeArgumentPooler;
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.forEachFunction = forEachFunction;
this.forEachContext = forEachContext;
}
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(traverseContext, child, name, i) {
var forEachBookKeeping = traverseContext;
forEachBookKeeping.forEachFunction.call(
forEachBookKeeping.forEachContext, child, i);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc.
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext =
ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, mapFunction, mapContext) {
this.mapResult = mapResult;
this.mapFunction = mapFunction;
this.mapContext = mapContext;
}
PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
function mapSingleChildIntoContext(traverseContext, child, name, i) {
var mapBookKeeping = traverseContext;
var mapResult = mapBookKeeping.mapResult;
var keyUnique = !mapResult.hasOwnProperty(name);
if ("production" !== "development") {
("production" !== "development" ? warning(
keyUnique,
'ReactChildren.map(...): Encountered two children with the same key, ' +
'`%s`. Child keys must be unique; when two children share a key, only ' +
'the first child will be used.',
name
) : null);
}
if (keyUnique) {
var mappedChild =
mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
mapResult[name] = mappedChild;
}
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* TODO: This may likely break any calls to `ReactChildren.map` that were
* previously relying on the fact that we guarded against null children.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var mapResult = {};
var traverseContext = MapBookKeeping.getPooled(mapResult, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
return ReactFragment.create(mapResult);
}
function forEachSingleChildDummy(traverseContext, child, name, i) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
count: countChildren
};
module.exports = ReactChildren;
},{"153":153,"154":154,"28":28,"63":63}],33:[function(_dereq_,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 ReactClass
*/
'use strict';
var ReactComponent = _dereq_(34);
var ReactCurrentOwner = _dereq_(39);
var ReactElement = _dereq_(57);
var ReactErrorUtils = _dereq_(60);
var ReactInstanceMap = _dereq_(67);
var ReactLifeCycle = _dereq_(68);
var ReactPropTypeLocations = _dereq_(77);
var ReactPropTypeLocationNames = _dereq_(76);
var ReactUpdateQueue = _dereq_(86);
var assign = _dereq_(27);
var invariant = _dereq_(135);
var keyMirror = _dereq_(140);
var keyOf = _dereq_(141);
var warning = _dereq_(154);
var MIXINS_KEY = keyOf({mixins: null});
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or native 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 available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.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: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.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: SpecPolicy.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: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.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}
* @nosideeffects
* @required
*/
render: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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 ("production" !== "development") {
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
}
Constructor.childContextTypes = assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
if ("production" !== "development") {
validateTypeDef(
Constructor,
contextTypes,
ReactPropTypeLocations.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 ("production" !== "development") {
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
}
Constructor.propTypes = assign(
{},
Constructor.propTypes,
propTypes
);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
}
};
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 not in __DEV__
("production" !== "development" ? 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
) : null);
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ?
ReactClassInterface[name] :
null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === 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
) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === 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
) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
("production" !== "development" ? invariant(
typeof spec !== 'function',
'ReactClass: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(typeof spec !== 'function'));
("production" !== "development" ? invariant(
!ReactElement.isValidElement(spec),
'ReactClass: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactElement.isValidElement(spec)));
var proto = Constructor.prototype;
// 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];
validateMethodOverride(proto, 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 isAlreadyDefined = proto.hasOwnProperty(name);
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isReactClassMethod &&
!isAlreadyDefined &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride
("production" !== "development" ? invariant(
isReactClassMethod && (
(specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)
),
'ReactClass: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
) : invariant(isReactClassMethod && (
(specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)
)));
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("production" !== "development") {
// 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;
("production" !== "development" ? 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
) : invariant(!isReserved));
var isInherited = name in Constructor;
("production" !== "development" ? invariant(
!isInherited,
'ReactClass: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
) : invariant(!isInherited));
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) {
("production" !== "development" ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
for (var key in two) {
if (two.hasOwnProperty(key)) {
("production" !== "development" ? 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
) : invariant(one[key] === undefined));
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 ("production" !== "development") {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
/* eslint-disable block-scoped-var, no-undef */
boundMethod.bind = function(newThis ) {for (var args=[],$__0=1,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
// 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) {
("production" !== "development" ? warning(
false,
'bind(): React component methods may only be bound to the ' +
'component instance. See %s',
componentName
) : null);
} else if (!args.length) {
("production" !== "development" ? 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
) : null);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
/* eslint-enable */
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
for (var autoBindKey in component.__reactAutoBindMap) {
if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
var method = component.__reactAutoBindMap[autoBindKey];
component[autoBindKey] = bindAutoBindMethod(
component,
ReactErrorUtils.guard(
method,
component.constructor.displayName + '.' + autoBindKey
)
);
}
}
}
var typeDeprecationDescriptor = {
enumerable: false,
get: function() {
var displayName = this.displayName || this.name || 'Component';
("production" !== "development" ? warning(
false,
'%s.type is deprecated. Use %s directly to access the class.',
displayName,
displayName
) : null);
Object.defineProperty(this, 'type', {
value: this
});
return this;
}
};
/**
* 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) {
ReactUpdateQueue.enqueueReplaceState(this, newState);
if (callback) {
ReactUpdateQueue.enqueueCallback(this, callback);
}
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
if ("production" !== "development") {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
("production" !== "development" ? warning(
owner._warnedAboutRefsInRender,
'%s is accessing isMounted inside its render() function. ' +
'render() should be a pure function of props and state. It should ' +
'never access something that requires stale data from the previous ' +
'render, such as refs. Move this logic to componentDidMount and ' +
'componentDidUpdate instead.',
owner.getName() || 'A component'
) : null);
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(this);
return (
internalInstance &&
internalInstance !== ReactLifeCycle.currentlyMountingInstance
);
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
setProps: function(partialProps, callback) {
ReactUpdateQueue.enqueueSetProps(this, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallback(this, callback);
}
},
/**
* Replace all the props.
*
* @param {object} newProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
replaceProps: function(newProps, callback) {
ReactUpdateQueue.enqueueReplaceProps(this, newProps);
if (callback) {
ReactUpdateQueue.enqueueCallback(this, callback);
}
}
};
var ReactClassComponent = function() {};
assign(
ReactClassComponent.prototype,
ReactComponent.prototype,
ReactClassMixin
);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function(props, context) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("production" !== "development") {
("production" !== "development" ? warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: http://fb.me/react-legacyfactory'
) : null);
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
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 ("production" !== "development") {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' &&
this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
("production" !== "development" ? invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
injectedMixins.forEach(
mixSpecIntoComponent.bind(null, Constructor)
);
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ("production" !== "development") {
// 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 = {};
}
}
("production" !== "development" ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== "development") {
("production" !== "development" ? 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'
) : null);
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
// Legacy hook
Constructor.type = Constructor;
if ("production" !== "development") {
try {
Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor);
} catch (x) {
// IE will fail on defineProperty (es5-shim/sham too)
}
}
return Constructor;
},
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
},{"135":135,"140":140,"141":141,"154":154,"27":27,"34":34,"39":39,"57":57,"60":60,"67":67,"68":68,"76":76,"77":77,"86":86}],34:[function(_dereq_,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 ReactComponent
*/
'use strict';
var ReactUpdateQueue = _dereq_(86);
var invariant = _dereq_(135);
var warning = _dereq_(154);
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context) {
this.props = props;
this.context = context;
}
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function(partialState, callback) {
("production" !== "development" ? invariant(
typeof partialState === 'object' ||
typeof partialState === 'function' ||
partialState == null,
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.'
) : invariant(typeof partialState === 'object' ||
typeof partialState === 'function' ||
partialState == null));
if ("production" !== "development") {
("production" !== "development" ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
ReactUpdateQueue.enqueueSetState(this, partialState);
if (callback) {
ReactUpdateQueue.enqueueCallback(this, callback);
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function(callback) {
ReactUpdateQueue.enqueueForceUpdate(this);
if (callback) {
ReactUpdateQueue.enqueueCallback(this, callback);
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if ("production" !== "development") {
var deprecatedAPIs = {
getDOMNode: 'getDOMNode',
isMounted: 'isMounted',
replaceProps: 'replaceProps',
replaceState: 'replaceState',
setProps: 'setProps'
};
var defineDeprecationWarning = function(methodName, displayName) {
try {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function() {
("production" !== "development" ? warning(
false,
'%s(...) is deprecated in plain JavaScript React classes.',
displayName
) : null);
return undefined;
}
});
} catch (x) {
// IE will fail on defineProperty (es5-shim/sham too)
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
},{"135":135,"154":154,"86":86}],35:[function(_dereq_,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 ReactComponentBrowserEnvironment
*/
/*jslint evil: true */
'use strict';
var ReactDOMIDOperations = _dereq_(44);
var ReactMount = _dereq_(70);
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates:
ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkupByID:
ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function(rootNodeID) {
ReactMount.purgeID(rootNodeID);
}
};
module.exports = ReactComponentBrowserEnvironment;
},{"44":44,"70":70}],36:[function(_dereq_,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 ReactComponentEnvironment
*/
'use strict';
var invariant = _dereq_(135);
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*/
unmountIDFromEnvironment: null,
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkupByID: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function(environment) {
("production" !== "development" ? invariant(
!injected,
'ReactCompositeComponent: injectEnvironment() can only be called once.'
) : invariant(!injected));
ReactComponentEnvironment.unmountIDFromEnvironment =
environment.unmountIDFromEnvironment;
ReactComponentEnvironment.replaceNodeWithMarkupByID =
environment.replaceNodeWithMarkupByID;
ReactComponentEnvironment.processChildrenUpdates =
environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
},{"135":135}],37:[function(_dereq_,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 ReactCompositeComponent
*/
'use strict';
var ReactComponentEnvironment = _dereq_(36);
var ReactContext = _dereq_(38);
var ReactCurrentOwner = _dereq_(39);
var ReactElement = _dereq_(57);
var ReactElementValidator = _dereq_(58);
var ReactInstanceMap = _dereq_(67);
var ReactLifeCycle = _dereq_(68);
var ReactNativeComponent = _dereq_(73);
var ReactPerf = _dereq_(75);
var ReactPropTypeLocations = _dereq_(77);
var ReactPropTypeLocationNames = _dereq_(76);
var ReactReconciler = _dereq_(81);
var ReactUpdates = _dereq_(87);
var assign = _dereq_(27);
var emptyObject = _dereq_(115);
var invariant = _dereq_(135);
var shouldUpdateReactComponent = _dereq_(151);
var warning = _dereq_(154);
function getDeclarationErrorAddendum(component) {
var owner = component._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function(element) {
this._currentElement = element;
this._rootNodeID = null;
this._instance = null;
// See ReactUpdateQueue
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._isTopLevel = false;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function(rootID, transaction, context) {
this._context = context;
this._mountOrder = nextMountID++;
this._rootNodeID = rootID;
var publicProps = this._processProps(this._currentElement.props);
var publicContext = this._processContext(this._currentElement._context);
var Component = ReactNativeComponent.getComponentClassForElement(
this._currentElement
);
// Initialize the public class
var inst = new Component(publicProps, publicContext);
if ("production" !== "development") {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
("production" !== "development" ? warning(
inst.render != null,
'%s(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render` in your ' +
'component or you may have accidentally tried to render an element ' +
'whose type is a function that isn\'t a React component.',
Component.displayName || Component.name || 'Component'
) : null);
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if ("production" !== "development") {
this._warnIfContextsDiffer(this._currentElement._context, context);
}
if ("production" !== "development") {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
("production" !== "development" ? warning(
!inst.getInitialState ||
inst.getInitialState.isReactClassApproved,
'getInitialState was defined on %s, a plain JavaScript class. ' +
'This is only supported for classes created using React.createClass. ' +
'Did you mean to define a state property instead?',
this.getName() || 'a component'
) : null);
("production" !== "development" ? warning(
!inst.propTypes,
'propTypes was defined as an instance property on %s. Use a static ' +
'property to define propTypes instead.',
this.getName() || 'a component'
) : null);
("production" !== "development" ? warning(
!inst.contextTypes,
'contextTypes was defined as an instance property on %s. Use a ' +
'static property to define contextTypes instead.',
this.getName() || 'a component'
) : null);
("production" !== "development" ? warning(
typeof inst.componentShouldUpdate !== 'function',
'%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.',
(this.getName() || 'A component')
) : null);
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
("production" !== "development" ? invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.state: must be set to an object or null',
this.getName() || 'ReactCompositeComponent'
) : invariant(typeof initialState === 'object' && !Array.isArray(initialState)));
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
var renderedElement;
var previouslyMounting = ReactLifeCycle.currentlyMountingInstance;
ReactLifeCycle.currentlyMountingInstance = this;
try {
if (inst.componentWillMount) {
inst.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
renderedElement = this._renderValidatedComponent();
} finally {
ReactLifeCycle.currentlyMountingInstance = previouslyMounting;
}
this._renderedComponent = this._instantiateReactComponent(
renderedElement,
this._currentElement.type // The wrapping type
);
var markup = ReactReconciler.mountComponent(
this._renderedComponent,
rootID,
transaction,
this._processChildContext(context)
);
if (inst.componentDidMount) {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
var inst = this._instance;
if (inst.componentWillUnmount) {
var previouslyUnmounting = ReactLifeCycle.currentlyUnmountingInstance;
ReactLifeCycle.currentlyUnmountingInstance = this;
try {
inst.componentWillUnmount();
} finally {
ReactLifeCycle.currentlyUnmountingInstance = previouslyUnmounting;
}
}
ReactReconciler.unmountComponent(this._renderedComponent);
this._renderedComponent = null;
// Reset pending fields
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Schedule a partial update to the props. Only used for internal testing.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @internal
*/
_setPropsInternal: function(partialProps, callback) {
// This is a deoptimized path. We optimize for always having an element.
// This creates an extra internal element.
var element = this._pendingElement || this._currentElement;
this._pendingElement = ReactElement.cloneAndReplaceProps(
element,
assign({}, element.props, partialProps)
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function(context) {
var maskedContext = null;
// This really should be getting the component class for the element,
// but we know that we're not going to need it for built-ins.
if (typeof this._currentElement.type === 'string') {
return emptyObject;
}
var contextTypes = this._currentElement.type.contextTypes;
if (!contextTypes) {
return emptyObject;
}
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function(context) {
var maskedContext = this._maskContext(context);
if ("production" !== "development") {
var Component = ReactNativeComponent.getComponentClassForElement(
this._currentElement
);
if (Component.contextTypes) {
this._checkPropTypes(
Component.contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var inst = this._instance;
var childContext = inst.getChildContext && inst.getChildContext();
if (childContext) {
("production" !== "development" ? invariant(
typeof inst.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
this.getName() || 'ReactCompositeComponent'
) : invariant(typeof inst.constructor.childContextTypes === 'object'));
if ("production" !== "development") {
this._checkPropTypes(
inst.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== "development" ? invariant(
name in inst.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
this.getName() || 'ReactCompositeComponent',
name
) : invariant(name in inst.constructor.childContextTypes));
}
return assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function(newProps) {
if ("production" !== "development") {
var Component = ReactNativeComponent.getComponentClassForElement(
this._currentElement
);
if (Component.propTypes) {
this._checkPropTypes(
Component.propTypes,
newProps,
ReactPropTypeLocations.prop
);
}
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function(propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
("production" !== "development" ? invariant(
typeof propTypes[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually ' +
'from React.PropTypes.',
componentName || 'React class',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof propTypes[propName] === 'function'));
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// React.render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
if (location === ReactPropTypeLocations.prop) {
// Preface gives us something to blacklist in warning module
("production" !== "development" ? warning(
false,
'Failed Composite propType: %s%s',
error.message,
addendum
) : null);
} else {
("production" !== "development" ? warning(
false,
'Failed Context Types: %s%s',
error.message,
addendum
) : null);
}
}
}
}
},
receiveComponent: function(nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(
transaction,
prevElement,
nextElement,
prevContext,
nextContext
);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(
this,
this._pendingElement || this._currentElement,
transaction,
this._context
);
}
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
if ("production" !== "development") {
ReactElementValidator.checkAndWarnForMutatedProps(
this._currentElement
);
}
this.updateComponent(
transaction,
this._currentElement,
this._currentElement,
this._context,
this._context
);
}
},
/**
* Compare two contexts, warning if they are different
* TODO: Remove this check when owner-context is removed
*/
_warnIfContextsDiffer: function(ownerBasedContext, parentBasedContext) {
ownerBasedContext = this._maskContext(ownerBasedContext);
parentBasedContext = this._maskContext(parentBasedContext);
var parentKeys = Object.keys(parentBasedContext).sort();
var displayName = this.getName() || 'ReactCompositeComponent';
for (var i = 0; i < parentKeys.length; i++) {
var key = parentKeys[i];
("production" !== "development" ? warning(
ownerBasedContext[key] === parentBasedContext[key],
'owner-based and parent-based contexts differ ' +
'(values: `%s` vs `%s`) for key (%s) while mounting %s ' +
'(see: http://fb.me/react-context-by-parent)',
ownerBasedContext[key],
parentBasedContext[key],
key,
displayName
) : null);
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function(
transaction,
prevParentElement,
nextParentElement,
prevUnmaskedContext,
nextUnmaskedContext
) {
var inst = this._instance;
var nextContext = inst.context;
var nextProps = inst.props;
// Distinguish between a props update versus a simple state update
if (prevParentElement !== nextParentElement) {
nextContext = this._processContext(nextParentElement._context);
nextProps = this._processProps(nextParentElement.props);
if ("production" !== "development") {
if (nextUnmaskedContext != null) {
this._warnIfContextsDiffer(
nextParentElement._context,
nextUnmaskedContext
);
}
}
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (inst.componentWillReceiveProps) {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate =
this._pendingForceUpdate ||
!inst.shouldComponentUpdate ||
inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("production" !== "development") {
("production" !== "development" ? warning(
typeof shouldUpdate !== 'undefined',
'%s.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.',
this.getName() || 'ReactCompositeComponent'
) : null);
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextParentElement,
nextProps,
nextState,
nextContext,
transaction,
nextUnmaskedContext
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function(props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
var nextState = assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
assign(
nextState,
typeof partial === 'function' ?
partial.call(inst, nextState, props, context) :
partial
);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function(
nextElement,
nextProps,
nextState,
nextContext,
transaction,
unmaskedContext
) {
var inst = this._instance;
var prevProps = inst.props;
var prevState = inst.state;
var prevContext = inst.context;
if (inst.componentWillUpdate) {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (inst.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext),
inst
);
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function(transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(
prevComponentInstance,
nextRenderedElement,
transaction,
this._processChildContext(context)
);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
ReactReconciler.unmountComponent(prevComponentInstance);
this._renderedComponent = this._instantiateReactComponent(
nextRenderedElement,
this._currentElement.type
);
var nextMarkup = ReactReconciler.mountComponent(
this._renderedComponent,
thisID,
transaction,
context
);
this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
}
},
/**
* @protected
*/
_replaceNodeWithMarkupByID: function(prevComponentID, nextMarkup) {
ReactComponentEnvironment.replaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function() {
var inst = this._instance;
var renderedComponent = inst.render();
if ("production" !== "development") {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof renderedComponent === 'undefined' &&
inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedComponent = null;
}
}
return renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(
this._currentElement._context
);
ReactCurrentOwner.current = this;
try {
renderedComponent =
this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== "development" ? invariant(
// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false ||
ReactElement.isValidElement(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
this.getName() || 'ReactCompositeComponent'
) : invariant(// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false ||
ReactElement.isValidElement(renderedComponent)));
return renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function(ref, component) {
var inst = this.getPublicInstance();
var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs;
refs[ref] = component.getPublicInstance();
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function() {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return (
type.displayName || (constructor && constructor.displayName) ||
type.name || (constructor && constructor.name) ||
null
);
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by React.render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function() {
return this._instance;
},
// Stub
_instantiateReactComponent: null
};
ReactPerf.measureMethods(
ReactCompositeComponentMixin,
'ReactCompositeComponent',
{
mountComponent: 'mountComponent',
updateComponent: 'updateComponent',
_renderValidatedComponent: '_renderValidatedComponent'
}
);
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
},{"115":115,"135":135,"151":151,"154":154,"27":27,"36":36,"38":38,"39":39,"57":57,"58":58,"67":67,"68":68,"73":73,"75":75,"76":76,"77":77,"81":81,"87":87}],38:[function(_dereq_,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 ReactContext
*/
'use strict';
var assign = _dereq_(27);
var emptyObject = _dereq_(115);
var warning = _dereq_(154);
var didWarn = false;
/**
* Keeps track of the current context.
*
* The context is automatically passed down the component ownership hierarchy
* and is accessible via `this.context` on ReactCompositeComponents.
*/
var ReactContext = {
/**
* @internal
* @type {object}
*/
current: emptyObject,
/**
* Temporarily extends the current context while executing scopedCallback.
*
* A typical use case might look like
*
* render: function() {
* var children = ReactContext.withContext({foo: 'foo'}, () => (
*
* ));
* return <div>{children}</div>;
* }
*
* @param {object} newContext New context to merge into the existing context
* @param {function} scopedCallback Callback to run with the new context
* @return {ReactComponent|array<ReactComponent>}
*/
withContext: function(newContext, scopedCallback) {
if ("production" !== "development") {
("production" !== "development" ? warning(
didWarn,
'withContext is deprecated and will be removed in a future version. ' +
'Use a wrapper component with getChildContext instead.'
) : null);
didWarn = true;
}
var result;
var previousContext = ReactContext.current;
ReactContext.current = assign({}, previousContext, newContext);
try {
result = scopedCallback();
} finally {
ReactContext.current = previousContext;
}
return result;
}
};
module.exports = ReactContext;
},{"115":115,"154":154,"27":27}],39:[function(_dereq_,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 ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*
* The depth indicate how many composite components are above this render level.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],40:[function(_dereq_,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 ReactDOM
* @typechecks static-only
*/
'use strict';
var ReactElement = _dereq_(57);
var ReactElementValidator = _dereq_(58);
var mapObject = _dereq_(142);
/**
* Create a factory that creates HTML tag elements.
*
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMFactory(tag) {
if ("production" !== "development") {
return ReactElementValidator.createFactory(tag);
}
return ReactElement.createFactory(tag);
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = mapObject({
a: 'a',
abbr: 'abbr',
address: 'address',
area: 'area',
article: 'article',
aside: 'aside',
audio: 'audio',
b: 'b',
base: 'base',
bdi: 'bdi',
bdo: 'bdo',
big: 'big',
blockquote: 'blockquote',
body: 'body',
br: 'br',
button: 'button',
canvas: 'canvas',
caption: 'caption',
cite: 'cite',
code: 'code',
col: 'col',
colgroup: 'colgroup',
data: 'data',
datalist: 'datalist',
dd: 'dd',
del: 'del',
details: 'details',
dfn: 'dfn',
dialog: 'dialog',
div: 'div',
dl: 'dl',
dt: 'dt',
em: 'em',
embed: 'embed',
fieldset: 'fieldset',
figcaption: 'figcaption',
figure: 'figure',
footer: 'footer',
form: 'form',
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
head: 'head',
header: 'header',
hr: 'hr',
html: 'html',
i: 'i',
iframe: 'iframe',
img: 'img',
input: 'input',
ins: 'ins',
kbd: 'kbd',
keygen: 'keygen',
label: 'label',
legend: 'legend',
li: 'li',
link: 'link',
main: 'main',
map: 'map',
mark: 'mark',
menu: 'menu',
menuitem: 'menuitem',
meta: 'meta',
meter: 'meter',
nav: 'nav',
noscript: 'noscript',
object: 'object',
ol: 'ol',
optgroup: 'optgroup',
option: 'option',
output: 'output',
p: 'p',
param: 'param',
picture: 'picture',
pre: 'pre',
progress: 'progress',
q: 'q',
rp: 'rp',
rt: 'rt',
ruby: 'ruby',
s: 's',
samp: 'samp',
script: 'script',
section: 'section',
select: 'select',
small: 'small',
source: 'source',
span: 'span',
strong: 'strong',
style: 'style',
sub: 'sub',
summary: 'summary',
sup: 'sup',
table: 'table',
tbody: 'tbody',
td: 'td',
textarea: 'textarea',
tfoot: 'tfoot',
th: 'th',
thead: 'thead',
time: 'time',
title: 'title',
tr: 'tr',
track: 'track',
u: 'u',
ul: 'ul',
'var': 'var',
video: 'video',
wbr: 'wbr',
// SVG
circle: 'circle',
defs: 'defs',
ellipse: 'ellipse',
g: 'g',
line: 'line',
linearGradient: 'linearGradient',
mask: 'mask',
path: 'path',
pattern: 'pattern',
polygon: 'polygon',
polyline: 'polyline',
radialGradient: 'radialGradient',
rect: 'rect',
stop: 'stop',
svg: 'svg',
text: 'text',
tspan: 'tspan'
}, createDOMFactory);
module.exports = ReactDOM;
},{"142":142,"57":57,"58":58}],41:[function(_dereq_,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 ReactDOMButton
*/
'use strict';
var AutoFocusMixin = _dereq_(2);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var keyMirror = _dereq_(140);
var button = ReactElement.createFactory('button');
var mouseListenerNames = keyMirror({
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
});
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = ReactClass.createClass({
displayName: 'ReactDOMButton',
tagName: 'BUTTON',
mixins: [AutoFocusMixin, ReactBrowserComponentMixin],
render: function() {
var props = {};
// Copy the props; except the mouse listeners if we're disabled
for (var key in this.props) {
if (this.props.hasOwnProperty(key) &&
(!this.props.disabled || !mouseListenerNames[key])) {
props[key] = this.props[key];
}
}
return button(props, this.props.children);
}
});
module.exports = ReactDOMButton;
},{"140":140,"2":2,"29":29,"33":33,"57":57}],42:[function(_dereq_,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 ReactDOMComponent
* @typechecks static-only
*/
/* global hasOwnProperty:true */
'use strict';
var CSSPropertyOperations = _dereq_(5);
var DOMProperty = _dereq_(10);
var DOMPropertyOperations = _dereq_(11);
var ReactBrowserEventEmitter = _dereq_(30);
var ReactComponentBrowserEnvironment =
_dereq_(35);
var ReactMount = _dereq_(70);
var ReactMultiChild = _dereq_(71);
var ReactPerf = _dereq_(75);
var assign = _dereq_(27);
var escapeTextContentForBrowser = _dereq_(116);
var invariant = _dereq_(135);
var isEventSupported = _dereq_(136);
var keyOf = _dereq_(141);
var warning = _dereq_(154);
var deleteListener = ReactBrowserEventEmitter.deleteListener;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = {'string': true, 'number': true};
var STYLE = keyOf({style: null});
var ELEMENT_NODE_TYPE = 1;
/**
* Optionally injectable operations for mutating the DOM
*/
var BackendIDOperations = null;
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (props.dangerouslySetInnerHTML != null) {
("production" !== "development" ? invariant(
props.children == null,
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
) : invariant(props.children == null));
("production" !== "development" ? invariant(
props.dangerouslySetInnerHTML.__html != null,
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
'Please visit http://fb.me/react-invariant-dangerously-set-inner-html ' +
'for more information.'
) : invariant(props.dangerouslySetInnerHTML.__html != null));
}
if ("production" !== "development") {
("production" !== "development" ? warning(
props.innerHTML == null,
'Directly setting property `innerHTML` is not permitted. ' +
'For more information, lookup documentation on `dangerouslySetInnerHTML`.'
) : null);
("production" !== "development" ? warning(
!props.contentEditable || props.children == null,
'A component is `contentEditable` and contains `children` managed by ' +
'React. It is now your responsibility to guarantee that none of ' +
'those nodes are unexpectedly modified or duplicated. This is ' +
'probably not intentional.'
) : null);
}
("production" !== "development" ? invariant(
props.style == null || typeof props.style === 'object',
'The `style` prop expects a mapping from style properties to values, ' +
'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' +
'using JSX.'
) : invariant(props.style == null || typeof props.style === 'object'));
}
function putListener(id, registrationName, listener, transaction) {
if ("production" !== "development") {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
("production" !== "development" ? warning(
registrationName !== 'onScroll' || isEventSupported('scroll', true),
'This browser doesn\'t support the `onScroll` event'
) : null);
}
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ?
container.ownerDocument :
container;
listenTo(registrationName, doc);
}
transaction.getPutListenerQueue().enqueuePutListener(
id,
registrationName,
listener
);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special cased tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
// NOTE: menuitem's close tag should be omitted, but that causes problems.
};
// We accept any tag to be rendered but since this gets injected into abitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = {}.hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
("production" !== "development" ? invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag) : invariant(VALID_TAG_REGEX.test(tag)));
validatedTagCache[tag] = true;
}
}
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag) {
validateDangerousTag(tag);
this._tag = tag;
this._renderedChildren = null;
this._previousStyleCopy = null;
this._rootNodeID = null;
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
construct: function(element) {
this._currentElement = element;
},
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} The computed markup.
*/
mountComponent: function(rootID, transaction, context) {
this._rootNodeID = rootID;
assertValidProps(this._currentElement.props);
var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>';
return (
this._createOpenTagMarkupAndPutListeners(transaction) +
this._createContentMarkup(transaction, context) +
closeTag
);
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function(transaction) {
var props = this._currentElement.props;
var ret = '<' + this._tag;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
putListener(this._rootNodeID, propKey, propValue, transaction);
} else {
if (propKey === STYLE) {
if (propValue) {
propValue = this._previousStyleCopy = assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup =
DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret + '>';
}
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
return ret + ' ' + markupForID + '>';
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction, context) {
var prefix = '';
if (this._tag === 'listing' ||
this._tag === 'pre' ||
this._tag === 'textarea') {
// Add an initial newline because browsers ignore the first newline in
// a <listing>, <pre>, or <textarea> as an "authoring convenience" -- see
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody.
prefix = '\n';
}
var props = this._currentElement.props;
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return prefix + innerHTML.__html;
}
} else {
var contentToUse =
CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
return prefix + escapeTextContentForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
childrenToUse,
transaction,
context
);
return prefix + mountImages.join('');
}
}
return prefix;
},
receiveComponent: function(nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function(transaction, prevElement, nextElement, context) {
assertValidProps(this._currentElement.props);
this._updateDOMProperties(prevElement.props, transaction);
this._updateDOMChildren(prevElement.props, transaction, context);
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMProperties: function(lastProps, transaction) {
var nextProps = this._currentElement.props;
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) ||
!lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
deleteListener(this._rootNodeID, propKey);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
BackendIDOperations.deletePropertyByID(
this._rootNodeID,
propKey
);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ?
this._previousStyleCopy :
lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
nextProp = this._previousStyleCopy = assign({}, nextProp);
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) &&
(!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) &&
lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
putListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
BackendIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
if (styleUpdates) {
BackendIDOperations.updateStylesByID(
this._rootNodeID,
styleUpdates
);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMChildren: function(lastProps, transaction, context) {
var nextProps = this._currentElement.props;
var lastContent =
CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent =
CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml =
lastProps.dangerouslySetInnerHTML &&
lastProps.dangerouslySetInnerHTML.__html;
var nextHtml =
nextProps.dangerouslySetInnerHTML &&
nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
BackendIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextHtml
);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction, context);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function() {
this.unmountChildren();
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
}
};
ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent'
});
assign(
ReactDOMComponent.prototype,
ReactDOMComponent.Mixin,
ReactMultiChild.Mixin
);
ReactDOMComponent.injection = {
injectIDOperations: function(IDOperations) {
ReactDOMComponent.BackendIDOperations = BackendIDOperations = IDOperations;
}
};
module.exports = ReactDOMComponent;
},{"10":10,"11":11,"116":116,"135":135,"136":136,"141":141,"154":154,"27":27,"30":30,"35":35,"5":5,"70":70,"71":71,"75":75}],43:[function(_dereq_,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 ReactDOMForm
*/
'use strict';
var EventConstants = _dereq_(15);
var LocalEventTrapMixin = _dereq_(25);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var form = ReactElement.createFactory('form');
/**
* Since onSubmit doesn't bubble OR capture on the top level in IE8, we need
* to capture it on the <form> element itself. There are lots of hacks we could
* do to accomplish this, but the most reliable is to make <form> a
* composite component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMForm = ReactClass.createClass({
displayName: 'ReactDOMForm',
tagName: 'FORM',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
render: function() {
// TODO: Instead of using `ReactDOM` directly, we should use JSX. However,
// `jshint` fails to parse JSX so in order for linting to work in the open
// source repo, we need to just use `ReactDOM.form`.
return form(this.props);
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset');
this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit');
}
});
module.exports = ReactDOMForm;
},{"15":15,"25":25,"29":29,"33":33,"57":57}],44:[function(_dereq_,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 ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
'use strict';
var CSSPropertyOperations = _dereq_(5);
var DOMChildrenOperations = _dereq_(9);
var DOMPropertyOperations = _dereq_(11);
var ReactMount = _dereq_(70);
var ReactPerf = _dereq_(75);
var invariant = _dereq_(135);
var setInnerHTML = _dereq_(148);
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactDOMComponent.BackendIDOperations`.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
},
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
DOMPropertyOperations.deleteValueForProperty(node, name, value);
},
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: function(id, styles) {
var node = ReactMount.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
},
/**
* Updates a DOM node's innerHTML.
*
* @param {string} id ID of the node to update.
* @param {string} html An HTML string.
* @internal
*/
updateInnerHTMLByID: function(id, html) {
var node = ReactMount.getNode(id);
setInnerHTML(node, html);
},
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: function(id, content) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.updateTextContent(node, content);
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function(id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
};
ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', {
updatePropertyByID: 'updatePropertyByID',
deletePropertyByID: 'deletePropertyByID',
updateStylesByID: 'updateStylesByID',
updateInnerHTMLByID: 'updateInnerHTMLByID',
updateTextContentByID: 'updateTextContentByID',
dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID',
dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates'
});
module.exports = ReactDOMIDOperations;
},{"11":11,"135":135,"148":148,"5":5,"70":70,"75":75,"9":9}],45:[function(_dereq_,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 ReactDOMIframe
*/
'use strict';
var EventConstants = _dereq_(15);
var LocalEventTrapMixin = _dereq_(25);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var iframe = ReactElement.createFactory('iframe');
/**
* Since onLoad doesn't bubble OR capture on the top level in IE8, we need to
* capture it on the <iframe> element itself. There are lots of hacks we could
* do to accomplish this, but the most reliable is to make <iframe> a composite
* component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMIframe = ReactClass.createClass({
displayName: 'ReactDOMIframe',
tagName: 'IFRAME',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
render: function() {
return iframe(this.props);
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load');
}
});
module.exports = ReactDOMIframe;
},{"15":15,"25":25,"29":29,"33":33,"57":57}],46:[function(_dereq_,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 ReactDOMImg
*/
'use strict';
var EventConstants = _dereq_(15);
var LocalEventTrapMixin = _dereq_(25);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var img = ReactElement.createFactory('img');
/**
* Since onLoad doesn't bubble OR capture on the top level in IE8, we need to
* capture it on the <img> element itself. There are lots of hacks we could do
* to accomplish this, but the most reliable is to make <img> a composite
* component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMImg = ReactClass.createClass({
displayName: 'ReactDOMImg',
tagName: 'IMG',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
render: function() {
return img(this.props);
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load');
this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error');
}
});
module.exports = ReactDOMImg;
},{"15":15,"25":25,"29":29,"33":33,"57":57}],47:[function(_dereq_,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 ReactDOMInput
*/
'use strict';
var AutoFocusMixin = _dereq_(2);
var DOMPropertyOperations = _dereq_(11);
var LinkedValueUtils = _dereq_(24);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var ReactMount = _dereq_(70);
var ReactUpdates = _dereq_(87);
var assign = _dereq_(27);
var invariant = _dereq_(135);
var input = ReactElement.createFactory('input');
var instancesByReactID = {};
function forceUpdateIfMounted() {
/*jshint validthis:true */
if (this.isMounted()) {
this.forceUpdate();
}
}
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = ReactClass.createClass({
displayName: 'ReactDOMInput',
tagName: 'INPUT',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
return {
initialChecked: this.props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null
};
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = assign({}, this.props);
props.defaultChecked = null;
props.defaultValue = null;
var value = LinkedValueUtils.getValue(this);
props.value = value != null ? value : this.state.initialValue;
var checked = LinkedValueUtils.getChecked(this);
props.checked = checked != null ? checked : this.state.initialChecked;
props.onChange = this._handleChange;
return input(props, this.props.children);
},
componentDidMount: function() {
var id = ReactMount.getID(this.getDOMNode());
instancesByReactID[id] = this;
},
componentWillUnmount: function() {
var rootNode = this.getDOMNode();
var id = ReactMount.getID(rootNode);
delete instancesByReactID[id];
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var rootNode = this.getDOMNode();
if (this.props.checked != null) {
DOMPropertyOperations.setValueForProperty(
rootNode,
'checked',
this.props.checked || false
);
}
var value = LinkedValueUtils.getValue(this);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
returnValue = onChange.call(this, event);
}
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = this.props.name;
if (this.props.type === 'radio' && name != null) {
var rootNode = this.getDOMNode();
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll(
'input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0, groupLen = group.length; i < groupLen; i++) {
var otherNode = group[i];
if (otherNode === rootNode ||
otherNode.form !== rootNode.form) {
continue;
}
var otherID = ReactMount.getID(otherNode);
("production" !== "development" ? invariant(
otherID,
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
'same `name` is not supported.'
) : invariant(otherID));
var otherInstance = instancesByReactID[otherID];
("production" !== "development" ? invariant(
otherInstance,
'ReactDOMInput: Unknown radio button ID %s.',
otherID
) : invariant(otherInstance));
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
});
module.exports = ReactDOMInput;
},{"11":11,"135":135,"2":2,"24":24,"27":27,"29":29,"33":33,"57":57,"70":70,"87":87}],48:[function(_dereq_,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 ReactDOMOption
*/
'use strict';
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var warning = _dereq_(154);
var option = ReactElement.createFactory('option');
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = ReactClass.createClass({
displayName: 'ReactDOMOption',
tagName: 'OPTION',
mixins: [ReactBrowserComponentMixin],
componentWillMount: function() {
// TODO (yungsters): Remove support for `selected` in <option>.
if ("production" !== "development") {
("production" !== "development" ? warning(
this.props.selected == null,
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.'
) : null);
}
},
render: function() {
return option(this.props, this.props.children);
}
});
module.exports = ReactDOMOption;
},{"154":154,"29":29,"33":33,"57":57}],49:[function(_dereq_,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 ReactDOMSelect
*/
'use strict';
var AutoFocusMixin = _dereq_(2);
var LinkedValueUtils = _dereq_(24);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var ReactUpdates = _dereq_(87);
var assign = _dereq_(27);
var select = ReactElement.createFactory('select');
function updateOptionsIfPendingUpdateAndMounted() {
/*jshint validthis:true */
if (this._pendingUpdate) {
this._pendingUpdate = false;
var value = LinkedValueUtils.getValue(this);
if (value != null && this.isMounted()) {
updateOptions(this, value);
}
}
}
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function selectValueType(props, propName, componentName) {
if (props[propName] == null) {
return null;
}
if (props.multiple) {
if (!Array.isArray(props[propName])) {
return new Error(
("The `" + propName + "` prop supplied to <select> must be an array if ") +
("`multiple` is true.")
);
}
} else {
if (Array.isArray(props[propName])) {
return new Error(
("The `" + propName + "` prop supplied to <select> must be a scalar ") +
("value if `multiple` is false.")
);
}
}
}
/**
* @param {ReactComponent} component Instance of ReactDOMSelect
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(component, propValue) {
var selectedValue, i, l;
var options = component.getDOMNode().options;
if (component.props.multiple) {
selectedValue = {};
for (i = 0, l = propValue.length; i < l; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0, l = options.length; i < l; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0, l = options.length; i < l; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = ReactClass.createClass({
displayName: 'ReactDOMSelect',
tagName: 'SELECT',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
propTypes: {
defaultValue: selectValueType,
value: selectValueType
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = assign({}, this.props);
props.onChange = this._handleChange;
props.value = null;
return select(props, this.props.children);
},
componentWillMount: function() {
this._pendingUpdate = false;
},
componentDidMount: function() {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
updateOptions(this, value);
} else if (this.props.defaultValue != null) {
updateOptions(this, this.props.defaultValue);
}
},
componentDidUpdate: function(prevProps) {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
this._pendingUpdate = false;
updateOptions(this, value);
} else if (!prevProps.multiple !== !this.props.multiple) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (this.props.defaultValue != null) {
updateOptions(this, this.props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(this, this.props.multiple ? [] : '');
}
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
returnValue = onChange.call(this, event);
}
this._pendingUpdate = true;
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
});
module.exports = ReactDOMSelect;
},{"2":2,"24":24,"27":27,"29":29,"33":33,"57":57,"87":87}],50:[function(_dereq_,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 ReactDOMSelection
*/
'use strict';
var ExecutionEnvironment = _dereq_(21);
var getNodeForCharacterOffset = _dereq_(128);
var getTextContentAccessor = _dereq_(130);
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(
selection.anchorNode,
selection.anchorOffset,
selection.focusNode,
selection.focusOffset
);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(
tempRange.startContainer,
tempRange.startOffset,
tempRange.endContainer,
tempRange.endOffset
);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (typeof offsets.end === 'undefined') {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ?
start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = (
ExecutionEnvironment.canUseDOM &&
'selection' in document &&
!('getSelection' in window)
);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"128":128,"130":130,"21":21}],51:[function(_dereq_,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 ReactDOMTextComponent
* @typechecks static-only
*/
'use strict';
var DOMPropertyOperations = _dereq_(11);
var ReactComponentBrowserEnvironment =
_dereq_(35);
var ReactDOMComponent = _dereq_(42);
var assign = _dereq_(27);
var escapeTextContentForBrowser = _dereq_(116);
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function(props) {
// This constructor and its argument is currently used by mocks.
};
assign(ReactDOMTextComponent.prototype, {
/**
* @param {ReactText} text
* @internal
*/
construct: function(text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// Properties
this._rootNodeID = null;
this._mountIndex = 0;
},
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID, transaction, context) {
this._rootNodeID = rootID;
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this in a `span` for the reasons stated above, but
// since this is a situation where React won't take over (static pages),
// we can simply return the text as it is.
return escapedText;
}
return (
'<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' +
escapedText +
'</span>'
);
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
ReactDOMComponent.BackendIDOperations.updateTextContentByID(
this._rootNodeID,
nextStringText
);
}
}
},
unmountComponent: function() {
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
}
});
module.exports = ReactDOMTextComponent;
},{"11":11,"116":116,"27":27,"35":35,"42":42}],52:[function(_dereq_,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 ReactDOMTextarea
*/
'use strict';
var AutoFocusMixin = _dereq_(2);
var DOMPropertyOperations = _dereq_(11);
var LinkedValueUtils = _dereq_(24);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var ReactUpdates = _dereq_(87);
var assign = _dereq_(27);
var invariant = _dereq_(135);
var warning = _dereq_(154);
var textarea = ReactElement.createFactory('textarea');
function forceUpdateIfMounted() {
/*jshint validthis:true */
if (this.isMounted()) {
this.forceUpdate();
}
}
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = ReactClass.createClass({
displayName: 'ReactDOMTextarea',
tagName: 'TEXTAREA',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = this.props.children;
if (children != null) {
if ("production" !== "development") {
("production" !== "development" ? warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.'
) : null);
}
("production" !== "development" ? invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.'
) : invariant(defaultValue == null));
if (Array.isArray(children)) {
("production" !== "development" ? invariant(
children.length <= 1,
'<textarea> can only have at most one child.'
) : invariant(children.length <= 1));
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(this);
return {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue)
};
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = assign({}, this.props);
("production" !== "development" ? invariant(
props.dangerouslySetInnerHTML == null,
'`dangerouslySetInnerHTML` does not make sense on <textarea>.'
) : invariant(props.dangerouslySetInnerHTML == null));
props.defaultValue = null;
props.value = null;
props.onChange = this._handleChange;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
return textarea(props, this.state.initialValue);
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
var rootNode = this.getDOMNode();
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
returnValue = onChange.call(this, event);
}
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
});
module.exports = ReactDOMTextarea;
},{"11":11,"135":135,"154":154,"2":2,"24":24,"27":27,"29":29,"33":33,"57":57,"87":87}],53:[function(_dereq_,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 ReactDefaultBatchingStrategy
*/
'use strict';
var ReactUpdates = _dereq_(87);
var Transaction = _dereq_(103);
var assign = _dereq_(27);
var emptyFunction = _dereq_(114);
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function() {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
assign(
ReactDefaultBatchingStrategyTransaction.prototype,
Transaction.Mixin,
{
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
}
}
);
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function(callback, a, b, c, d) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d);
} else {
transaction.perform(callback, null, a, b, c, d);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"103":103,"114":114,"27":27,"87":87}],54:[function(_dereq_,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 ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = _dereq_(3);
var ChangeEventPlugin = _dereq_(7);
var ClientReactRootIndex = _dereq_(8);
var DefaultEventPluginOrder = _dereq_(13);
var EnterLeaveEventPlugin = _dereq_(14);
var ExecutionEnvironment = _dereq_(21);
var HTMLDOMPropertyConfig = _dereq_(23);
var MobileSafariClickEventPlugin = _dereq_(26);
var ReactBrowserComponentMixin = _dereq_(29);
var ReactClass = _dereq_(33);
var ReactComponentBrowserEnvironment =
_dereq_(35);
var ReactDefaultBatchingStrategy = _dereq_(53);
var ReactDOMComponent = _dereq_(42);
var ReactDOMButton = _dereq_(41);
var ReactDOMForm = _dereq_(43);
var ReactDOMImg = _dereq_(46);
var ReactDOMIDOperations = _dereq_(44);
var ReactDOMIframe = _dereq_(45);
var ReactDOMInput = _dereq_(47);
var ReactDOMOption = _dereq_(48);
var ReactDOMSelect = _dereq_(49);
var ReactDOMTextarea = _dereq_(52);
var ReactDOMTextComponent = _dereq_(51);
var ReactElement = _dereq_(57);
var ReactEventListener = _dereq_(62);
var ReactInjection = _dereq_(64);
var ReactInstanceHandles = _dereq_(66);
var ReactMount = _dereq_(70);
var ReactReconcileTransaction = _dereq_(80);
var SelectEventPlugin = _dereq_(89);
var ServerReactRootIndex = _dereq_(90);
var SimpleEventPlugin = _dereq_(91);
var SVGDOMPropertyConfig = _dereq_(88);
var createFullPageComponent = _dereq_(111);
function autoGenerateWrapperClass(type) {
return ReactClass.createClass({
tagName: type.toUpperCase(),
render: function() {
return new ReactElement(
type,
null,
null,
null,
null,
this.props
);
}
});
}
function inject() {
ReactInjection.EventEmitter.injectReactEventListener(
ReactEventListener
);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
MobileSafariClickEventPlugin: MobileSafariClickEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.NativeComponent.injectGenericComponentClass(
ReactDOMComponent
);
ReactInjection.NativeComponent.injectTextComponentClass(
ReactDOMTextComponent
);
ReactInjection.NativeComponent.injectAutoWrapper(
autoGenerateWrapperClass
);
// This needs to happen before createFullPageComponent() otherwise the mixin
// won't be included.
ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
ReactInjection.NativeComponent.injectComponentClasses({
'button': ReactDOMButton,
'form': ReactDOMForm,
'iframe': ReactDOMIframe,
'img': ReactDOMImg,
'input': ReactDOMInput,
'option': ReactDOMOption,
'select': ReactDOMSelect,
'textarea': ReactDOMTextarea,
'html': createFullPageComponent('html'),
'head': createFullPageComponent('head'),
'body': createFullPageComponent('body')
});
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
ReactInjection.Updates.injectReconcileTransaction(
ReactReconcileTransaction
);
ReactInjection.Updates.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
ReactInjection.RootIndex.injectCreateReactRootIndex(
ExecutionEnvironment.canUseDOM ?
ClientReactRootIndex.createReactRootIndex :
ServerReactRootIndex.createReactRootIndex
);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
ReactInjection.DOMComponent.injectIDOperations(ReactDOMIDOperations);
if ("production" !== "development") {
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
if ((/[?&]react_perf\b/).test(url)) {
var ReactDefaultPerf = _dereq_(55);
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"111":111,"13":13,"14":14,"21":21,"23":23,"26":26,"29":29,"3":3,"33":33,"35":35,"41":41,"42":42,"43":43,"44":44,"45":45,"46":46,"47":47,"48":48,"49":49,"51":51,"52":52,"53":53,"55":55,"57":57,"62":62,"64":64,"66":66,"7":7,"70":70,"8":8,"80":80,"88":88,"89":89,"90":90,"91":91}],55:[function(_dereq_,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 ReactDefaultPerf
* @typechecks static-only
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactDefaultPerfAnalysis = _dereq_(56);
var ReactMount = _dereq_(70);
var ReactPerf = _dereq_(75);
var performanceNow = _dereq_(146);
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_injected: false,
start: function() {
if (!ReactDefaultPerf._injected) {
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
}
ReactDefaultPerf._allMeasurements.length = 0;
ReactPerf.enableMeasure = true;
},
stop: function() {
ReactPerf.enableMeasure = false;
},
getLastMeasurements: function() {
return ReactDefaultPerf._allMeasurements;
},
printExclusive: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
console.table(summary.map(function(item) {
return {
'Component class name': item.componentName,
'Total inclusive time (ms)': roundFloat(item.inclusive),
'Exclusive mount time (ms)': roundFloat(item.exclusive),
'Exclusive render time (ms)': roundFloat(item.render),
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
'Render time per instance (ms)': roundFloat(item.render / item.count),
'Instances': item.count
};
}));
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
// number.
},
printInclusive: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
console.table(summary.map(function(item) {
return {
'Owner > component': item.componentName,
'Inclusive time (ms)': roundFloat(item.time),
'Instances': item.count
};
}));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
getMeasurementsSummaryMap: function(measurements) {
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(
measurements,
true
);
return summary.map(function(item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
});
},
printWasted: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
printDOM: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
console.table(summary.map(function(item) {
var result = {};
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
result['type'] = item.type;
result['args'] = JSON.stringify(item.args);
return result;
}));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
_recordWrite: function(id, fnName, totalTime, args) {
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
var writes =
ReactDefaultPerf
._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]
.writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function(moduleName, fnName, func) {
return function() {for (var args=[],$__0=0,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
var totalTime;
var rv;
var start;
if (fnName === '_renderNewRootComponent' ||
fnName === 'flushBatchedUpdates') {
// A "measurement" is a set of metrics recorded for each flush. We want
// to group the metrics for a given flush together so we can look at the
// components that rendered and the DOM operations that actually
// happened to determine the amount of "wasted work" performed.
ReactDefaultPerf._allMeasurements.push({
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
].totalTime = performanceNow() - start;
return rv;
} else if (fnName === '_mountImageIntoNode' ||
moduleName === 'ReactDOMIDOperations') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === '_mountImageIntoNode') {
var mountID = ReactMount.getID(args[1]);
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[0].forEach(function(update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.textContent !== null) {
writeArgs.textContent = update.textContent;
}
if (update.markupIndex !== null) {
writeArgs.markup = args[1][update.markupIndex];
}
ReactDefaultPerf._recordWrite(
update.parentID,
update.type,
totalTime,
writeArgs
);
});
} else {
// basic format
ReactDefaultPerf._recordWrite(
args[0],
fnName,
totalTime,
Array.prototype.slice.call(args, 1)
);
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (
(// TODO: receiveComponent()?
(fnName === 'mountComponent' ||
fnName === 'updateComponent' || fnName === '_renderValidatedComponent')))) {
if (typeof this._currentElement.type === 'string') {
return func.apply(this, args);
}
var rootNodeID = fnName === 'mountComponent' ?
args[0] :
this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
var entry = ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
];
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
mountStack.push(0);
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (isRender) {
addValue(entry.render, rootNodeID, totalTime);
} else if (isMount) {
var subMountTime = mountStack.pop();
mountStack[mountStack.length - 1] += totalTime;
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
addValue(entry.inclusive, rootNodeID, totalTime);
} else {
addValue(entry.inclusive, rootNodeID, totalTime);
}
entry.displayNames[rootNodeID] = {
current: this.getName(),
owner: this._currentElement._owner ?
this._currentElement._owner.getName() :
'<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"10":10,"146":146,"56":56,"70":70,"75":75}],56:[function(_dereq_,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 ReactDefaultPerfAnalysis
*/
var assign = _dereq_(27);
// Don't try to save users less than 1.2ms (a number I made up)
var DONT_CARE_THRESHOLD = 1.2;
var DOM_OPERATION_TYPES = {
'_mountImageIntoNode': 'set innerHTML',
INSERT_MARKUP: 'set innerHTML',
MOVE_EXISTING: 'move',
REMOVE_NODE: 'remove',
TEXT_CONTENT: 'set textContent',
'updatePropertyByID': 'update attribute',
'deletePropertyByID': 'delete attribute',
'updateStylesByID': 'update styles',
'updateInnerHTMLByID': 'set innerHTML',
'dangerouslyReplaceNodeWithMarkupByID': 'replace'
};
function getTotalTime(measurements) {
// TODO: return number of DOM ops? could be misleading.
// TODO: measure dropped frames after reconcile?
// TODO: log total time of each reconcile and the top-level component
// class that triggered it.
var totalTime = 0;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
totalTime += measurement.totalTime;
}
return totalTime;
}
function getDOMSummary(measurements) {
var items = [];
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var id;
for (id in measurement.writes) {
measurement.writes[id].forEach(function(write) {
items.push({
id: id,
type: DOM_OPERATION_TYPES[write.type] || write.type,
args: write.args
});
});
}
}
return items;
}
function getExclusiveSummary(measurements) {
var candidates = {};
var displayName;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign(
{},
measurement.exclusive,
measurement.inclusive
);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
render: 0,
count: 0
};
if (measurement.render[id]) {
candidates[displayName].render += measurement.render[id];
}
if (measurement.exclusive[id]) {
candidates[displayName].exclusive += measurement.exclusive[id];
}
if (measurement.inclusive[id]) {
candidates[displayName].inclusive += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[displayName].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (displayName in candidates) {
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
arr.push(candidates[displayName]);
}
}
arr.sort(function(a, b) {
return b.exclusive - a.exclusive;
});
return arr;
}
function getInclusiveSummary(measurements, onlyClean) {
var candidates = {};
var inclusiveKey;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign(
{},
measurement.exclusive,
measurement.inclusive
);
var cleanComponents;
if (onlyClean) {
cleanComponents = getUnchangedComponents(measurement);
}
for (var id in allIDs) {
if (onlyClean && !cleanComponents[id]) {
continue;
}
var displayName = measurement.displayNames[id];
// Inclusive time is not useful for many components without knowing where
// they are instantiated. So we aggregate inclusive time with both the
// owner and current displayName as the key.
inclusiveKey = displayName.owner + ' > ' + displayName.current;
candidates[inclusiveKey] = candidates[inclusiveKey] || {
componentName: inclusiveKey,
time: 0,
count: 0
};
if (measurement.inclusive[id]) {
candidates[inclusiveKey].time += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[inclusiveKey].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (inclusiveKey in candidates) {
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
arr.push(candidates[inclusiveKey]);
}
}
arr.sort(function(a, b) {
return b.time - a.time;
});
return arr;
}
function getUnchangedComponents(measurement) {
// For a given reconcile, look at which components did not actually
// render anything to the DOM and return a mapping of their ID to
// the amount of time it took to render the entire subtree.
var cleanComponents = {};
var dirtyLeafIDs = Object.keys(measurement.writes);
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggered
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
},{"27":27}],57:[function(_dereq_,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 ReactElement
*/
'use strict';
var ReactContext = _dereq_(38);
var ReactCurrentOwner = _dereq_(39);
var assign = _dereq_(27);
var warning = _dereq_(154);
var RESERVED_PROPS = {
key: true,
ref: true
};
/**
* Warn for mutations.
*
* @internal
* @param {object} object
* @param {string} key
*/
function defineWarningProperty(object, key) {
Object.defineProperty(object, key, {
configurable: false,
enumerable: true,
get: function() {
if (!this._store) {
return null;
}
return this._store[key];
},
set: function(value) {
("production" !== "development" ? warning(
false,
'Don\'t set the %s property of the React element. Instead, ' +
'specify the correct value when initially creating the element.',
key
) : null);
this._store[key] = value;
}
});
}
/**
* This is updated to true if the membrane is successfully created.
*/
var useMutationMembrane = false;
/**
* Warn for mutations.
*
* @internal
* @param {object} element
*/
function defineMutationMembrane(prototype) {
try {
var pseudoFrozenProperties = {
props: true
};
for (var key in pseudoFrozenProperties) {
defineWarningProperty(prototype, key);
}
useMutationMembrane = true;
} catch (x) {
// IE will fail on defineProperty
}
}
/**
* Base constructor for all React elements. This is only used to make this
* work with a dynamic instanceof check. Nothing should live on this prototype.
*
* @param {*} type
* @param {string|object} ref
* @param {*} key
* @param {*} props
* @internal
*/
var ReactElement = function(type, key, ref, owner, context, props) {
// Built-in properties that belong on the element
this.type = type;
this.key = key;
this.ref = ref;
// Record the component responsible for creating this element.
this._owner = owner;
// TODO: Deprecate withContext, and then the context becomes accessible
// through the owner.
this._context = context;
if ("production" !== "development") {
// The validation flag and props are currently mutative. We put them on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
this._store = {props: props, originalProps: assign({}, props)};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
try {
Object.defineProperty(this._store, 'validated', {
configurable: false,
enumerable: false,
writable: true
});
} catch (x) {
}
this._store.validated = false;
// We're not allowed to set props directly on the object so we early
// return and rely on the prototype membrane to forward to the backing
// store.
if (useMutationMembrane) {
Object.freeze(this);
return;
}
}
this.props = props;
};
// We intentionally don't expose the function on the constructor property.
// ReactElement should be indistinguishable from a plain object.
ReactElement.prototype = {
_isReactElement: true
};
if ("production" !== "development") {
defineMutationMembrane(ReactElement.prototype);
}
ReactElement.createElement = function(type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
// Remaining properties are added to a new props object
for (propName in config) {
if (config.hasOwnProperty(propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
}
return new ReactElement(
type,
key,
ref,
ReactCurrentOwner.current,
ReactContext.current,
props
);
};
ReactElement.createFactory = function(type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. <Foo />.type === Foo.type.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceProps = function(oldElement, newProps) {
var newElement = new ReactElement(
oldElement.type,
oldElement.key,
oldElement.ref,
oldElement._owner,
oldElement._context,
newProps
);
if ("production" !== "development") {
// If the key on the original is valid, then the clone is valid
newElement._store.validated = oldElement._store.validated;
}
return newElement;
};
ReactElement.cloneElement = function(element, config, children) {
var propName;
// Original props are copied
var props = assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (config.ref !== undefined) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (config.key !== undefined) {
key = '' + config.key;
}
// Remaining properties override existing props
for (propName in config) {
if (config.hasOwnProperty(propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return new ReactElement(
element.type,
key,
ref,
owner,
element._context,
props
);
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function(object) {
// ReactTestUtils is often used outside of beforeEach where as React is
// within it. This leads to two different instances of React on the same
// page. To identify a element from a different React instance we use
// a flag instead of an instanceof check.
var isElement = !!(object && object._isReactElement);
// if (isElement && !(object instanceof ReactElement)) {
// This is an indicator that you're using multiple versions of React at the
// same time. This will screw with ownership and stuff. Fix it, please.
// TODO: We could possibly warn here.
// }
return isElement;
};
module.exports = ReactElement;
},{"154":154,"27":27,"38":38,"39":39}],58:[function(_dereq_,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 ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactElement = _dereq_(57);
var ReactFragment = _dereq_(63);
var ReactPropTypeLocations = _dereq_(77);
var ReactPropTypeLocationNames = _dereq_(76);
var ReactCurrentOwner = _dereq_(39);
var ReactNativeComponent = _dereq_(73);
var getIteratorFn = _dereq_(126);
var invariant = _dereq_(135);
var warning = _dereq_(154);
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
var loggedTypeFailures = {};
var NUMERIC_PROPERTY_REGEX = /^\d+$/;
/**
* Gets the instance's name for use in warnings.
*
* @internal
* @return {?string} Display name or undefined
*/
function getName(instance) {
var publicInstance = instance && instance.getPublicInstance();
if (!publicInstance) {
return undefined;
}
var constructor = publicInstance.constructor;
if (!constructor) {
return undefined;
}
return constructor.displayName || constructor.name || undefined;
}
/**
* Gets the current owner's displayName for use in warnings.
*
* @internal
* @return {?string} Display name or undefined
*/
function getCurrentOwnerDisplayName() {
var current = ReactCurrentOwner.current;
return (
current && getName(current) || undefined
);
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
warnAndMonitorForKeyUse(
'Each child in an array or iterator should have a unique "key" prop.',
element,
parentType
);
}
/**
* Warn if the key is being defined as an object property but has an incorrect
* value.
*
* @internal
* @param {string} name Property name of the key.
* @param {ReactElement} element Component that requires a key.
* @param {*} parentType element's parent's type.
*/
function validatePropertyKey(name, element, parentType) {
if (!NUMERIC_PROPERTY_REGEX.test(name)) {
return;
}
warnAndMonitorForKeyUse(
'Child objects should have non-numeric keys so ordering is preserved.',
element,
parentType
);
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} message The base warning that gets output.
* @param {ReactElement} element Component that requires a key.
* @param {*} parentType element's parent's type.
*/
function warnAndMonitorForKeyUse(message, element, parentType) {
var ownerName = getCurrentOwnerDisplayName();
var parentName = typeof parentType === 'string' ?
parentType : parentType.displayName || parentType.name;
var useName = ownerName || parentName;
var memoizer = ownerHasKeyUseWarning[message] || (
(ownerHasKeyUseWarning[message] = {})
);
if (memoizer.hasOwnProperty(useName)) {
return;
}
memoizer[useName] = true;
var parentOrOwnerAddendum =
ownerName ? (" Check the render method of " + ownerName + ".") :
parentName ? (" Check the React.render call using <" + parentName + ">.") :
'';
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwnerAddendum = '';
if (element &&
element._owner &&
element._owner !== ReactCurrentOwner.current) {
// Name of the component that originally created this child.
var childOwnerName = getName(element._owner);
childOwnerAddendum = (" It was passed a child from " + childOwnerName + ".");
}
("production" !== "development" ? warning(
false,
message + '%s%s See http://fb.me/react-warning-keys for more information.',
parentOrOwnerAddendum,
childOwnerAddendum
) : null);
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
node._store.validated = true;
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
} else if (typeof node === 'object') {
var fragment = ReactFragment.extractIfFragment(node);
for (var key in fragment) {
if (fragment.hasOwnProperty(key)) {
validatePropertyKey(key, fragment[key], parentType);
}
}
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
("production" !== "development" ? invariant(
typeof propTypes[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
componentName || 'React class',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof propTypes[propName] === 'function'));
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum(this);
("production" !== "development" ? warning(false, 'Failed propType: %s%s', error.message, addendum) : null);
}
}
}
}
var warnedPropsMutations = {};
/**
* Warn about mutating props when setting `propName` on `element`.
*
* @param {string} propName The string key within props that was set
* @param {ReactElement} element
*/
function warnForPropsMutation(propName, element) {
var type = element.type;
var elementName = typeof type === 'string' ? type : type.displayName;
var ownerName = element._owner ?
element._owner.getPublicInstance().constructor.displayName : null;
var warningKey = propName + '|' + elementName + '|' + ownerName;
if (warnedPropsMutations.hasOwnProperty(warningKey)) {
return;
}
warnedPropsMutations[warningKey] = true;
var elementInfo = '';
if (elementName) {
elementInfo = ' <' + elementName + ' />';
}
var ownerInfo = '';
if (ownerName) {
ownerInfo = ' The element was created by ' + ownerName + '.';
}
("production" !== "development" ? warning(
false,
'Don\'t set .props.%s of the React component%s. ' +
'Instead, specify the correct value when ' +
'initially creating the element.%s',
propName,
elementInfo,
ownerInfo
) : null);
}
// Inline Object.is polyfill
function is(a, b) {
if (a !== a) {
// NaN
return b !== b;
}
if (a === 0 && b === 0) {
// +-0
return 1 / a === 1 / b;
}
return a === b;
}
/**
* Given an element, check if its props have been mutated since element
* creation (or the last call to this function). In particular, check if any
* new props have been added, which we can't directly catch by defining warning
* properties on the props object.
*
* @param {ReactElement} element
*/
function checkAndWarnForMutatedProps(element) {
if (!element._store) {
// Element was created using `new ReactElement` directly or with
// `ReactElement.createElement`; skip mutation checking
return;
}
var originalProps = element._store.originalProps;
var props = element.props;
for (var propName in props) {
if (props.hasOwnProperty(propName)) {
if (!originalProps.hasOwnProperty(propName) ||
!is(originalProps[propName], props[propName])) {
warnForPropsMutation(propName, element);
// Copy over the new value so that the two props objects match again
originalProps[propName] = props[propName];
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
if (element.type == null) {
// This has already warned. Don't throw.
return;
}
// Extract the component class from the element. Converts string types
// to a composite class which may have propTypes.
// TODO: Validating a string's propTypes is not decoupled from the
// rendering target which is problematic.
var componentClass = ReactNativeComponent.getComponentClassForElement(
element
);
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkPropTypes(
name,
componentClass.propTypes,
element.props,
ReactPropTypeLocations.prop
);
}
if (typeof componentClass.getDefaultProps === 'function') {
("production" !== "development" ? warning(
componentClass.getDefaultProps.isReactClassApproved,
'getDefaultProps is only used on classic React.createClass ' +
'definitions. Use a static property named `defaultProps` instead.'
) : null);
}
}
var ReactElementValidator = {
checkAndWarnForMutatedProps: checkAndWarnForMutatedProps,
createElement: function(type, props, children) {
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
("production" !== "development" ? warning(
type != null,
'React.createElement: type should not be null or undefined. It should ' +
'be a string (for DOM elements) or a ReactClass (for composite ' +
'components).'
) : null);
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
validatePropTypes(element);
return element;
},
createFactory: function(type) {
var validatedFactory = ReactElementValidator.createElement.bind(
null,
type
);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if ("production" !== "development") {
try {
Object.defineProperty(
validatedFactory,
'type',
{
enumerable: false,
get: function() {
("production" !== "development" ? warning(
false,
'Factory.type is deprecated. Access the class directly ' +
'before passing it to createFactory.'
) : null);
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
}
);
} catch (x) {
// IE will fail on defineProperty (es5-shim/sham too)
}
}
return validatedFactory;
},
cloneElement: function(element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
},{"126":126,"135":135,"154":154,"39":39,"57":57,"63":63,"73":73,"76":76,"77":77}],59:[function(_dereq_,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 ReactEmptyComponent
*/
'use strict';
var ReactElement = _dereq_(57);
var ReactInstanceMap = _dereq_(67);
var invariant = _dereq_(135);
var component;
// This registry keeps track of the React IDs of the components that rendered to
// `null` (in reality a placeholder such as `noscript`)
var nullComponentIDsRegistry = {};
var ReactEmptyComponentInjection = {
injectEmptyComponent: function(emptyComponent) {
component = ReactElement.createFactory(emptyComponent);
}
};
var ReactEmptyComponentType = function() {};
ReactEmptyComponentType.prototype.componentDidMount = function() {
var internalInstance = ReactInstanceMap.get(this);
// TODO: Make sure we run these methods in the correct order, we shouldn't
// need this check. We're going to assume if we're here it means we ran
// componentWillUnmount already so there is no internal instance (it gets
// removed as part of the unmounting process).
if (!internalInstance) {
return;
}
registerNullComponentID(internalInstance._rootNodeID);
};
ReactEmptyComponentType.prototype.componentWillUnmount = function() {
var internalInstance = ReactInstanceMap.get(this);
// TODO: Get rid of this check. See TODO in componentDidMount.
if (!internalInstance) {
return;
}
deregisterNullComponentID(internalInstance._rootNodeID);
};
ReactEmptyComponentType.prototype.render = function() {
("production" !== "development" ? invariant(
component,
'Trying to return null from a render, but no null placeholder component ' +
'was injected.'
) : invariant(component));
return component();
};
var emptyElement = ReactElement.createElement(ReactEmptyComponentType);
/**
* Mark the component as having rendered to null.
* @param {string} id Component's `_rootNodeID`.
*/
function registerNullComponentID(id) {
nullComponentIDsRegistry[id] = true;
}
/**
* Unmark the component as having rendered to null: it renders to something now.
* @param {string} id Component's `_rootNodeID`.
*/
function deregisterNullComponentID(id) {
delete nullComponentIDsRegistry[id];
}
/**
* @param {string} id Component's `_rootNodeID`.
* @return {boolean} True if the component is rendered to null.
*/
function isNullComponentID(id) {
return !!nullComponentIDsRegistry[id];
}
var ReactEmptyComponent = {
emptyElement: emptyElement,
injection: ReactEmptyComponentInjection,
isNullComponentID: isNullComponentID
};
module.exports = ReactEmptyComponent;
},{"135":135,"57":57,"67":67}],60:[function(_dereq_,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 ReactErrorUtils
* @typechecks
*/
"use strict";
var ReactErrorUtils = {
/**
* Creates a guarded version of a function. This is supposed to make debugging
* of event handlers easier. To aid debugging with the browser's debugger,
* this currently simply returns the original function.
*
* @param {function} func Function to be executed
* @param {string} name The name of the guard
* @return {function}
*/
guard: function(func, name) {
return func;
}
};
module.exports = ReactErrorUtils;
},{}],61:[function(_dereq_,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 ReactEventEmitterMixin
*/
'use strict';
var EventPluginHub = _dereq_(17);
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue();
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native environment event.
*/
handleTopLevel: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events = EventPluginHub.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
},{"17":17}],62:[function(_dereq_,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 ReactEventListener
* @typechecks static-only
*/
'use strict';
var EventListener = _dereq_(16);
var ExecutionEnvironment = _dereq_(21);
var PooledClass = _dereq_(28);
var ReactInstanceHandles = _dereq_(66);
var ReactMount = _dereq_(70);
var ReactUpdates = _dereq_(87);
var assign = _dereq_(27);
var getEventTarget = _dereq_(125);
var getUnboundedScrollPosition = _dereq_(131);
/**
* Finds the parent React component of `node`.
*
* @param {*} node
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
* is not nested.
*/
function findParent(node) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function() {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(
TopLevelCallbackBookKeeping,
PooledClass.twoArgumentPooler
);
function handleTopLevelImpl(bookKeeping) {
var topLevelTarget = ReactMount.getFirstReactDOM(
getEventTarget(bookKeeping.nativeEvent)
) || window;
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = topLevelTarget;
while (ancestor) {
bookKeeping.ancestors.push(ancestor);
ancestor = findParent(ancestor);
}
for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventListener._handleTopLevel(
bookKeeping.topLevelType,
topLevelTarget,
topLevelTargetID,
bookKeeping.nativeEvent
);
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function(handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function(enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function() {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function(topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.listen(
element,
handlerBaseName,
ReactEventListener.dispatchEvent.bind(null, topLevelType)
);
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function(topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.capture(
element,
handlerBaseName,
ReactEventListener.dispatchEvent.bind(null, topLevelType)
);
},
monitorScrollValue: function(refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function(topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(
topLevelType,
nativeEvent
);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
},{"125":125,"131":131,"16":16,"21":21,"27":27,"28":28,"66":66,"70":70,"87":87}],63:[function(_dereq_,module,exports){
/**
* Copyright 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 ReactFragment
*/
'use strict';
var ReactElement = _dereq_(57);
var warning = _dereq_(154);
/**
* We used to allow keyed objects to serve as a collection of ReactElements,
* or nested sets. This allowed us a way to explicitly key a set a fragment of
* components. This is now being replaced with an opaque data structure.
* The upgrade path is to call React.addons.createFragment({ key: value }) to
* create a keyed fragment. The resulting data structure is opaque, for now.
*/
if ("production" !== "development") {
var fragmentKey = '_reactFragment';
var didWarnKey = '_reactDidWarn';
var canWarnForReactFragment = false;
try {
// Feature test. Don't even try to issue this warning if we can't use
// enumerable: false.
var dummy = function() {
return 1;
};
Object.defineProperty(
{},
fragmentKey,
{enumerable: false, value: true}
);
Object.defineProperty(
{},
'key',
{enumerable: true, get: dummy}
);
canWarnForReactFragment = true;
} catch (x) { }
var proxyPropertyAccessWithWarning = function(obj, key) {
Object.defineProperty(obj, key, {
enumerable: true,
get: function() {
("production" !== "development" ? warning(
this[didWarnKey],
'A ReactFragment is an opaque type. Accessing any of its ' +
'properties is deprecated. Pass it to one of the React.Children ' +
'helpers.'
) : null);
this[didWarnKey] = true;
return this[fragmentKey][key];
},
set: function(value) {
("production" !== "development" ? warning(
this[didWarnKey],
'A ReactFragment is an immutable opaque type. Mutating its ' +
'properties is deprecated.'
) : null);
this[didWarnKey] = true;
this[fragmentKey][key] = value;
}
});
};
var issuedWarnings = {};
var didWarnForFragment = function(fragment) {
// We use the keys and the type of the value as a heuristic to dedupe the
// warning to avoid spamming too much.
var fragmentCacheKey = '';
for (var key in fragment) {
fragmentCacheKey += key + ':' + (typeof fragment[key]) + ',';
}
var alreadyWarnedOnce = !!issuedWarnings[fragmentCacheKey];
issuedWarnings[fragmentCacheKey] = true;
return alreadyWarnedOnce;
};
}
var ReactFragment = {
// Wrap a keyed object in an opaque proxy that warns you if you access any
// of its properties.
create: function(object) {
if ("production" !== "development") {
if (typeof object !== 'object' || !object || Array.isArray(object)) {
("production" !== "development" ? warning(
false,
'React.addons.createFragment only accepts a single object.',
object
) : null);
return object;
}
if (ReactElement.isValidElement(object)) {
("production" !== "development" ? warning(
false,
'React.addons.createFragment does not accept a ReactElement ' +
'without a wrapper object.'
) : null);
return object;
}
if (canWarnForReactFragment) {
var proxy = {};
Object.defineProperty(proxy, fragmentKey, {
enumerable: false,
value: object
});
Object.defineProperty(proxy, didWarnKey, {
writable: true,
enumerable: false,
value: false
});
for (var key in object) {
proxyPropertyAccessWithWarning(proxy, key);
}
Object.preventExtensions(proxy);
return proxy;
}
}
return object;
},
// Extract the original keyed object from the fragment opaque type. Warn if
// a plain object is passed here.
extract: function(fragment) {
if ("production" !== "development") {
if (canWarnForReactFragment) {
if (!fragment[fragmentKey]) {
("production" !== "development" ? warning(
didWarnForFragment(fragment),
'Any use of a keyed object should be wrapped in ' +
'React.addons.createFragment(object) before being passed as a ' +
'child.'
) : null);
return fragment;
}
return fragment[fragmentKey];
}
}
return fragment;
},
// Check if this is a fragment and if so, extract the keyed object. If it
// is a fragment-like object, warn that it should be wrapped. Ignore if we
// can't determine what kind of object this is.
extractIfFragment: function(fragment) {
if ("production" !== "development") {
if (canWarnForReactFragment) {
// If it is the opaque type, return the keyed object.
if (fragment[fragmentKey]) {
return fragment[fragmentKey];
}
// Otherwise, check each property if it has an element, if it does
// it is probably meant as a fragment, so we can warn early. Defer,
// the warning to extract.
for (var key in fragment) {
if (fragment.hasOwnProperty(key) &&
ReactElement.isValidElement(fragment[key])) {
// This looks like a fragment object, we should provide an
// early warning.
return ReactFragment.extract(fragment);
}
}
}
}
return fragment;
}
};
module.exports = ReactFragment;
},{"154":154,"57":57}],64:[function(_dereq_,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 ReactInjection
*/
'use strict';
var DOMProperty = _dereq_(10);
var EventPluginHub = _dereq_(17);
var ReactComponentEnvironment = _dereq_(36);
var ReactClass = _dereq_(33);
var ReactEmptyComponent = _dereq_(59);
var ReactBrowserEventEmitter = _dereq_(30);
var ReactNativeComponent = _dereq_(73);
var ReactDOMComponent = _dereq_(42);
var ReactPerf = _dereq_(75);
var ReactRootIndex = _dereq_(83);
var ReactUpdates = _dereq_(87);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMComponent: ReactDOMComponent.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"10":10,"17":17,"30":30,"33":33,"36":36,"42":42,"59":59,"73":73,"75":75,"83":83,"87":87}],65:[function(_dereq_,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 ReactInputSelection
*/
'use strict';
var ReactDOMSelection = _dereq_(50);
var containsNode = _dereq_(109);
var focusNode = _dereq_(119);
var getActiveElement = _dereq_(121);
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function(elem) {
return elem && (
((elem.nodeName === 'INPUT' && elem.type === 'text') ||
elem.nodeName === 'TEXTAREA' || elem.contentEditable === 'true')
);
},
getSelectionInformation: function() {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange:
ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
ReactInputSelection.getSelection(focusedElem) :
null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function(priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem &&
isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(
priorFocusedElem,
priorSelectionRange
);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function(input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName === 'INPUT') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || {start: 0, end: 0};
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName === 'INPUT') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
},{"109":109,"119":119,"121":121,"50":50}],66:[function(_dereq_,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 ReactInstanceHandles
* @typechecks static-only
*/
'use strict';
var ReactRootIndex = _dereq_(83);
var invariant = _dereq_(135);
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 100;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || (
id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR
);
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return (
descendantID.indexOf(ancestorID) === 0 &&
isBoundary(descendantID, ancestorID.length)
);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
("production" !== "development" ? invariant(
isValidID(ancestorID) && isValidID(destinationID),
'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
) : invariant(isValidID(ancestorID) && isValidID(destinationID)));
("production" !== "development" ? invariant(
isAncestorIDOf(ancestorID, destinationID),
'getNextDescendantID(...): React has made an invalid assumption about ' +
'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
) : invariant(isAncestorIDOf(ancestorID, destinationID)));
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
var i;
for (i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
("production" !== "development" ? invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
) : invariant(isValidID(longestCommonID)));
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them. If the
* callback returns `false`, traversal is stopped.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
("production" !== "development" ? invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
) : invariant(start !== stop));
var traverseUp = isAncestorIDOf(stop, start);
("production" !== "development" ? invariant(
traverseUp || isAncestorIDOf(start, stop),
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
) : invariant(traverseUp || isAncestorIDOf(start, stop)));
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start; /* until break */; id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
("production" !== "development" ? invariant(
depth++ < MAX_TREE_DEPTH,
'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
start, stop
) : invariant(depth++ < MAX_TREE_DEPTH));
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function() {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function(rootID, name) {
return rootID + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function(id) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function(targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseAncestors: function(targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
/**
* Exposed for unit testing.
* @private
*/
_getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
},{"135":135,"83":83}],67:[function(_dereq_,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 ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function(key) {
key._reactInternalInstance = undefined;
},
get: function(key) {
return key._reactInternalInstance;
},
has: function(key) {
return key._reactInternalInstance !== undefined;
},
set: function(key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
},{}],68:[function(_dereq_,module,exports){
/**
* Copyright 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 ReactLifeCycle
*/
'use strict';
/**
* This module manages the bookkeeping when a component is in the process
* of being mounted or being unmounted. This is used as a way to enforce
* invariants (or warnings) when it is not recommended to call
* setState/forceUpdate.
*
* currentlyMountingInstance: During the construction phase, it is not possible
* to trigger an update since the instance is not fully mounted yet. However, we
* currently allow this as a convenience for mutating the initial state.
*
* currentlyUnmountingInstance: During the unmounting phase, the instance is
* still mounted and can therefore schedule an update. However, this is not
* recommended and probably an error since it's about to be unmounted.
* Therefore we still want to trigger in an error for that case.
*/
var ReactLifeCycle = {
currentlyMountingInstance: null,
currentlyUnmountingInstance: null
};
module.exports = ReactLifeCycle;
},{}],69:[function(_dereq_,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 ReactMarkupChecksum
*/
'use strict';
var adler32 = _dereq_(106);
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function(markup) {
var checksum = adler32(markup);
return markup.replace(
'>',
' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '">'
);
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function(markup, element) {
var existingChecksum = element.getAttribute(
ReactMarkupChecksum.CHECKSUM_ATTR_NAME
);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
},{"106":106}],70:[function(_dereq_,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 ReactMount
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactBrowserEventEmitter = _dereq_(30);
var ReactCurrentOwner = _dereq_(39);
var ReactElement = _dereq_(57);
var ReactElementValidator = _dereq_(58);
var ReactEmptyComponent = _dereq_(59);
var ReactInstanceHandles = _dereq_(66);
var ReactInstanceMap = _dereq_(67);
var ReactMarkupChecksum = _dereq_(69);
var ReactPerf = _dereq_(75);
var ReactReconciler = _dereq_(81);
var ReactUpdateQueue = _dereq_(86);
var ReactUpdates = _dereq_(87);
var emptyObject = _dereq_(115);
var containsNode = _dereq_(109);
var getReactRootElementInContainer = _dereq_(129);
var instantiateReactComponent = _dereq_(134);
var invariant = _dereq_(135);
var setInnerHTML = _dereq_(148);
var shouldUpdateReactComponent = _dereq_(151);
var warning = _dereq_(154);
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if ("production" !== "development") {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
("production" !== "development" ? invariant(
!isValid(cached, id),
'ReactMount: Two valid but unequal nodes with the same `%s`: %s',
ATTR_NAME, id
) : invariant(!isValid(cached, id)));
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* Finds the node with the supplied public React instance.
*
* @param {*} instance A public React instance.
* @return {?DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNodeFromInstance(instance) {
var id = ReactInstanceMap.get(instance)._rootNodeID;
if (ReactEmptyComponent.isNullComponentID(id)) {
return null;
}
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
("production" !== "development" ? invariant(
internalGetID(node) === id,
'ReactMount: Unexpected modification of `%s`',
ATTR_NAME
) : invariant(internalGetID(node) === id));
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
var deepestNodeSoFar = null;
function findDeepestCachedAncestorImpl(ancestorID) {
var ancestor = nodeCache[ancestorID];
if (ancestor && isValid(ancestor, ancestorID)) {
deepestNodeSoFar = ancestor;
} else {
// This node isn't populated in the cache, so presumably none of its
// descendants are. Break out of the loop.
return false;
}
}
/**
* Return the deepest cached node whose ID is a prefix of `targetID`.
*/
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(
targetID,
findDeepestCachedAncestorImpl
);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(
componentInstance,
rootID,
container,
transaction,
shouldReuseMarkup) {
var markup = ReactReconciler.mountComponent(
componentInstance, rootID, transaction, emptyObject
);
componentInstance._isTopLevel = true;
ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(
componentInstance,
rootID,
container,
shouldReuseMarkup) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
transaction.perform(
mountComponentIntoNode,
null,
componentInstance,
rootID,
container,
transaction,
shouldReuseMarkup
);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
/** Exposed for debugging purposes **/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function(container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function(
prevComponent,
nextElement,
container,
callback) {
if ("production" !== "development") {
ReactElementValidator.checkAndWarnForMutatedProps(nextElement);
}
ReactMount.scrollMonitor(container, function() {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
if ("production" !== "development") {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] =
getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and starts scroll value
* monitoring
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function(nextComponent, container) {
("production" !== "development" ? invariant(
container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
),
'_registerComponent(...): Target container is not a DOM element.'
) : invariant(container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
)));
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function(
nextElement,
container,
shouldReuseMarkup
) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'_renderNewRootComponent(): Render methods should be a pure function ' +
'of props and state; triggering nested component updates from ' +
'render is not allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
var componentInstance = instantiateReactComponent(nextElement, null);
var reactRootID = ReactMount._registerComponent(
componentInstance,
container
);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(
batchedMountComponentIntoNode,
componentInstance,
reactRootID,
container,
shouldReuseMarkup
);
if ("production" !== "development") {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] =
getReactRootElementInContainer(container);
}
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function(nextElement, container, callback) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(nextElement),
'React.render(): Invalid component element.%s',
(
typeof nextElement === 'string' ?
' Instead of passing an element string, make sure to instantiate ' +
'it by passing it to React.createElement.' :
typeof nextElement === 'function' ?
' Instead of passing a component class, make sure to instantiate ' +
'it by passing it to React.createElement.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ?
' This may be caused by unintentionally loading two independent ' +
'copies of React.' :
''
)
) : invariant(ReactElement.isValidElement(nextElement)));
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevElement = prevComponent._currentElement;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
return ReactMount._updateRootComponent(
prevComponent,
nextElement,
container,
callback
).getPublicInstance();
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement);
if ("production" !== "development") {
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (ReactMount.isRenderedByReact(rootElementSibling)) {
("production" !== "development" ? warning(
false,
'render(): Target node has markup rendered by React, but there ' +
'are unrelated nodes as well. This is most commonly caused by ' +
'white-space inserted around server-rendered markup.'
) : null);
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent;
var component = ReactMount._renderNewRootComponent(
nextElement,
container,
shouldReuseMarkup
).getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into the supplied `container`.
*
* @param {function} constructor React component constructor.
* @param {?object} props Initial props of the component instance.
* @param {DOMElement} container DOM element to render into.
* @return {ReactComponent} Component instance rendered in `container`.
*/
constructAndRenderComponent: function(constructor, props, container) {
var element = ReactElement.createElement(constructor, props);
return ReactMount.render(element, container);
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into a container node identified by supplied `id`.
*
* @param {function} componentConstructor React component constructor
* @param {?object} props Initial props of the component instance.
* @param {string} id ID of the DOM element to render into.
* @return {ReactComponent} Component instance rendered in the container node.
*/
constructAndRenderComponentByID: function(constructor, props, id) {
var domNode = document.getElementById(id);
("production" !== "development" ? invariant(
domNode,
'Tried to get element with id of "%s" but it is not present on the page.',
id
) : invariant(domNode));
return ReactMount.constructAndRenderComponent(constructor, props, domNode);
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reactRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function(container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function(container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'unmountComponentAtNode(): Render methods should be a pure function of ' +
'props and state; triggering nested component updates from render is ' +
'not allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
("production" !== "development" ? invariant(
container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
),
'unmountComponentAtNode(...): Target container is not a DOM element.'
) : invariant(container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
)));
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
return false;
}
ReactMount.unmountComponentFromNode(component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if ("production" !== "development") {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
unmountComponentFromNode: function(instance, container) {
ReactReconciler.unmountComponent(instance);
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function(id) {
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if ("production" !== "development") {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
("production" !== "development" ? invariant(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID,
'ReactMount: Root element ID differed from reactRootID.'
) : invariant(// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID));
var containerChild = container.firstChild;
if (containerChild &&
reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
("production" !== "development" ? warning(
false,
'ReactMount: Root element has been removed from its original ' +
'container. New container:', rootElement.parentNode
) : null);
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function(id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* True if the supplied `node` is rendered by React.
*
* @param {*} node DOM Element to check.
* @return {boolean} True if the DOM Element appears to be rendered by React.
* @internal
*/
isRenderedByReact: function(node) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
return false;
}
var id = ReactMount.getID(node);
return id ? id.charAt(0) === SEPARATOR : false;
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function(node) {
var current = node;
while (current && current.parentNode !== current) {
if (ReactMount.isRenderedByReact(current)) {
return current;
}
current = current.parentNode;
}
return null;
},
/**
* Finds a node with the supplied `targetID` inside of the supplied
* `ancestorNode`. Exploits the ID naming scheme to perform the search
* quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} targetID ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
* @internal
*/
findComponentRoot: function(ancestorNode, targetID) {
var firstChildren = findComponentRootReusableArray;
var childIndex = 0;
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
firstChildren[0] = deepestAncestor.firstChild;
firstChildren.length = 1;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
var targetChild;
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
// Even if we find the node we're looking for, we finish looping
// through its siblings to ensure they're cached so that we don't have
// to revisit this node again. Otherwise, we make n^2 calls to getID
// when visiting the many children of a single node in order.
if (targetID === childID) {
targetChild = child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
if (targetChild) {
// Emptying firstChildren/findComponentRootReusableArray is
// not necessary for correctness, but it helps the GC reclaim
// any nodes that were left at the end of the search.
firstChildren.length = 0;
return targetChild;
}
}
firstChildren.length = 0;
("production" !== "development" ? invariant(
false,
'findComponentRoot(..., %s): Unable to find element. This probably ' +
'means the DOM was unexpectedly mutated (e.g., by the browser), ' +
'usually due to forgetting a <tbody> when using tables, nesting tags ' +
'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' +
'parent. ' +
'Try inspecting the child nodes of the element with React ID `%s`.',
targetID,
ReactMount.getID(ancestorNode)
) : invariant(false));
},
_mountImageIntoNode: function(markup, container, shouldReuseMarkup) {
("production" !== "development" ? invariant(
container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
),
'mountComponentIntoNode(...): Target container is not valid.'
) : invariant(container && (
(container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE)
)));
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
return;
} else {
var checksum = rootElement.getAttribute(
ReactMarkupChecksum.CHECKSUM_ATTR_NAME
);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(
ReactMarkupChecksum.CHECKSUM_ATTR_NAME,
checksum
);
var diffIndex = firstDifferenceIndex(markup, rootMarkup);
var difference = ' (client) ' +
markup.substring(diffIndex - 20, diffIndex + 20) +
'\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'You\'re trying to render a component to the document using ' +
'server rendering but the checksum was invalid. This usually ' +
'means you rendered a different component type or props on ' +
'the client from the one on the server, or your render() ' +
'methods are impure. React cannot handle this case due to ' +
'cross-browser quirks by rendering at the document root. You ' +
'should look for environment dependent code in your components ' +
'and ensure the props are the same client and server side:\n%s',
difference
) : invariant(container.nodeType !== DOC_NODE_TYPE));
if ("production" !== "development") {
("production" !== "development" ? warning(
false,
'React attempted to reuse markup in a container but the ' +
'checksum was invalid. This generally means that you are ' +
'using server rendering and the markup generated on the ' +
'server was not what the client was expecting. React injected ' +
'new markup to compensate which works but you have lost many ' +
'of the benefits of server rendering. Instead, figure out ' +
'why the markup being generated is different on the client ' +
'or server:\n%s',
difference
) : null);
}
}
}
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'You\'re trying to render a component to the document but ' +
'you didn\'t use server rendering. We can\'t do this ' +
'without using server rendering due to cross-browser quirks. ' +
'See React.renderToString() for server rendering.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
setInnerHTML(container, markup);
},
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
getNodeFromInstance: getNodeFromInstance,
purgeID: purgeID
};
ReactPerf.measureMethods(ReactMount, 'ReactMount', {
_renderNewRootComponent: '_renderNewRootComponent',
_mountImageIntoNode: '_mountImageIntoNode'
});
module.exports = ReactMount;
},{"10":10,"109":109,"115":115,"129":129,"134":134,"135":135,"148":148,"151":151,"154":154,"30":30,"39":39,"57":57,"58":58,"59":59,"66":66,"67":67,"69":69,"75":75,"81":81,"86":86,"87":87}],71:[function(_dereq_,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 ReactMultiChild
* @typechecks static-only
*/
'use strict';
var ReactComponentEnvironment = _dereq_(36);
var ReactMultiChildUpdateTypes = _dereq_(72);
var ReactReconciler = _dereq_(81);
var ReactChildReconciler = _dereq_(31);
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
textContent: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponentEnvironment.processChildrenUpdates(
updateQueue,
markupQueue
);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function(nestedChildren, transaction, context) {
var children = ReactChildReconciler.instantiateChildren(
nestedChildren, transaction, context
);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(
child,
rootID,
transaction,
context
);
child._mountIndex = index;
mountImages.push(mountImage);
index++;
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function(nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
// TODO: The setTextContent operation should be enough
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction, context) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildren, transaction, context);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildren, transaction, context) {
var prevChildren = this._renderedChildren;
var nextChildren = ReactChildReconciler.updateChildren(
prevChildren, nextNestedChildren, transaction, context
);
this._renderedChildren = nextChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChildByName(prevChild, name);
}
// The child must be instantiated before it's mounted.
this._mountChildByNameAtIndex(
nextChild, name, nextIndex, transaction, context
);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren.hasOwnProperty(name))) {
this._unmountChildByName(prevChildren[name], name);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function() {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function(child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function(child, mountImage) {
enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function(child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function(textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function(
child,
name,
index,
transaction,
context) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(
child,
rootID,
transaction,
context
);
child._mountIndex = index;
this.createChild(child, mountImage);
},
/**
* Unmounts a rendered child by name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @param {string} name Name of the child in `this._renderedChildren`.
* @private
*/
_unmountChildByName: function(child, name) {
this.removeChild(child);
child._mountIndex = null;
}
}
};
module.exports = ReactMultiChild;
},{"31":31,"36":36,"72":72,"81":81}],72:[function(_dereq_,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 ReactMultiChildUpdateTypes
*/
'use strict';
var keyMirror = _dereq_(140);
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"140":140}],73:[function(_dereq_,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 ReactNativeComponent
*/
'use strict';
var assign = _dereq_(27);
var invariant = _dereq_(135);
var autoGenerateWrapperClass = null;
var genericComponentClass = null;
// This registry keeps track of wrapper classes around native tags
var tagToComponentClass = {};
var textComponentClass = null;
var ReactNativeComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function(componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function(componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function(componentClasses) {
assign(tagToComponentClass, componentClasses);
},
// Temporary hack since we expect DOM refs to behave like composites,
// for this release.
injectAutoWrapper: function(wrapperFactory) {
autoGenerateWrapperClass = wrapperFactory;
}
};
/**
* Get a composite component wrapper class for a specific tag.
*
* @param {ReactElement} element The tag for which to get the class.
* @return {function} The React class constructor function.
*/
function getComponentClassForElement(element) {
if (typeof element.type === 'function') {
return element.type;
}
var tag = element.type;
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
}
return componentClass;
}
/**
* Get a native internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
("production" !== "development" ? invariant(
genericComponentClass,
'There is no registered component for the tag %s',
element.type
) : invariant(genericComponentClass));
return new genericComponentClass(element.type, element.props);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactNativeComponent = {
getComponentClassForElement: getComponentClassForElement,
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
},{"135":135,"27":27}],74:[function(_dereq_,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 ReactOwner
*/
'use strict';
var invariant = _dereq_(135);
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function(object) {
return !!(
(object &&
typeof object.attachRef === 'function' && typeof object.detachRef === 'function')
);
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function(component, ref, owner) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to add a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function(component, ref, owner) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to remove a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
},{"135":135}],75:[function(_dereq_,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 ReactPerf
* @typechecks static-only
*/
'use strict';
/**
* ReactPerf is a general AOP system designed to measure performance. This
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
*/
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* @param {object} object
* @param {string} objectName
* @param {object<string>} methodNames
*/
measureMethods: function(object, objectName, methodNames) {
if ("production" !== "development") {
for (var key in methodNames) {
if (!methodNames.hasOwnProperty(key)) {
continue;
}
object[key] = ReactPerf.measure(
objectName,
methodNames[key],
object[key]
);
}
}
},
/**
* Use this to wrap methods you want to measure. Zero overhead in production.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function(objName, fnName, func) {
if ("production" !== "development") {
var measuredFunc = null;
var wrapper = function() {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
wrapper.displayName = objName + '_' + fnName;
return wrapper;
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function(measure) {
ReactPerf.storedMeasure = measure;
}
}
};
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
},{}],76:[function(_dereq_,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 ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if ("production" !== "development") {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],77:[function(_dereq_,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 ReactPropTypeLocations
*/
'use strict';
var keyMirror = _dereq_(140);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"140":140}],78:[function(_dereq_,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 ReactPropTypes
*/
'use strict';
var ReactElement = _dereq_(57);
var ReactFragment = _dereq_(63);
var ReactPropTypeLocationNames = _dereq_(76);
var emptyFunction = _dereq_(114);
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var elementTypeChecker = createElementTypeChecker();
var nodeTypeChecker = createNodeChecker();
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: elementTypeChecker,
instanceOf: createInstanceTypeChecker,
node: nodeTypeChecker,
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error(
("Required " + locationName + " `" + propName + "` was not specified in ") +
("`" + componentName + "`.")
);
}
return null;
} else {
return validate(props, propName, componentName, location);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new Error(
("Invalid " + locationName + " `" + propName + "` of type `" + preciseType + "` ") +
("supplied to `" + componentName + "`, expected `" + expectedType + "`.")
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error(
("Invalid " + locationName + " `" + propName + "` of type ") +
("`" + propType + "` supplied to `" + componentName + "`, expected an array.")
);
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a ReactElement.")
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected instance of `" + expectedClassName + "`.")
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error(
("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") +
("supplied to `" + componentName + "`, expected one of " + valuesString + ".")
);
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` of type ") +
("`" + propType + "` supplied to `" + componentName + "`, expected an object.")
);
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
function validate(props, propName, componentName, location) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`.")
);
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a ReactNode.")
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` of type `" + propType + "` ") +
("supplied to `" + componentName + "`, expected `object`.")
);
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
propValue = ReactFragment.extractIfFragment(propValue);
for (var k in propValue) {
if (!isNode(propValue[k])) {
return false;
}
}
return true;
default:
return false;
}
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
module.exports = ReactPropTypes;
},{"114":114,"57":57,"63":63,"76":76}],79:[function(_dereq_,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 ReactPutListenerQueue
*/
'use strict';
var PooledClass = _dereq_(28);
var ReactBrowserEventEmitter = _dereq_(30);
var assign = _dereq_(27);
function ReactPutListenerQueue() {
this.listenersToPut = [];
}
assign(ReactPutListenerQueue.prototype, {
enqueuePutListener: function(rootNodeID, propKey, propValue) {
this.listenersToPut.push({
rootNodeID: rootNodeID,
propKey: propKey,
propValue: propValue
});
},
putListeners: function() {
for (var i = 0; i < this.listenersToPut.length; i++) {
var listenerToPut = this.listenersToPut[i];
ReactBrowserEventEmitter.putListener(
listenerToPut.rootNodeID,
listenerToPut.propKey,
listenerToPut.propValue
);
}
},
reset: function() {
this.listenersToPut.length = 0;
},
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactPutListenerQueue);
module.exports = ReactPutListenerQueue;
},{"27":27,"28":28,"30":30}],80:[function(_dereq_,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 ReactReconcileTransaction
* @typechecks static-only
*/
'use strict';
var CallbackQueue = _dereq_(6);
var PooledClass = _dereq_(28);
var ReactBrowserEventEmitter = _dereq_(30);
var ReactInputSelection = _dereq_(65);
var ReactPutListenerQueue = _dereq_(79);
var Transaction = _dereq_(103);
var assign = _dereq_(27);
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function() {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occured. `close`
* restores the previous value.
*/
close: function(previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactMountReady.notifyAll();
}
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.reset();
},
close: function() {
this.putListenerQueue.putListeners();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [
PUT_LISTENER_QUEUEING,
SELECTION_RESTORATION,
EVENT_SUPPRESSION,
ON_DOM_READY_QUEUEING
];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction() {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap proceedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function() {
return this.reactMountReady;
},
getPutListenerQueue: function() {
return this.putListenerQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
ReactPutListenerQueue.release(this.putListenerQueue);
this.putListenerQueue = null;
}
};
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"103":103,"27":27,"28":28,"30":30,"6":6,"65":65,"79":79}],81:[function(_dereq_,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 ReactReconciler
*/
'use strict';
var ReactRef = _dereq_(82);
var ReactElementValidator = _dereq_(58);
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function(internalInstance, rootID, transaction, context) {
var markup = internalInstance.mountComponent(rootID, transaction, context);
if ("production" !== "development") {
ReactElementValidator.checkAndWarnForMutatedProps(
internalInstance._currentElement
);
}
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function(internalInstance) {
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent();
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function(
internalInstance, nextElement, transaction, context
) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && nextElement._owner != null) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
return;
}
if ("production" !== "development") {
ReactElementValidator.checkAndWarnForMutatedProps(nextElement);
}
var refsChanged = ReactRef.shouldUpdateRefs(
prevElement,
nextElement
);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(
internalInstance,
transaction
) {
internalInstance.performUpdateIfNecessary(transaction);
}
};
module.exports = ReactReconciler;
},{"58":58,"82":82}],82:[function(_dereq_,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 ReactRef
*/
'use strict';
var ReactOwner = _dereq_(74);
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function(instance, element) {
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function(prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
return (
nextElement._owner !== prevElement._owner ||
nextElement.ref !== prevElement.ref
);
};
ReactRef.detachRefs = function(instance, element) {
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
},{"74":74}],83:[function(_dereq_,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 ReactRootIndex
* @typechecks
*/
'use strict';
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function(_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
},{}],84:[function(_dereq_,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.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
'use strict';
var ReactElement = _dereq_(57);
var ReactInstanceHandles = _dereq_(66);
var ReactMarkupChecksum = _dereq_(69);
var ReactServerRenderingTransaction =
_dereq_(85);
var emptyObject = _dereq_(115);
var instantiateReactComponent = _dereq_(134);
var invariant = _dereq_(135);
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToString(element) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(element),
'renderToString(): You must pass a valid ReactElement.'
) : invariant(ReactElement.isValidElement(element)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(element, null);
var markup =
componentInstance.mountComponent(id, transaction, emptyObject);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
/**
* @param {ReactElement} element
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderToStaticMarkup(element) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(element),
'renderToStaticMarkup(): You must pass a valid ReactElement.'
) : invariant(ReactElement.isValidElement(element)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(element, null);
return componentInstance.mountComponent(id, transaction, emptyObject);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
},{"115":115,"134":134,"135":135,"57":57,"66":66,"69":69,"85":85}],85:[function(_dereq_,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 ReactServerRenderingTransaction
* @typechecks
*/
'use strict';
var PooledClass = _dereq_(28);
var CallbackQueue = _dereq_(6);
var ReactPutListenerQueue = _dereq_(79);
var Transaction = _dereq_(103);
var assign = _dereq_(27);
var emptyFunction = _dereq_(114);
/**
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
close: emptyFunction
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.reset();
},
close: emptyFunction
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [
PUT_LISTENER_QUEUEING,
ON_DOM_READY_QUEUEING
];
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.reactMountReady = CallbackQueue.getPooled(null);
this.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap proceedures.
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function() {
return this.reactMountReady;
},
getPutListenerQueue: function() {
return this.putListenerQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
ReactPutListenerQueue.release(this.putListenerQueue);
this.putListenerQueue = null;
}
};
assign(
ReactServerRenderingTransaction.prototype,
Transaction.Mixin,
Mixin
);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
},{"103":103,"114":114,"27":27,"28":28,"6":6,"79":79}],86:[function(_dereq_,module,exports){
/**
* Copyright 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 ReactUpdateQueue
*/
'use strict';
var ReactLifeCycle = _dereq_(68);
var ReactCurrentOwner = _dereq_(39);
var ReactElement = _dereq_(57);
var ReactInstanceMap = _dereq_(67);
var ReactUpdates = _dereq_(87);
var assign = _dereq_(27);
var invariant = _dereq_(135);
var warning = _dereq_(154);
function enqueueUpdate(internalInstance) {
if (internalInstance !== ReactLifeCycle.currentlyMountingInstance) {
// If we're in a componentWillMount handler, don't enqueue a rerender
// because ReactUpdates assumes we're in a browser context (which is
// wrong for server rendering) and we're about to do a render anyway.
// See bug in #1740.
ReactUpdates.enqueueUpdate(internalInstance);
}
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
("production" !== "development" ? invariant(
ReactCurrentOwner.current == null,
'%s(...): Cannot update during an existing state transition ' +
'(such as within `render`). Render methods should be a pure function ' +
'of props and state.',
callerName
) : invariant(ReactCurrentOwner.current == null));
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if ("production" !== "development") {
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
("production" !== "development" ? warning(
!callerName,
'%s(...): Can only update a mounted or mounting component. ' +
'This usually means you called %s() on an unmounted ' +
'component. This is a no-op.',
callerName,
callerName
) : null);
}
return null;
}
if (internalInstance === ReactLifeCycle.currentlyUnmountingInstance) {
return null;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function(publicInstance, callback) {
("production" !== "development" ? invariant(
typeof callback === 'function',
'enqueueCallback(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
) : invariant(typeof callback === 'function'));
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance ||
internalInstance === ReactLifeCycle.currentlyMountingInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function(internalInstance, callback) {
("production" !== "development" ? invariant(
typeof callback === 'function',
'enqueueCallback(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
) : invariant(typeof callback === 'function'));
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function(publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(
publicInstance,
'forceUpdate'
);
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function(publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(
publicInstance,
'replaceState'
);
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function(publicInstance, partialState) {
var internalInstance = getInternalInstanceReadyForUpdate(
publicInstance,
'setState'
);
if (!internalInstance) {
return;
}
var queue =
internalInstance._pendingStateQueue ||
(internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function(publicInstance, partialProps) {
var internalInstance = getInternalInstanceReadyForUpdate(
publicInstance,
'setProps'
);
if (!internalInstance) {
return;
}
("production" !== "development" ? invariant(
internalInstance._isTopLevel,
'setProps(...): You called `setProps` on a ' +
'component with a parent. This is an anti-pattern since props will ' +
'get reactively updated when rendered. Instead, change the owner\'s ' +
'`render` method to pass the correct value as props to the component ' +
'where it is created.'
) : invariant(internalInstance._isTopLevel));
// Merge with the pending element if it exists, otherwise with existing
// element props.
var element = internalInstance._pendingElement ||
internalInstance._currentElement;
var props = assign({}, element.props, partialProps);
internalInstance._pendingElement = ReactElement.cloneAndReplaceProps(
element,
props
);
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function(publicInstance, props) {
var internalInstance = getInternalInstanceReadyForUpdate(
publicInstance,
'replaceProps'
);
if (!internalInstance) {
return;
}
("production" !== "development" ? invariant(
internalInstance._isTopLevel,
'replaceProps(...): You called `replaceProps` on a ' +
'component with a parent. This is an anti-pattern since props will ' +
'get reactively updated when rendered. Instead, change the owner\'s ' +
'`render` method to pass the correct value as props to the component ' +
'where it is created.'
) : invariant(internalInstance._isTopLevel));
// Merge with the pending element if it exists, otherwise with existing
// element props.
var element = internalInstance._pendingElement ||
internalInstance._currentElement;
internalInstance._pendingElement = ReactElement.cloneAndReplaceProps(
element,
props
);
enqueueUpdate(internalInstance);
},
enqueueElementInternal: function(internalInstance, newElement) {
internalInstance._pendingElement = newElement;
enqueueUpdate(internalInstance);
}
};
module.exports = ReactUpdateQueue;
},{"135":135,"154":154,"27":27,"39":39,"57":57,"67":67,"68":68,"87":87}],87:[function(_dereq_,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 ReactUpdates
*/
'use strict';
var CallbackQueue = _dereq_(6);
var PooledClass = _dereq_(28);
var ReactCurrentOwner = _dereq_(39);
var ReactPerf = _dereq_(75);
var ReactReconciler = _dereq_(81);
var Transaction = _dereq_(103);
var assign = _dereq_(27);
var invariant = _dereq_(135);
var warning = _dereq_(154);
var dirtyComponents = [];
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
("production" !== "development" ? invariant(
ReactUpdates.ReactReconcileTransaction && batchingStrategy,
'ReactUpdates: must inject a reconcile transaction class and batching ' +
'strategy'
) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy));
}
var NESTED_UPDATES = {
initialize: function() {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function() {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function() {
this.callbackQueue.reset();
},
close: function() {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction =
ReactUpdates.ReactReconcileTransaction.getPooled();
}
assign(
ReactUpdatesFlushTransaction.prototype,
Transaction.Mixin, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
destructor: function() {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function(method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(
this,
this.reconcileTransaction.perform,
this.reconcileTransaction,
method,
scope,
a
);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b, c, d);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
("production" !== "development" ? invariant(
len === dirtyComponents.length,
'Expected flush transaction\'s stored dirty-components length (%s) to ' +
'match dirty-components array length (%s).',
len,
dirtyComponents.length
) : invariant(len === dirtyComponents.length));
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
ReactReconciler.performUpdateIfNecessary(
component,
transaction.reconcileTransaction
);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(
callbacks[j],
component.getPublicInstance()
);
}
}
}
}
var flushBatchedUpdates = function() {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
flushBatchedUpdates = ReactPerf.measure(
'ReactUpdates',
'flushBatchedUpdates',
flushBatchedUpdates
);
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'enqueueUpdate(): Render methods should be a pure function of props ' +
'and state; triggering nested component updates from render is not ' +
'allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
("production" !== "development" ? invariant(
batchingStrategy.isBatchingUpdates,
'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' +
'updates are not being batched.'
) : invariant(batchingStrategy.isBatchingUpdates));
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function(ReconcileTransaction) {
("production" !== "development" ? invariant(
ReconcileTransaction,
'ReactUpdates: must provide a reconcile transaction class'
) : invariant(ReconcileTransaction));
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function(_batchingStrategy) {
("production" !== "development" ? invariant(
_batchingStrategy,
'ReactUpdates: must provide a batching strategy'
) : invariant(_batchingStrategy));
("production" !== "development" ? invariant(
typeof _batchingStrategy.batchedUpdates === 'function',
'ReactUpdates: must provide a batchedUpdates() function'
) : invariant(typeof _batchingStrategy.batchedUpdates === 'function'));
("production" !== "development" ? invariant(
typeof _batchingStrategy.isBatchingUpdates === 'boolean',
'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean'));
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
},{"103":103,"135":135,"154":154,"27":27,"28":28,"39":39,"6":6,"75":75,"81":81}],88:[function(_dereq_,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 SVGDOMPropertyConfig
*/
/*jslint bitwise: true*/
'use strict';
var DOMProperty = _dereq_(10);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var SVGDOMPropertyConfig = {
Properties: {
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
dx: MUST_USE_ATTRIBUTE,
dy: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fillOpacity: MUST_USE_ATTRIBUTE,
fontFamily: MUST_USE_ATTRIBUTE,
fontSize: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
markerEnd: MUST_USE_ATTRIBUTE,
markerMid: MUST_USE_ATTRIBUTE,
markerStart: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
opacity: MUST_USE_ATTRIBUTE,
patternContentUnits: MUST_USE_ATTRIBUTE,
patternUnits: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
preserveAspectRatio: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeDasharray: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeOpacity: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
textAnchor: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
patternContentUnits: 'patternContentUnits',
patternUnits: 'patternUnits',
preserveAspectRatio: 'preserveAspectRatio',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox'
}
};
module.exports = SVGDOMPropertyConfig;
},{"10":10}],89:[function(_dereq_,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 SelectEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(20);
var ReactInputSelection = _dereq_(65);
var SyntheticEvent = _dereq_(95);
var getActiveElement = _dereq_(121);
var isTextInputElement = _dereq_(138);
var keyOf = _dereq_(141);
var shallowEqual = _dereq_(150);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({onSelect: null}),
captured: keyOf({onSelectCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topContextMenu,
topLevelTypes.topFocus,
topLevelTypes.topKeyDown,
topLevelTypes.topMouseDown,
topLevelTypes.topMouseUp,
topLevelTypes.topSelectionChange
]
}
};
var activeElement = null;
var activeElementID = null;
var lastSelection = null;
var mouseDown = false;
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @param {object}
*/
function getSelection(node) {
if ('selectionStart' in node &&
ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown ||
activeElement == null ||
activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(
eventTypes.select,
activeElementID,
nativeEvent
);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) ||
topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't).
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
case topLevelTypes.topSelectionChange:
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent);
}
}
};
module.exports = SelectEventPlugin;
},{"121":121,"138":138,"141":141,"15":15,"150":150,"20":20,"65":65,"95":95}],90:[function(_dereq_,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 ServerReactRootIndex
* @typechecks
*/
'use strict';
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. In the future we need a way to generate GUIDs but for
* now this will work on a smaller scale.
*/
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var ServerReactRootIndex = {
createReactRootIndex: function() {
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = ServerReactRootIndex;
},{}],91:[function(_dereq_,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 SimpleEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginUtils = _dereq_(19);
var EventPropagators = _dereq_(20);
var SyntheticClipboardEvent = _dereq_(92);
var SyntheticEvent = _dereq_(95);
var SyntheticFocusEvent = _dereq_(96);
var SyntheticKeyboardEvent = _dereq_(98);
var SyntheticMouseEvent = _dereq_(99);
var SyntheticDragEvent = _dereq_(94);
var SyntheticTouchEvent = _dereq_(100);
var SyntheticUIEvent = _dereq_(101);
var SyntheticWheelEvent = _dereq_(102);
var getEventCharCode = _dereq_(122);
var invariant = _dereq_(135);
var keyOf = _dereq_(141);
var warning = _dereq_(154);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
blur: {
phasedRegistrationNames: {
bubbled: keyOf({onBlur: true}),
captured: keyOf({onBlurCapture: true})
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({onClick: true}),
captured: keyOf({onClickCapture: true})
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({onContextMenu: true}),
captured: keyOf({onContextMenuCapture: true})
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({onCopy: true}),
captured: keyOf({onCopyCapture: true})
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({onCut: true}),
captured: keyOf({onCutCapture: true})
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({onDoubleClick: true}),
captured: keyOf({onDoubleClickCapture: true})
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({onDrag: true}),
captured: keyOf({onDragCapture: true})
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onDragEnd: true}),
captured: keyOf({onDragEndCapture: true})
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({onDragEnter: true}),
captured: keyOf({onDragEnterCapture: true})
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({onDragExit: true}),
captured: keyOf({onDragExitCapture: true})
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({onDragLeave: true}),
captured: keyOf({onDragLeaveCapture: true})
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({onDragOver: true}),
captured: keyOf({onDragOverCapture: true})
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({onDragStart: true}),
captured: keyOf({onDragStartCapture: true})
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({onDrop: true}),
captured: keyOf({onDropCapture: true})
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({onFocus: true}),
captured: keyOf({onFocusCapture: true})
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({onInput: true}),
captured: keyOf({onInputCapture: true})
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyDown: true}),
captured: keyOf({onKeyDownCapture: true})
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyPress: true}),
captured: keyOf({onKeyPressCapture: true})
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyUp: true}),
captured: keyOf({onKeyUpCapture: true})
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({onLoad: true}),
captured: keyOf({onLoadCapture: true})
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({onError: true}),
captured: keyOf({onErrorCapture: true})
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseDown: true}),
captured: keyOf({onMouseDownCapture: true})
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseMove: true}),
captured: keyOf({onMouseMoveCapture: true})
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseOut: true}),
captured: keyOf({onMouseOutCapture: true})
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseOver: true}),
captured: keyOf({onMouseOverCapture: true})
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseUp: true}),
captured: keyOf({onMouseUpCapture: true})
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({onPaste: true}),
captured: keyOf({onPasteCapture: true})
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({onReset: true}),
captured: keyOf({onResetCapture: true})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({onScroll: true}),
captured: keyOf({onScrollCapture: true})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({onSubmit: true}),
captured: keyOf({onSubmitCapture: true})
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchCancel: true}),
captured: keyOf({onTouchCancelCapture: true})
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchEnd: true}),
captured: keyOf({onTouchEndCapture: true})
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchMove: true}),
captured: keyOf({onTouchMoveCapture: true})
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchStart: true}),
captured: keyOf({onTouchStartCapture: true})
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({onWheel: true}),
captured: keyOf({onWheelCapture: true})
}
}
};
var topLevelEventsToDispatchConfig = {
topBlur: eventTypes.blur,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSubmit: eventTypes.submit,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[type].dependencies = [type];
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* Same as the default implementation, except cancels the event when return
* value is false. This behavior will be disabled in a future release.
*
* @param {object} Event to be dispatched.
* @param {function} Application-level callback.
* @param {string} domID DOM ID to pass to the callback.
*/
executeDispatch: function(event, listener, domID) {
var returnValue = EventPluginUtils.executeDispatch(event, listener, domID);
("production" !== "development" ? warning(
typeof returnValue !== 'boolean',
'Returning `false` from an event handler is deprecated and will be ' +
'ignored in a future release. Instead, manually call ' +
'e.stopPropagation() or e.preventDefault(), as appropriate.'
) : null);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
},
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topError:
case topLevelTypes.topReset:
case topLevelTypes.topSubmit:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// FireFox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
("production" !== "development" ? invariant(
EventConstructor,
'SimpleEventPlugin: Unhandled event type, `%s`.',
topLevelType
) : invariant(EventConstructor));
var event = EventConstructor.getPooled(
dispatchConfig,
topLevelTargetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = SimpleEventPlugin;
},{"100":100,"101":101,"102":102,"122":122,"135":135,"141":141,"15":15,"154":154,"19":19,"20":20,"92":92,"94":94,"95":95,"96":96,"98":98,"99":99}],92:[function(_dereq_,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 SyntheticClipboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(95);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function(event) {
return (
'clipboardData' in event ?
event.clipboardData :
window.clipboardData
);
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"95":95}],93:[function(_dereq_,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 SyntheticCompositionEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(95);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(
dispatchConfig,
dispatchMarker,
nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticCompositionEvent,
CompositionEventInterface
);
module.exports = SyntheticCompositionEvent;
},{"95":95}],94:[function(_dereq_,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 SyntheticDragEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = _dereq_(99);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"99":99}],95:[function(_dereq_,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 SyntheticEvent
* @typechecks static-only
*/
'use strict';
var PooledClass = _dereq_(28);
var assign = _dereq_(27);
var emptyFunction = _dereq_(114);
var getEventTarget = _dereq_(125);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: getEventTarget,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function(event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
this[propName] = nativeEvent[propName];
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ?
nativeEvent.defaultPrevented :
nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
assign(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function() {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function() {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function(Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler);
module.exports = SyntheticEvent;
},{"114":114,"125":125,"27":27,"28":28}],96:[function(_dereq_,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 SyntheticFocusEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(101);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"101":101}],97:[function(_dereq_,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 SyntheticInputEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(95);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(
dispatchConfig,
dispatchMarker,
nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticInputEvent,
InputEventInterface
);
module.exports = SyntheticInputEvent;
},{"95":95}],98:[function(_dereq_,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 SyntheticKeyboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(101);
var getEventCharCode = _dereq_(122);
var getEventKey = _dereq_(123);
var getEventModifierState = _dereq_(124);
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function(event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function(event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function(event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"101":101,"122":122,"123":123,"124":124}],99:[function(_dereq_,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 SyntheticMouseEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(101);
var ViewportMetrics = _dereq_(104);
var getEventModifierState = _dereq_(124);
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function(event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function(event) {
return event.relatedTarget || (
((event.fromElement === event.srcElement ? event.toElement : event.fromElement))
);
},
// "Proprietary" Interface.
pageX: function(event) {
return 'pageX' in event ?
event.pageX :
event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function(event) {
return 'pageY' in event ?
event.pageY :
event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"101":101,"104":104,"124":124}],100:[function(_dereq_,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 SyntheticTouchEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(101);
var getEventModifierState = _dereq_(124);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"101":101,"124":124}],101:[function(_dereq_,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 SyntheticUIEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(95);
var getEventTarget = _dereq_(125);
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function(event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target != null && target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function(event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"125":125,"95":95}],102:[function(_dereq_,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 SyntheticWheelEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = _dereq_(99);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function(event) {
return (
'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0
);
},
deltaY: function(event) {
return (
'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0
);
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"99":99}],103:[function(_dereq_,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 Transaction
*/
'use strict';
var invariant = _dereq_(135);
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function() {
this.transactionWrappers = this.getTransactionWrappers();
if (!this.wrapperInitData) {
this.wrapperInitData = [];
} else {
this.wrapperInitData.length = 0;
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function() {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} args... Arguments to pass to the method (optional).
* Helps prevent need to bind in many cases.
* @return Return value from `method`.
*/
perform: function(method, scope, a, b, c, d, e, f) {
("production" !== "development" ? invariant(
!this.isInTransaction(),
'Transaction.perform(...): Cannot initialize a transaction when there ' +
'is already an outstanding transaction.'
) : invariant(!this.isInTransaction()));
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {
}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function(startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ?
wrapper.initialize.call(this) :
null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {
}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function(startIndex) {
("production" !== "development" ? invariant(
this.isInTransaction(),
'Transaction.closeAll(): Cannot close transaction when none are open.'
) : invariant(this.isInTransaction()));
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {
}
}
}
}
this.wrapperInitData.length = 0;
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occured.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
},{"135":135}],104:[function(_dereq_,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 ViewportMetrics
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function(scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{}],105:[function(_dereq_,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 accumulateInto
*/
'use strict';
var invariant = _dereq_(135);
/**
*
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
("production" !== "development" ? invariant(
next != null,
'accumulateInto(...): Accumulated items must not be null or undefined.'
) : invariant(next != null));
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray && nextIsArray) {
current.push.apply(current, next);
return current;
}
if (currentIsArray) {
current.push(next);
return current;
}
if (nextIsArray) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
},{"135":135}],106:[function(_dereq_,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 adler32
*/
/* jslint bitwise:true */
'use strict';
var MOD = 65521;
// This is a clean-room implementation of adler32 designed for detecting
// if markup is not what we expect it to be. It does not need to be
// cryptographically strong, only reasonably good at detecting if markup
// generated on the server is different than that on the client.
function adler32(data) {
var a = 1;
var b = 0;
for (var i = 0; i < data.length; i++) {
a = (a + data.charCodeAt(i)) % MOD;
b = (b + a) % MOD;
}
return a | (b << 16);
}
module.exports = adler32;
},{}],107:[function(_dereq_,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 camelize
* @typechecks
*/
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function(_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
},{}],108:[function(_dereq_,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 camelizeStyleName
* @typechecks
*/
"use strict";
var camelize = _dereq_(107);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
},{"107":107}],109:[function(_dereq_,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 containsNode
* @typechecks
*/
var isTextNode = _dereq_(139);
/*jslint bitwise:true */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
},{"139":139}],110:[function(_dereq_,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 createArrayFromMixed
* @typechecks
*/
var toArray = _dereq_(152);
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return (
// not null/false
!!obj &&
// arrays are objects, NodeLists are functions in Safari
(typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
('length' in obj) &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
(typeof obj.nodeType != 'number') &&
(
// a real array
(// HTMLCollection/NodeList
(Array.isArray(obj) ||
// arguments
('callee' in obj) || 'item' in obj))
)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
},{"152":152}],111:[function(_dereq_,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 createFullPageComponent
* @typechecks
*/
'use strict';
// Defeat circular references by requiring this directly.
var ReactClass = _dereq_(33);
var ReactElement = _dereq_(57);
var invariant = _dereq_(135);
/**
* Create a component that will throw an exception when unmounted.
*
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*
* @param {string} tag The tag to wrap
* @return {function} convenience constructor of new component
*/
function createFullPageComponent(tag) {
var elementFactory = ReactElement.createFactory(tag);
var FullPageComponent = ReactClass.createClass({
tagName: tag.toUpperCase(),
displayName: 'ReactFullPageComponent' + tag,
componentWillUnmount: function() {
("production" !== "development" ? invariant(
false,
'%s tried to unmount. Because of cross-browser quirks it is ' +
'impossible to unmount some top-level components (eg <html>, <head>, ' +
'and <body>) reliably and efficiently. To fix this, have a single ' +
'top-level component that never unmounts render these elements.',
this.constructor.displayName
) : invariant(false));
},
render: function() {
return elementFactory(this.props);
}
});
return FullPageComponent;
}
module.exports = createFullPageComponent;
},{"135":135,"33":33,"57":57}],112:[function(_dereq_,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 createNodesFromMarkup
* @typechecks
*/
/*jslint evil: true, sub: true */
var ExecutionEnvironment = _dereq_(21);
var createArrayFromMixed = _dereq_(110);
var getMarkupWrap = _dereq_(127);
var invariant = _dereq_(135);
/**
* Dummy container used to render all markup.
*/
var dummyNode =
ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode));
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
("production" !== "development" ? invariant(
handleScript,
'createNodesFromMarkup(...): Unexpected <script> element rendered.'
) : invariant(handleScript));
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = createArrayFromMixed(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"110":110,"127":127,"135":135,"21":21}],113:[function(_dereq_,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 dangerousStyleValue
* @typechecks static-only
*/
'use strict';
var CSSProperty = _dereq_(4);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 ||
isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"4":4}],114:[function(_dereq_,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 emptyFunction
*/
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.
*/
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;
},{}],115:[function(_dereq_,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 emptyObject
*/
"use strict";
var emptyObject = {};
if ("production" !== "development") {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],116:[function(_dereq_,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 escapeTextContentForBrowser
*/
'use strict';
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
var ESCAPE_REGEX = /[&><"']/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextContentForBrowser;
},{}],117:[function(_dereq_,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 findDOMNode
* @typechecks static-only
*/
'use strict';
var ReactCurrentOwner = _dereq_(39);
var ReactInstanceMap = _dereq_(67);
var ReactMount = _dereq_(70);
var invariant = _dereq_(135);
var isNode = _dereq_(137);
var warning = _dereq_(154);
/**
* Returns the DOM node rendered by this element.
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if ("production" !== "development") {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
("production" !== "development" ? warning(
owner._warnedAboutRefsInRender,
'%s is accessing getDOMNode or findDOMNode inside its render(). ' +
'render() should be a pure function of props and state. It should ' +
'never access something that requires stale data from the previous ' +
'render, such as refs. Move this logic to componentDidMount and ' +
'componentDidUpdate instead.',
owner.getName() || 'A component'
) : null);
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (isNode(componentOrElement)) {
return componentOrElement;
}
if (ReactInstanceMap.has(componentOrElement)) {
return ReactMount.getNodeFromInstance(componentOrElement);
}
("production" !== "development" ? invariant(
componentOrElement.render == null ||
typeof componentOrElement.render !== 'function',
'Component (with keys: %s) contains `render` method ' +
'but is not mounted in the DOM',
Object.keys(componentOrElement)
) : invariant(componentOrElement.render == null ||
typeof componentOrElement.render !== 'function'));
("production" !== "development" ? invariant(
false,
'Element appears to be neither ReactComponent nor DOMNode (keys: %s)',
Object.keys(componentOrElement)
) : invariant(false));
}
module.exports = findDOMNode;
},{"135":135,"137":137,"154":154,"39":39,"67":67,"70":70}],118:[function(_dereq_,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 flattenChildren
*/
'use strict';
var traverseAllChildren = _dereq_(153);
var warning = _dereq_(154);
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = !result.hasOwnProperty(name);
if ("production" !== "development") {
("production" !== "development" ? warning(
keyUnique,
'flattenChildren(...): Encountered two children with the same key, ' +
'`%s`. Child keys must be unique; when two children share a key, only ' +
'the first child will be used.',
name
) : null);
}
if (keyUnique && child != null) {
result[name] = child;
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
},{"153":153,"154":154}],119:[function(_dereq_,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 focusNode
*/
"use strict";
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch(e) {
}
}
module.exports = focusNode;
},{}],120:[function(_dereq_,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 forEachAccumulated
*/
'use strict';
/**
* @param {array} an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function(arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
},{}],121:[function(_dereq_,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 getActiveElement
* @typechecks
*/
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document body is not yet defined.
*/
function getActiveElement() /*?DOMElement*/ {
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
},{}],122:[function(_dereq_,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 getEventCharCode
* @typechecks static-only
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
},{}],123:[function(_dereq_,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 getEventKey
* @typechecks static-only
*/
'use strict';
var getEventCharCode = _dereq_(122);
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
},{"122":122}],124:[function(_dereq_,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 getEventModifierState
* @typechecks static-only
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
/*jshint validthis:true */
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
},{}],125:[function(_dereq_,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 getEventTarget
* @typechecks static-only
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
},{}],126:[function(_dereq_,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 getIteratorFn
* @typechecks static-only
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (
(ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL])
);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
},{}],127:[function(_dereq_,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 getMarkupWrap
*/
var ExecutionEnvironment = _dereq_(21);
var invariant = _dereq_(135);
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode =
ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {
// Force wrapping for SVG elements because if they get created inside a <div>,
// they will be initialized in the wrong namespace (and will not display).
'circle': true,
'defs': true,
'ellipse': true,
'g': true,
'line': true,
'linearGradient': true,
'path': true,
'polygon': true,
'polyline': true,
'radialGradient': true,
'rect': true,
'stop': true,
'text': true
};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg>', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap,
'circle': svgWrap,
'defs': svgWrap,
'ellipse': svgWrap,
'g': svgWrap,
'line': svgWrap,
'linearGradient': svgWrap,
'path': svgWrap,
'polygon': svgWrap,
'polyline': svgWrap,
'radialGradient': svgWrap,
'rect': svgWrap,
'stop': svgWrap,
'text': svgWrap
};
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode));
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
},{"135":135,"21":21}],128:[function(_dereq_,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 getNodeForCharacterOffset
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
},{}],129:[function(_dereq_,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 getReactRootElementInContainer
*/
'use strict';
var DOC_NODE_TYPE = 9;
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
module.exports = getReactRootElementInContainer;
},{}],130:[function(_dereq_,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 getTextContentAccessor
*/
'use strict';
var ExecutionEnvironment = _dereq_(21);
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ?
'textContent' :
'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"21":21}],131:[function(_dereq_,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 getUnboundedScrollPosition
* @typechecks
*/
"use strict";
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
},{}],132:[function(_dereq_,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 hyphenate
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],133:[function(_dereq_,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 hyphenateStyleName
* @typechecks
*/
"use strict";
var hyphenate = _dereq_(132);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
},{"132":132}],134:[function(_dereq_,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 instantiateReactComponent
* @typechecks static-only
*/
'use strict';
var ReactCompositeComponent = _dereq_(37);
var ReactEmptyComponent = _dereq_(59);
var ReactNativeComponent = _dereq_(73);
var assign = _dereq_(27);
var invariant = _dereq_(135);
var warning = _dereq_(154);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function() { };
assign(
ReactCompositeComponentWrapper.prototype,
ReactCompositeComponent.Mixin,
{
_instantiateReactComponent: instantiateReactComponent
}
);
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return (
typeof type === 'function' &&
typeof type.prototype.mountComponent === 'function' &&
typeof type.prototype.receiveComponent === 'function'
);
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @param {*} parentCompositeType The composite type that resolved this.
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node, parentCompositeType) {
var instance;
if (node === null || node === false) {
node = ReactEmptyComponent.emptyElement;
}
if (typeof node === 'object') {
var element = node;
if ("production" !== "development") {
("production" !== "development" ? warning(
element && (typeof element.type === 'function' ||
typeof element.type === 'string'),
'Only functions or strings can be mounted as React components.'
) : null);
}
// Special case string values
if (parentCompositeType === element.type &&
typeof element.type === 'string') {
// Avoid recursion if the wrapper renders itself.
instance = ReactNativeComponent.createInternalComponent(element);
// All native components are currently wrapped in a composite so we're
// safe to assume that this is what we should instantiate.
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// represenations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
} else {
instance = new ReactCompositeComponentWrapper();
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactNativeComponent.createInstanceForText(node);
} else {
("production" !== "development" ? invariant(
false,
'Encountered invalid React node of type %s',
typeof node
) : invariant(false));
}
if ("production" !== "development") {
("production" !== "development" ? warning(
typeof instance.construct === 'function' &&
typeof instance.mountComponent === 'function' &&
typeof instance.receiveComponent === 'function' &&
typeof instance.unmountComponent === 'function',
'Only React Components can be mounted.'
) : null);
}
// Sets up the instance. This can probably just move into the constructor now.
instance.construct(node);
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if ("production" !== "development") {
instance._isOwnerNecessary = false;
instance._warnedAboutRefsInRender = false;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if ("production" !== "development") {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
module.exports = instantiateReactComponent;
},{"135":135,"154":154,"27":27,"37":37,"59":59,"73":73}],135:[function(_dereq_,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 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.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if ("production" !== "development") {
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(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
},{}],136:[function(_dereq_,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 isEventSupported
*/
'use strict';
var ExecutionEnvironment = _dereq_(21);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature =
document.implementation &&
document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM ||
capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
},{"21":21}],137:[function(_dereq_,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 isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
return !!(object && (
((typeof Node === 'function' ? object instanceof Node : typeof object === 'object' &&
typeof object.nodeType === 'number' &&
typeof object.nodeName === 'string'))
));
}
module.exports = isNode;
},{}],138:[function(_dereq_,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 isTextInputElement
*/
'use strict';
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
return elem && (
(elem.nodeName === 'INPUT' && supportedInputTypes[elem.type] || elem.nodeName === 'TEXTAREA')
);
}
module.exports = isTextInputElement;
},{}],139:[function(_dereq_,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 isTextNode
* @typechecks
*/
var isNode = _dereq_(137);
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
},{"137":137}],140:[function(_dereq_,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 keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = _dereq_(135);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
("production" !== "development" ? invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
) : invariant(obj instanceof Object && !Array.isArray(obj)));
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"135":135}],141:[function(_dereq_,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 loosing 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.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],142:[function(_dereq_,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 mapObject
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Executes the provided `callback` once for each enumerable own property in the
* object and constructs a new object from the results. The `callback` is
* invoked with three arguments:
*
* - the property value
* - the property name
* - the object being traversed
*
* Properties that are added after the call to `mapObject` will not be visited
* by `callback`. If the values of existing properties are changed, the value
* passed to `callback` will be the value at the time `mapObject` visits them.
* Properties that are deleted before being visited are not visited.
*
* @grep function objectMap()
* @grep function objMap()
*
* @param {?object} object
* @param {function} callback
* @param {*} context
* @return {?object}
*/
function mapObject(object, callback, context) {
if (!object) {
return null;
}
var result = {};
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result[name] = callback.call(context, object[name], name, object);
}
}
return result;
}
module.exports = mapObject;
},{}],143:[function(_dereq_,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 memoizeStringOnly
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function(string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
},{}],144:[function(_dereq_,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 onlyChild
*/
'use strict';
var ReactElement = _dereq_(57);
var invariant = _dereq_(135);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection. The current implementation of this
* function assumes that a single child gets passed without a wrapper, but the
* purpose of this helper function is to abstract away the particular structure
* of children.
*
* @param {?object} children Child collection structure.
* @return {ReactComponent} The first and only `ReactComponent` contained in the
* structure.
*/
function onlyChild(children) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(children),
'onlyChild must be passed a children with exactly one child.'
) : invariant(ReactElement.isValidElement(children)));
return children;
}
module.exports = onlyChild;
},{"135":135,"57":57}],145:[function(_dereq_,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 performance
* @typechecks
*/
"use strict";
var ExecutionEnvironment = _dereq_(21);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance =
window.performance ||
window.msPerformance ||
window.webkitPerformance;
}
module.exports = performance || {};
},{"21":21}],146:[function(_dereq_,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 performanceNow
* @typechecks
*/
var performance = _dereq_(145);
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (!performance || !performance.now) {
performance = Date;
}
var performanceNow = performance.now.bind(performance);
module.exports = performanceNow;
},{"145":145}],147:[function(_dereq_,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 quoteAttributeValueForBrowser
*/
'use strict';
var escapeTextContentForBrowser = _dereq_(116);
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
},{"116":116}],148:[function(_dereq_,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 setInnerHTML
*/
/* globals MSApp */
'use strict';
var ExecutionEnvironment = _dereq_(21);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = function(node, html) {
node.innerHTML = html;
};
// Win8 apps: Allow all html to be inserted
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
setInnerHTML = function(node, html) {
MSApp.execUnsafeLocalFunction(function() {
node.innerHTML = html;
});
};
}
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function(node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) ||
html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
node.innerHTML = '\uFEFF' + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
}
module.exports = setInnerHTML;
},{"21":21}],149:[function(_dereq_,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 setTextContent
*/
'use strict';
var ExecutionEnvironment = _dereq_(21);
var escapeTextContentForBrowser = _dereq_(116);
var setInnerHTML = _dereq_(148);
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function(node, text) {
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function(node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
},{"116":116,"148":148,"21":21}],150:[function(_dereq_,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 shallowEqual
*/
'use strict';
/**
* Performs equality by iterating through keys on an object and returning
* false when any key has values which are not strictly equal between
* objA and objB. Returns true when the values of all keys are strictly equal.
*
* @return {boolean}
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B's keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],151:[function(_dereq_,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 shouldUpdateReactComponent
* @typechecks static-only
*/
'use strict';
var warning = _dereq_(154);
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
if (prevElement != null && nextElement != null) {
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return (nextType === 'string' || nextType === 'number');
} else {
if (nextType === 'object' &&
prevElement.type === nextElement.type &&
prevElement.key === nextElement.key) {
var ownersMatch = prevElement._owner === nextElement._owner;
var prevName = null;
var nextName = null;
var nextDisplayName = null;
if ("production" !== "development") {
if (!ownersMatch) {
if (prevElement._owner != null &&
prevElement._owner.getPublicInstance() != null &&
prevElement._owner.getPublicInstance().constructor != null) {
prevName =
prevElement._owner.getPublicInstance().constructor.displayName;
}
if (nextElement._owner != null &&
nextElement._owner.getPublicInstance() != null &&
nextElement._owner.getPublicInstance().constructor != null) {
nextName =
nextElement._owner.getPublicInstance().constructor.displayName;
}
if (nextElement.type != null &&
nextElement.type.displayName != null) {
nextDisplayName = nextElement.type.displayName;
}
if (nextElement.type != null && typeof nextElement.type === 'string') {
nextDisplayName = nextElement.type;
}
if (typeof nextElement.type !== 'string' ||
nextElement.type === 'input' ||
nextElement.type === 'textarea') {
if ((prevElement._owner != null &&
prevElement._owner._isOwnerNecessary === false) ||
(nextElement._owner != null &&
nextElement._owner._isOwnerNecessary === false)) {
if (prevElement._owner != null) {
prevElement._owner._isOwnerNecessary = true;
}
if (nextElement._owner != null) {
nextElement._owner._isOwnerNecessary = true;
}
("production" !== "development" ? warning(
false,
'<%s /> is being rendered by both %s and %s using the same ' +
'key (%s) in the same place. Currently, this means that ' +
'they don\'t preserve state. This behavior should be very ' +
'rare so we\'re considering deprecating it. Please contact ' +
'the React team and explain your use case so that we can ' +
'take that into consideration.',
nextDisplayName || 'Unknown Component',
prevName || '[Unknown]',
nextName || '[Unknown]',
prevElement.key
) : null);
}
}
}
}
return ownersMatch;
}
}
}
return false;
}
module.exports = shouldUpdateReactComponent;
},{"154":154}],152:[function(_dereq_,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 toArray
* @typechecks
*/
var invariant = _dereq_(135);
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
// old versions of Safari).
("production" !== "development" ? invariant(
!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function'),
'toArray: Array-like object expected'
) : invariant(!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function')));
("production" !== "development" ? invariant(
typeof length === 'number',
'toArray: Object needs a length property'
) : invariant(typeof length === 'number'));
("production" !== "development" ? invariant(
length === 0 ||
(length - 1) in obj,
'toArray: Object should have keys for indices'
) : invariant(length === 0 ||
(length - 1) in obj));
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
module.exports = toArray;
},{"135":135}],153:[function(_dereq_,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 traverseAllChildren
*/
'use strict';
var ReactElement = _dereq_(57);
var ReactFragment = _dereq_(63);
var ReactInstanceHandles = _dereq_(66);
var getIteratorFn = _dereq_(126);
var invariant = _dereq_(135);
var warning = _dereq_(154);
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
var didWarnAboutMaps = false;
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
if (component && component.key != null) {
// Explicit key
return wrapUserProvidedKey(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Escape a component key so that it is safe to use in a reactid.
*
* @param {*} key Component key to be escaped.
* @return {string} An escaped string.
*/
function escapeUserProvidedKey(text) {
return ('' + text).replace(
userProvidedKeyEscapeRegex,
userProvidedKeyEscaper
);
}
/**
* Wrap a `key` value explicitly provided by the user to distinguish it from
* implicitly-generated keys generated by a component's index in its parent.
*
* @param {string} key Value of a user-provided `key` attribute
* @return {string}
*/
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!number} indexSoFar Number of children encountered until this point.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(
children,
nameSoFar,
indexSoFar,
callback,
traverseContext
) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null ||
type === 'string' ||
type === 'number' ||
ReactElement.isValidElement(children)) {
callback(
traverseContext,
children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar,
indexSoFar
);
return 1;
}
var child, nextName, nextIndex;
var subtreeCount = 0; // Count of children found in the current subtree.
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = (
(nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
getComponentKey(child, i)
);
nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = (
(nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
getComponentKey(child, ii++)
);
nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
if ("production" !== "development") {
("production" !== "development" ? warning(
didWarnAboutMaps,
'Using Maps as children is not yet fully supported. It is an ' +
'experimental feature that might be removed. Convert it to a ' +
'sequence / iterable of keyed ReactElements instead.'
) : null);
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = (
(nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
wrapUserProvidedKey(entry[0]) + SUBSEPARATOR +
getComponentKey(child, 0)
);
nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
}
}
} else if (type === 'object') {
("production" !== "development" ? invariant(
children.nodeType !== 1,
'traverseAllChildren(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.'
) : invariant(children.nodeType !== 1));
var fragment = ReactFragment.extract(children);
for (var key in fragment) {
if (fragment.hasOwnProperty(key)) {
child = fragment[key];
nextName = (
(nameSoFar !== '' ? nameSoFar + SUBSEPARATOR : SEPARATOR) +
wrapUserProvidedKey(key) + SUBSEPARATOR +
getComponentKey(child, 0)
);
nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
}
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', 0, callback, traverseContext);
}
module.exports = traverseAllChildren;
},{"126":126,"135":135,"154":154,"57":57,"63":63,"66":66}],154:[function(_dereq_,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 warning
*/
"use strict";
var emptyFunction = _dereq_(114);
/**
* 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 ("production" !== "development") {
warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || /^[s\W]*$/.test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];});
console.warn(message);
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
},{"114":114}]},{},[1])(1)
}); |
examples/CustomPaging.js | BenjaminNeilDavis/react-slick | import React, { Component } from 'react'
import Slider from '../src/slider'
import {baseUrl} from './config'
export default class CenterMode extends Component {
render() {
const settings = {
customPaging: function(i) {
return <a><img src={`${baseUrl}/abstract0${i+1}.jpg`}/></a>
},
dots: true,
dotsClass: 'slick-dots slick-thumb',
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
};
return (
<div>
<h2>Custom Paging</h2>
<Slider {...settings}>
<div><img src={baseUrl + '/abstract01.jpg'} /></div>
<div><img src={baseUrl + '/abstract02.jpg'} /></div>
<div><img src={baseUrl + '/abstract03.jpg'} /></div>
<div><img src={baseUrl + '/abstract04.jpg'} /></div>
</Slider>
</div>
)
}
}
|
src/plantactionselector/PlantActionSelector.js | BushrootPDX/app | import React, { Component } from 'react';
import styled from 'styled-components';
export default class PlantActionSelector extends Component {
componentWillUnmount() {
this.props.actionReset();
}
render() {
const { addAction, removeAction } = this.props;
const PlantActionDiv = styled.div`
border-style: solid;
border-width: 2px;
border-color: red;
`;
return (
<PlantActionDiv>
<button
type="submit"
onClick={event => {
event.preventDefault();
addAction();
}}
>Add</button>
<button
type="submit"
onClick={event => {
event.preventDefault();
removeAction();
}}
>Remove</button>
</PlantActionDiv>
);
}
} |
frontend/webpack.config.js | auronzhong/pratice-node-project | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./entry.js',
],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build'
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css'
}, {
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loaders: ['react-hot', 'babel'],
}, {
test: /\.(woff|woff2)$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf$/,
loader: "file-loader"
}, {
test: /\.eot$/,
loader: "file-loader"
}, {
test: /\.svg$/,
loader: "file-loader"
}, {
test: /\/bootstrap\/js\//,
loader: 'imports?jQuery=jquery'
}]
},
devServer: {
contentBase: __dirname,
port: 3000,
inline: true,
historyApiFallback: true,
stats: {
colors: true
},
hot: true,
proxy: {
'*': 'http://127.0.0.1:3001',
}
},
babel: {
presets: ['react', 'es2015']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.